feat(opencode): bridge native /goal command, status and round output

This commit is contained in:
2026-11-18 03:37:42 +08:00
parent 0a72a377a4
commit 09495f779b
21 changed files with 462 additions and 12 deletions
@@ -56,6 +56,7 @@ const harness = vi.hoisted(() => ({
sessionId: string;
onRetry: (retry: { attempt: number; message: string }) => void;
onEvent?: (type: string, properties: Record<string, unknown>, eventId?: string) => void;
onGoalChange?: (goal: unknown) => void;
}>,
eventStreamCloseCount: 0,
// Soft-steer (mid-turn inject) controls.
@@ -1837,6 +1838,16 @@ describe('opencodeRemoteLauncher inline model switch', () => {
expect(JSON.stringify(harness.promptContents[1])).not.toContain('skill_lookup');
});
it('forwards a /goal batch verbatim over ACP without the first-prompt instruction prefix', async () => {
const { session } = createSessionStub([
{ message: '/goal ship the login fix', mode: { ...createMode(), operation: 'goal' } }
]);
await opencodeRemoteLauncher(session as never);
expect(harness.promptContents).toEqual([[{ type: 'text', text: '/goal ship the login fix' }]]);
});
it('spawns the ACP backend with an explicit --port/--hostname from allocateFreePort', async () => {
const { session } = createSessionStub([
{ message: 'first', mode: createMode() }
@@ -4725,6 +4736,28 @@ describe('opencodeRemoteLauncher v2 flavor wiring', () => {
}
});
it('v2: projects an OpenCode goal change to the status panel', async () => {
harness.detectedVersion = 'v2';
harness.discoveredPort = 41234;
harness.discoveredPassword = 'pw-secret';
harness.sessionModelsMetadata = { currentModelId: 'ollama/x', availableModels: [] };
const { session, agentMessages } = createSessionStub([], { keepOpen: true });
const launcherPromise = opencodeRemoteLauncher(session as never);
await vi.waitFor(() => expect(harness.eventStreamOptions).toHaveLength(1));
harness.eventStreamOptions[0].onGoalChange!({
id: 'goal-1', objective: 'ship it', status: 'active', rounds: 2, maxRounds: 50, updatedAt: 1
});
expect(agentMessages).toContainEqual(expect.objectContaining({
type: 'thread_goal_updated',
goal: expect.objectContaining({ objective: 'ship it', status: 'active' })
}));
session.queue.close();
await launcherPromise;
});
it('v2: reports one automatic application start without changing turn thinking for preparation', async () => {
harness.detectedVersion = 'v2';
harness.discoveredPort = 41234;
+92 -6
View File
@@ -40,6 +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 { formatOpencodePromptError } from './utils/opencodeErrorText';
import {
formatOpencodeRetryStatus,
@@ -202,6 +203,10 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
/** Subscription to the agent's own server event stream; null until the ACP session id is known, closed in cleanup(). */
private eventStream: OpencodeEventSubscription | null = null;
private nativeTranscript: OpencodeNativeTranscript | null = null;
/** Latest goal read from OpenCode's plugin RPC, projected to the hub for the status panel. */
private goalState: OpencodeGoalState | null = null;
private goalProjectionKey: string | null = null;
private goalPollTimer: ReturnType<typeof setInterval> | null = null;
private stallErrorReportedForPrompt = false;
/** True while a normal (non-compact/clear) prompt turn is in flight — the only steerable state. */
private promptInFlight = false;
@@ -440,7 +445,13 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
},
onReadFailure: () => session.sendSessionEvent({ type: 'message', message: 'OpenCode native transcript is temporarily unavailable. Retrying on reconnect or at the end of the turn.' }),
onText: (part) => {
if (this.majorVersion !== 'v1' || part.role !== 'assistant') return;
if (part.role !== 'assistant') return;
// v1 has no ACP text path. In v2 ACP owns the text of an active
// prompt turn; only background turns (the /goal loop runs via
// the core plugin's `experimental.idle` hook, outside ACP)
// need the native event bridge. Without this the goal loop is
// healthy but completely invisible in HAPI.
if (this.majorVersion === 'v2' && this.promptInFlight) return;
const converted = convertAgentMessage(part.type === 'reasoning'
? { type: 'reasoning', id: part.id, text: part.text, live: !part.complete }
: { type: 'text', id: part.id, text: part.text, streamSnapshot: true, live: !part.complete });
@@ -465,12 +476,38 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
} : undefined,
mode: this.majorVersion ?? 'v1',
onRetry: (retry) => this.surfaceUpstreamRetry(retry),
onConnected: () => { void this.nativeTranscript?.refresh(); },
onConnected: () => {
void this.nativeTranscript?.refresh();
if (this.majorVersion === 'v2' && this.v2RestInfo) {
void fetchOpencodeGoal({
baseUrl: restBaseUrl,
directory: session.path,
sessionID: acpSessionId,
headers: nativeHeaders ?? {}
}).then(goal => this.projectGoal(session, acpSessionId, goal, true)).catch(() => {});
}
},
onEvent: (type, properties, eventId) => {
this.nativeTranscript?.event(type, properties, eventId);
this.handleV2SteerEvent(type, properties);
}
},
onGoalChange: (value) => this.projectGoal(session, acpSessionId, asOpencodeGoalState(value))
});
if (this.majorVersion === 'v2' && this.v2RestInfo) {
const readGoal = () => {
void fetchOpencodeGoal({
baseUrl: restBaseUrl,
directory: session.path,
sessionID: acpSessionId,
headers: nativeHeaders ?? {}
}).then(goal => this.projectGoal(session, acpSessionId, goal)).catch(() => {});
};
// A goal can be paused by *another* OpenCode server boot, whose
// `changed` event never reaches this session's event stream. Poll
// so the status panel cannot stay stuck on "active".
this.goalPollTimer = setInterval(() => { if (!this.shouldExit) readGoal(); }, 5_000);
this.goalPollTimer.unref?.();
}
}
// Seed currentBackendModel from the ACP session metadata so the first
@@ -911,12 +948,19 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
continue;
}
// /goal is OpenCode's own slash command: its core plugin parses
// the objective and the pause/resume/clear controls. Keep the text
// byte-for-byte as the user typed it — the instruction prefix and
// the native REST prompt path below would both hide the leading
// "/" from OpenCode's ACP command detector.
const isGoalBatch = batch.mode.operation === 'goal';
// Inject title instructions on first prompt
let messageText = batch.message;
if (batch.mode.permissionMode === 'plan') {
if (!isGoalBatch && batch.mode.permissionMode === 'plan') {
messageText = `${PLAN_MODE_INSTRUCTION}\n\n${messageText}`;
}
if (!this.instructionsSent) {
if (!isGoalBatch && !this.instructionsSent) {
messageText = `${getOpencodeNativeToolInstruction()}\n\n${messageText}`;
this.instructionsSent = true;
}
@@ -946,7 +990,7 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
? this.currentBackendEffort
: null;
const nativeModel = splitProviderModel(this.currentBackendModel);
if (nativeVariant && nativeModel && backend.promptWithVariant && this.baseUrl) {
if (!isGoalBatch && nativeVariant && nativeModel && backend.promptWithVariant && this.baseUrl) {
await backend.promptWithVariant(acpSessionId, promptContent, (message: AgentMessage) => {
this.handleAgentMessage(message);
}, {
@@ -1284,6 +1328,44 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
);
}
/**
* Project OpenCode's goal into the shapes the web already understands for
* Codex: a `thread_goal_updated` event feeds the top status panel. The
* goal loop itself runs outside ACP, so this is the only signal HAPI can
* see; the loop's text is projected by the native transcript instead.
*/
private projectGoal(session: OpencodeSession, acpSessionId: string, goal: OpencodeGoalState | null, forceClear = false): void {
// On attach we must clear a goal left in the hub by a previous CLI
// process even though this process has never seen one.
if (!goal && !this.goalState && !forceClear) return;
const key = goal ? `${goal.id}:${goal.status}:${goal.rounds}:${goal.objective}` : null;
if (key === this.goalProjectionKey) return;
this.goalProjectionKey = key;
this.goalState = 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.
if (!this.promptInFlight) session.onThinkingChange(goal?.status === 'active');
if (!goal) {
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 });
}
private handleV2SteerEvent(type: string, properties: Record<string, unknown>): void {
if (this.majorVersion !== 'v2' || typeof properties.inboxID !== 'string') return;
for (const entry of this.v2Steers.values()) {
@@ -1632,6 +1714,10 @@ class OpencodeRemoteLauncher extends RemoteLauncherBase {
}));
// Before anything that can fail: a stream left open would keep
// reconnecting to a subprocess that is on its way out.
if (this.goalPollTimer) {
clearInterval(this.goalPollTimer);
this.goalPollTimer = null;
}
this.nativeTranscript?.close();
this.nativeTranscript = null;
this.eventStream?.close();
+29
View File
@@ -415,6 +415,35 @@ describe('runOpencode set-session-config handler', () => {
expect(harness.session.sendAgentMessage).not.toHaveBeenCalled();
});
it('queues /goal verbatim as its own isolated operation', async () => {
await runOpencode({});
const messageQueue = harness.opencodeLoopArgs[0]?.messageQueue as
{ queue: Array<{ message: string; mode: { operation?: string }; localId?: string; isolate?: boolean }> };
const userMessageHandler = harness.session.onUserMessage.mock.calls[0]?.[0] as
((msg: { content: { text: string; attachments?: unknown[] } }, localId?: string) => void)
| undefined;
expect(userMessageHandler).toBeDefined();
userMessageHandler!({ content: { text: '/goal ship the login fix' } }, 'local-goal');
for (let i = 0; i < 5; i++) {
await new Promise((resolve) => setTimeout(resolve, 0));
}
expect(messageQueue.queue).toEqual([
{
message: '/goal ship the login fix',
mode: expect.objectContaining({ operation: 'goal' }),
modeHash: expect.any(String),
localId: 'local-goal',
isolate: true
}
]);
// OpenCode owns the command; HAPI must not answer it synchronously.
expect(harness.session.sendAgentMessage).not.toHaveBeenCalled();
});
it('queues runner-backed /clear as its own FIFO operation without acknowledging it early', async () => {
await runOpencode({ startedBy: 'runner' });
+12
View File
@@ -371,6 +371,18 @@ export async function runOpencode(opts: {
return;
}
if (slash.kind === 'goal') {
// OpenCode owns this command (core plugin, v2.2.1+): it
// parses the objective and the pause/resume/clear controls
// itself. Queue the raw slash text as an isolated item so
// the remote launcher forwards it verbatim over ACP, and
// local mode's PTY hands it straight to the TUI. Like
// /compact, it is acked automatically at dequeue time and
// keeps its real FIFO position via pushIsolated.
messageQueue.pushIsolated(slash.text, { ...buildMode(), operation: 'goal' }, localId);
return;
}
if (slash.kind !== 'passthrough') {
if (slash.updates) {
if (slash.updates.permissionMode !== undefined) {
+1 -1
View File
@@ -16,7 +16,7 @@ export interface OpencodeMode {
// calling `backend.prompt()`, which keeps /compact from "cutting in
// line" ahead of prompts that were already queued when it arrived.
// `undefined` for normal prompts.
operation?: 'compact' | 'clear';
operation?: 'compact' | 'clear' | 'goal';
}
export type OpencodeHookEvent = {
@@ -100,7 +100,7 @@ export class OpencodeCompactionProjector {
private projectText(parts: Iterable<RecordValue> = this.parts.values()): void {
for (const part of parts) {
if ((part.type !== 'text' && part.type !== 'reasoning') || typeof part.text !== 'string') continue;
if ((part.type !== 'text' && part.type !== 'reasoning') || typeof part.text !== 'string' || !part.text.trim()) continue;
const info = typeof part.messageID === 'string' ? this.messages.get(part.messageID) : undefined;
if (!info || info.summary === true || info.type === 'compaction' || part.ignored === true) continue;
if (part.synthetic === true && isObject(part.metadata) && part.metadata.compaction_continue === true) continue;
@@ -2,6 +2,7 @@ import { asNumber, asString, isObject } from '@hapi/protocol';
import { logger } from '@/ui/logger';
import type { FetchLike } from './opencodeCompactBridge';
import { collapseWhitespace, truncateOpencodeProviderText } from './opencodeErrorText';
import { extractOpencodeGoalChange } from './opencodeGoal';
/**
* `session.status` with `type: "retry"` — OpenCode announcing that it hit an
@@ -39,6 +40,8 @@ export type OpencodeEventStreamOptions = {
onRetry: (retry: OpencodeRetryStatus) => void;
/** Native transcript consumer; receives normalized, session-scoped events. */
onEvent?: (type: string, properties: Record<string, unknown>, eventId?: string) => void;
/** `rpc.opencode.goal.changed` payloads. Goal events are not ordinary session messages. */
onGoalChange?: (goal: unknown) => void;
onConnected?: () => void;
/**
* Extra request headers merged into every (re)connect attempt. Required
@@ -290,6 +293,16 @@ export function subscribeToOpencodeEvents(options: OpencodeEventStreamOptions):
const handleEvent = (event: unknown): void => {
if (!isObject(event)) return;
const properties = isObject(event.properties) ? event.properties : null;
const goalType = typeof event.type === 'string' && event.type.includes('goal.changed')
|| isObject(properties) && typeof properties.type === 'string' && properties.type.includes('goal.changed')
|| isObject(properties) && isObject(properties.data) && typeof properties.data.type === 'string'
&& properties.data.type.includes('goal.changed');
if (goalType && properties) {
const change = extractOpencodeGoalChange(properties);
if (change && (!change.sessionID || change.sessionID === sessionId)) {
options.onGoalChange?.(change.goal);
}
}
if (properties && typeof event.type === 'string') {
const record = isObject(properties.info) ? properties.info : isObject(properties.part) ? properties.part : properties;
if (record.sessionID === sessionId) options.onEvent?.(event.type, properties, typeof event.id === 'string' ? event.id : undefined);
@@ -0,0 +1,78 @@
import { describe, expect, it } from 'vitest';
import { asOpencodeGoalState, extractOpencodeGoalChange, fetchOpencodeGoal } from './opencodeGoal';
describe('asOpencodeGoalState', () => {
it('accepts a live OpenCode goal', () => {
expect(asOpencodeGoalState({
id: 'goal-1',
objective: 'ship it',
status: 'active',
rounds: 3,
maxRounds: 50,
boot: 'boot-1',
updatedAt: 123
})).toMatchObject({ id: 'goal-1', status: 'active', rounds: 3 });
});
it('rejects malformed or unsupported statuses', () => {
expect(asOpencodeGoalState(null)).toBeNull();
expect(asOpencodeGoalState({ id: 'g', objective: 'x', status: 'waiting', rounds: 0, maxRounds: 50 })).toBeNull();
expect(asOpencodeGoalState({ id: 'g', objective: '', status: 'active', rounds: 0, maxRounds: 50 })).toBeNull();
});
});
describe('extractOpencodeGoalChange', () => {
it('reads a flat goal.changed payload', () => {
expect(extractOpencodeGoalChange({ sessionID: 'ses_1', goal: { id: 'g' } })).toEqual({
sessionID: 'ses_1', goal: { id: 'g' }
});
});
it('walks the v2 data envelope', () => {
expect(extractOpencodeGoalChange({
type: 'rpc.opencode.goal.changed',
data: { data: { sessionID: 'ses_1', goal: null } }
})).toEqual({ sessionID: 'ses_1', goal: null });
});
it('returns null when no goal payload exists', () => {
expect(extractOpencodeGoalChange({ sessionID: 'ses_1' })).toBeNull();
expect(extractOpencodeGoalChange(null)).toBeNull();
});
});
describe('fetchOpencodeGoal', () => {
it('reads opencode.goal/get through the plugin RPC', async () => {
const goal = { id: 'g', objective: 'ship', status: 'paused', rounds: 2, maxRounds: 50, updatedAt: 9 };
let seenUrl = '';
let seenBody = '';
const response = {
ok: true,
json: async () => ({ output: goal })
} as Response;
const fetchImpl = (async (url: string | URL | Request, init?: RequestInit) => {
seenUrl = String(url);
seenBody = String(init?.body ?? '');
return response;
}) as unknown as typeof fetch;
const result = await fetchOpencodeGoal({
baseUrl: 'http://127.0.0.1:1234',
directory: '/project',
sessionID: 'ses_1',
headers: { authorization: 'Basic abc' },
fetchImpl
});
expect(seenUrl).toContain('/api/rpc/opencode.goal/get?directory=%2Fproject');
expect(JSON.parse(seenBody)).toEqual({ input: { sessionID: 'ses_1' } });
expect(result).toMatchObject({ id: 'g', status: 'paused' });
});
it('returns null on a failed RPC call', async () => {
const fetchImpl = (async () => ({ ok: false, json: async () => ({}) }) as Response) as unknown as typeof fetch;
await expect(fetchOpencodeGoal({
baseUrl: 'http://127.0.0.1:1234', directory: '/p', sessionID: 's', headers: {}, fetchImpl
})).resolves.toBeNull();
});
});
+70
View File
@@ -0,0 +1,70 @@
import { isObject } from '@hapi/protocol';
/** The subset of OpenCode's `Goal.State` HAPI projects into the session. */
export type OpencodeGoalState = {
id: string;
objective: string;
status: 'active' | 'paused' | 'complete';
rounds: number;
maxRounds: number;
reason?: string;
updatedAt: number;
};
export function asOpencodeGoalState(value: unknown): OpencodeGoalState | null {
if (!isObject(value)) return null;
const { id, objective, status, rounds, maxRounds, updatedAt } = value;
if (typeof id !== 'string' || typeof objective !== 'string' || !objective.trim()) return null;
if (status !== 'active' && status !== 'paused' && status !== 'complete') return null;
if (typeof rounds !== 'number' || typeof maxRounds !== 'number') return null;
return {
id,
objective,
status,
rounds,
maxRounds,
...(typeof value.reason === 'string' ? { reason: value.reason } : {}),
...(typeof updatedAt === 'number' ? { updatedAt } : { updatedAt: 0 })
};
}
/** Read a goal through OpenCode's plugin RPC (`opencode.goal/get`). */
export async function fetchOpencodeGoal(opts: {
baseUrl: string;
directory: string;
sessionID: string;
headers: Record<string, string>;
fetchImpl?: typeof fetch;
}): Promise<OpencodeGoalState | null> {
const url = `${opts.baseUrl}/api/rpc/opencode.goal/get?directory=${encodeURIComponent(opts.directory)}`;
const response = await (opts.fetchImpl ?? fetch)(url, {
method: 'POST',
headers: { 'content-type': 'application/json', ...opts.headers },
body: JSON.stringify({ input: { sessionID: opts.sessionID } }),
signal: AbortSignal.timeout(10_000)
});
if (!response.ok) return null;
const body: unknown = await response.json();
const output = isObject(body) ? body.output : undefined;
return asOpencodeGoalState(output ?? null);
}
/**
* Pull `{ sessionID, goal }` out of an `rpc.opencode.goal.changed` event.
* v2 event frames wrap the body twice (`{ type, data: { type, data, location } }`
* in some builds, flat `{ type, data: { sessionID, goal } }` in others), so
* walk a bounded number of `data` levels instead of assuming one shape.
*/
export function extractOpencodeGoalChange(properties: unknown): { sessionID?: string; goal: unknown } | null {
if (!isObject(properties)) return null;
let current: Record<string, unknown> = properties;
for (let depth = 0; depth < 4; depth++) {
if ('sessionID' in current || 'goal' in current) {
const sessionID = typeof current.sessionID === 'string' ? current.sessionID : undefined;
if ('goal' in current) return { sessionID, goal: current.goal };
}
if (!isObject(current.data)) return null;
current = current.data;
}
return null;
}
@@ -190,6 +190,39 @@ describe('OpenCode native transcript reconciliation', () => {
});
describe('v2 background turn text (OpenCode 2.2.x events)', () => {
it('projects session.text.delta and finalizes on session.step.ended', () => {
const onText = vi.fn();
const transcript = new OpencodeNativeTranscript({
baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v2',
fetchImpl: vi.fn(async () => Response.json([])), onSummary: vi.fn(), onText
});
transcript.event('session.text.started', { sessionID: 'ses', assistantMessageID: 'msg1', ordinal: 0 });
transcript.event('session.text.delta', { sessionID: 'ses', assistantMessageID: 'msg1', ordinal: 0, delta: 'hello ' });
transcript.event('session.text.delta', { sessionID: 'ses', assistantMessageID: 'msg1', ordinal: 0, delta: 'world' });
transcript.event('session.step.ended', { sessionID: 'ses', assistantMessageID: 'msg1' });
expect(onText).toHaveBeenCalledWith(expect.objectContaining({
id: 'v2:msg1:0', messageId: 'msg1', role: 'assistant', type: 'text',
text: 'hello world', complete: true
}));
transcript.close();
});
it('ignores text events from another session', () => {
const onText = vi.fn();
const transcript = new OpencodeNativeTranscript({
baseUrl: 'http://127.0.0.1:1', sessionId: 'ses', directory: '/project', mode: 'v2',
fetchImpl: vi.fn(async () => Response.json([])), onSummary: vi.fn(), onText
});
transcript.event('session.text.delta', { sessionID: 'foreign', assistantMessageID: 'm', ordinal: 0, delta: 'nope' });
expect(onText).not.toHaveBeenCalled();
transcript.close();
});
});
describe('v2 durable application start', () => {
it('keeps the start identity across fast completion and running snapshot replay without observing preparation usage', async () => {
const onStart = vi.fn(), onSummary = vi.fn();
@@ -1,4 +1,4 @@
import { isObject } from '@hapi/protocol';
import { asString, isObject } from '@hapi/protocol';
import type { FetchLike } from './opencodeCompactBridge';
import { logger } from '@/ui/logger';
import { OpencodeCompactionProjector, type OpencodeNativeText, type OpencodeCompactionTrigger } from './opencodeCompactionProjector';
@@ -20,6 +20,8 @@ export class OpencodeNativeTranscript {
private readonly unbasedDeltas = new Map<string, string>();
private readonly pendingText = new Map<string, OpencodeNativeText>();
private readonly textTimers = new Map<string, ReturnType<typeof setTimeout>>();
/** v2.2+ replaced `message.part.updated` with `session.text.*` events. */
private readonly v2Text = new Map<string, { text: string }>();
constructor(private readonly options: {
baseUrl: string;
@@ -84,6 +86,37 @@ export class OpencodeNativeTranscript {
this.unbasedDeltas.set(properties.partID, (this.unbasedDeltas.get(properties.partID) ?? '') + properties.delta);
}
}
// OpenCode 2.2.x no longer emits `message.updated`/`message.part.updated`
// for assistant turns. Text arrives as `session.text.started` +
// `session.text.delta`, and a step closes with `session.step.ended`.
// ACP owns the text of a foreground prompt; these events are what
// remains visible for the /goal loop's background turns.
if (this.options.mode === 'v2' && isObject(properties)
&& properties.sessionID === this.options.sessionId) {
const messageID = asString(properties.assistantMessageID);
const ordinal = asString(properties.ordinal) ?? '0';
const key = messageID ? `${messageID}:${ordinal}` : null;
if (key && type === 'session.text.started') {
this.v2Text.set(key, { text: '' });
} else if (key && type === 'session.text.delta' && typeof properties.delta === 'string') {
const entry = this.v2Text.get(key) ?? { text: '' };
entry.text += properties.delta;
this.v2Text.set(key, entry);
this.emitText({
id: `v2:${key}`, messageId: messageID!, role: 'assistant',
type: 'text', text: entry.text, complete: false
});
} else if (messageID && type === 'session.step.ended') {
for (const [openKey, entry] of this.v2Text) {
if (!openKey.startsWith(`${messageID}:`)) continue;
this.emitText({
id: `v2:${openKey}`, messageId: messageID, role: 'assistant',
type: 'text', text: entry.text, complete: true
});
this.v2Text.delete(openKey);
}
}
}
if (type === 'session.status' && isObject(properties.status) && properties.status.type === 'idle') void this.refresh();
if (type.startsWith('session.compaction.')) void this.refresh();
}
@@ -127,6 +127,20 @@ describe('resolveOpencodeSlashCommand', () => {
expect(resolveOpencodeSlashCommand('/compact', state)).toEqual({ kind: 'compact' });
});
it('forwards /goal verbatim so OpenCode parses the objective itself', () => {
expect(resolveOpencodeSlashCommand('/goal ship the login fix', state)).toEqual({
kind: 'goal',
text: '/goal ship the login fix'
});
});
it.each(['pause', 'resume', 'clear'])('forwards /goal %s verbatim', (control) => {
expect(resolveOpencodeSlashCommand(`/goal ${control}`, state)).toEqual({
kind: 'goal',
text: `/goal ${control}`
});
});
it('resolves /compact the same way regardless of trailing arguments (compaction takes no arguments)', () => {
expect(resolveOpencodeSlashCommand('/compact now please', state)).toEqual({ kind: 'compact' });
});
@@ -165,6 +179,7 @@ describe('resolveOpencodeSlashCommand', () => {
expect(help.message).toContain('/plan');
expect(help.message).toContain('/permissions');
expect(help.message).toContain('/compact` — compact (summarize) the OpenCode session context (remote sessions only)');
expect(help.message).toContain('/goal <objective>` — keep working until a reviewer confirms the objective is met (OpenCode v2.2.1+)');
expect(help.message).toContain('/clear` — archive this HAPI session and open a fresh OpenCode session');
}
});
+12
View File
@@ -27,6 +27,12 @@ export type OpencodeSlashResolution =
// /clear exits the current runner-backed HAPI process after its FIFO
// predecessors finish, then asks the hub to spawn a fresh OpenCode one.
| { kind: 'clear' }
// /goal is OpenCode's native persistent-objective command (core plugin,
// v2.2.1+). The launcher must forward the raw slash text over ACP so
// OpenCode parses the command itself; HAPI must not prepend its own
// instructions or switch to the native REST prompt path (neither leaves
// a leading "/" for OpenCode's ACP command detector).
| { kind: 'goal'; text: string }
| {
kind: 'handled';
message: string;
@@ -176,6 +182,10 @@ export function resolveOpencodeSlashCommand(
return { kind: 'compact' };
}
if (command === 'goal') {
return { kind: 'goal', text };
}
if (command === 'clear') {
return { kind: 'clear' };
}
@@ -204,6 +214,8 @@ export function resolveOpencodeSlashCommand(
'- `/default` — return to default permission mode',
'- `/init [extra]` — generate or refresh AGENTS.md for this project',
'- `/compact` — compact (summarize) the OpenCode session context (remote sessions only)',
'- `/goal <objective>` — keep working until a reviewer confirms the objective is met (OpenCode v2.2.1+)',
'- `/goal pause|resume|clear` — control the active goal',
'- `/clear` — archive this HAPI session and open a fresh OpenCode session',
'',
'Model, reasoning effort, and permission mode have dedicated buttons in the composer. ' +