@devries-cameron20 / t3code-1 / commits / 0e2841d5a7
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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.

Yash Singh committed Nov 10, 2026 at 11:29 UTC 0e2841d5a778552343109274d2e658f545fec824
11 files changed +945 -58
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+555 -11
@@ -82,6 +82,7 @@ const event = (
82 id: `evt_${type.replaceAll(".", "")}0000`,
83 created: 1,
84 type,
85 + ...(type.startsWith("rpc.") ? { location: { directory: WORK } } : {}),
86 data,
87 durable: { ...durable.durable, version },
88 },
@@ -163,6 +164,7 @@ const withInstructions = (
164 "session.compact",
165 "command.list",
166 "skill.list",
167 + "rpc.call",
168 ].includes(String(entry.frame.type)),
169 );
170 const after = entries.findIndex(
@@ -315,6 +317,8 @@ const colorForm = {
317 const resumed = (
318 entries: ReadonlyArray<ProviderReplayEntry>,
319 options?: {
320 + readonly version?: "2.2.5";
321 + readonly goal?: OrchestrationV2ProviderThread["goal"];
322 readonly external?: boolean;
323 readonly supervised?: boolean;
324 readonly replayGate?: ProviderReplayGate;
@@ -326,22 +330,28 @@ const resumed = (
330 ) =>
331 Effect.gen(function* () {
332 const runtime = yield* openCode2ReplayRuntime(
329 - withInstructions([
333 + [
334 ...opening,
335 out("session.get", { sessionID: SESSION }),
336 replyData("session.get", sessionInfo()),
337 ...noOpenRequests,
334 - ...(options?.supervised === true
335 - ? [
336 - out("agent.list", "<any>"),
337 - reply("agent.list", agentList),
338 - out("session.update", { sessionID: SESSION, permissions: supervisedRules }),
339 - reply("session.update", null),
340 - ]
338 + ...(options?.version === "2.2.5"
339 + ? [out("rpc.call", "<any>"), reply("rpc.call", { output: null })]
340 : []),
342 - ...entries,
343 - ]),
341 + ...withInstructions([
342 + ...(options?.supervised === true
343 + ? [
344 + out("agent.list", "<any>"),
345 + reply("agent.list", agentList),
346 + out("session.update", { sessionID: SESSION, permissions: supervisedRules }),
347 + reply("session.update", null),
348 + ]
349 + : []),
350 + ...entries,
351 + ]),
352 + ],
353 {
354 + ...(options?.version === undefined ? {} : { version: options.version }),
355 ...(options?.fileSystem === undefined ? {} : { fileSystem: options.fileSystem }),
356 ...(options?.onPrompt === undefined ? {} : { onPrompt: options.onPrompt }),
357 ...(options?.external === undefined ? {} : { external: options.external }),
@@ -355,7 +365,10 @@ const resumed = (
365 },
366 );
367 const thread = yield* runtime.resumeThread({
358 - providerThread: providerThread(yield* DateTime.now),
368 + providerThread: {
369 + ...providerThread(yield* DateTime.now),
370 + ...(options?.goal === undefined ? {} : { goal: options.goal }),
371 + },
372 threadId,
373 modelSelection: bigPickle,
374 runtimePolicy: policy(options?.supervised === true ? "approval-required" : "full-access"),
@@ -422,6 +435,17 @@ const history = {
435 cursor: {},
436 };
437
438 +const nativeGoal = (status: "active" | "paused" | "complete") => ({
439 + id: "goal-1",
440 + objective: "Write proof.txt",
441 + status,
442 + rounds: 2,
443 + maxRounds: 100,
444 + boot: "boot-1",
445 + updatedAt: 1,
446 + reason: "Checked proof.txt",
447 +});
448 +
449 it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
450 it.effect("switches the session's model and variant before a turn that changed them", () =>
451 Effect.gen(function* () {
@@ -2297,6 +2321,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2321 active: Record<string, unknown>,
2322 ended?: "succeeded",
2323 assistant: Record<string, unknown> = {},
2324 + deliveredSteer?: string,
2325 ) => [
2326 { type: "runtime_exit", status: "success" } as const,
2327 out("event.subscribe"),
@@ -2333,6 +2358,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2358 finish: "stop",
2359 ...assistant,
2360 },
2361 + ...(deliveredSteer === undefined
2362 + ? []
2363 + : [{ id: deliveredSteer, time: { created: 2 }, text: "steered", type: "user" }]),
2364 {
2365 id: "msg_0eb735d41001NJee1EvVePJAK5",
2366 time: { created: 1 },
@@ -2358,6 +2386,90 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2386 event.type === "turn_item.updated" ? [`${event.turnItem.type}:${event.turnItem.status}`] : [],
2387 );
2388
2389 + it.effect.each(["delivered", "pending"] as const)(
2390 + "reconciles a %s steer after reconnect without losing its execution",
2391 + (delivery) =>
2392 + Effect.gen(function* () {
2393 + const steerId = `msg_t3_steer_${SESSION}:message:opencode2-adapter:steer`;
2394 + const reconnect = reconnected(
2395 + {},
2396 + "succeeded",
2397 + {},
2398 + delivery === "delivered" ? steerId : undefined,
2399 + );
2400 + const { runtime, thread } = yield* resumed(
2401 + [
2402 + out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
2403 + promptAccepted,
2404 + ...(delivery === "pending"
2405 + ? [
2406 + event("rpc.opencode.goal.changed", {
2407 + sessionID: SESSION,
2408 + goal: nativeGoal("active"),
2409 + }),
2410 + ]
2411 + : []),
2412 + out("session.prompt", "<any>"),
2413 + replyData("session.prompt", {
2414 + id: steerId,
2415 + sessionID: SESSION,
2416 + time: { created: 2 },
2417 + type: "user",
2418 + payload: { text: "steered" },
2419 + delivery: "steer",
2420 + }),
2421 + ...reconnect.slice(0, 2),
2422 + ...(delivery === "pending"
2423 + ? [out("rpc.call", "<any>"), reply("rpc.call", { output: { unreadable: true } })]
2424 + : []),
2425 + ...reconnect.slice(2),
2426 + ...(delivery === "pending"
2427 + ? [
2428 + event("session.execution.started", { sessionID: SESSION }),
2429 + event("session.inbox.delivered", { sessionID: SESSION, inboxID: steerId }),
2430 + event("session.text.ended", {
2431 + sessionID: SESSION,
2432 + assistantMessageID: "msg_delayed_steer",
2433 + ordinal: 0,
2434 + text: "Steer processed",
2435 + }),
2436 + event("session.execution.succeeded", { sessionID: SESSION }),
2437 + ]
2438 + : [event("session.execution.interrupted", { sessionID: SESSION, reason: "user" })]),
2439 + ],
2440 + delivery === "pending" ? { version: "2.2.5" } : undefined,
2441 + );
2442 + const events = yield* runtime.events.pipe(
2443 + Stream.takeUntil((e) => e.type === "turn.terminal"),
2444 + Stream.runCollect,
2445 + Effect.forkScoped,
2446 + );
2447 + yield* runtime.startTurn(turnInput(thread));
2448 + yield* runtime.steerTurn({
2449 + providerThread: thread,
2450 + providerTurnId: yield* providerTurnId,
2451 + threadId,
2452 + runId: turnInput(thread).runId,
2453 + message: {
2454 + ...turnInput(thread).message,
2455 + messageId: MessageId.make("message:opencode2-adapter:steer"),
2456 + text: "steered",
2457 + },
2458 + });
2459 + const collected = yield* Fiber.join(events);
2460 + assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
2461 + if (delivery === "pending")
2462 + assert.isTrue(
2463 + collected.some(
2464 + (e) =>
2465 + e.type === "turn_item.updated" &&
2466 + e.turnItem.type === "assistant_message" &&
2467 + e.turnItem.text === "Steer processed",
2468 + ),
2469 + );
2470 + }).pipe(Effect.scoped),
2471 + );
2472 +
2473 it.effect("does not end a turn from an earlier turn's history when its prompt is not there", () =>
2474 Effect.gen(function* () {
2475 const { runtime, thread } = yield* resumed([
@@ -5139,6 +5251,438 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5251 assert.lengthOf(offers, 1);
5252 }).pipe(Effect.scoped, Effect.provide(IdAllocator.layer)),
5253 );
5254 + it.effect.each(["", "pause", "clear", "resume", "Write proof.txt"])(
5255 + "preserves older OpenCode goal command execution for /goal %s",
5256 + (control) =>
5257 + Effect.gen(function* () {
5258 + const { runtime, thread } = yield* resumed(
5259 + [
5260 + out("command.list", "<any>"),
5261 + reply("command.list", { location: { directory: WORK }, data: [{ name: "goal" }] }),
5262 + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }),
5263 + reply("message.list", { data: [], cursor: {} }),
5264 + out("session.command", { sessionID: SESSION, name: "goal", text: control }),
5265 + reply("session.command", null),
5266 + event("session.text.ended", {
5267 + sessionID: SESSION,
5268 + assistantMessageID: "msg_legacy_goal",
5269 + ordinal: 0,
5270 + text: "Legacy command finished",
5271 + }),
5272 + event("session.execution.succeeded", { sessionID: SESSION }),
5273 + ],
5274 + { goal: { objective: "Saved before downgrade", status: "active" } },
5275 + );
5276 + assert.isFalse(runtime.providerSession.capabilities.turns.supportsNativeGoals);
5277 + const events = yield* runtime.events.pipe(
5278 + Stream.takeUntil((e) => e.type === "turn.terminal"),
5279 + Stream.runCollect,
5280 + Effect.forkScoped,
5281 + );
5282 + const input = turnInput(thread);
5283 + yield* runtime.startTurn({
5284 + ...input,
5285 + message: { ...input.message, text: `/goal ${control}`.trim() },
5286 + });
5287 + const collected = yield* Fiber.join(events);
5288 + assert.isTrue(
5289 + collected.some(
5290 + (e) =>
5291 + e.type === "turn_item.updated" &&
5292 + e.turnItem.type === "assistant_message" &&
5293 + e.turnItem.text === "Legacy command finished",
5294 + ),
5295 + );
5296 + assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
5297 + }).pipe(Effect.scoped),
5298 + );
5299 +
5300 + it.effect("reads an existing OpenCode 2.2.5 goal when resuming a session", () =>
5301 + Effect.gen(function* () {
5302 + const runtime = yield* openCode2ReplayRuntime(
5303 + [
5304 + ...opening,
5305 + out("session.get", { sessionID: SESSION }),
5306 + replyData("session.get", sessionInfo()),
5307 + ...noOpenRequests,
5308 + out("rpc.call", {
5309 + rpcID: "opencode.goal",
5310 + method: "get",
5311 + "location[directory]": WORK,
5312 + input: { sessionID: SESSION },
5313 + }),
5314 + reply("rpc.call", { output: nativeGoal("paused") }),
5315 + ],
5316 + { version: "2.2.5" },
5317 + );
5318 + assert.isTrue(runtime.providerSession.capabilities.turns.supportsNativeGoals);
5319 + const thread = yield* runtime.resumeThread({
5320 + providerThread: providerThread(yield* DateTime.now),
5321 + threadId,
5322 + modelSelection: bigPickle,
5323 + runtimePolicy: policy(),
5324 + });
5325 + assert.deepEqual(thread.goal, {
5326 + objective: "Write proof.txt",
5327 + status: "paused",
5328 + checks: 2,
5329 + lastCheck: "Checked proof.txt",
5330 + });
5331 + }).pipe(Effect.scoped),
5332 + );
5333 +
5334 + it.effect.each([
5335 + { status: "complete", reconnect: false },
5336 + { status: "paused", reconnect: false },
5337 + { status: "complete", reconnect: true },
5338 + ] as const)(
5339 + "keeps an OpenCode goal turn open until $status, with reconnect $reconnect",
5340 + ({ status, reconnect }) =>
5341 + Effect.gen(function* () {
5342 + const recovered = reconnected({ [SESSION]: { type: "running" } });
5343 + const { runtime, thread } = yield* resumed(
5344 + [
5345 + out("command.list", "<any>"),
5346 + reply("command.list", { location: { directory: WORK }, data: [{ name: "goal" }] }),
5347 + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }),
5348 + reply("message.list", { data: [], cursor: {} }),
5349 + out("session.command", { sessionID: SESSION, name: "goal", text: "Write proof.txt" }),
5350 + reply("session.command", null),
5351 + event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal("active") }),
5352 + event("session.execution.succeeded", { sessionID: SESSION }),
5353 + ...(status === "complete"
5354 + ? reconnect
5355 + ? [
5356 + ...recovered.slice(0, 2),
5357 + out("rpc.call", "<any>"),
5358 + reply("rpc.call", { output: nativeGoal("active") }),
5359 + ...recovered.slice(2),
5360 + ...noOpenRequests,
5361 + ]
5362 + : [event("session.execution.started", { sessionID: SESSION })]
5363 + : []),
5364 + event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal(status) }),
5365 + ...(status === "complete"
5366 + ? [
5367 + event("session.text.ended", {
5368 + sessionID: SESSION,
5369 + assistantMessageID: "msg_goal_final",
5370 + ordinal: 0,
5371 + text: "Final goal output",
5372 + }),
5373 + event("session.execution.succeeded", { sessionID: SESSION }),
5374 + ]
5375 + : []),
5376 + ],
5377 + { version: "2.2.5" },
5378 + );
5379 + const events = yield* runtime.events.pipe(
5380 + Stream.takeUntil((e) => e.type === "turn.terminal"),
5381 + Stream.runCollect,
5382 + Effect.forkScoped,
5383 + );
5384 + const input = turnInput(thread);
5385 + yield* runtime.startTurn({
5386 + ...input,
5387 + message: { ...input.message, text: "/goal Write proof.txt" },
5388 + });
5389 + const collected = yield* Fiber.join(events);
5390 + const goals = collected.flatMap((e) =>
5391 + e.type === "provider_thread.updated" && e.providerThread.goal
5392 + ? [e.providerThread.goal]
5393 + : [],
5394 + );
5395 + assert.includeDeepMembers(goals, [
5396 + {
5397 + objective: "Write proof.txt",
5398 + status: "active",
5399 + checks: 2,
5400 + lastCheck: "Checked proof.txt",
5401 + },
5402 + {
5403 + objective: "Write proof.txt",
5404 + status,
5405 + checks: 2,
5406 + lastCheck: "Checked proof.txt",
5407 + },
5408 + ]);
5409 + if (status === "complete")
5410 + assert.isTrue(
5411 + collected.some(
5412 + (e) =>
5413 + e.type === "turn_item.updated" &&
5414 + e.turnItem.type === "assistant_message" &&
5415 + e.turnItem.text === "Final goal output",
5416 + ),
5417 + );
5418 + assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
5419 + }).pipe(Effect.scoped),
5420 + );
5421 +
5422 + it.effect("does not replace a newer goal event with an older goal RPC response", () =>
5423 + Effect.gen(function* () {
5424 + const gate = makeProviderReplayGate(["release-goal-read"]);
5425 + const { runtime, thread } = yield* resumed(
5426 + [
5427 + out("rpc.call", "<any>"),
5428 + event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal("paused") }),
5429 + event(
5430 + "rpc.opencode.goal.changed",
5431 + { sessionID: SESSION, goal: nativeGoal("paused") },
5432 + "release-goal-read",
5433 + ),
5434 + reply("rpc.call", { output: nativeGoal("active") }),
5435 + ],
5436 + { version: "2.2.5", replayGate: gate },
5437 + );
5438 + const changed = yield* Deferred.make<void>();
5439 + const events = yield* runtime.events.pipe(
5440 + Stream.tap((e) =>
5441 + e.type === "provider_thread.updated" && e.providerThread.goal?.status === "paused"
5442 + ? Deferred.succeed(changed, undefined)
5443 + : Effect.void,
5444 + ),
5445 + Stream.takeUntil((e) => e.type === "turn.terminal"),
5446 + Stream.runCollect,
5447 + Effect.forkScoped,
5448 + );
5449 + const input = turnInput(thread);
5450 + const starting = yield* runtime
5451 + .startTurn({ ...input, message: { ...input.message, text: "/goal" } })
5452 + .pipe(Effect.forkScoped);
5453 + yield* Deferred.await(changed);
5454 + gate.release("release-goal-read");
5455 + yield* Fiber.join(starting);
5456 + const collected = yield* Fiber.join(events);
5457 + const updated = collected.findLast((e) => e.type === "provider_thread.updated");
5458 + assert.equal(
5459 + updated?.type === "provider_thread.updated"
5460 + ? updated.providerThread.goal?.status
5461 + : undefined,
5462 + "paused",
5463 + );
5464 + }).pipe(Effect.scoped),
5465 + );
5466 +
5467 + it.effect.each(["unreadable", "stalled"] as const)(
5468 + "settles a completed execution after reconnect when goal refresh is %s",
5469 + (failure) =>
5470 + Effect.gen(function* () {
5471 + const gate = makeProviderReplayGate(["goal-refresh-stalled"]);
5472 + const reconnect = reconnected({}, "succeeded");
5473 + const { runtime, thread } = yield* resumed(
5474 + [
5475 + out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
5476 + promptAccepted,
5477 + event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal("active") }),
5478 + ...reconnect.slice(0, 2),
5479 + out("rpc.call", "<any>"),
5480 + reply("rpc.call", failure === "stalled" ? "<hang>" : { output: { unreadable: true } }),
5481 + ...(failure === "stalled"
5482 + ? [
5483 + event(
5484 + "rpc.opencode.goal.changed",
5485 + { sessionID: SESSION, goal: null },
5486 + "goal-refresh-stalled",
5487 + ),
5488 + ]
5489 + : []),
5490 + ...reconnect.slice(2),
5491 + ],
5492 + { version: "2.2.5", replayGate: gate },
5493 + );
5494 + const events = yield* runtime.events.pipe(
5495 + Stream.takeUntil((e) => e.type === "turn.terminal"),
5496 + Stream.runCollect,
5497 + Effect.forkScoped,
5498 + );
5499 + yield* runtime.startTurn(turnInput(thread));
5500 + if (failure === "stalled") {
5501 + yield* Effect.promise(() => gate.waitForReached("goal-refresh-stalled"));
5502 + gate.release("goal-refresh-stalled");
5503 + yield* TestClock.adjust("5 seconds");
5504 + }
5505 + const collected = yield* Fiber.join(events);
5506 + assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
5507 + }).pipe(Effect.scoped),
5508 + );
5509 +
5510 + it.effect.each([
5511 + { initial: "active", recovered: "paused" },
5512 + { initial: "paused", recovered: "active" },
5513 + { initial: "active", recovered: "unreadable" },
5514 + ] as const)(
5515 + "recovers unreadable native goal updates when cached goal is $initial and RPC returns $recovered",
5516 + ({ initial, recovered }) =>
5517 + Effect.gen(function* () {
5518 + const { runtime, thread } = yield* resumed(
5519 + [
5520 + out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),
5521 + promptAccepted,
5522 + event("rpc.opencode.goal.changed", { sessionID: SESSION, goal: nativeGoal(initial) }),
5523 + event("rpc.opencode.goal.changed", {
5524 + sessionID: SESSION,
5525 + goal: { ...nativeGoal(initial), status: "unknown" },
5526 + }),
5527 + event("session.execution.succeeded", { sessionID: SESSION }),
5528 + out("rpc.call", "<any>"),
5529 + reply("rpc.call", { output: recovered === "unreadable" ? {} : nativeGoal(recovered) }),
5530 + ...(recovered === "active"
5531 + ? [
5532 + event("session.execution.started", { sessionID: SESSION }),
5533 + event("session.text.ended", {
5534 + sessionID: SESSION,
5535 + assistantMessageID: "msg_recovered_goal",
5536 + ordinal: 0,
5537 + text: "Continued work",
5538 + }),
5539 + event("rpc.opencode.goal.changed", {
5540 + sessionID: SESSION,
5541 + goal: nativeGoal("complete"),
5542 + }),
5543 + event("session.execution.succeeded", { sessionID: SESSION }),
5544 + ]
5545 + : []),
5546 + ],
5547 + { version: "2.2.5" },
5548 + );
5549 + const events = yield* runtime.events.pipe(
5550 + Stream.takeUntil((e) => e.type === "turn.terminal"),
5551 + Stream.runCollect,
5552 + Effect.forkScoped,
5553 + );
5554 + yield* runtime.startTurn(turnInput(thread));
5555 + const collected = yield* Fiber.join(events);
5556 + const updated = collected.findLast((e) => e.type === "provider_thread.updated");
5557 + assert.equal(
5558 + updated?.type === "provider_thread.updated"
5559 + ? updated.providerThread.goal?.status
5560 + : undefined,
5561 + recovered === "active" ? "complete" : recovered === "paused" ? "paused" : "active",
5562 + );
5563 + if (recovered === "active")
5564 + assert.isTrue(
5565 + collected.some(
5566 + (e) =>
5567 + e.type === "turn_item.updated" &&
5568 + e.turnItem.type === "assistant_message" &&
5569 + e.turnItem.text === "Continued work",
5570 + ),
5571 + );
5572 + assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
5573 + }).pipe(Effect.scoped),
5574 + );
5575 +
5576 + it.effect.each(["show", "pause", "clear"] as const)(
5577 + "a delayed /goal %s response cannot finish its replacement turn",
5578 + (control) =>
5579 + Effect.gen(function* () {
5580 + const operation = control === "show" ? "rpc.call" : "session.command";
5581 + const { runtime, thread } = yield* resumed(
5582 + [
5583 + ...(control === "show"
5584 + ? []
5585 + : [
5586 + out("command.list", "<any>"),
5587 + reply("command.list", {
5588 + location: { directory: WORK },
5589 + data: [{ name: "goal" }],
5590 + }),
5591 + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }),
5592 + reply("message.list", { data: [], cursor: {} }),
5593 + ]),
5594 + out(operation, "<any>"),
5595 + event("session.execution.interrupted", { sessionID: SESSION, reason: "user" }),
5596 + out("session.prompt", "<any>"),
5597 + promptAccepted,
5598 + reply(operation, control === "show" ? { output: nativeGoal("paused") } : null),
5599 + event("session.text.ended", {
5600 + sessionID: SESSION,
5601 + assistantMessageID: "msg_replacement",
5602 + ordinal: 0,
5603 + text: "Replacement still tracked",
5604 + }),
5605 + event("session.execution.succeeded", { sessionID: SESSION }),
5606 + ],
5607 + { version: "2.2.5" },
5608 + );
5609 + const interrupted = yield* Deferred.make<void>();
5610 + const events = yield* runtime.events.pipe(
5611 + Stream.tap((e) =>
5612 + e.type === "turn.terminal" && e.status === "interrupted"
5613 + ? Deferred.succeed(interrupted, undefined)
5614 + : Effect.void,
5615 + ),
5616 + Stream.takeUntil((e) => e.type === "turn.terminal" && e.status === "completed"),
5617 + Stream.runCollect,
5618 + Effect.forkScoped,
5619 + );
5620 + const input = turnInput(thread);
5621 + const starting = yield* runtime
5622 + .startTurn({
5623 + ...input,
5624 + message: { ...input.message, text: control === "show" ? "/goal" : `/goal ${control}` },
5625 + })
5626 + .pipe(Effect.forkScoped);
5627 + yield* Deferred.await(interrupted);
5628 + yield* runtime.startTurn({
5629 + ...input,
5630 + attemptId: RunAttemptId.make("replacement"),
5631 + providerTurnOrdinal: 2,
5632 + });
5633 + yield* Fiber.join(starting);
5634 + const collected = yield* Fiber.join(events);
5635 + assert.isTrue(
5636 + collected.some(
5637 + (e) =>
5638 + e.type === "turn_item.updated" &&
5639 + e.turnItem.type === "assistant_message" &&
5640 + e.turnItem.text === "Replacement still tracked",
5641 + ),
5642 + );
5643 + }).pipe(Effect.scoped),
5644 + );
5645 +
5646 + it.effect.each(["show", "pause", "clear"] as const)(
5647 + "settles OpenCode /goal %s without waiting for an execution",
5648 + (control) =>
5649 + Effect.gen(function* () {
5650 + const goal = control === "clear" ? null : nativeGoal("paused");
5651 + const { runtime, thread } = yield* resumed(
5652 + control === "show"
5653 + ? [out("rpc.call", "<any>"), reply("rpc.call", { output: goal })]
5654 + : [
5655 + out("command.list", "<any>"),
5656 + reply("command.list", { location: { directory: WORK }, data: [{ name: "goal" }] }),
5657 + out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }),
5658 + reply("message.list", { data: [], cursor: {} }),
5659 + out("session.command", { sessionID: SESSION, name: "goal", text: control }),
5660 + event("rpc.opencode.goal.changed", { sessionID: SESSION, goal }),
5661 + reply("session.command", null),
5662 + ],
5663 + { version: "2.2.5" },
5664 + );
5665 + const events = yield* runtime.events.pipe(
5666 + Stream.takeUntil((e) => e.type === "turn.terminal"),
5667 + Stream.runCollect,
5668 + Effect.forkScoped,
5669 + );
5670 + const input = turnInput(thread);
5671 + yield* runtime.startTurn({
5672 + ...input,
5673 + message: { ...input.message, text: control === "show" ? "/goal" : `/goal ${control}` },
5674 + });
5675 + const collected = yield* Fiber.join(events);
5676 + const updated = collected.findLast((e) => e.type === "provider_thread.updated");
5677 + assert.equal(
5678 + updated?.type === "provider_thread.updated"
5679 + ? (updated.providerThread.goal?.status ?? null)
5680 + : undefined,
5681 + goal?.status ?? null,
5682 + );
5683 + assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
5684 + }).pipe(Effect.scoped),
5685 + );
5686 });
5687
5688 const providerTurnId = Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts
+8 -1
@@ -54,6 +54,12 @@ const operationOf = (
54 query: Record<string, unknown>,
55 body: unknown,
56 ) => {
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 + };
63 const session = /^\/api\/session\/([^/]+)(\/.*)?$/.exec(path);
64 if (method === "GET" && path === "/api/event") return { type: "event.subscribe" };
65 if (method === "GET" && path === "/api/model") return { type: "model.list", input: query };
@@ -292,6 +298,7 @@ export const openCode2ReplayRuntime = (
298 entries: ReadonlyArray<ProviderReplayEntry>,
299 options?: {
300 readonly external?: boolean;
301 + readonly version?: string;
302 readonly onPrompt?: (input: unknown) => void;
303 readonly borrowers?: { current: number };
304 readonly replayGate?: ProviderReplayGate;
@@ -306,7 +313,7 @@ export const openCode2ReplayRuntime = (
313 {
314 provider: OPENCODE_PROVIDER,
315 protocol: OPENCODE2_HTTP_PROTOCOL,
309 - version: "2.0.18",
316 + version: options?.version ?? "2.0.18",
317 scenario: "opencode2_adapter",
318 entries,
319 },
apps/server/src/orchestration-v2/Orchestrator.ts
+7 -4
@@ -1168,9 +1168,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1168 command: OrchestrationV2ServerCommand,
1169 providerInstanceId: ProviderInstanceId,
1170 ) {
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 + }
1177 return driver === "codex" || driver === "claudeAgent" ? driver : undefined;
1178 });
1179
@@ -6107,7 +6110,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
6110 ) {
6111 dispatchMode = { type: "queue_after_active" };
6112 }
6110 - // Codex and Claude own /goal; elsewhere it is ordinary text that cannot steer.
6113 + // Native goal commands must not steer an existing turn.
6114 const parsedGoalCommand = parseGoalCommand(command);
6115 const goalCommand =
6116 parsedGoalCommand === null ||
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+26 -2
@@ -269,6 +269,7 @@ it.each([
269
270 function makeLocalCommandHarness(input: {
271 readonly text: string;
272 + readonly nativeGoals?: boolean;
273 readonly worktreePath?: string;
274 readonly worktreesDir?: string;
275 readonly workspaceRoot?: string;
@@ -337,7 +338,7 @@ function makeLocalCommandHarness(input: {
338 };
339 const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = {
340 id: providerThreadId,
340 - driver: ProviderDriverKind.make("codex"),
341 + driver: ProviderDriverKind.make(input.nativeGoals === undefined ? "codex" : "opencode"),
342 providerInstanceId: newInstanceId,
343 providerSessionId,
344 appThreadId: threadId,
@@ -778,7 +779,13 @@ function makeLocalCommandHarness(input: {
779 status: "ready",
780 cwd: "/tmp/native-account-command",
781 model: null,
781 - capabilities: CodexProviderCapabilitiesV2,
782 + capabilities: {
783 + ...CodexProviderCapabilitiesV2,
784 + turns: {
785 + ...CodexProviderCapabilitiesV2.turns,
786 + ...(input.nativeGoals === undefined ? {} : { supportsNativeGoals: input.nativeGoals }),
787 + },
788 + },
789 createdAt: now,
790 updatedAt: now,
791 lastError: null,
@@ -1338,6 +1345,23 @@ effectIt.effect.each([
1345 }),
1346 );
1347
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 +
1365 effectIt.effect.each([
1366 { runStatus: "failed", turnStatus: "completed" },
1367 { runStatus: "completed", turnStatus: "completed" },
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+6 -2
@@ -841,8 +841,12 @@ export const layer: Layer.Layer<
841 text: message.text,
842 records: message.context?.records ?? [],
843 });
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);
850 const goalCommand = goalDriver && parseGoalCommand(message) !== null;
851 // The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively.
852 const noteContinuation = isRestartNoteContinuation(
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+39 -21
@@ -488,7 +488,9 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
488 canSteer = true,
489 interruptTurn: Effect.Effect<void> = Effect.void,
490 steeringAcceptsAttachments = true,
491 + nativeGoals?: boolean,
492 ) {
493 + const driver = ProviderDriverKind.make(nativeGoals === undefined ? "codex" : "opencode");
494 const cwd = yield* checkpointWorkspace(name);
495 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
496 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
@@ -501,6 +503,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
503 supportsActiveSteering: canSteer,
504 supportsSteeringByInterruptRestart: canRestart,
505 activeSteeringAcceptsAttachments: steeringAcceptsAttachments,
506 + ...(nativeGoals === undefined ? {} : { supportsNativeGoals: nativeGoals }),
507 },
508 };
509 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
@@ -2060,8 +2063,15 @@ it.effect("queues a plain send behind the stopped queue and releases its hold",
2063 ),
2064 );
2065
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 + );
2075 const send = (id: string, text: string, delivery: "queue" | "auto", freshContext = false) =>
2076 Effect.gen(function* () {
2077 const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2101,26 +2111,34 @@ const goalHarness = Effect.fn("goalHarness")(function* (name: string) {
2111 return { ...harness, send, read };
2112 });
2113
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();
2132
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 + ),
2142 );
2143
2144 it.effect("starts a goal that names no model on the thread's model ahead of a queued pick", () =>
docs/user/composer.md
+3 -3
@@ -304,15 +304,15 @@ Claude instances can also compact idle threads for you. See
304
305 ## Goals
306
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
308 `/goal all tests in packages/api pass`. The agent keeps working across turns
309 until it judges the goal met. The thread shows **Goal** while it works, and a
310 line at the end of the thread (above the composer on mobile) shows the goal and
311 its progress.
312
313 - `/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.
316 - Stopping Claude ends the current turn, but the goal stays set. Claude checks it
317 again at the end of your next message.
318 - Sending a new goal, or `/goal resume`, while the agent works stops the current
packages/contracts/src/orchestrationV2.ts
+1
@@ -278,6 +278,7 @@ export const OrchestrationV2ThreadCapabilities = Schema.Struct({
278 export type OrchestrationV2ThreadCapabilities = typeof OrchestrationV2ThreadCapabilities.Type;
279
280 export const OrchestrationV2TurnCapabilities = Schema.Struct({
281 + supportsNativeGoals: Schema.optional(Schema.Boolean),
282 exposesNativeTurnId: Schema.Boolean,
283 emitsTurnStarted: Schema.Boolean,
284 emitsTurnCompleted: Schema.Boolean,
packages/provider-opencode/src/server/driver.test.ts
+111
@@ -222,6 +222,117 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
222 }).pipe(Effect.scoped),
223 );
224
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 +
336 it.effect("answers capability reads without waiting on an unreachable server", () =>
337 Effect.gen(function* () {
338 const hang = HttpClient.make(() => Effect.never);
packages/provider-opencode/src/server/driver.ts
+15 -1
@@ -18,6 +18,7 @@ import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderL
18 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
19 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
20 import * as HostProcess from "@t3tools/shared/HostProcess";
21 +import { compareSemverVersions } from "@t3tools/shared/semver";
22 import * as OpenCodeAdapterV2 from "./adapter.ts";
23 import * as OpenCode2AdapterV2 from "./v2/adapter.ts";
24 import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -120,7 +121,20 @@ function selectOpenCodeRuntimeAdapter(input: {
121 return {
122 instanceId: input.v1.instanceId,
123 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 + }),
138 planSelectionTransition: (transition) =>
139 Effect.flatMap(hot, (adapter) => adapter.planSelectionTransition(transition)),
140 openSession: (session) =>
packages/provider-opencode/src/server/v2/adapter.ts
+174 -13
@@ -16,6 +16,7 @@ import {
16 import { Mcp } from "@opencode/schema/mcp";
17 import {
18 isOrchestrationV2WorkActive,
19 + parseGoalCommand,
20 type ChatAttachment,
21 type OrchestrationV2AppThread,
22 type OrchestrationV2ConversationMessage,
@@ -61,6 +62,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
62 import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
63 import { t3OrchestrationSystemPrompt } from "@t3tools/provider-core/server/orchestrationInstructions";
64 import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
65 +import { compareSemverVersions } from "@t3tools/shared/semver";
66 import * as KeyedLock from "@t3tools/shared/KeyedLock";
67 import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model";
68 import { causeErrorTag } from "@t3tools/shared/observability";
@@ -89,6 +91,16 @@ import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/sel
91 import { OPENCODE_PROVIDER, openCodePermissionRequestKind } from "../adapter.ts";
92 import { openCodeCommandFailed, openCodeToolTurnItem } from "../toolItems.ts";
93
94 +const NativeGoal = Schema.NullOr(
95 + Schema.Struct({
96 + objective: Schema.NonEmptyString,
97 + status: Schema.Literals(["active", "paused", "complete"]),
98 + rounds: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
99 + reason: Schema.optional(Schema.String),
100 + }),
101 +);
102 +const decodeGoal = Schema.decodeUnknownEffect(NativeGoal);
103 +
104 const OpenCode2ProviderCapabilities = {
105 sessions: {
106 supportsMultipleProviderThreadsPerSession: true,
@@ -279,6 +291,9 @@ interface ThreadState {
291 readonly sessionId: string;
292 providerThread: OrchestrationV2ProviderThread;
293 publishedBackgroundWork?: boolean;
294 + goalRevision: number;
295 + goalFresh: boolean;
296 + goalRefreshing: boolean;
297 readonly providerTurns: Map<string, OrchestrationV2ProviderTurn>;
298 active: ActiveTurn | undefined;
299 model: ModelRef | undefined;
@@ -673,6 +688,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
688 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
689 const crypto = yield* Digest.Digest;
690 const driver = OPENCODE_PROVIDER;
691 + let nativeGoalSupport: boolean | undefined;
692 const mcpServerNameFor = (threadId: string) =>
693 t3McpServerName(threadId).pipe(Effect.provideService(Digest.Digest, crypto));
694
@@ -700,6 +716,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
716 },
717 ) {
718 let connection = initial.connection;
719 + const supportsNativeGoals = () => compareSemverVersions(connection.version, "2.2.5") >= 0;
720 + nativeGoalSupport = supportsNativeGoals();
721 + const goalHoldsTurn = (state: ThreadState) =>
722 + supportsNativeGoals() &&
723 + (state.goalRefreshing || (state.goalFresh && state.providerThread.goal?.status === "active"));
724 let client = connection.client;
725 const sessionScope = yield* Effect.scope;
726 // Project config changes model limits; key by directory because this runtime serves all instance threads.
@@ -715,7 +736,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
736 status: "ready",
737 cwd: input.runtimePolicy.cwd ?? host.paths.cwd,
738 model: input.modelSelection.model,
718 - capabilities: OpenCode2ProviderCapabilities,
739 + capabilities: {
740 + ...OpenCode2ProviderCapabilities,
741 + turns: {
742 + ...OpenCode2ProviderCapabilities.turns,
743 + supportsNativeGoals: supportsNativeGoals(),
744 + },
745 + },
746 createdAt: now,
747 updatedAt: now,
748 lastError: null,
@@ -754,6 +781,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
781 ): ThreadState => ({
782 sessionId,
783 providerThread,
784 + goalRevision: 0,
785 + goalFresh: false,
786 + goalRefreshing: false,
787 providerTurns: new Map(),
788 active: undefined,
789 model: undefined,
@@ -845,6 +875,46 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
875 });
876 });
877
878 + // Goal changes share the event stream, so do not create a span per notification.
879 + const updateGoal = Effect.fnUntraced(function* (
880 + state: ThreadState,
881 + goal: typeof NativeGoal.Type,
882 + ) {
883 + state.goalRevision += 1;
884 + state.goalFresh = true;
885 + state.goalRefreshing = false;
886 + state.providerThread = {
887 + ...state.providerThread,
888 + goal:
889 + goal === null
890 + ? null
891 + : {
892 + objective: goal.objective,
893 + status: goal.status,
894 + checks: goal.rounds,
895 + ...(goal.reason === undefined ? {} : { lastCheck: goal.reason }),
896 + },
897 + updatedAt: yield* DateTime.now,
898 + };
899 + yield* emitProviderThread(state);
900 + });
901 +
902 + const readGoal = Effect.fn("OpenCode2Adapter.readGoal")(function* (state: ThreadState) {
903 + const revision = state.goalRevision;
904 + const result = yield* client.rpc.call({
905 + rpcID: "opencode.goal",
906 + method: "get",
907 + location: { directory: state.directory },
908 + input: { sessionID: state.sessionId },
909 + });
910 + const goal = yield* decodeGoal(result.output);
911 + yield* lock.withPermit(
912 + Effect.gen(function* () {
913 + if (state.goalRevision === revision) yield* updateGoal(state, goal);
914 + }),
915 + );
916 + });
917 +
918 const setSessionStatus =
919 /* Provider events include streaming deltas; avoid a span for each update. */
920 Effect.fnUntraced(function* (
@@ -2286,7 +2356,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2356 turn: ActiveTurn,
2357 end: TurnTerminal,
2358 ) {
2289 - if (end.status === "completed" && turn.steers.size > 0) {
2359 + if (end.status === "completed" && (turn.steers.size > 0 || goalHoldsTurn(state))) {
2360 turn.heldEnd = end;
2361 return;
2362 }
@@ -2294,7 +2364,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2364 });
2365
2366 const endIfSettled = (state: ThreadState, turn: ActiveTurn) =>
2297 - turn.heldEnd !== undefined && turn.steers.size === 0
2367 + turn.heldEnd !== undefined && turn.steers.size === 0 && !goalHoldsTurn(state)
2368 ? finishTurn(state, turn.heldEnd)
2369 : Effect.void;
2370
@@ -2419,6 +2489,42 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2489 if (sessionId === undefined) return;
2490 const state = threads.get(sessionId);
2491 if (state === undefined) return;
2492 + if (event.type === "rpc.opencode.goal.changed") {
2493 + if (!supportsNativeGoals()) return;
2494 + const goal = yield* decodeGoal(event.data["goal"]).pipe(Effect.result);
2495 + if (goal._tag === "Failure") {
2496 + state.goalFresh = false;
2497 + state.goalRefreshing = true;
2498 + state.goalRevision += 1;
2499 + const revision = state.goalRevision;
2500 + yield* Effect.logWarning(
2501 + "Could not decode an OpenCode goal update; refreshing its state.",
2502 + );
2503 + yield* Effect.forkIn(
2504 + readGoal(state).pipe(
2505 + Effect.timeout(INVENTORY_TIMEOUT),
2506 + Effect.catch(() =>
2507 + Effect.logWarning(
2508 + "Could not refresh OpenCode goal state after an unreadable update.",
2509 + ),
2510 + ),
2511 + Effect.ensuring(
2512 + lock.withPermit(
2513 + Effect.gen(function* () {
2514 + if (state.goalRevision === revision) state.goalRefreshing = false;
2515 + if (state.active !== undefined) yield* endIfSettled(state, state.active);
2516 + }),
2517 + ),
2518 + ),
2519 + ),
2520 + sessionScope,
2521 + );
2522 + return;
2523 + }
2524 + yield* updateGoal(state, goal.success);
2525 + if (state.active !== undefined) yield* endIfSettled(state, state.active);
2526 + return;
2527 + }
2528 if (event.type === "session.model.selected" || event.type === "session.step.started") {
2529 if (event.type === "session.model.selected") state.model = event.data.model;
2530 const providerThread = withReportedModel(state.providerThread, event.data.model);
@@ -2513,6 +2619,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2619 const found = start === null || read.at(-1)?.id === start;
2620 if (!found) return undefined;
2621 const recent = before !== undefined && before !== null ? read.slice(0, -1) : read;
2622 + for (const message of recent) {
2623 + if (message.type === "user" && turn.steers.delete(message.id)) {
2624 + turn.settledInbox.add(message.id);
2625 + }
2626 + }
2627 const idle = recent.find((message) => message.type === "idle");
2628 const assistant = recent.find((message) => message.type === "assistant");
2629 if (assistant?.retry !== undefined) {
@@ -2585,7 +2696,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2696 });
2697
2698 // Restarts retain the previous session.outcome; without an idle item, the lost execution was interrupted.
2588 - const reconcile = Effect.gen(function* () {
2699 + const reconcile = Effect.fn("OpenCode2Adapter.reconcile")(function* () {
2700 // Read deepest sessions first; subagent turns end before their waiting parents.
2701 const running = [...threads]
2702 .filter(([, state]) => state.active !== undefined)
@@ -2614,9 +2725,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2725 if (turn === undefined) continue;
2726 turn.missedEvents = true;
2727 const ended = yield* backfill(sessionId, state);
2617 - if (sessionId in active || state.active !== turn) continue;
2618 - yield* finishTurn(
2619 - state,
2728 + if (state.active !== turn) continue;
2729 + if (sessionId in active) {
2730 + turn.heldEnd = undefined;
2731 + continue;
2732 + }
2733 + const terminal: TurnTerminal =
2734 ended?.outcome === "succeeded"
2735 ? { status: turn.interrupted ? "interrupted" : "completed" }
2736 : ended?.outcome === "failed"
@@ -2628,8 +2742,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2742 class: "provider_error",
2743 }),
2744 }
2631 - : { status: "interrupted" },
2632 - );
2745 + : { status: "interrupted" };
2746 + yield* endExecution(state, turn, terminal);
2747 }
2748 for (const state of background) {
2749 for (const call of runningCalls(state)) {
@@ -2683,11 +2797,31 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
2797 const previous = currentScope;
2798 connection = next;
2799 client = next.client;
2800 + nativeGoalSupport = supportsNativeGoals();
2801 + session = {
2802 + ...session,
2803 + capabilities: {
2804 + ...session.capabilities,
2805 + turns: { ...session.capabilities.turns, supportsNativeGoals: supportsNativeGoals() },
2806 + },
2807 + };
2808 currentScope = scope;
2809 yield* Scope.close(previous, Exit.void);
2810 // A restarted server forgot T3's MCP servers; the next turn adds them again.
2689 - for (const state of threads.values()) state.mcp = undefined;
2690 - yield* lock.withPermit(reconcile).pipe(Effect.timeout(RECONCILE_TIMEOUT));
2811 + for (const state of threads.values()) {
2812 + state.mcp = undefined;
2813 + state.goalFresh = false;
2814 + state.goalRefreshing = false;
2815 + state.goalRevision += 1;
2816 + }
2817 + if (supportsNativeGoals()) {
2818 + yield* Effect.forEach(
2819 + [...threads.values()],
2820 + (state) => readGoal(state).pipe(Effect.ignore({ log: true })),
2821 + { concurrency: 4, discard: true },
2822 + ).pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.ignore({ log: true }));
2823 + }
2824 + yield* lock.withPermit(reconcile()).pipe(Effect.timeout(RECONCILE_TIMEOUT));
2825 return stream;
2826 }).pipe(
2827 Effect.retry({ times: RECONNECT_ATTEMPTS - 1, schedule: Schedule.spaced(RECONNECT_DELAY) }),
@@ -3388,9 +3522,20 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3522 turn.unsent = false;
3523 return true;
3524 };
3525 + const finishControl = lock.withPermit(
3526 + Effect.suspend(() =>
3527 + state.active === turn ? finishTurn(state, { status: "completed" }) : Effect.void,
3528 + ),
3529 + );
3530 const text = turnInput.message.text.trim();
3531 const bare = turnInput.message.attachments.length === 0;
3532 const id = turnPromptId(sessionId, turnInput.attemptId);
3533 + const goalCommand = supportsNativeGoals() ? parseGoalCommand(turnInput.message) : null;
3534 + if (goalCommand?.type === "show") {
3535 + if (!sending()) return;
3536 + yield* readGoal(state);
3537 + return yield* finishControl;
3538 + }
3539 if (bare && text === "/compact") {
3540 if (!sending()) return;
3541 return yield* client.session.compact({ sessionID, id }).pipe(Effect.asVoid);
@@ -3408,7 +3553,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3553 const newest = yield* client.message.list({ sessionID, order: "desc", limit: 1 });
3554 yield* markBefore(sessionId, newest.data[0]?.id ?? null);
3555 if (!sending()) return;
3411 - return yield* client.session.command({ sessionID, ...command });
3556 + yield* client.session.command({ sessionID, ...command });
3557 + if (goalCommand?.type === "pause" || goalCommand?.type === "clear") {
3558 + yield* finishControl;
3559 + }
3560 + return;
3561 }
3562 }
3563 const mentions = skillMentions(text);
@@ -3546,6 +3695,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
3695 const loaded = threads.has(sessionId);
3696 const state = register(providerThread, native, cwd ?? native.location.directory);
3697 if (!loaded) yield* stopLeftoverRequests(state);
3698 + if (!loaded && supportsNativeGoals()) {
3699 + yield* readGoal(state).pipe(
3700 + Effect.timeout(INVENTORY_TIMEOUT),
3701 + Effect.ignore({ log: true }),
3702 + );
3703 + }
3704 yield* writeRules(state, threadInput.runtimePolicy ?? state.policy);
3705 if (cwd != null && native.location.directory !== cwd) {
3706 yield* client.session.move({
@@ -4134,7 +4289,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr
4289 instanceId,
4290 driver,
4291 getCapabilities: Effect.fn("OpencodeAdapter.getCapabilities")(function () {
4137 - return Effect.succeed(OpenCode2ProviderCapabilities);
4292 + return Effect.succeed({
4293 + ...OpenCode2ProviderCapabilities,
4294 + turns: {
4295 + ...OpenCode2ProviderCapabilities.turns,
4296 + ...(nativeGoalSupport === undefined ? {} : { supportsNativeGoals: nativeGoalSupport }),
4297 + },
4298 + });
4299 }),
4300 planSelectionTransition: Effect.fn("OpencodeAdapter.planSelectionTransition")(function () {
4301 return Effect.succeed(turnScopedSelectionTransition());