feat(opencode): expose goal through live RPC like Codex

This commit is contained in:
2026-11-18 05:29:00 +08:00
parent 1efb55332f
commit 8338c17e4c
15 changed files with 201 additions and 29 deletions
+4
View File
@@ -8,6 +8,7 @@ import { opencodeRemoteLauncher } from './opencodeRemoteLauncher';
import { ApiClient, ApiSessionClient } from '@/lib';
import type { OpencodeMode, PermissionMode } from './types';
import type { OpencodeHookServer } from './utils/startOpencodeHookServer';
import type { OpencodeGoalState } from './utils/opencodeGoal';
interface OpencodeLoopOptions {
path: string;
@@ -28,6 +29,8 @@ interface OpencodeLoopOptions {
onReasoningEffortRollback?: (effort: string | null) => void;
onSteerCancelHandlerChange?: (handler: OpencodeSteerCancelHandler | null) => void;
onCompactAvailabilityChange?: (available: boolean) => void;
/** Latest OpenCode goal state, used by the goal RPC handler. */
onOpencodeGoalStateChange?: (goal: OpencodeGoalState | null) => void;
onClearRequested?: () => Promise<void>;
onClearCleanupComplete?: () => Promise<void>;
onClearCleanupFailed?: () => Promise<void>;
@@ -87,6 +90,7 @@ export async function opencodeLoop(opts: OpencodeLoopOptions): Promise<void> {
onModelRollback: opts.onModelRollback,
onReasoningEffortRollback: opts.onReasoningEffortRollback,
onCompactAvailabilityChange: opts.onCompactAvailabilityChange,
onOpencodeGoalStateChange: opts.onOpencodeGoalStateChange,
onSteerCancelHandlerChange: opts.onSteerCancelHandlerChange,
isLocalIdCancelled: opts.isLocalIdCancelled,
onClearRequested: opts.onClearRequested,
+8 -15
View File
@@ -40,7 +40,7 @@ import {
} from './utils/opencodeCompactBridge';
import { OpencodeNativeTranscript } from './utils/opencodeNativeTranscript';
import { opencodeCompactionEventId } from './utils/opencodeCompactionProjector';
import { asOpencodeGoalState, fetchOpencodeGoal, type OpencodeGoalState } from './utils/opencodeGoal';
import { asOpencodeGoalState, fetchOpencodeGoal, toThreadGoal, type OpencodeGoalState } from './utils/opencodeGoal';
import { formatOpencodePromptError } from './utils/opencodeErrorText';
import {
formatOpencodeRetryStatus,
@@ -65,6 +65,7 @@ type OpencodeRemoteLauncherOptions = {
// a `/compact` message should be queued or immediately answered with a
// "not yet supported" reply — see its `slash.kind === 'compact'` branch.
onCompactAvailabilityChange?: (available: boolean) => void;
onOpencodeGoalStateChange?: (goal: OpencodeGoalState | null) => void;
// Consumes (delete-and-return) whether the queued item with this localId
// was cancelled via runOpencode.ts's `onCancelQueuedMessage` fallback
// branch (see the comment on `cancelledDequeuedLocalIds` there for what
@@ -1345,6 +1346,7 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
if (key === this.goalProjectionKey) return;
this.goalProjectionKey = key;
this.goalState = goal;
this.options.onOpencodeGoalStateChange?.(goal);
// A goal loop runs outside ACP turns, so nothing else marks the
// session as working. Without this the session list shows it idle
// while the agent is actively working through rounds.
@@ -1353,20 +1355,11 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
session.client.sendAgentMessage({ type: 'thread_goal_cleared', thread_id: acpSessionId });
return;
}
const webGoal = {
source: 'opencode' as const,
threadId: acpSessionId,
objective: goal.objective,
status: goal.status,
// OpenCode counts continuation rounds, not tokens. Keep them in
// their own fields so the UI never labels them as tokens.
rounds: goal.rounds,
maxRounds: goal.maxRounds,
createdAt: goal.updatedAt,
updatedAt: goal.updatedAt,
timeUsedSeconds: 0
};
session.client.sendAgentMessage({ type: 'thread_goal_updated', thread_id: acpSessionId, goal: webGoal });
session.client.sendAgentMessage({
type: 'thread_goal_updated',
thread_id: acpSessionId,
goal: toThreadGoal(goal, acpSessionId)
});
}
private handleV2SteerEvent(type: string, properties: Record<string, unknown>): void {
+32
View File
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildCliArgs } from '@/runner/run';
import { parseRemoteAgentCommandOptions } from '@/commands/agentCommandOptions';
import { OPENCODE_PERMISSION_MODES } from '@hapi/protocol/modes';
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
import type { MessageQueue2 } from '@/utils/MessageQueue2';
import type { OpencodeMode } from './types';
@@ -47,6 +48,7 @@ const harness = vi.hoisted(() => ({
// run without throwing when a test invokes the real onModeChange
// wrapper passed to opencodeLoop.
updateAgentState: vi.fn(),
updateMetadata: vi.fn(),
rpcHandlerManager: {
registerHandler: vi.fn()
}
@@ -165,6 +167,7 @@ describe('runOpencode set-session-config handler', () => {
harness.session.sendSessionEvent.mockReset();
harness.session.emitMessagesConsumed.mockReset();
harness.session.updateAgentState.mockReset();
harness.session.updateMetadata.mockReset();
harness.session.rpcHandlerManager.registerHandler.mockReset();
harness.listSlashCommands.mockReset();
harness.listSlashCommands.mockResolvedValue([]);
@@ -415,6 +418,35 @@ describe('runOpencode set-session-config handler', () => {
expect(harness.session.sendAgentMessage).not.toHaveBeenCalled();
});
it('serves the OpenCode goal over RPC and queues controls as native commands', async () => {
await runOpencode({});
const handler = harness.session.rpcHandlerManager.registerHandler.mock.calls
.find(call => call[0] === RPC_METHODS.OpencodeGoal)?.[1] as
| ((request: Record<string, unknown>) => Promise<{ goal: Record<string, unknown> | null }>)
| undefined;
expect(handler).toBeDefined();
await expect(handler!({ action: 'get' })).resolves.toEqual({ goal: null });
const loopArgs = harness.opencodeLoopArgs[0];
const onGoalStateChange = loopArgs.onOpencodeGoalStateChange as
| ((goal: Record<string, unknown> | null) => void) | undefined;
onGoalStateChange!({ id: 'g', objective: 'x', status: 'active', rounds: 2, maxRounds: 50, updatedAt: 1 });
await expect(handler!({ action: 'get' })).resolves.toMatchObject({
goal: { status: 'active', rounds: 2, source: 'opencode' }
});
await handler!({ action: 'pause' });
const messageQueue = loopArgs.messageQueue as
{ queue: Array<{ message: string; mode: { operation?: string } }> };
expect(messageQueue.queue[0]).toMatchObject({
message: '/goal pause',
mode: { operation: 'goal' }
});
});
it('queues /goal verbatim as its own isolated operation', async () => {
await runOpencode({});
+29
View File
@@ -19,6 +19,9 @@ import { listSlashCommands } from '@/modules/common/slashCommands';
import { resolveOpencodeSlashCommand } from './utils/slashCommands';
import { isRetryableConnectionError } from '@/utils/errorUtils';
import { withRetry } from '@/utils/time';
import { RPC_METHODS } from '@hapi/protocol/rpcMethods';
import { OpencodeGoalRequestSchema } from '@hapi/protocol/apiTypes';
import { toThreadGoal, type OpencodeGoalState } from './utils/opencodeGoal';
export async function runOpencode(opts: {
startedBy?: 'runner' | 'terminal';
@@ -133,6 +136,31 @@ export async function runOpencode(opts: {
let currentPermissionMode: PermissionMode = opts.permissionMode ?? 'default';
let sessionModel: string | null = initialModel;
let sessionModelReasoningEffort: string | null = initialModelReasoningEffort;
let opencodeGoalState: OpencodeGoalState | null = null;
// Same control surface Codex exposes over `codex-goal`: the web queries
// the live goal instead of inferring it from chat messages, and controls
// are queued as the native `/goal` commands OpenCode owns.
session.rpcHandlerManager.registerHandler(RPC_METHODS.OpencodeGoal, async raw => {
const request = OpencodeGoalRequestSchema.parse(raw);
if (request.action !== 'get') {
const text = request.action === 'update' ? `/goal ${request.objective}` : `/goal ${request.action}`;
messageQueue.pushIsolated(text, {
permissionMode: currentPermissionMode,
model: sessionModel,
modelReasoningEffort: sessionModelReasoningEffort,
operation: 'goal'
});
}
return {
goal: opencodeGoalState ? toThreadGoal(opencodeGoalState, session.sessionId) : null
};
});
session.updateMetadata(metadata => ({
...metadata,
capabilities: { ...metadata.capabilities, opencodeGoal: true }
}));
const hookServer = await startOpencodeHookServer({
onEvent: (event) => {
const currentSession = sessionWrapperRef.current;
@@ -537,6 +565,7 @@ export async function runOpencode(opts: {
resumeSessionId: opts.resumeSessionId,
hookServer,
hookUrl,
onOpencodeGoalStateChange: (goal) => { opencodeGoalState = goal; },
onModeChange: (mode) => {
if (mode === 'remote') {
// A fresh remote entry is beginning (first-ever, or a
+15
View File
@@ -49,6 +49,21 @@ export async function fetchOpencodeGoal(opts: {
return asOpencodeGoalState(output ?? null);
}
/** Project OpenCode's goal state into the shared ThreadGoal shape. */
export function toThreadGoal(goal: OpencodeGoalState, threadId: string) {
return {
source: 'opencode' as const,
threadId,
objective: goal.objective,
status: goal.status,
rounds: goal.rounds,
maxRounds: goal.maxRounds,
createdAt: goal.updatedAt,
updatedAt: goal.updatedAt,
timeUsedSeconds: 0
}
}
/**
* Pull `{ sessionID, goal }` out of an `rpc.opencode.goal.changed` event.
* v2 event frames wrap the body twice (`{ type, data: { type, data, location } }`