Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off -- the rule builders below need a sync hash.
2import * as NodeCrypto from "node:crypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, describe, it } from "@effect/vitest";
5import {
6 CommandId,
7 MessageId,
8 type ModelSelection,
9 type OrchestrationV2Command,
10 type OrchestrationV2Run,
11 ProjectId,
12 type ProviderInteractionMode,
13 ProviderInstanceId,
14 type ProviderReplayEntry,
15 type RuntimeMode,
16 ThreadId,
17} from "@t3tools/contracts";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20
21import {
22 OPENCODE2_HTTP_PROTOCOL,
23 OpenCode2OrchestratorReplayHarness,
24} from "./Adapters/OpenCode2AdapterV2.testkit.ts";
25import { OPENCODE_PROVIDER } from "@t3tools/provider-opencode/testing";
26import { provideDeterministicTestRuntime } from "./testkit/DeterministicRuntime.ts";
27import type { OrchestratorV2ScenarioStep } from "./testkit/OrchestratorScenario.ts";
28import { runOrchestratorV2ProviderReplayScenario } from "./testkit/ProviderReplayHarness.ts";
29import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
30import { readProviderReplayTranscript } from "@t3tools/provider-testing/replayTranscript";
31import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
32
33const SESSION = "ses_f148ca2deffeJcwCnRQtb0YFNX";
34
35const FIRST_TURN_END = "first-turn-end";
36
37const BACKGROUND_HOLD = "background-hold";
38
39const BACKGROUND_PARENT = "ses_f1485cda4ffeXuc6GjAU9vDiRb";
40
41const BACKGROUND_CHILD = "ses_f1485c529ffea4URrYruwEg0Ja";
42const BACKGROUND_PROMPT =
43 "Use the subagent tool with background enabled to delegate to the general subagent with the prompt: 'Run the shell command `sleep 20` with the bash tool and then reply exactly CHILD_OK.' As soon as it is launched, reply exactly PARENT_OK and end your turn without waiting for it.";
44const instanceId = ProviderInstanceId.make("opencode");
45const bigPickle: ModelSelection = { instanceId, model: "opencode/big-pickle" };
46const mimo: ModelSelection = { instanceId, model: "opencode/mimo-v2.6-flash-free" };
47
48const out = (type: string, input?: unknown): ProviderReplayEntry => ({
49 type: "expect_outbound",
50 frame: input === undefined ? { type } : { type, input },
51});
52const reply = (operation: string, data: unknown): ProviderReplayEntry => ({
53 type: "emit_inbound",
54 frame: { type: "sdk.response", operation, data },
55});
56const event = (type: string, data: Record<string, unknown>): ProviderReplayEntry => ({
57 type: "emit_inbound",
58 frame: {
59 type: "sdk.event",
60 event: { id: `evt_${type.replaceAll(".", "")}`, created: 1, type, data },
61 },
62});
63const labelled = (entry: ProviderReplayEntry, label: string): ProviderReplayEntry =>
64 entry.type === "runtime_exit" ? entry : { ...entry, label };
65/**
66 * MCP rules are last-match-wins; allow this thread after denying all T3 servers.
67 * No thread's own MCP servers are allowed, since these threads have none.
68 */
69const mcpRules = (name: string) => [
70 { action: "t3-code-*", resource: "*", effect: "deny" },
71 {
72 action: `t3-code-${NodeCrypto.createHash("sha256").update(`thread:${name}`).digest("hex").slice(0, 16)}_*`,
73 resource: "*",
74 effect: "allow",
75 },
76 { action: "t3u-*", resource: "*", effect: "deny" },
77];
78const FULL_ACCESS = [{ action: "*", resource: "*", effect: "allow" }];
79
80const t3Rules = (name: string) => [...FULL_ACCESS, ...mcpRules(name)];
81
82const BUILD_PATHS = [
83 {
84 action: "external_directory",
85 resource: "/home/.local/share/opencode/tool-output/*",
86 effect: "allow",
87 },
88];
89const PLAN_PATHS = [
90 ...BUILD_PATHS,
91 { action: "edit", resource: "/home/.opencode/plan/*", effect: "allow" },
92 { action: "external_directory", resource: "/home/.opencode/plan/*", effect: "allow" },
93];
94const agentInfo = (id: string, description: string, permissions: ReadonlyArray<unknown>) => ({
95 id,
96 name: id === "plan" ? "Plan" : "Build",
97 request: { settings: {}, headers: {}, body: {} },
98 description,
99 mode: "primary",
100 hidden: false,
101 permissions,
102});
103
104const agentList = (directory: string) => ({
105 location: { directory },
106 data: [
107 agentInfo("build", "The default agent.", [
108 { action: "*", resource: "*", effect: "allow" },
109 { action: "external_directory", resource: "*", effect: "ask" },
110 ...BUILD_PATHS,
111 ]),
112 agentInfo("plan", "Read-only agent for planning.", [
113 { action: "*", resource: "*", effect: "allow" },
114 { action: "external_directory", resource: "*", effect: "ask" },
115 ...BUILD_PATHS,
116 { action: "edit", resource: "*", effect: "deny" },
117 ...PLAN_PATHS.slice(BUILD_PATHS.length),
118 ]),
119 ],
120});
121
122const autoEditRules = (name: string) => [
123 { action: "shell", resource: "*", effect: "ask" },
124 { action: "edit", resource: "*", effect: "allow" },
125 { action: "external_directory", resource: "*", effect: "ask" },
126 ...BUILD_PATHS,
127 ...mcpRules(name),
128];
129
130const planRules = (name: string) => [
131 { action: "*", resource: "*", effect: "allow" },
132 { action: "edit", resource: "*", effect: "deny" },
133 ...PLAN_PATHS,
134 ...mcpRules(name),
135];
136
137const sessionInfo = (directory: string, permissions: ReadonlyArray<unknown>, title: string) => ({
138 data: {
139 id: SESSION,
140 title,
141 projectID: "global",
142 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
143 cost: 0,
144 tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
145 time: { created: 1790656601394, updated: 1790656601394 },
146 location: { directory },
147 permissions,
148 },
149});
150
151const instructionsWritten: ReadonlyArray<ProviderReplayEntry> = [
152 out("session.instructions.entry.put", { sessionID: SESSION, key: "t3-code", value: "<any>" }),
153 reply("session.instructions.entry.put", null),
154];
155
156const answeredPrompt = (text: string): ReadonlyArray<ProviderReplayEntry> => [
157 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
158 reply("session.prompt", {
159 data: {
160 id: `msg_user_${text}`,
161 sessionID: SESSION,
162 time: { created: 1790656601410 },
163 type: "user",
164 payload: { text: "<prompt>" },
165 delivery: "steer",
166 },
167 }),
168 event("session.text.ended", {
169 sessionID: SESSION,
170 assistantMessageID: `msg_assistant_${text}`,
171 ordinal: 0,
172 text,
173 }),
174 event("session.execution.succeeded", { sessionID: SESSION }),
175];
176
177/** A `/api/model` entry as 2.0.18 lists it; a known window means no re-read after a turn. */
178const catalogModel = (id: string, name: string) => ({
179 id,
180 modelID: id,
181 providerID: "opencode",
182 family: id,
183 name,
184 compatibility: { reasoningField: "reasoning_content" },
185 package: "@opencode/ai/providers/openai-compatible",
186 settings: { apiKey: "public", baseURL: "https://opencode.ai/zen/v1", provider: "opencode" },
187 capabilities: { tools: true, input: ["text"], output: ["text"] },
188 variants: [],
189 time: { released: 1760659200000 },
190 cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
191 status: "active",
192 enabled: true,
193 limit: { context: 200000, input: 160000, output: 32000 },
194});
195const createdSession = (
196 directory: string,
197 name: string,
198 permissions: ReadonlyArray<unknown> = t3Rules(name),
199
200 narrows = false,
201): ReadonlyArray<ProviderReplayEntry> => [
202 out("event.subscribe"),
203 out("model.list", "<any>"),
204 reply("model.list", {
205 location: { directory },
206 data: [
207 catalogModel("big-pickle", "Big Pickle"),
208 catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
209 ],
210 }),
211 ...(narrows ? [out("agent.list", "<any>"), reply("agent.list", agentList(directory))] : []),
212
213 out("session.create", { location: { directory }, model: "<any>", permissions }),
214 reply("session.create", sessionInfo(directory, permissions, name)),
215];
216
217const withDirectory = <T>(value: T, directory: string): T => {
218 const replace = (entry: unknown): unknown =>
219 entry === "<work>"
220 ? directory
221 : Array.isArray(entry)
222 ? entry.map(replace)
223 : typeof entry === "object" && entry !== null
224 ? Object.fromEntries(Object.entries(entry).map(([key, inner]) => [key, replace(inner)]))
225 : entry;
226 return replace(value) as T;
227};
228
229const threadCommands = (input: {
230 readonly name: string;
231 readonly worktreePath: string;
232 readonly runtimeMode?: RuntimeMode;
233 readonly interactionMode?: ProviderInteractionMode;
234}) => {
235 const threadId = ThreadId.make(`thread:${input.name}`);
236 const command = (key: string) => CommandId.make(`command:${input.name}:${key}`);
237 return {
238 threadId,
239 create: {
240 type: "thread.create",
241 createdBy: "user",
242 creationSource: "web",
243 commandId: command("create"),
244 threadId,
245 projectId: ProjectId.make(`project:${input.name}`),
246 title: input.name,
247 modelSelection: bigPickle,
248 runtimeMode: input.runtimeMode ?? "full-access",
249 interactionMode: input.interactionMode ?? "default",
250 branch: null,
251 worktreePath: input.worktreePath,
252 } satisfies OrchestrationV2Command,
253 message: (key: string, modelSelection: ModelSelection = bigPickle, text?: string) =>
254 ({
255 type: "message.dispatch",
256 createdBy: "user",
257 creationSource: "web",
258 commandId: command(key),
259 threadId,
260 messageId: MessageId.make(`message:${input.name}:${key}`),
261 text: text ?? `Reply with exactly: ${key}`,
262 attachments: [],
263 modelSelection,
264 dispatchMode: { type: "start_immediately" },
265 }) satisfies OrchestrationV2Command,
266 interactionMode: (key: string, interactionMode: "default" | "plan") =>
267 ({
268 type: "thread.interaction-mode.set",
269 commandId: command(key),
270 threadId,
271 interactionMode,
272 }) satisfies OrchestrationV2Command,
273 command,
274 };
275};
276
277const runScenario = (input: {
278 readonly name: string;
279 readonly threadId: ThreadId;
280 readonly entries: ReadonlyArray<ProviderReplayEntry>;
281 readonly commands: ReadonlyArray<OrchestrationV2Command>;
282}) =>
283 Effect.gen(function* () {
284 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
285 provider: OPENCODE_PROVIDER,
286 protocol: OPENCODE2_HTTP_PROTOCOL,
287 version: "2.0.18",
288 scenario: input.name,
289 entries: input.entries,
290 });
291 const steps = input.commands.flatMap((command): Array<OrchestratorV2ScenarioStep> => [
292 { type: "dispatch", command },
293 { type: "advance_clock", duration: "1 millis" },
294 ...(command.type === "message.dispatch"
295 ? [{ type: "await_thread_idle" as const, threadId: input.threadId }]
296 : []),
297 ]);
298 const result = yield* runOrchestratorV2ProviderReplayScenario(
299 { name: input.name, transcript, commands: input.commands, steps },
300 OpenCode2OrchestratorReplayHarness,
301 ).pipe(provideDeterministicTestRuntime);
302 const projection = result.projections.get(input.threadId);
303 assert.isDefined(projection);
304 return projection;
305 });
306
307describe("OpenCode 2 through the orchestrator", () => {
308 it.effect.each(["message", "thread settings"] as const)(
309 "switches the session's model before the next prompt when changed from the %s",
310 (via) =>
311 Effect.gen(function* () {
312 const name = `opencode2-model-switch-${via.replace(" ", "-")}`;
313 const cwd = yield* checkpointWorkspace(name);
314 const thread = threadCommands({ name, worktreePath: cwd });
315 const projection = yield* runScenario({
316 name,
317 threadId: thread.threadId,
318 entries: [
319 ...createdSession(cwd, name),
320 ...instructionsWritten,
321 ...answeredPrompt("FIRST"),
322
323 out("session.get", { sessionID: SESSION }),
324 reply("session.get", sessionInfo(cwd, t3Rules(name), name)),
325 out("session.switchModel", {
326 sessionID: SESSION,
327 model: { providerID: "opencode", id: "mimo-v2.6-flash-free" },
328 }),
329 reply("session.switchModel", null),
330
331 ...instructionsWritten,
332 ...answeredPrompt("SECOND"),
333 ],
334 commands: [
335 thread.create,
336 thread.message("first"),
337 ...(via === "thread settings"
338 ? [
339 {
340 type: "thread.model-selection.set",
341 commandId: thread.command("model"),
342 threadId: thread.threadId,
343 modelSelection: mimo,
344 } satisfies OrchestrationV2Command,
345 ]
346 : []),
347 thread.message("second", mimo),
348 ],
349 });
350 assert.deepEqual(
351 projection.runs.map((run) => [run.status, run.modelSelection.model]),
352 [
353 ["completed", bigPickle.model],
354 ["completed", mimo.model],
355 ],
356 );
357
358 assert.lengthOf(projection.providerThreads, 1);
359 }),
360 );
361
362 it.effect("rewrites the session's rules when the thread's mode changes between turns", () =>
363 Effect.gen(function* () {
364 const name = "opencode2-mode-change";
365 const cwd = yield* checkpointWorkspace(name);
366 const thread = threadCommands({ name, worktreePath: cwd });
367 const setMode = (key: string, runtimeMode: RuntimeMode) =>
368 ({
369 type: "thread.runtime-mode.set",
370 commandId: thread.command(key),
371 threadId: thread.threadId,
372 runtimeMode,
373 }) satisfies OrchestrationV2Command;
374 const projection = yield* runScenario({
375 name,
376 threadId: thread.threadId,
377 entries: [
378 ...createdSession(cwd, name),
379 ...instructionsWritten,
380 ...answeredPrompt("FIRST"),
381
382 out("session.get", { sessionID: SESSION }),
383 reply("session.get", sessionInfo(cwd, t3Rules(name), name)),
384 out("agent.list", "<any>"),
385 reply("agent.list", agentList(cwd)),
386 out("session.update", { sessionID: SESSION, permissions: autoEditRules(name) }),
387 reply("session.update", null),
388 ...answeredPrompt("SECOND"),
389
390 out("session.get", { sessionID: SESSION }),
391 reply("session.get", sessionInfo(cwd, autoEditRules(name), name)),
392 out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
393 reply("session.update", null),
394 ...answeredPrompt("THIRD"),
395 ],
396 commands: [
397 thread.create,
398 thread.message("first"),
399 setMode("auto-edit", "auto-accept-edits"),
400 thread.message("second"),
401 setMode("full", "full-access"),
402 thread.message("third"),
403 ],
404 });
405 assert.deepEqual(
406 projection.runs.map((run) => run.status),
407 ["completed", "completed", "completed"],
408 );
409 assert.lengthOf(projection.providerThreads, 1);
410 }),
411 );
412
413 it.effect("denies edits outside the plan directory in plan mode and lifts it after", () =>
414 Effect.gen(function* () {
415 const name = "opencode2-plan-rules";
416 const cwd = yield* checkpointWorkspace(name);
417 const thread = threadCommands({ name, worktreePath: cwd, interactionMode: "plan" });
418 const projection = yield* runScenario({
419 name,
420 threadId: thread.threadId,
421 entries: [
422 ...createdSession(cwd, name, planRules(name), true),
423
424 out("session.switchAgent", { sessionID: SESSION, agent: "plan" }),
425 reply("session.switchAgent", null),
426 ...instructionsWritten,
427 ...answeredPrompt("PLANNED"),
428 out("session.get", { sessionID: SESSION }),
429 reply("session.get", sessionInfo(cwd, planRules(name), name)),
430 out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
431 reply("session.update", null),
432 out("session.switchAgent", { sessionID: SESSION, agent: "build" }),
433 reply("session.switchAgent", null),
434 ...answeredPrompt("BUILT"),
435 ],
436 commands: [
437 thread.create,
438 thread.message("plan"),
439 {
440 type: "thread.interaction-mode.set",
441 commandId: thread.command("default"),
442 threadId: thread.threadId,
443 interactionMode: "default",
444 },
445 thread.message("build"),
446 ],
447 });
448 assert.deepEqual(
449 projection.runs.map((run) => run.status),
450 ["completed", "completed"],
451 );
452 }),
453 );
454
455 it.effect.each(["prompt", "slash command"])("forks before the next %s", (nextTurn) =>
456 Effect.gen(function* () {
457 const name = "opencode2-fork";
458 const cwd = yield* checkpointWorkspace(name);
459 const recorded = yield* readProviderReplayTranscript(
460 new URL("./testkit/fixtures/opencode2_fork/opencode_transcript.ndjson", import.meta.url),
461 );
462
463 const sessionID = String(recorded.metadata?.["nativeSessionId"]);
464 const entries = recorded.entries.flatMap((entry): ReadonlyArray<ProviderReplayEntry> => {
465 if (nextTurn === "prompt" || entry.type === "runtime_exit") return [entry];
466 if (entry.label === "session.prompt.2") {
467 return [
468 out("command.list", "<any>"),
469 reply("command.list", { location: { directory: cwd }, data: [{ name: "hello" }] }),
470 out("message.list", { sessionID, order: "desc", limit: "1" }),
471 reply("message.list", {
472 data: [
473 { id: "msg_idle_one", type: "idle", time: { created: 1 }, outcome: "succeeded" },
474 ],
475 cursor: { previous: "after-turn-one" },
476 }),
477 out("session.command", { sessionID, name: "hello", text: "TWO" }),
478 reply("session.command", null),
479 out("session.active"),
480 reply("session.active", { data: { [sessionID]: { type: "running" } } }),
481 ];
482 }
483 if (entry.label === "session.message.get") {
484 return [
485 out("message.list", { sessionID, cursor: "after-turn-one", limit: "1" }),
486 reply("message.list", {
487 data: [
488 {
489 id: "msg_0eb7b1f9f001g95Bduh3bi8syS",
490 type: "user",
491 time: { created: 2 },
492 text: "Reply exactly TWO.",
493 },
494 ],
495 cursor: {},
496 }),
497 ];
498 }
499 return entry.label === "session.prompt.response.2" ||
500 entry.label === "session.message.get.response"
501 ? []
502 : [entry];
503 });
504 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript(
505 withDirectory({ ...recorded, entries }, cwd),
506 );
507 const source = threadCommands({ name, worktreePath: cwd });
508 const target = ThreadId.make(`thread:${name}:target`);
509 const commands: ReadonlyArray<OrchestrationV2Command> = [
510 source.create,
511 source.message("one"),
512 source.message("two", bigPickle, nextTurn === "slash command" ? "/hello TWO" : undefined),
513 {
514 type: "thread.fork",
515 createdBy: "user",
516 creationSource: "web",
517 commandId: source.command("fork"),
518 sourceThreadId: source.threadId,
519 targetThreadId: target,
520 sourcePoint: {
521 type: "run",
522 runId: (yield* IdAllocator.IdAllocatorV2).derive.run({
523 threadId: source.threadId,
524 ordinal: 1,
525 }),
526 },
527 },
528 {
529 ...source.message("repeat"),
530 threadId: target,
531 messageId: MessageId.make(`message:${name}:repeat`),
532 },
533 ];
534 const steps: Array<OrchestratorV2ScenarioStep> = commands.flatMap((command) => [
535 { type: "dispatch" as const, command },
536 { type: "advance_clock" as const, duration: "1 millis" as const },
537 ...(command.type === "message.dispatch"
538 ? [{ type: "await_thread_idle" as const, threadId: command.threadId }]
539 : []),
540 ]);
541 const result = yield* runOrchestratorV2ProviderReplayScenario(
542 { name, transcript, commands, steps, projectionThreadIds: [source.threadId, target] },
543 OpenCode2OrchestratorReplayHarness,
544 ).pipe(provideDeterministicTestRuntime);
545 const forked = result.projections.get(target);
546 assert.isDefined(forked);
547 assert.equal(forked.contextTransfers[0]?.resolution?.strategy, "native_fork");
548 assert.equal(
549 forked.providerThreads[0]?.nativeThreadRef?.nativeId,
550 recorded.metadata?.["forkedNativeSessionId"],
551 );
552
553 assert.deepEqual(
554 forked.runs.map((run) => run.status),
555 ["completed"],
556 );
557 const visible = forked.visibleTurnItems.flatMap((row) =>
558 row.item.type === "assistant_message" ? [row.item.text] : [],
559 );
560 assert.deepEqual(visible, ["ONE", "ONE"]);
561 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
562 );
563
564 it.effect("never sends OpenCode a queued message that was cancelled", () =>
565 Effect.gen(function* () {
566 const name = "opencode2-queued-cancel";
567 const cwd = yield* checkpointWorkspace(name);
568 const thread = threadCommands({ name, worktreePath: cwd });
569 const queued = (key: string): OrchestrationV2Command => ({
570 ...thread.message(key),
571 dispatchMode: { type: "queue_after_active" },
572 });
573 const ids = yield* IdAllocator.IdAllocatorV2;
574 const run = (ordinal: number) => ids.derive.run({ threadId: thread.threadId, ordinal });
575
576 const [first, second, third] = [thread.message("first"), queued("second"), queued("third")];
577 const cancel: OrchestrationV2Command = {
578 type: "queued-run.cancel",
579 commandId: thread.command("cancel"),
580 threadId: thread.threadId,
581 runId: run(2),
582 };
583 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
584 provider: OPENCODE_PROVIDER,
585 protocol: OPENCODE2_HTTP_PROTOCOL,
586 version: "2.0.18",
587 scenario: name,
588 entries: [
589 ...createdSession(cwd, name),
590 ...instructionsWritten,
591 out("session.prompt", { sessionID: SESSION, id: "<any>", text: "<any>" }),
592 reply("session.prompt", {
593 data: {
594 id: "msg_user_FIRST",
595 sessionID: SESSION,
596 time: { created: 1 },
597 type: "user",
598 payload: { text: "<prompt>" },
599 delivery: "steer",
600 },
601 }),
602
603 ...answeredPrompt("THIRD"),
604 ],
605 });
606 const steps: Array<OrchestratorV2ScenarioStep> = [
607 { type: "dispatch", command: thread.create },
608 { type: "advance_clock", duration: "1 millis" },
609 { type: "dispatch", command: first, await: false, key: "first" },
610 { type: "await_run_steerable", threadId: thread.threadId, runId: run(1) },
611 { type: "dispatch", command: second },
612 { type: "dispatch", command: third },
613 { type: "dispatch", command: cancel },
614 { type: "await_run_status", threadId: thread.threadId, runId: run(2), status: "cancelled" },
615 { type: "release_replay_gate", label: FIRST_TURN_END },
616 { type: "await", key: "first" },
617 { type: "await_thread_idle", threadId: thread.threadId },
618 ];
619 const result = yield* runOrchestratorV2ProviderReplayScenario(
620 {
621 name,
622 transcript: {
623 ...transcript,
624 entries: [
625 ...transcript.entries.slice(0, -4),
626 labelled(
627 event("session.execution.succeeded", { sessionID: SESSION }),
628 FIRST_TURN_END,
629 ),
630 ...transcript.entries.slice(-4),
631 ],
632 },
633 commands: [thread.create, first, second, third, cancel],
634 steps,
635 },
636 OpenCode2OrchestratorReplayHarness,
637 ).pipe(provideDeterministicTestRuntime);
638 const projection = result.projections.get(thread.threadId);
639 assert.isDefined(projection);
640 assert.deepEqual(
641 projection.runs.map((candidate) => candidate.status),
642 ["completed", "cancelled", "completed"],
643 );
644 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
645 );
646
647 const backgroundReconnect = Effect.fn("backgroundReconnect")(function* (input: {
648 readonly name: string;
649 readonly cut: string;
650 readonly hold?: string;
651 readonly reconnect: (parent: string) => ReadonlyArray<ProviderReplayEntry>;
652 readonly steps: (
653 thread: ReturnType<typeof threadCommands>,
654 run: (ordinal: number) => OrchestrationV2Run["id"],
655 ) => ReadonlyArray<OrchestratorV2ScenarioStep>;
656 readonly commands: (
657 thread: ReturnType<typeof threadCommands>,
658 ) => ReadonlyArray<OrchestrationV2Command>;
659 }) {
660 const cwd = yield* checkpointWorkspace(input.name);
661 const recorded = yield* readProviderReplayTranscript(
662 new URL(
663 "./testkit/fixtures/opencode2_background/opencode_transcript.ndjson",
664 import.meta.url,
665 ),
666 );
667 const cut = recorded.entries.findIndex(
668 (entry) => entry.type !== "runtime_exit" && entry.label === input.cut,
669 );
670 assert.isAtLeast(cut, 0);
671 const kept = recorded.entries
672 .slice(0, cut)
673 .map((entry) =>
674 entry.type !== "runtime_exit" && entry.label === input.hold
675 ? labelled(entry, BACKGROUND_HOLD)
676 : entry,
677 );
678 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
679 ...recorded,
680 scenario: input.name,
681 entries: [
682 ...kept,
683 { type: "runtime_exit", status: "success" },
684 ...input.reconnect(BACKGROUND_PARENT),
685 ],
686 });
687 const thread = threadCommands({ name: input.name, worktreePath: cwd });
688 const ids = yield* IdAllocator.IdAllocatorV2;
689 const run = (ordinal: number) => ids.derive.run({ threadId: thread.threadId, ordinal });
690 const result = yield* runOrchestratorV2ProviderReplayScenario(
691 {
692 name: input.name,
693 transcript,
694 commands: input.commands(thread),
695 steps: input.steps(thread, run),
696 },
697 OpenCode2OrchestratorReplayHarness,
698
699 { runContinuationWorker: true },
700 ).pipe(provideDeterministicTestRuntime);
701 const projection = result.projections.get(thread.threadId);
702 assert.isDefined(projection);
703 return { result, projection };
704 });
705
706 it.effect("backfills a follow-up whose stream dropped mid-run and ends it completed", () =>
707 Effect.gen(function* () {
708 const { result, projection } = yield* backgroundReconnect({
709 name: "opencode2-follow-up-reconnect",
710
711 cut: "session.step.streamed.5",
712 hold: "session.text.ended.3",
713 reconnect: (parent) => [
714 out("event.subscribe"),
715 out("session.active"),
716 reply("session.active", { data: {} }),
717
718 out("message.list", { sessionID: parent, order: "desc", limit: "50" }),
719 reply("message.list", {
720 data: [
721 {
722 id: "msg_0eb7a99c0001idleFollowUp00",
723 time: { created: 5 },
724 type: "idle",
725 outcome: "succeeded",
726 },
727 {
728 id: "msg_0eb7a96bb00170K1f1HJUeBNwF",
729 time: { created: 4 },
730 type: "assistant",
731 agent: "build",
732 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
733 content: [
734 {
735 type: "text",
736 text: "The background subagent finished and returned `CHILD_OK`.",
737 },
738 ],
739 finish: "stop",
740 },
741 {
742 id: "msg_0eb7a3aee0015KmTB8XkMDW8iy",
743 time: { created: 3 },
744 type: "synthetic",
745 text: "<subagent>CHILD_OK</subagent>",
746 },
747 {
748 id: "msg_0eb7a3e3c001idleParentTurn0",
749 time: { created: 2 },
750 type: "idle",
751 outcome: "succeeded",
752 },
753 ],
754 cursor: {},
755 }),
756 ],
757 commands: (thread) => [
758 thread.create,
759 thread.message("start", bigPickle, BACKGROUND_PROMPT),
760 ],
761 steps: (thread, run) => [
762 { type: "dispatch", command: thread.create },
763 { type: "advance_clock", duration: "1 millis" },
764
765 {
766 type: "dispatch",
767 command: thread.message("start", bigPickle, BACKGROUND_PROMPT),
768 await: false,
769 key: "start",
770 },
771 { type: "advance_clock", duration: "1 millis" },
772
773 { type: "await_run_steerable", threadId: thread.threadId, runId: run(2) },
774 { type: "release_replay_gate", label: BACKGROUND_HOLD },
775 {
776 type: "await_run_status",
777 threadId: thread.threadId,
778 runId: run(2),
779 status: "completed",
780 },
781 { type: "await", key: "start" },
782 { type: "await_thread_idle", threadId: thread.threadId },
783 ],
784 });
785 assert.deepEqual(
786 projection.runs.map((candidate) => candidate.status),
787 ["completed", "completed"],
788 );
789 const followUp = projection.runs[1];
790 assert.deepEqual(
791 projection.turnItems.flatMap((item) =>
792 item.runId === followUp?.id && item.type === "assistant_message" ? [item.text] : [],
793 ),
794 ["The background subagent finished and returned `CHILD_OK`."],
795 );
796 const shell = result.shellSnapshot.threads.find((row) => row.id === projection.thread.id);
797 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
798 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
799 );
800
801 it.effect(
802 "settles a background subagent whose end was lost with the stream, and takes the next turn",
803 () =>
804 Effect.gen(function* () {
805 const { result, projection } = yield* backgroundReconnect({
806 name: "opencode2-background-lost",
807
808 cut: "session.step.started.3",
809 reconnect: (parent) => [
810 out("event.subscribe"),
811
812 out("session.active"),
813 reply("session.active", { data: {} }),
814
815 out("message.list", { sessionID: BACKGROUND_CHILD, order: "desc", limit: "50" }),
816 reply("message.list", {
817 data: [
818 {
819 id: "msg_0eb7a99b0001idleChildTurn0",
820 time: { created: 4 },
821 type: "idle",
822 outcome: "succeeded",
823 },
824 {
825 id: "msg_0eb7a916c001NRJQJ5gwIT0QnU",
826 time: { created: 3 },
827 type: "assistant",
828 agent: "general",
829 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
830 content: [{ type: "text", text: "CHILD_OK" }],
831 finish: "stop",
832 },
833 {
834 id: "msg_0eb7a3aea001Lw1Pav5d4akfEg",
835 time: { created: 2 },
836 type: "user",
837 text: "Run the shell command `sleep 20` with the bash tool and then reply exactly CHILD_OK.",
838 },
839 ],
840 cursor: {},
841 }),
842 out("session.prompt", { sessionID: parent, id: "<any>", text: "<any>" }),
843 reply("session.prompt", {
844 data: {
845 id: "msg_next",
846 sessionID: parent,
847 time: { created: 9 },
848 type: "user",
849 payload: { text: "<prompt>" },
850 delivery: "steer",
851 },
852 }),
853 event("session.execution.started", { sessionID: parent }),
854 event("session.text.ended", {
855 sessionID: parent,
856 assistantMessageID: "msg_next_reply",
857 ordinal: 0,
858 text: "NEXT",
859 }),
860 event("session.execution.succeeded", { sessionID: parent }),
861 ],
862 commands: (thread) => [
863 thread.create,
864 thread.message("start", bigPickle, BACKGROUND_PROMPT),
865 thread.message("next"),
866 ],
867 steps: (thread, run) => [
868 { type: "dispatch", command: thread.create },
869 { type: "advance_clock", duration: "1 millis" },
870 { type: "dispatch", command: thread.message("start", bigPickle, BACKGROUND_PROMPT) },
871 { type: "advance_clock", duration: "1 millis" },
872 { type: "await_thread_idle", threadId: thread.threadId },
873 { type: "dispatch", command: thread.message("next") },
874 { type: "advance_clock", duration: "1 millis" },
875 {
876 type: "await_run_status",
877 threadId: thread.threadId,
878 runId: run(2),
879 status: "completed",
880 },
881 { type: "await_thread_idle", threadId: thread.threadId },
882 ],
883 });
884
885 assert.deepEqual(
886 projection.runs.map((candidate) => candidate.status),
887 ["completed", "completed"],
888 );
889 assert.lengthOf(projection.subagents, 1);
890 assert.deepInclude(projection.subagents[0], { status: "interrupted" });
891 assert.include(projection.subagents[0]?.result ?? "", "lost its connection to OpenCode");
892 assert.isFalse(
893 projection.turnItems.some(
894 (item) => item.status === "running" || item.status === "waiting",
895 ),
896 );
897 const shell = result.shellSnapshot.threads.find((row) => row.id === projection.thread.id);
898 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
899 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
900 );
901
902 it.effect(
903 "settles a background subagent whose report OpenCode delivers into the launching turn",
904 () =>
905 Effect.gen(function* () {
906 // OpenCode 2.0.18 can deliver a child report into the parent's still-running execution, which then answers it.
907
908 const cwd = yield* checkpointWorkspace("opencode2-background-in-turn");
909 const recorded = yield* readProviderReplayTranscript(
910 new URL(
911 "./testkit/fixtures/opencode2_background/opencode_transcript.ndjson",
912 import.meta.url,
913 ),
914 );
915 const byLabel = (label: string) => {
916 const entry = recorded.entries.find(
917 (candidate) => candidate.type !== "runtime_exit" && candidate.label === label,
918 );
919 assert.isDefined(entry);
920 return entry!;
921 };
922 const parentEnd = recorded.entries.findIndex(
923 (entry) => entry.type !== "runtime_exit" && entry.label === "session.execution.succeeded",
924 );
925 const childStart = recorded.entries.findIndex(
926 (entry) => entry.type !== "runtime_exit" && entry.label === "session.step.started.3",
927 );
928 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
929 ...recorded,
930 scenario: "opencode2-background-in-turn",
931 entries: [
932 ...recorded.entries.slice(0, parentEnd),
933
934 ...recorded.entries.slice(
935 childStart,
936 recorded.entries.indexOf(byLabel("session.inbox.enqueued.3")),
937 ),
938
939 byLabel("session.inbox.enqueued.3"),
940 byLabel("session.inbox.delivered.3"),
941
942 byLabel("session.text.ended.3"),
943 byLabel("session.execution.succeeded.3"),
944 ],
945 });
946 const thread = threadCommands({ name: "opencode2-background-in-turn", worktreePath: cwd });
947 const ids = yield* IdAllocator.IdAllocatorV2;
948 const result = yield* runOrchestratorV2ProviderReplayScenario(
949 {
950 name: "opencode2-background-in-turn",
951 transcript,
952 commands: [thread.create, thread.message("start", bigPickle, BACKGROUND_PROMPT)],
953 steps: [
954 { type: "dispatch", command: thread.create },
955 { type: "advance_clock", duration: "1 millis" },
956 { type: "dispatch", command: thread.message("start", bigPickle, BACKGROUND_PROMPT) },
957 { type: "advance_clock", duration: "1 millis" },
958 {
959 type: "await_run_status",
960 threadId: thread.threadId,
961 runId: ids.derive.run({ threadId: thread.threadId, ordinal: 1 }),
962 status: "completed",
963 },
964 { type: "await_thread_idle", threadId: thread.threadId },
965 ],
966 },
967 OpenCode2OrchestratorReplayHarness,
968 { runContinuationWorker: true },
969 ).pipe(provideDeterministicTestRuntime);
970 const projection = result.projections.get(thread.threadId);
971 assert.isDefined(projection);
972
973 assert.deepEqual(
974 projection!.runs.map((candidate) => candidate.status),
975 ["completed"],
976 );
977 assert.lengthOf(projection!.subagents, 1);
978 assert.deepInclude(projection!.subagents[0], { status: "completed" });
979 assert.include(projection!.subagents[0]?.result ?? "", "CHILD_OK");
980 assert.isTrue(
981 projection!.turnItems.some(
982 (item) =>
983 item.type === "assistant_message" && item.text.includes("finished and returned"),
984 ),
985 );
986 assert.isFalse(
987 projection!.turnItems.some(
988 (item) => item.status === "running" || item.status === "waiting",
989 ),
990 );
991 const shell = result.shellSnapshot.threads.find((row) => row.id === projection!.thread.id);
992 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
993 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
994 );
995});