Skip to content

Commit 0e2841d

Browse files
authored
feat(opencode): mirror native goals across clients (#33758)
OpenCode native goals were missing from the shared goal projection and turn lifecycle. Synchronize goal state and continuation executions, gate dispatch on supported connected versions, and preserve older-version commands and provider-switch context. Handle reconnect freshness, pending steers, delayed control replies, and unreadable goal updates without losing tracked work. Reuse the existing goal UI across clients. Verified with check:changed, 264 affected tests, focused Codex/Claude goal tests, and CI. Live provider and manual client verification were not performed. Created with GPT-6.1 Sol through the Codex harness.
1 parent 8ee7183 commit 0e2841d

11 files changed

Lines changed: 945 additions & 58 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts‎

Lines changed: 555 additions & 11 deletions
Large diffs are not rendered by default.

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,12 @@ const operationOf = (
5454
query: Record<string, unknown>,
5555
body: unknown,
5656
) => {
57+
const rpc = /^\/api\/rpc\/([^/]+)\/([^/]+)$/.exec(path);
58+
if (method === "POST" && rpc !== null)
59+
return {
60+
type: "rpc.call",
61+
input: { rpcID: rpc[1], method: rpc[2], ...query, ...(body as object) },
62+
};
5763
const session = /^\/api\/session\/([^/]+)(\/.*)?$/.exec(path);
5864
if (method === "GET" && path === "/api/event") return { type: "event.subscribe" };
5965
if (method === "GET" && path === "/api/model") return { type: "model.list", input: query };
@@ -292,6 +298,7 @@ export const openCode2ReplayRuntime = (
292298
entries: ReadonlyArray<ProviderReplayEntry>,
293299
options?: {
294300
readonly external?: boolean;
301+
readonly version?: string;
295302
readonly onPrompt?: (input: unknown) => void;
296303
readonly borrowers?: { current: number };
297304
readonly replayGate?: ProviderReplayGate;
@@ -306,7 +313,7 @@ export const openCode2ReplayRuntime = (
306313
{
307314
provider: OPENCODE_PROVIDER,
308315
protocol: OPENCODE2_HTTP_PROTOCOL,
309-
version: "2.0.18",
316+
version: options?.version ?? "2.0.18",
310317
scenario: "opencode2_adapter",
311318
entries,
312319
},

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1168,9 +1168,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11681168
command: OrchestrationV2ServerCommand,
11691169
providerInstanceId: ProviderInstanceId,
11701170
) {
1171-
const { driver } = yield* providerAdapters
1172-
.get(providerInstanceId)
1173-
.pipe(mapDispatchError(command));
1171+
const adapter = yield* providerAdapters.get(providerInstanceId).pipe(mapDispatchError(command));
1172+
const { driver } = adapter;
1173+
if (driver === "opencode") {
1174+
const capabilities = yield* adapter.getCapabilities().pipe(mapDispatchError(command));
1175+
return capabilities.turns.supportsNativeGoals === true ? driver : undefined;
1176+
}
11741177
return driver === "codex" || driver === "claudeAgent" ? driver : undefined;
11751178
});
11761179

@@ -6107,7 +6110,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
61076110
) {
61086111
dispatchMode = { type: "queue_after_active" };
61096112
}
6110-
// Codex and Claude own /goal; elsewhere it is ordinary text that cannot steer.
6113+
// Native goal commands must not steer an existing turn.
61116114
const parsedGoalCommand = parseGoalCommand(command);
61126115
const goalCommand =
61136116
parsedGoalCommand === null ||

‎apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@ it.each([
269269

270270
function makeLocalCommandHarness(input: {
271271
readonly text: string;
272+
readonly nativeGoals?: boolean;
272273
readonly worktreePath?: string;
273274
readonly worktreesDir?: string;
274275
readonly workspaceRoot?: string;
@@ -337,7 +338,7 @@ function makeLocalCommandHarness(input: {
337338
};
338339
const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = {
339340
id: providerThreadId,
340-
driver: ProviderDriverKind.make("codex"),
341+
driver: ProviderDriverKind.make(input.nativeGoals === undefined ? "codex" : "opencode"),
341342
providerInstanceId: newInstanceId,
342343
providerSessionId,
343344
appThreadId: threadId,
@@ -778,7 +779,13 @@ function makeLocalCommandHarness(input: {
778779
status: "ready",
779780
cwd: "/tmp/native-account-command",
780781
model: null,
781-
capabilities: CodexProviderCapabilitiesV2,
782+
capabilities: {
783+
...CodexProviderCapabilitiesV2,
784+
turns: {
785+
...CodexProviderCapabilitiesV2.turns,
786+
...(input.nativeGoals === undefined ? {} : { supportsNativeGoals: input.nativeGoals }),
787+
},
788+
},
782789
createdAt: now,
783790
updatedAt: now,
784791
lastError: null,
@@ -1338,6 +1345,23 @@ effectIt.effect.each([
13381345
}),
13391346
);
13401347

1348+
effectIt.effect.each([false, true])(
1349+
"OpenCode goal prompts defer switched-provider history only with native support: %s",
1350+
(nativeGoals) =>
1351+
Effect.gen(function* () {
1352+
const harness = makeLocalCommandHarness({
1353+
text: "/goal all tests pass",
1354+
nativeGoals,
1355+
sideChat: { contextRun: "failed", switchedProvider: true },
1356+
});
1357+
harness.tryHandlePromptCommand.mockReturnValue(Effect.succeed(false));
1358+
yield* harness.start;
1359+
expect(harness.startTurn.mock.calls[0]?.[0].message.text.includes("SIDE_CHAT_CONTEXT")).toBe(
1360+
!nativeGoals,
1361+
);
1362+
}),
1363+
);
1364+
13411365
effectIt.effect.each([
13421366
{ runStatus: "failed", turnStatus: "completed" },
13431367
{ runStatus: "completed", turnStatus: "completed" },

‎apps/server/src/orchestration-v2/ProviderTurnStartService.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -841,8 +841,12 @@ export const layer: Layer.Layer<
841841
text: message.text,
842842
records: message.context?.records ?? [],
843843
});
844-
// Codex and Claude parse /goal from the prompt, so it goes verbatim and history waits a turn.
845-
const goalDriver = session.driver === "codex" || session.driver === "claudeAgent";
844+
// Native goal commands go verbatim; handoff history waits a turn.
845+
const goalDriver =
846+
session.driver === "codex" ||
847+
session.driver === "claudeAgent" ||
848+
(session.driver === "opencode" &&
849+
session.providerSession.capabilities.turns.supportsNativeGoals === true);
846850
const goalCommand = goalDriver && parseGoalCommand(message) !== null;
847851
// The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively.
848852
const noteContinuation = isRestartNoteContinuation(

‎apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts‎

Lines changed: 39 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,9 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
488488
canSteer = true,
489489
interruptTurn: Effect.Effect<void> = Effect.void,
490490
steeringAcceptsAttachments = true,
491+
nativeGoals?: boolean,
491492
) {
493+
const driver = ProviderDriverKind.make(nativeGoals === undefined ? "codex" : "opencode");
492494
const cwd = yield* checkpointWorkspace(name);
493495
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
494496
const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
@@ -501,6 +503,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
501503
supportsActiveSteering: canSteer,
502504
supportsSteeringByInterruptRestart: canRestart,
503505
activeSteeringAcceptsAttachments: steeringAcceptsAttachments,
506+
...(nativeGoals === undefined ? {} : { supportsNativeGoals: nativeGoals }),
504507
},
505508
};
506509
const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
@@ -2060,8 +2063,15 @@ it.effect("queues a plain send behind the stopped queue and releases its hold",
20602063
),
20612064
);
20622065

2063-
const goalHarness = Effect.fn("goalHarness")(function* (name: string) {
2064-
const harness = yield* nextTurnSelectionHarness(name);
2066+
const goalHarness = Effect.fn("goalHarness")(function* (name: string, nativeGoals?: boolean) {
2067+
const harness = yield* nextTurnSelectionHarness(
2068+
name,
2069+
false,
2070+
true,
2071+
Effect.void,
2072+
true,
2073+
nativeGoals,
2074+
);
20652075
const send = (id: string, text: string, delivery: "queue" | "auto", freshContext = false) =>
20662076
Effect.gen(function* () {
20672077
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2101,26 +2111,34 @@ const goalHarness = Effect.fn("goalHarness")(function* (name: string) {
21012111
return { ...harness, send, read };
21022112
});
21032113

2104-
it.effect("stops the running turn and starts a goal sent into it next", () =>
2105-
Effect.scoped(
2106-
Effect.gen(function* () {
2107-
const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-steer");
2108-
yield* Effect.gen(function* () {
2109-
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2110-
const threadId = yield* startFirstTurn;
2111-
yield* send("queued", "queued", "queue");
2112-
yield* send("goal", "/goal all tests pass", "auto");
2113-
yield* worker.drain();
2114+
it.effect.each([undefined, false, true])(
2115+
"goal dispatch stops the active turn only with native support: %s",
2116+
(nativeGoals) =>
2117+
Effect.scoped(
2118+
Effect.gen(function* () {
2119+
const { steered, layer, startFirstTurn, send, read } = yield* goalHarness(
2120+
"goal-steer",
2121+
nativeGoals,
2122+
);
2123+
yield* Effect.gen(function* () {
2124+
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2125+
const threadId = yield* startFirstTurn;
2126+
yield* send("queued", "queued", "queue");
2127+
const sending = send("goal", "/goal all tests pass", "auto");
2128+
if (nativeGoals === false) {
2129+
yield* Effect.flip(sending);
2130+
} else yield* sending;
2131+
yield* worker.drain();
21142132

2115-
assert.deepEqual(steered, []);
2116-
assert.deepEqual(yield* read(threadId), {
2117-
queue: ["queued"],
2118-
started: ["first", "/goal all tests pass"],
2119-
stopRequested: true,
2120-
});
2121-
}).pipe(Effect.provide(layer));
2122-
}),
2123-
),
2133+
assert.deepEqual(steered, []);
2134+
assert.deepEqual(yield* read(threadId), {
2135+
queue: ["queued"],
2136+
started: nativeGoals === false ? ["first"] : ["first", "/goal all tests pass"],
2137+
stopRequested: nativeGoals !== false,
2138+
});
2139+
}).pipe(Effect.provide(layer));
2140+
}),
2141+
),
21242142
);
21252143

21262144
it.effect("starts a goal that names no model on the thread's model ahead of a queued pick", () =>

‎docs/user/composer.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -304,15 +304,15 @@ Claude instances can also compact idle threads for you. See
304304

305305
## Goals
306306

307-
With Codex and Claude, send `/goal` followed by what "done" means, for example
307+
With Codex, Claude, and OpenCode 2.2.5 or later, send `/goal` followed by what "done" means, for example
308308
`/goal all tests in packages/api pass`. The agent keeps working across turns
309309
until it judges the goal met. The thread shows **Goal** while it works, and a
310310
line at the end of the thread (above the composer on mobile) shows the goal and
311311
its progress.
312312

313313
- `/goal` alone shows the current goal. `/goal clear` removes it.
314-
- Codex also supports `/goal pause` and `/goal resume`. Stopping a Codex goal
315-
pauses it, and so does Codex ending its work without meeting the goal.
314+
- Codex and OpenCode also support `/goal pause` and `/goal resume`. Stopping
315+
their goal pauses it. Codex also pauses when its work ends without meeting the goal.
316316
- Stopping Claude ends the current turn, but the goal stays set. Claude checks it
317317
again at the end of your next message.
318318
- Sending a new goal, or `/goal resume`, while the agent works stops the current

‎packages/contracts/src/orchestrationV2.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,7 @@ export const OrchestrationV2ThreadCapabilities = Schema.Struct({
278278
export type OrchestrationV2ThreadCapabilities = typeof OrchestrationV2ThreadCapabilities.Type;
279279

280280
export const OrchestrationV2TurnCapabilities = Schema.Struct({
281+
supportsNativeGoals: Schema.optional(Schema.Boolean),
281282
exposesNativeTurnId: Schema.Boolean,
282283
emitsTurnStarted: Schema.Boolean,
283284
emitsTurnCompleted: Schema.Boolean,

‎packages/provider-opencode/src/server/driver.test.ts‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,117 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
222222
}).pipe(Effect.scoped),
223223
);
224224

225+
it.effect.each([
226+
"1.18.32",
227+
"opencode v2.0.18",
228+
"opencode v2.2.4",
229+
"opencode v2.2.5",
230+
"opencode v2.2.6",
231+
])("advertises native goal support only for supported OpenCode versions: %s", (version) =>
232+
Effect.gen(function* () {
233+
const fs = yield* FileSystem.FileSystem;
234+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-goal-capability-" });
235+
const binaryPath = NodePath.join(
236+
root,
237+
"lib",
238+
"node_modules",
239+
"@opencode",
240+
"cli",
241+
"bin",
242+
"opencode",
243+
);
244+
yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
245+
yield* fs.writeFileString(binaryPath, "");
246+
const instance = yield* create({ binaryPath }, noHttp).pipe(
247+
Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, {
248+
...openCode2Runtime,
249+
runOpenCodeCommand: () => Effect.succeed({ stdout: version, stderr: "", code: 0 }),
250+
}),
251+
);
252+
yield* instance.snapshot.resolveMaintenance({ fresh: true });
253+
const capabilities = yield* instance.orchestrationAdapter.getCapabilities();
254+
assert.equal(
255+
capabilities.turns.supportsNativeGoals === true,
256+
version.endsWith("2.2.5") || version.endsWith("2.2.6"),
257+
);
258+
}).pipe(Effect.scoped),
259+
);
260+
261+
it.effect("uses the connected OpenCode version for goal support after an upgrade", () =>
262+
Effect.gen(function* () {
263+
const fs = yield* FileSystem.FileSystem;
264+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-upgraded-goals-" });
265+
const binaryPath = NodePath.join(
266+
root,
267+
"lib",
268+
"node_modules",
269+
"@opencode",
270+
"cli",
271+
"bin",
272+
"opencode",
273+
);
274+
yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
275+
yield* fs.writeFileString(binaryPath, "");
276+
const http = HttpClient.make((request) => {
277+
const path = new URL(request.url).pathname;
278+
if (path === "/api/info")
279+
return Effect.succeed(
280+
HttpClientResponse.fromWeb(
281+
request,
282+
Response.json({
283+
...JSON.parse(OPENCODE_2_RESPONSES["/api/info"].body),
284+
version: "2.2.5",
285+
}),
286+
),
287+
);
288+
if (path === "/api/model")
289+
return Effect.succeed(
290+
HttpClientResponse.fromWeb(
291+
request,
292+
Response.json({ location: { directory: "/work" }, data: [] }),
293+
),
294+
);
295+
if (path === "/api/event")
296+
return Effect.succeed(
297+
HttpClientResponse.fromWeb(
298+
request,
299+
new Response(new ReadableStream(), {
300+
headers: { "content-type": "text/event-stream" },
301+
}),
302+
),
303+
);
304+
return Effect.die(`Unexpected request: ${path}`);
305+
});
306+
const instance = yield* create({ binaryPath }, http).pipe(
307+
Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, {
308+
...openCode2Runtime,
309+
runOpenCodeCommand: () =>
310+
Effect.succeed({ stdout: "opencode v2.2.4", stderr: "", code: 0 }),
311+
startOpenCodeServerProcess: ({ verify }) =>
312+
Effect.gen(function* () {
313+
const url = "http://127.0.0.1:4096";
314+
const version = verify ? yield* verify(url) : "2.2.5";
315+
return { url, version, isRunning: Effect.succeed(true), exitCode: Effect.never };
316+
}),
317+
}),
318+
);
319+
yield* instance.snapshot.resolveMaintenance({ fresh: true });
320+
assert.isFalse(
321+
(yield* instance.orchestrationAdapter.getCapabilities()).turns.supportsNativeGoals,
322+
);
323+
const session = yield* instance.orchestrationAdapter.openSession({
324+
threadId: ThreadId.make("upgraded-goal"),
325+
providerSessionId: ProviderSessionId.make("upgraded-goal"),
326+
modelSelection: { instanceId: instance.instanceId, model: "opencode/big-pickle" },
327+
runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: null },
328+
});
329+
assert.isTrue(session.providerSession.capabilities.turns.supportsNativeGoals);
330+
assert.isTrue(
331+
(yield* instance.orchestrationAdapter.getCapabilities()).turns.supportsNativeGoals,
332+
);
333+
}).pipe(Effect.scoped),
334+
);
335+
225336
it.effect("answers capability reads without waiting on an unreachable server", () =>
226337
Effect.gen(function* () {
227338
const hang = HttpClient.make(() => Effect.never);

‎packages/provider-opencode/src/server/driver.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderL
1818
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
1919
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
2020
import * as HostProcess from "@t3tools/shared/HostProcess";
21+
import { compareSemverVersions } from "@t3tools/shared/semver";
2122
import * as OpenCodeAdapterV2 from "./adapter.ts";
2223
import * as OpenCode2AdapterV2 from "./v2/adapter.ts";
2324
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -120,7 +121,20 @@ function selectOpenCodeRuntimeAdapter(input: {
120121
return {
121122
instanceId: input.v1.instanceId,
122123
driver: DRIVER_KIND,
123-
getCapabilities: () => Effect.flatMap(hot, (adapter) => adapter.getCapabilities()),
124+
getCapabilities: Effect.fn("OpenCodeDriver.getCapabilities")(function* () {
125+
const probed = Option.getOrUndefined(yield* input.probe.lastSuccess);
126+
const adapter = yield* pick(Effect.succeed(probed));
127+
const capabilities = yield* adapter.getCapabilities();
128+
return {
129+
...capabilities,
130+
turns: {
131+
...capabilities.turns,
132+
supportsNativeGoals:
133+
capabilities.turns.supportsNativeGoals ??
134+
(probed?.generation === "v2" && compareSemverVersions(probed.version, "2.2.5") >= 0),
135+
},
136+
};
137+
}),
124138
planSelectionTransition: (transition) =>
125139
Effect.flatMap(hot, (adapter) => adapter.planSelectionTransition(transition)),
126140
openSession: (session) =>

0 commit comments

Comments
 (0)