Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCode2OrchestratorV2.integration.test.ts

1,183 lines47.0 KB

1/**
2 * OpenCode 2 through the whole orchestrator, against a replayed HTTP server:
3 * the transcript fixes the order of every request the adapter sends, so a
4 * request the orchestrator never lets it make fails the run.
5 */
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { assert, describe, it } from "@effect/vitest";
8import {
9 CommandId,
10 MessageId,
11 type ModelSelection,
12 type OrchestrationV2Command,
13 type OrchestrationV2Run,
14 ProjectId,
15 type ProviderInteractionMode,
16 ProviderInstanceId,
17 type ProviderReplayEntry,
18 type RuntimeMode,
19 ThreadId,
20} from "@t3tools/contracts";
21import * as Effect from "effect/Effect";
22import * as Layer from "effect/Layer";
23import * as FileSystem from "effect/FileSystem";
24import * as Path from "effect/Path";
25​
26import {
27 OPENCODE2_HTTP_PROTOCOL,
28 OpenCode2OrchestratorReplayHarness,
29} from "./Adapters/OpenCode2AdapterV2.testkit.ts";
30import { OPENCODE_PROVIDER } from "./Adapters/OpenCodeAdapterV2.ts";
31import { provideDeterministicTestRuntime } from "./testkit/DeterministicRuntime.ts";
32import type { OrchestratorV2ScenarioStep } from "./testkit/OrchestratorScenario.ts";
33import { runOrchestratorV2ProviderReplayScenario } from "./testkit/ProviderReplayHarness.ts";
34import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
35import {
36 decodeProviderReplayNdjson,
37 readProviderReplayTranscript,
38} from "./testkit/ReplayTranscriptNdjson.ts";
39import * as IdAllocator from "./IdAllocator.ts";
40​
41const SESSION = "ses_f148ca2deffeJcwCnRQtb0YFNX";
42/** Held until the scenario releases it, so the turn is still running meanwhile. */
43const FIRST_TURN_END = "first-turn-end";
44/** Held until the scenario releases it, so a follow-up is running when its stream drops. */
45const BACKGROUND_HOLD = "background-hold";
46/** The parent session of the recorded background run. */
47const BACKGROUND_PARENT = "ses_f1485cda4ffeXuc6GjAU9vDiRb";
48/** Its background subagent's session. */
49const BACKGROUND_CHILD = "ses_f1485c529ffea4URrYruwEg0Ja";
50const BACKGROUND_PROMPT =
51 "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.";
52const instanceId = ProviderInstanceId.make("opencode");
53const bigPickle: ModelSelection = { instanceId, model: "opencode/big-pickle" };
54const mimo: ModelSelection = { instanceId, model: "opencode/mimo-v2.6-flash-free" };
55const nemotron: ModelSelection = { instanceId, model: "opencode/nemotron-3.5-lightning-free" };
56​
57const out = (type: string, input?: unknown): ProviderReplayEntry => ({
58 type: "expect_outbound",
59 frame: input === undefined ? { type } : { type, input },
60});
61const reply = (operation: string, data: unknown): ProviderReplayEntry => ({
62 type: "emit_inbound",
63 frame: { type: "sdk.response", operation, data },
64});
65const event = (type: string, data: Record<string, unknown>): ProviderReplayEntry => ({
66 type: "emit_inbound",
67 frame: {
68 type: "sdk.event",
69 event: { id: `evt_${type.replaceAll(".", "")}`, created: 1, type, data },
70 },
71});
72const labelled = (entry: ProviderReplayEntry, label: string): ProviderReplayEntry =>
73 entry.type === "runtime_exit" ? entry : { ...entry, label };
74/**
75 * T3's own rules after a mode's: every thread's T3 MCP server is denied, and
76 * then this thread's own is allowed again (last match wins).
77 */
78const mcpRules = (name: string) => [
79 { action: "t3-code-*", resource: "*", effect: "deny" },
80 { action: `t3-code-thread_${name}_*`, resource: "*", effect: "allow" },
81];
82const FULL_ACCESS = [{ action: "*", resource: "*", effect: "allow" }];
83/** Full access for the thread named `name`. */
84const t3Rules = (name: string) => [...FULL_ACCESS, ...mcpRules(name)];
85/** Paths the build and plan agents allow for themselves, as 2.0.18 lists them. */
86const BUILD_PATHS = [
87 {
88 action: "external_directory",
89 resource: "/home/.local/share/opencode/tool-output/*",
90 effect: "allow",
91 },
92];
93const PLAN_PATHS = [
94 ...BUILD_PATHS,
95 { action: "edit", resource: "/home/.opencode/plan/*", effect: "allow" },
96 { action: "external_directory", resource: "/home/.opencode/plan/*", effect: "allow" },
97];
98const agentInfo = (id: string, description: string, permissions: ReadonlyArray<unknown>) => ({
99 id,
100 name: id === "plan" ? "Plan" : "Build",
101 request: { settings: {}, headers: {}, body: {} },
102 description,
103 mode: "primary",
104 hidden: false,
105 permissions,
106});
107/** `/api/agent` trimmed to the two agents a T3 session runs. */
108const agentList = (directory: string) => ({
109 location: { directory },
110 data: [
111 agentInfo("build", "The default agent.", [
112 { action: "*", resource: "*", effect: "allow" },
113 { action: "external_directory", resource: "*", effect: "ask" },
114 ...BUILD_PATHS,
115 ]),
116 agentInfo("plan", "Read-only agent for planning.", [
117 { action: "*", resource: "*", effect: "allow" },
118 { action: "external_directory", resource: "*", effect: "ask" },
119 ...BUILD_PATHS,
120 { action: "edit", resource: "*", effect: "deny" },
121 ...PLAN_PATHS.slice(BUILD_PATHS.length),
122 ]),
123 ],
124});
125/** A session this runtime loads again (after a detach) waits on nothing. */
126const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
127 out("permission.list", { sessionID: SESSION }),
128 reply("permission.list", { data: [] }),
129 out("session.form.list", { sessionID: SESSION }),
130 reply("session.form.list", { data: [] }),
131];
132const supervisedRules = (name: string) => [
133 { action: "shell", resource: "*", effect: "ask" },
134 { action: "edit", resource: "*", effect: "ask" },
135 { action: "external_directory", resource: "*", effect: "ask" },
136 ...BUILD_PATHS,
137 ...mcpRules(name),
138];
139const autoEditRules = (name: string) => [
140 { action: "shell", resource: "*", effect: "ask" },
141 { action: "edit", resource: "*", effect: "allow" },
142 { action: "external_directory", resource: "*", effect: "ask" },
143 ...BUILD_PATHS,
144 ...mcpRules(name),
145];
146/** Plan mode on Full access: edits are denied except the plan agent's own plan files. */
147const planRules = (name: string) => [
148 { action: "*", resource: "*", effect: "allow" },
149 { action: "edit", resource: "*", effect: "deny" },
150 ...PLAN_PATHS,
151 ...mcpRules(name),
152];
153​
154const sessionInfo = (directory: string, permissions: ReadonlyArray<unknown>) => ({
155 data: {
156 id: SESSION,
157 projectID: "global",
158 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
159 cost: 0,
160 tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
161 time: { created: 1790656601394, updated: 1790656601394 },
162 location: { directory },
163 permissions,
164 },
165});
166/** T3's instructions entry, written before a thread's first prompt and whenever it changes. */
167const instructionsWritten: ReadonlyArray<ProviderReplayEntry> = [
168 out("session.instructions.entry.put", { sessionID: SESSION, key: "t3-code", value: "<any>" }),
169 reply("session.instructions.entry.put", null),
170];
171/** One prompt the server accepts and answers with `text`. */
172const answeredPrompt = (text: string): ReadonlyArray<ProviderReplayEntry> => [
173 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
174 reply("session.prompt", {
175 data: {
176 id: `msg_user_${text}`,
177 sessionID: SESSION,
178 time: { created: 1790656601410 },
179 type: "user",
180 payload: { text: "<prompt>" },
181 delivery: "steer",
182 },
183 }),
184 event("session.text.ended", {
185 sessionID: SESSION,
186 assistantMessageID: `msg_assistant_${text}`,
187 ordinal: 0,
188 text,
189 }),
190 event("session.execution.succeeded", { sessionID: SESSION }),
191];
192/** The model list read the first time a thread runs in `directory`. */
193const directoryModels = (directory: string): ReadonlyArray<ProviderReplayEntry> => [
194 out("model.list", { "location[directory]": directory }),
195 reply("model.list", {
196 location: { directory },
197 data: [
198 catalogModel("big-pickle", "Big Pickle"),
199 catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
200 ],
201 }),
202];
203/** A `/api/model` entry as 2.0.18 lists it; a known window means no re-read after a turn. */
204const catalogModel = (id: string, name: string) => ({
205 id,
206 modelID: id,
207 providerID: "opencode",
208 family: id,
209 name,
210 compatibility: { reasoningField: "reasoning_content" },
211 package: "@opencode/ai/providers/openai-compatible",
212 settings: { apiKey: "public", baseURL: "https://opencode.ai/zen/v1", provider: "opencode" },
213 capabilities: { tools: true, input: ["text"], output: ["text"] },
214 variants: [],
215 time: { released: 1760659200000 },
216 cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
217 status: "active",
218 enabled: true,
219 limit: { context: 200000, input: 160000, output: 32000 },
220});
221const createdSession = (
222 directory: string,
223 name: string,
224 permissions: ReadonlyArray<unknown> = t3Rules(name),
225 // Only a mode that narrows Full access reads the agents' own path rules.
226 narrows = false,
227): ReadonlyArray<ProviderReplayEntry> => [
228 out("event.subscribe"),
229 out("model.list", "<any>"),
230 reply("model.list", {
231 location: { directory },
232 data: [
233 catalogModel("big-pickle", "Big Pickle"),
234 catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
235 ],
236 }),
237 ...(narrows ? [out("agent.list", "<any>"), reply("agent.list", agentList(directory))] : []),
238 out("session.create", { location: { directory }, model: "<any>", permissions }),
239 reply("session.create", sessionInfo(directory, permissions)),
240];
241​
242/** A recording with its scrubbed `<work>` directory replaced by `directory`. */
243const withDirectory = <T>(value: T, directory: string): T => {
244 const replace = (entry: unknown): unknown =>
245 entry === "<work>"
246 ? directory
247 : Array.isArray(entry)
248 ? entry.map(replace)
249 : typeof entry === "object" && entry !== null
250 ? Object.fromEntries(Object.entries(entry).map(([key, inner]) => [key, replace(inner)]))
251 : entry;
252 return replace(value) as T;
253};
254​
255const threadCommands = (input: {
256 readonly name: string;
257 readonly worktreePath: string;
258 readonly runtimeMode?: RuntimeMode;
259 readonly interactionMode?: ProviderInteractionMode;
260}) => {
261 const threadId = ThreadId.make(`thread:${input.name}`);
262 const command = (key: string) => CommandId.make(`command:${input.name}:${key}`);
263 return {
264 threadId,
265 create: {
266 type: "thread.create",
267 createdBy: "user",
268 creationSource: "web",
269 commandId: command("create"),
270 threadId,
271 projectId: ProjectId.make(`project:${input.name}`),
272 title: input.name,
273 modelSelection: bigPickle,
274 runtimeMode: input.runtimeMode ?? "full-access",
275 interactionMode: input.interactionMode ?? "default",
276 branch: null,
277 worktreePath: input.worktreePath,
278 } satisfies OrchestrationV2Command,
279 message: (key: string, modelSelection: ModelSelection = bigPickle, text?: string) =>
280 ({
281 type: "message.dispatch",
282 createdBy: "user",
283 creationSource: "web",
284 commandId: command(key),
285 threadId,
286 messageId: MessageId.make(`message:${input.name}:${key}`),
287 text: text ?? `Reply with exactly: ${key}`,
288 attachments: [],
289 modelSelection,
290 dispatchMode: { type: "start_immediately" },
291 }) satisfies OrchestrationV2Command,
292 interactionMode: (key: string, interactionMode: "default" | "plan") =>
293 ({
294 type: "thread.interaction-mode.set",
295 commandId: command(key),
296 threadId,
297 interactionMode,
298 }) satisfies OrchestrationV2Command,
299 command,
300 };
301};
302​
303/** Runs `commands` in order, letting the thread go idle after each message. */
304const runScenario = (input: {
305 readonly name: string;
306 readonly threadId: ThreadId;
307 readonly entries: ReadonlyArray<ProviderReplayEntry>;
308 readonly commands: ReadonlyArray<OrchestrationV2Command>;
309}) =>
310 Effect.gen(function* () {
311 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
312 provider: OPENCODE_PROVIDER,
313 protocol: OPENCODE2_HTTP_PROTOCOL,
314 version: "2.0.18",
315 scenario: input.name,
316 entries: input.entries,
317 });
318 const steps = input.commands.flatMap((command): Array<OrchestratorV2ScenarioStep> => [
319 { type: "dispatch", command },
320 { type: "advance_clock", duration: "1 millis" },
321 ...(command.type === "message.dispatch"
322 ? [{ type: "await_thread_idle" as const, threadId: input.threadId }]
323 : []),
324 ]);
325 const result = yield* runOrchestratorV2ProviderReplayScenario(
326 { name: input.name, transcript, commands: input.commands, steps },
327 OpenCode2OrchestratorReplayHarness,
328 ).pipe(provideDeterministicTestRuntime);
329 const projection = result.projections.get(input.threadId);
330 assert.isDefined(projection);
331 return projection;
332 });
333​
334describe("OpenCode 2 through the orchestrator", () => {
335 for (const via of ["message", "thread settings"] as const) {
336 it.effect(
337 `switches the session's model before the next prompt when changed from the ${via}`,
338 () =>
339 Effect.gen(function* () {
340 const name = `opencode2-model-switch-${via.replace(" ", "-")}`;
341 const cwd = yield* checkpointWorkspace(name);
342 const thread = threadCommands({ name, worktreePath: cwd });
343 const projection = yield* runScenario({
344 name,
345 threadId: thread.threadId,
346 entries: [
347 ...createdSession(cwd, name),
348 ...instructionsWritten,
349 ...answeredPrompt("FIRST"),
350 // The next turn resumes the session at its new selection.
351 out("session.get", { sessionID: SESSION }),
352 reply("session.get", sessionInfo(cwd, t3Rules(name))),
353 out("session.switchModel", {
354 sessionID: SESSION,
355 model: { providerID: "opencode", id: "mimo-v2.6-flash-free" },
356 }),
357 reply("session.switchModel", null),
358 // The instructions name the model, so they are written again.
359 ...instructionsWritten,
360 ...answeredPrompt("SECOND"),
361 ],
362 commands: [
363 thread.create,
364 thread.message("first"),
365 ...(via === "thread settings"
366 ? [
367 {
368 type: "thread.model-selection.set",
369 commandId: thread.command("model"),
370 threadId: thread.threadId,
371 modelSelection: mimo,
372 } satisfies OrchestrationV2Command,
373 ]
374 : []),
375 thread.message("second", mimo),
376 ],
377 });
378 assert.deepEqual(
379 projection.runs.map((run) => [run.status, run.modelSelection.model]),
380 [
381 ["completed", bigPickle.model],
382 ["completed", mimo.model],
383 ],
384 );
385 // One native session carried both turns.
386 assert.lengthOf(projection.providerThreads, 1);
387 }).pipe(Effect.scoped),
388 );
389 }
390​
391 it.effect("moves the session to the thread's new worktree before the next prompt", () =>
392 Effect.gen(function* () {
393 const name = "opencode2-worktree-move";
394 const before = yield* checkpointWorkspace(`${name}-before`);
395 const after = yield* checkpointWorkspace(`${name}-after`);
396 const thread = threadCommands({ name, worktreePath: before });
397 const projection = yield* runScenario({
398 name,
399 threadId: thread.threadId,
400 entries: [
401 ...createdSession(before, name),
402 ...instructionsWritten,
403 ...answeredPrompt("FIRST"),
404 ...directoryModels(after),
405 out("session.get", { sessionID: SESSION }),
406 reply("session.get", sessionInfo(before, t3Rules(name))),
407 // The worktree change detached the thread, so its session is loaded afresh.
408 ...noOpenRequests,
409 out("session.move", { sessionID: SESSION, directory: after }),
410 reply("session.move", null),
411 // The moved thread reopens its session, which writes the entry again.
412 ...instructionsWritten,
413 ...answeredPrompt("SECOND"),
414 ],
415 commands: [
416 thread.create,
417 thread.message("first"),
418 {
419 type: "thread.metadata.update",
420 commandId: thread.command("worktree"),
421 threadId: thread.threadId,
422 worktreePath: after,
423 },
424 thread.message("second"),
425 ],
426 });
427 assert.deepEqual(
428 projection.runs.map((run) => run.status),
429 ["completed", "completed"],
430 );
431 assert.lengthOf(projection.providerThreads, 1);
432 }).pipe(Effect.scoped),
433 );
434​
435 it.effect("gives a session made with older rules T3's rules before its next prompt", () =>
436 Effect.gen(function* () {
437 const name = "opencode2-resume-rules";
438 const before = yield* checkpointWorkspace(`${name}-before`);
439 const after = yield* checkpointWorkspace(`${name}-after`);
440 const thread = threadCommands({ name, worktreePath: before });
441 const projection = yield* runScenario({
442 name,
443 threadId: thread.threadId,
444 entries: [
445 ...createdSession(before, name),
446 ...instructionsWritten,
447 ...answeredPrompt("FIRST"),
448 ...directoryModels(after),
449 // Reopened after a worktree change, the session reports the rules an
450 // older build gave it, which denied subagents; they are replaced
451 // before anything runs.
452 out("session.get", { sessionID: SESSION }),
453 reply(
454 "session.get",
455 sessionInfo(before, [
456 { action: "*", resource: "*", effect: "allow" },
457 { action: "subagent", resource: "*", effect: "deny" },
458 ]),
459 ),
460 ...noOpenRequests,
461 out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
462 reply("session.update", null),
463 out("session.move", { sessionID: SESSION, directory: after }),
464 reply("session.move", null),
465 ...instructionsWritten,
466 ...answeredPrompt("SECOND"),
467 ],
468 commands: [
469 thread.create,
470 thread.message("first"),
471 {
472 type: "thread.metadata.update",
473 commandId: thread.command("worktree"),
474 threadId: thread.threadId,
475 worktreePath: after,
476 },
477 thread.message("second"),
478 ],
479 });
480 assert.deepEqual(
481 projection.runs.map((run) => run.status),
482 ["completed", "completed"],
483 );
484 }).pipe(Effect.scoped),
485 );
486​
487 it.effect(
488 "creates a Supervised thread's session with rules that ask before shell and edits",
489 () =>
490 Effect.gen(function* () {
491 const name = "opencode2-supervised-rules";
492 const cwd = yield* checkpointWorkspace(name);
493 const thread = threadCommands({
494 name,
495 worktreePath: cwd,
496 runtimeMode: "approval-required",
497 });
498 const projection = yield* runScenario({
499 name,
500 threadId: thread.threadId,
501 entries: [
502 ...createdSession(cwd, name, supervisedRules(name), true),
503 ...instructionsWritten,
504 ...answeredPrompt("FIRST"),
505 ],
506 commands: [thread.create, thread.message("first")],
507 });
508 assert.deepEqual(
509 projection.runs.map((run) => run.status),
510 ["completed"],
511 );
512 }).pipe(Effect.scoped),
513 );
514​
515 it.effect("rewrites the session's rules when the thread's mode changes between turns", () =>
516 Effect.gen(function* () {
517 const name = "opencode2-mode-change";
518 const cwd = yield* checkpointWorkspace(name);
519 const thread = threadCommands({ name, worktreePath: cwd });
520 const setMode = (key: string, runtimeMode: RuntimeMode) =>
521 ({
522 type: "thread.runtime-mode.set",
523 commandId: thread.command(key),
524 threadId: thread.threadId,
525 runtimeMode,
526 }) satisfies OrchestrationV2Command;
527 const projection = yield* runScenario({
528 name,
529 threadId: thread.threadId,
530 entries: [
531 ...createdSession(cwd, name),
532 ...instructionsWritten,
533 ...answeredPrompt("FIRST"),
534 // A mode change detaches nothing: the same session is resumed with the new rules.
535 out("session.get", { sessionID: SESSION }),
536 reply("session.get", sessionInfo(cwd, t3Rules(name))),
537 out("agent.list", "<any>"),
538 reply("agent.list", agentList(cwd)),
539 out("session.update", { sessionID: SESSION, permissions: autoEditRules(name) }),
540 reply("session.update", null),
541 ...answeredPrompt("SECOND"),
542 // Back to Full access: the narrowing rules go.
543 out("session.get", { sessionID: SESSION }),
544 reply("session.get", sessionInfo(cwd, autoEditRules(name))),
545 out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
546 reply("session.update", null),
547 ...answeredPrompt("THIRD"),
548 ],
549 commands: [
550 thread.create,
551 thread.message("first"),
552 setMode("auto-edit", "auto-accept-edits"),
553 thread.message("second"),
554 setMode("full", "full-access"),
555 thread.message("third"),
556 ],
557 });
558 assert.deepEqual(
559 projection.runs.map((run) => run.status),
560 ["completed", "completed", "completed"],
561 );
562 assert.lengthOf(projection.providerThreads, 1);
563 }).pipe(Effect.scoped),
564 );
565​
566 it.effect("denies edits outside the plan directory in plan mode and lifts it after", () =>
567 Effect.gen(function* () {
568 const name = "opencode2-plan-rules";
569 const cwd = yield* checkpointWorkspace(name);
570 const thread = threadCommands({ name, worktreePath: cwd, interactionMode: "plan" });
571 const projection = yield* runScenario({
572 name,
573 threadId: thread.threadId,
574 entries: [
575 ...createdSession(cwd, name, planRules(name), true),
576 // Plan mode is also OpenCode's plan agent, switched before the prompt.
577 out("session.switchAgent", { sessionID: SESSION, agent: "plan" }),
578 reply("session.switchAgent", null),
579 ...instructionsWritten,
580 ...answeredPrompt("PLANNED"),
581 out("session.get", { sessionID: SESSION }),
582 reply("session.get", sessionInfo(cwd, planRules(name))),
583 out("session.update", { sessionID: SESSION, permissions: t3Rules(name) }),
584 reply("session.update", null),
585 out("session.switchAgent", { sessionID: SESSION, agent: "build" }),
586 reply("session.switchAgent", null),
587 ...answeredPrompt("BUILT"),
588 ],
589 commands: [
590 thread.create,
591 thread.message("plan"),
592 {
593 type: "thread.interaction-mode.set",
594 commandId: thread.command("default"),
595 threadId: thread.threadId,
596 interactionMode: "default",
597 },
598 thread.message("build"),
599 ],
600 });
601 assert.deepEqual(
602 projection.runs.map((run) => run.status),
603 ["completed", "completed"],
604 );
605 }).pipe(Effect.scoped),
606 );
607​
608 it.effect("forks from an earlier turn before the next turn's user message", () =>
609 Effect.gen(function* () {
610 const name = "opencode2-fork";
611 const cwd = yield* checkpointWorkspace(name);
612 const recorded = yield* readProviderReplayTranscript(
613 new URL("./testkit/fixtures/opencode2_fork/opencode_transcript.ndjson", import.meta.url),
614 );
615 // The recording scrubbed its directory to `<work>`; the fork it answers
616 // runs where its source does, which is this test's workspace.
617 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript(
618 withDirectory(recorded, cwd),
619 );
620 const source = threadCommands({ name, worktreePath: cwd });
621 const target = ThreadId.make(`thread:${name}:target`);
622 const [one, two] = [source.message("one"), source.message("two")];
623 const commands: ReadonlyArray<OrchestrationV2Command> = [
624 source.create,
625 one,
626 two,
627 {
628 type: "thread.fork",
629 createdBy: "user",
630 creationSource: "web",
631 commandId: source.command("fork"),
632 sourceThreadId: source.threadId,
633 targetThreadId: target,
634 sourcePoint: {
635 type: "run",
636 runId: (yield* IdAllocator.IdAllocatorV2).derive.run({
637 threadId: source.threadId,
638 ordinal: 1,
639 }),
640 },
641 },
642 {
643 ...source.message("repeat"),
644 threadId: target,
645 messageId: MessageId.make(`message:${name}:repeat`),
646 },
647 ];
648 const steps: Array<OrchestratorV2ScenarioStep> = commands.flatMap((command) => [
649 { type: "dispatch" as const, command },
650 { type: "advance_clock" as const, duration: "1 millis" as const },
651 ...(command.type === "message.dispatch"
652 ? [{ type: "await_thread_idle" as const, threadId: command.threadId }]
653 : []),
654 ]);
655 const result = yield* runOrchestratorV2ProviderReplayScenario(
656 { name, transcript, commands, steps, projectionThreadIds: [source.threadId, target] },
657 OpenCode2OrchestratorReplayHarness,
658 ).pipe(provideDeterministicTestRuntime);
659 const forked = result.projections.get(target);
660 assert.isDefined(forked);
661 assert.equal(forked.contextTransfers[0]?.resolution?.strategy, "native_fork");
662 assert.equal(
663 forked.providerThreads[0]?.nativeThreadRef?.nativeId,
664 recorded.metadata?.["forkedNativeSessionId"],
665 );
666 // The fork keeps the first turn and drops the second: the model answers
667 // from the first alone, and T3 shows the inherited turn but not the other.
668 assert.deepEqual(
669 forked.runs.map((run) => run.status),
670 ["completed"],
671 );
672 const visible = forked.visibleTurnItems.flatMap((row) =>
673 row.item.type === "assistant_message" ? [row.item.text] : [],
674 );
675 assert.deepEqual(visible, ["ONE", "ONE"]);
676 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
677 );
678​
679 it.effect("never sends OpenCode a queued message that was cancelled", () =>
680 Effect.gen(function* () {
681 const name = "opencode2-queued-cancel";
682 const cwd = yield* checkpointWorkspace(name);
683 const thread = threadCommands({ name, worktreePath: cwd });
684 const queued = (key: string): OrchestrationV2Command => ({
685 ...thread.message(key),
686 dispatchMode: { type: "queue_after_active" },
687 });
688 const ids = yield* IdAllocator.IdAllocatorV2;
689 const run = (ordinal: number) => ids.derive.run({ threadId: thread.threadId, ordinal });
690 // The first turn is held open until the queue has been changed: its end
691 // is the last event, after the cancel.
692 const [first, second, third] = [thread.message("first"), queued("second"), queued("third")];
693 const cancel: OrchestrationV2Command = {
694 type: "queued-run.cancel",
695 commandId: thread.command("cancel"),
696 threadId: thread.threadId,
697 runId: run(2),
698 };
699 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
700 provider: OPENCODE_PROVIDER,
701 protocol: OPENCODE2_HTTP_PROTOCOL,
702 version: "2.0.18",
703 scenario: name,
704 entries: [
705 ...createdSession(cwd, name),
706 ...instructionsWritten,
707 out("session.prompt", { sessionID: SESSION, id: "<any>", text: "<any>" }),
708 reply("session.prompt", {
709 data: {
710 id: "msg_user_FIRST",
711 sessionID: SESSION,
712 time: { created: 1 },
713 type: "user",
714 payload: { text: "<prompt>" },
715 delivery: "steer",
716 },
717 }),
718 // Only the third message reaches OpenCode, as the next turn.
719 ...answeredPrompt("THIRD"),
720 ],
721 });
722 const steps: Array<OrchestratorV2ScenarioStep> = [
723 { type: "dispatch", command: thread.create },
724 { type: "advance_clock", duration: "1 millis" },
725 { type: "dispatch", command: first, await: false, key: "first" },
726 { type: "await_run_steerable", threadId: thread.threadId, runId: run(1) },
727 { type: "dispatch", command: second },
728 { type: "dispatch", command: third },
729 { type: "dispatch", command: cancel },
730 { type: "await_run_status", threadId: thread.threadId, runId: run(2), status: "cancelled" },
731 { type: "release_replay_gate", label: FIRST_TURN_END },
732 { type: "await", key: "first" },
733 { type: "await_thread_idle", threadId: thread.threadId },
734 ];
735 const result = yield* runOrchestratorV2ProviderReplayScenario(
736 {
737 name,
738 transcript: {
739 ...transcript,
740 entries: [
741 ...transcript.entries.slice(0, -4),
742 labelled(
743 event("session.execution.succeeded", { sessionID: SESSION }),
744 FIRST_TURN_END,
745 ),
746 ...transcript.entries.slice(-4),
747 ],
748 },
749 commands: [thread.create, first, second, third, cancel],
750 steps,
751 },
752 OpenCode2OrchestratorReplayHarness,
753 ).pipe(provideDeterministicTestRuntime);
754 const projection = result.projections.get(thread.threadId);
755 assert.isDefined(projection);
756 assert.deepEqual(
757 projection.runs.map((candidate) => candidate.status),
758 ["completed", "cancelled", "completed"],
759 );
760 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
761 );
762​
763 /**
764 * The recorded background run (`opencode2_background`): the parent's turn
765 * ends while its subagent runs, then the subagent's report wakes the parent
766 * and T3 opens a continuation run for that follow-up. `reconnect` replaces
767 * the recording from `cut` on with a stream drop, a restarted stream and
768 * what the server answers then.
769 */
770 const backgroundReconnect = Effect.fn("backgroundReconnect")(function* (input: {
771 readonly name: string;
772 readonly cut: string;
773 readonly hold?: string;
774 readonly reconnect: (parent: string) => ReadonlyArray<ProviderReplayEntry>;
775 readonly steps: (
776 thread: ReturnType<typeof threadCommands>,
777 run: (ordinal: number) => OrchestrationV2Run["id"],
778 ) => ReadonlyArray<OrchestratorV2ScenarioStep>;
779 readonly commands: (
780 thread: ReturnType<typeof threadCommands>,
781 ) => ReadonlyArray<OrchestrationV2Command>;
782 }) {
783 const cwd = yield* checkpointWorkspace(input.name);
784 const recorded = yield* readProviderReplayTranscript(
785 new URL(
786 "./testkit/fixtures/opencode2_background/opencode_transcript.ndjson",
787 import.meta.url,
788 ),
789 );
790 const cut = recorded.entries.findIndex(
791 (entry) => entry.type !== "runtime_exit" && entry.label === input.cut,
792 );
793 assert.isAtLeast(cut, 0);
794 const kept = recorded.entries
795 .slice(0, cut)
796 .map((entry) =>
797 entry.type !== "runtime_exit" && entry.label === input.hold
798 ? labelled(entry, BACKGROUND_HOLD)
799 : entry,
800 );
801 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
802 ...recorded,
803 scenario: input.name,
804 entries: [
805 ...kept,
806 { type: "runtime_exit", status: "success" },
807 ...input.reconnect(BACKGROUND_PARENT),
808 ],
809 });
810 const thread = threadCommands({ name: input.name, worktreePath: cwd });
811 const ids = yield* IdAllocator.IdAllocatorV2;
812 const run = (ordinal: number) => ids.derive.run({ threadId: thread.threadId, ordinal });
813 const result = yield* runOrchestratorV2ProviderReplayScenario(
814 {
815 name: input.name,
816 transcript,
817 commands: input.commands(thread),
818 steps: input.steps(thread, run),
819 },
820 OpenCode2OrchestratorReplayHarness,
821 // Opens the continuation run a follow-up asks for, as the server does.
822 { runContinuationWorker: true },
823 ).pipe(provideDeterministicTestRuntime);
824 const projection = result.projections.get(thread.threadId);
825 assert.isDefined(projection);
826 return { result, projection };
827 });
828​
829 it.effect("backfills a follow-up whose stream dropped mid-run and ends it completed", () =>
830 Effect.gen(function* () {
831 const { result, projection } = yield* backgroundReconnect({
832 name: "opencode2-follow-up-reconnect",
833 // The follow-up streams its reply; then the stream drops before the
834 // execution's end.
835 cut: "session.step.streamed.5",
836 hold: "session.text.ended.3",
837 reconnect: (parent) => [
838 out("event.subscribe"),
839 out("session.active"),
840 reply("session.active", { data: {} }),
841 // The follow-up's history since the report it answers, newest first.
842 out("message.list", { sessionID: parent, order: "desc", limit: "50" }),
843 reply("message.list", {
844 data: [
845 {
846 id: "msg_0eb7a99c0001idleFollowUp00",
847 time: { created: 5 },
848 type: "idle",
849 outcome: "succeeded",
850 },
851 {
852 id: "msg_0eb7a96bb00170K1f1HJUeBNwF",
853 time: { created: 4 },
854 type: "assistant",
855 agent: "build",
856 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
857 content: [
858 {
859 type: "text",
860 text: "The background subagent finished and returned `CHILD_OK`.",
861 },
862 ],
863 finish: "stop",
864 },
865 {
866 id: "msg_0eb7a3aee0015KmTB8XkMDW8iy",
867 time: { created: 3 },
868 type: "synthetic",
869 text: "<subagent>CHILD_OK</subagent>",
870 },
871 {
872 id: "msg_0eb7a3e3c001idleParentTurn0",
873 time: { created: 2 },
874 type: "idle",
875 outcome: "succeeded",
876 },
877 ],
878 cursor: {},
879 }),
880 ],
881 commands: (thread) => [
882 thread.create,
883 thread.message("start", bigPickle, BACKGROUND_PROMPT),
884 ],
885 steps: (thread, run) => [
886 { type: "dispatch", command: thread.create },
887 { type: "advance_clock", duration: "1 millis" },
888 // A continuation run starts while the thread is busy, so this does not wait.
889 {
890 type: "dispatch",
891 command: thread.message("start", bigPickle, BACKGROUND_PROMPT),
892 await: false,
893 key: "start",
894 },
895 { type: "advance_clock", duration: "1 millis" },
896 // The follow-up's continuation turn has taken its execution when the
897 // stream drops: the held reply end is the next event.
898 { type: "await_run_steerable", threadId: thread.threadId, runId: run(2) },
899 { type: "release_replay_gate", label: BACKGROUND_HOLD },
900 {
901 type: "await_run_status",
902 threadId: thread.threadId,
903 runId: run(2),
904 status: "completed",
905 },
906 { type: "await", key: "start" },
907 { type: "await_thread_idle", threadId: thread.threadId },
908 ],
909 });
910 assert.deepEqual(
911 projection.runs.map((candidate) => candidate.status),
912 ["completed", "completed"],
913 );
914 const followUp = projection.runs[1];
915 assert.deepEqual(
916 projection.turnItems.flatMap((item) =>
917 item.runId === followUp?.id && item.type === "assistant_message" ? [item.text] : [],
918 ),
919 ["The background subagent finished and returned `CHILD_OK`."],
920 );
921 const shell = result.shellSnapshot.threads.find((row) => row.id === projection.thread.id);
922 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
923 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
924 );
925​
926 it.effect(
927 "settles a background subagent whose end was lost with the stream, and takes the next turn",
928 () =>
929 Effect.gen(function* () {
930 const { result, projection } = yield* backgroundReconnect({
931 name: "opencode2-background-lost",
932 // The subagent runs; the stream drops before its end, its report and
933 // the follow-up it started, none of which is read back.
934 cut: "session.step.started.3",
935 reconnect: (parent) => [
936 out("event.subscribe"),
937 // Nothing runs any more: the subagent and the follow-up both ended.
938 out("session.active"),
939 reply("session.active", { data: {} }),
940 // The subagent's turn was running, so its history since its prompt
941 // is read back: its end, as the recording's later events had it.
942 out("message.list", { sessionID: BACKGROUND_CHILD, order: "desc", limit: "50" }),
943 reply("message.list", {
944 data: [
945 {
946 id: "msg_0eb7a99b0001idleChildTurn0",
947 time: { created: 4 },
948 type: "idle",
949 outcome: "succeeded",
950 },
951 {
952 id: "msg_0eb7a916c001NRJQJ5gwIT0QnU",
953 time: { created: 3 },
954 type: "assistant",
955 agent: "general",
956 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
957 content: [{ type: "text", text: "CHILD_OK" }],
958 finish: "stop",
959 },
960 {
961 id: "msg_0eb7a3aea001Lw1Pav5d4akfEg",
962 time: { created: 2 },
963 type: "user",
964 text: "Run the shell command `sleep 20` with the bash tool and then reply exactly CHILD_OK.",
965 },
966 ],
967 cursor: {},
968 }),
969 out("session.prompt", { sessionID: parent, id: "<any>", text: "<any>" }),
970 reply("session.prompt", {
971 data: {
972 id: "msg_next",
973 sessionID: parent,
974 time: { created: 9 },
975 type: "user",
976 payload: { text: "<prompt>" },
977 delivery: "steer",
978 },
979 }),
980 event("session.execution.started", { sessionID: parent }),
981 event("session.text.ended", {
982 sessionID: parent,
983 assistantMessageID: "msg_next_reply",
984 ordinal: 0,
985 text: "NEXT",
986 }),
987 event("session.execution.succeeded", { sessionID: parent }),
988 ],
989 commands: (thread) => [
990 thread.create,
991 thread.message("start", bigPickle, BACKGROUND_PROMPT),
992 thread.message("next"),
993 ],
994 steps: (thread, run) => [
995 { type: "dispatch", command: thread.create },
996 { type: "advance_clock", duration: "1 millis" },
997 { type: "dispatch", command: thread.message("start", bigPickle, BACKGROUND_PROMPT) },
998 { type: "advance_clock", duration: "1 millis" },
999 { type: "await_thread_idle", threadId: thread.threadId },
1000 { type: "dispatch", command: thread.message("next") },
1001 { type: "advance_clock", duration: "1 millis" },
1003 type: "await_run_status",
1004 threadId: thread.threadId,
1005 runId: run(2),
1006 status: "completed",
1007 },
1008 { type: "await_thread_idle", threadId: thread.threadId },
1009 ],
1010 });
1011 // The parent's run ended; the lost subagent ended as interrupted and
1012 // said why; no follow-up is waited on; the next turn ran normally.
1013 assert.deepEqual(
1014 projection.runs.map((candidate) => candidate.status),
1015 ["completed", "completed"],
1016 );
1017 assert.lengthOf(projection.subagents, 1);
1018 assert.deepInclude(projection.subagents[0], { status: "interrupted" });
1019 assert.include(projection.subagents[0]?.result ?? "", "lost its connection to OpenCode");
1020 assert.isFalse(
1021 projection.turnItems.some(
1022 (item) => item.status === "running" || item.status === "waiting",
1023 ),
1024 );
1025 const shell = result.shellSnapshot.threads.find((row) => row.id === projection.thread.id);
1026 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
1027 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
1028 );
1029​
1030 it.effect(
1031 "settles a background subagent whose report OpenCode delivers into the launching turn",
1032 () =>
1033 Effect.gen(function* () {
1034 // The recorded background run, reordered as 2.0.18 ran it live when the
1035 // child ended first: the parent's execution is still answering when the
1036 // child's report is queued and delivered into it, and that one
1037 // execution then answers the report and ends. No execution starts on
1038 // its own, so no continuation run opens.
1039 const cwd = yield* checkpointWorkspace("opencode2-background-in-turn");
1040 const recorded = yield* readProviderReplayTranscript(
1041 new URL(
1042 "./testkit/fixtures/opencode2_background/opencode_transcript.ndjson",
1043 import.meta.url,
1044 ),
1045 );
1046 const byLabel = (label: string) => {
1047 const entry = recorded.entries.find(
1048 (candidate) => candidate.type !== "runtime_exit" && candidate.label === label,
1049 );
1050 assert.isDefined(entry);
1051 return entry!;
1052 };
1053 const parentEnd = recorded.entries.findIndex(
1054 (entry) => entry.type !== "runtime_exit" && entry.label === "session.execution.succeeded",
1055 );
1056 const childStart = recorded.entries.findIndex(
1057 (entry) => entry.type !== "runtime_exit" && entry.label === "session.step.started.3",
1058 );
1059 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
1060 ...recorded,
1061 scenario: "opencode2-background-in-turn",
1062 entries: [
1063 // The launch, up to the parent's answer, without its end.
1064 ...recorded.entries.slice(0, parentEnd),
1065 // The child runs to its end meanwhile.
1066 ...recorded.entries.slice(
1067 childStart,
1068 recorded.entries.indexOf(byLabel("session.inbox.enqueued.3")),
1069 ),
1070 // Its report is queued and delivered into the parent's running execution.
1071 byLabel("session.inbox.enqueued.3"),
1072 byLabel("session.inbox.delivered.3"),
1073 // That execution answers the report and ends.
1074 byLabel("session.text.ended.3"),
1075 byLabel("session.execution.succeeded.3"),
1076 ],
1077 });
1078 const thread = threadCommands({ name: "opencode2-background-in-turn", worktreePath: cwd });
1079 const ids = yield* IdAllocator.IdAllocatorV2;
1080 const result = yield* runOrchestratorV2ProviderReplayScenario(
1082 name: "opencode2-background-in-turn",
1083 transcript,
1084 commands: [thread.create, thread.message("start", bigPickle, BACKGROUND_PROMPT)],
1085 steps: [
1086 { type: "dispatch", command: thread.create },
1087 { type: "advance_clock", duration: "1 millis" },
1088 { type: "dispatch", command: thread.message("start", bigPickle, BACKGROUND_PROMPT) },
1089 { type: "advance_clock", duration: "1 millis" },
1091 type: "await_run_status",
1092 threadId: thread.threadId,
1093 runId: ids.derive.run({ threadId: thread.threadId, ordinal: 1 }),
1094 status: "completed",
1095 },
1096 { type: "await_thread_idle", threadId: thread.threadId },
1097 ],
1098 },
1099 OpenCode2OrchestratorReplayHarness,
1100 { runContinuationWorker: true },
1101 ).pipe(provideDeterministicTestRuntime);
1102 const projection = result.projections.get(thread.threadId);
1103 assert.isDefined(projection);
1104 // One run took the launch and the report; the subagent completed with
1105 // its output, and nothing waits on a follow-up.
1106 assert.deepEqual(
1107 projection!.runs.map((candidate) => candidate.status),
1108 ["completed"],
1109 );
1110 assert.lengthOf(projection!.subagents, 1);
1111 assert.deepInclude(projection!.subagents[0], { status: "completed" });
1112 assert.include(projection!.subagents[0]?.result ?? "", "CHILD_OK");
1113 assert.isTrue(
1114 projection!.turnItems.some(
1115 (item) =>
1116 item.type === "assistant_message" && item.text.includes("finished and returned"),
1117 ),
1118 );
1119 assert.isFalse(
1120 projection!.turnItems.some(
1121 (item) => item.status === "running" || item.status === "waiting",
1122 ),
1123 );
1124 const shell = result.shellSnapshot.threads.find((row) => row.id === projection!.thread.id);
1125 assert.deepEqual(shell?.pendingBackgroundTasks ?? [], []);
1126 }).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
1127 );
1128​
1129 it.effect(
1130 "runs plan mode as OpenCode's plan agent and switches back before the next prompt",
1131 () =>
1132 Effect.gen(function* () {
1133 const name = "opencode2_switch";
1134 const cwd = yield* checkpointWorkspace(name);
1135 const thread = threadCommands({ name, worktreePath: cwd });
1136 // The spike's recording: plan agent, then build agent and a new model on
1137 // one session. Its `<work>` is this test's workspace.
1138 const recorded = yield* Effect.gen(function* () {
1139 const fs = yield* FileSystem.FileSystem;
1140 const path = yield* Path.Path;
1141 const text = yield* fs.readFileString(
1142 yield* path.fromFileUrl(
1143 new URL(
1144 "./testkit/fixtures/opencode2_switch/opencode_transcript.ndjson",
1145 import.meta.url,
1146 ),
1147 ),
1148 );
1149 return yield* decodeProviderReplayNdjson(text.replaceAll("<work>", cwd));
1150 }).pipe(Effect.provide(NodeServices.layer));
1151 const projection = yield* runScenario({
1152 name,
1153 threadId: thread.threadId,
1154 entries: recorded.entries,
1155 commands: [
1156 thread.create,
1157 thread.interactionMode("mode-plan", "plan"),
1158 thread.message(
1159 "plan",
1160 bigPickle,
1161 "Create a file named plan_probe.txt containing HI using the write tool.",
1162 ),
1163 thread.interactionMode("mode-default", "default"),
1164 thread.message("switched", nemotron, "Reply exactly SWITCHED."),
1165 ],
1166 });
1167 assert.deepEqual(
1168 projection.runs.map((run) => [run.status, run.modelSelection.model]),
1170 ["completed", bigPickle.model],
1171 ["completed", nemotron.model],
1172 ],
1173 );
1174 const replies = projection.turnItems.flatMap((item) =>
1175 item.type === "assistant_message" ? [item.text] : [],
1176 );
1177 // The plan agent refused to write; OpenCode's own reminder told it why.
1178 assert.include(replies[0], "Plan mode");
1179 assert.equal(replies[1], "SWITCHED");
1180 assert.lengthOf(projection.providerThreads, 1);
1181 }).pipe(Effect.scoped),
1182 );
1183});