Open History to see the last commit
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 { assert, describe, it } from "@effect/vitest";
7import {
8 CommandId,
9 MessageId,
10 type ModelSelection,
11 type OrchestrationV2Command,
12 ProjectId,
13 type ProviderInteractionMode,
14 ProviderInstanceId,
15 type ProviderReplayEntry,
16 type RuntimeMode,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as Effect from "effect/Effect";
20
21import {
22 OPENCODE2_HTTP_PROTOCOL,
23 OpenCode2OrchestratorReplayHarness,
24} from "./Adapters/OpenCode2AdapterV2.testkit.ts";
25import { OPENCODE_PROVIDER } from "./Adapters/OpenCodeAdapterV2.ts";
26import { provideDeterministicTestRuntime } from "./testkit/DeterministicRuntime.ts";
27import type { OrchestratorV2ScenarioStep } from "./testkit/OrchestratorScenario.ts";
28import { runOrchestratorV2ProviderReplayScenario } from "./testkit/ProviderReplayHarness.ts";
29import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
30
31const SESSION = "ses_f148ca2deffeJcwCnRQtb0YFNX";
32const instanceId = ProviderInstanceId.make("opencode");
33const bigPickle: ModelSelection = { instanceId, model: "opencode/big-pickle" };
34const mimo: ModelSelection = { instanceId, model: "opencode/mimo-v2.6-flash-free" };
35
36const out = (type: string, input?: unknown): ProviderReplayEntry => ({
37 type: "expect_outbound",
38 frame: input === undefined ? { type } : { type, input },
39});
40const reply = (operation: string, data: unknown): ProviderReplayEntry => ({
41 type: "emit_inbound",
42 frame: { type: "sdk.response", operation, data },
43});
44const event = (type: string, data: Record<string, unknown>): ProviderReplayEntry => ({
45 type: "emit_inbound",
46 frame: {
47 type: "sdk.event",
48 event: { id: `evt_${type.replaceAll(".", "")}`, created: 1, type, data },
49 },
50});
51const T3_RULES = [
52 { action: "*", resource: "*", effect: "allow" },
53 { action: "subagent", resource: "*", effect: "deny" },
54];
55/** Paths the build and plan agents allow for themselves, as 2.0.18 lists them. */
56const BUILD_PATHS = [
57 {
58 action: "external_directory",
59 resource: "/home/.local/share/opencode/tool-output/*",
60 effect: "allow",
61 },
62];
63const PLAN_PATHS = [
64 ...BUILD_PATHS,
65 { action: "edit", resource: "/home/.opencode/plan/*", effect: "allow" },
66 { action: "external_directory", resource: "/home/.opencode/plan/*", effect: "allow" },
67];
68const agentInfo = (id: string, description: string, permissions: ReadonlyArray<unknown>) => ({
69 id,
70 name: id === "plan" ? "Plan" : "Build",
71 request: { settings: {}, headers: {}, body: {} },
72 description,
73 mode: "primary",
74 hidden: false,
75 permissions,
76});
77/** `/api/agent` trimmed to the two agents a T3 session runs. */
78const agentList = (directory: string) => ({
79 location: { directory },
80 data: [
81 agentInfo("build", "The default agent.", [
82 { action: "*", resource: "*", effect: "allow" },
83 { action: "external_directory", resource: "*", effect: "ask" },
84 ...BUILD_PATHS,
85 ]),
86 agentInfo("plan", "Read-only agent for planning.", [
87 { action: "*", resource: "*", effect: "allow" },
88 { action: "external_directory", resource: "*", effect: "ask" },
89 ...BUILD_PATHS,
90 { action: "edit", resource: "*", effect: "deny" },
91 ...PLAN_PATHS.slice(BUILD_PATHS.length),
92 ]),
93 ],
94});
95/** A session this runtime loads again (after a detach) waits on nothing. */
96const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
97 out("permission.list", { sessionID: SESSION }),
98 reply("permission.list", { data: [] }),
99 out("session.form.list", { sessionID: SESSION }),
100 reply("session.form.list", { data: [] }),
101];
102const SUPERVISED_RULES = [
103 { action: "shell", resource: "*", effect: "ask" },
104 { action: "edit", resource: "*", effect: "ask" },
105 { action: "external_directory", resource: "*", effect: "ask" },
106 ...BUILD_PATHS,
107 { action: "subagent", resource: "*", effect: "deny" },
108];
109const AUTO_EDIT_RULES = [
110 { action: "shell", resource: "*", effect: "ask" },
111 { action: "edit", resource: "*", effect: "allow" },
112 { action: "external_directory", resource: "*", effect: "ask" },
113 ...BUILD_PATHS,
114 { action: "subagent", resource: "*", effect: "deny" },
115];
116/** Plan mode on Full access: edits are denied except the plan agent's own plan files. */
117const PLAN_RULES = [
118 { action: "*", resource: "*", effect: "allow" },
119 { action: "edit", resource: "*", effect: "deny" },
120 ...PLAN_PATHS,
121 { action: "subagent", resource: "*", effect: "deny" },
122];
123
124const sessionInfo = (directory: string, permissions: ReadonlyArray<unknown> = T3_RULES) => ({
125 data: {
126 id: SESSION,
127 projectID: "global",
128 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
129 cost: 0,
130 tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
131 time: { created: 1790656601394, updated: 1790656601394 },
132 location: { directory },
133 permissions,
134 },
135});
136/** One prompt the server accepts and answers with `text`. */
137const answeredPrompt = (text: string): ReadonlyArray<ProviderReplayEntry> => [
138 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
139 reply("session.prompt", {
140 data: {
141 id: `msg_user_${text}`,
142 sessionID: SESSION,
143 time: { created: 1790656601410 },
144 type: "user",
145 payload: { text: "<prompt>" },
146 delivery: "steer",
147 },
148 }),
149 event("session.text.ended", {
150 sessionID: SESSION,
151 assistantMessageID: `msg_assistant_${text}`,
152 ordinal: 0,
153 text,
154 }),
155 event("session.execution.succeeded", { sessionID: SESSION }),
156];
157/** The model list read the first time a thread runs in `directory`. */
158const directoryModels = (directory: string): ReadonlyArray<ProviderReplayEntry> => [
159 out("model.list", { "location[directory]": directory }),
160 reply("model.list", {
161 location: { directory },
162 data: [
163 catalogModel("big-pickle", "Big Pickle"),
164 catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
165 ],
166 }),
167];
168/** A `/api/model` entry as 2.0.18 lists it; a known window means no re-read after a turn. */
169const catalogModel = (id: string, name: string) => ({
170 id,
171 modelID: id,
172 providerID: "opencode",
173 family: id,
174 name,
175 compatibility: { reasoningField: "reasoning_content" },
176 package: "@opencode/ai/providers/openai-compatible",
177 settings: { apiKey: "public", baseURL: "https://opencode.ai/zen/v1", provider: "opencode" },
178 capabilities: { tools: true, input: ["text"], output: ["text"] },
179 variants: [],
180 time: { released: 1760659200000 },
181 cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
182 status: "active",
183 enabled: true,
184 limit: { context: 200000, input: 160000, output: 32000 },
185});
186const createdSession = (
187 directory: string,
188 permissions: ReadonlyArray<unknown> = T3_RULES,
189): ReadonlyArray<ProviderReplayEntry> => [
190 out("event.subscribe"),
191 out("model.list", "<any>"),
192 reply("model.list", {
193 location: { directory },
194 data: [
195 catalogModel("big-pickle", "Big Pickle"),
196 catalogModel("mimo-v2.6-flash-free", "MiMo V2.6 Flash Free"),
197 ],
198 }),
199 // Only a mode that narrows Full access reads the agents' own path rules.
200 ...(permissions === T3_RULES
201 ? []
202 : [out("agent.list", "<any>"), reply("agent.list", agentList(directory))]),
203 out("session.create", { location: { directory }, model: "<any>", permissions }),
204 reply("session.create", sessionInfo(directory, permissions)),
205];
206
207const threadCommands = (input: {
208 readonly name: string;
209 readonly worktreePath: string;
210 readonly runtimeMode?: RuntimeMode;
211 readonly interactionMode?: ProviderInteractionMode;
212}) => {
213 const threadId = ThreadId.make(`thread:${input.name}`);
214 const command = (key: string) => CommandId.make(`command:${input.name}:${key}`);
215 return {
216 threadId,
217 create: {
218 type: "thread.create",
219 createdBy: "user",
220 creationSource: "web",
221 commandId: command("create"),
222 threadId,
223 projectId: ProjectId.make(`project:${input.name}`),
224 title: input.name,
225 modelSelection: bigPickle,
226 runtimeMode: input.runtimeMode ?? "full-access",
227 interactionMode: input.interactionMode ?? "default",
228 branch: null,
229 worktreePath: input.worktreePath,
230 } satisfies OrchestrationV2Command,
231 message: (key: string, modelSelection: ModelSelection = bigPickle) =>
232 ({
233 type: "message.dispatch",
234 createdBy: "user",
235 creationSource: "web",
236 commandId: command(key),
237 threadId,
238 messageId: MessageId.make(`message:${input.name}:${key}`),
239 text: `Reply with exactly: ${key}`,
240 attachments: [],
241 modelSelection,
242 dispatchMode: { type: "start_immediately" },
243 }) satisfies OrchestrationV2Command,
244 command,
245 };
246};
247
248/** Runs `commands` in order, letting the thread go idle after each message. */
249const runScenario = (input: {
250 readonly name: string;
251 readonly threadId: ThreadId;
252 readonly entries: ReadonlyArray<ProviderReplayEntry>;
253 readonly commands: ReadonlyArray<OrchestrationV2Command>;
254}) =>
255 Effect.gen(function* () {
256 const transcript = yield* OpenCode2OrchestratorReplayHarness.decodeTranscript({
257 provider: OPENCODE_PROVIDER,
258 protocol: OPENCODE2_HTTP_PROTOCOL,
259 version: "2.0.18",
260 scenario: input.name,
261 entries: input.entries,
262 });
263 const steps = input.commands.flatMap((command): Array<OrchestratorV2ScenarioStep> => [
264 { type: "dispatch", command },
265 { type: "advance_clock", duration: "1 millis" },
266 ...(command.type === "message.dispatch"
267 ? [{ type: "await_thread_idle" as const, threadId: input.threadId }]
268 : []),
269 ]);
270 const result = yield* runOrchestratorV2ProviderReplayScenario(
271 { name: input.name, transcript, commands: input.commands, steps },
272 OpenCode2OrchestratorReplayHarness,
273 ).pipe(provideDeterministicTestRuntime);
274 const projection = result.projections.get(input.threadId);
275 assert.isDefined(projection);
276 return projection;
277 });
278
279describe("OpenCode 2 through the orchestrator", () => {
280 for (const via of ["message", "thread settings"] as const) {
281 it.effect(
282 `switches the session's model before the next prompt when changed from the ${via}`,
283 () =>
284 Effect.gen(function* () {
285 const name = `opencode2-model-switch-${via.replace(" ", "-")}`;
286 const cwd = yield* checkpointWorkspace(name);
287 const thread = threadCommands({ name, worktreePath: cwd });
288 const projection = yield* runScenario({
289 name,
290 threadId: thread.threadId,
291 entries: [
292 ...createdSession(cwd),
293 ...answeredPrompt("FIRST"),
294 // The next turn resumes the session at its new selection.
295 out("session.get", { sessionID: SESSION }),
296 reply("session.get", sessionInfo(cwd)),
297 out("session.switchModel", {
298 sessionID: SESSION,
299 model: { providerID: "opencode", id: "mimo-v2.6-flash-free" },
300 }),
301 reply("session.switchModel", null),
302 ...answeredPrompt("SECOND"),
303 ],
304 commands: [
305 thread.create,
306 thread.message("first"),
307 ...(via === "thread settings"
308 ? [
309 {
310 type: "thread.model-selection.set",
311 commandId: thread.command("model"),
312 threadId: thread.threadId,
313 modelSelection: mimo,
314 } satisfies OrchestrationV2Command,
315 ]
316 : []),
317 thread.message("second", mimo),
318 ],
319 });
320 assert.deepEqual(
321 projection.runs.map((run) => [run.status, run.modelSelection.model]),
322 [
323 ["completed", bigPickle.model],
324 ["completed", mimo.model],
325 ],
326 );
327 // One native session carried both turns.
328 assert.lengthOf(projection.providerThreads, 1);
329 }).pipe(Effect.scoped),
330 );
331 }
332
333 it.effect("moves the session to the thread's new worktree before the next prompt", () =>
334 Effect.gen(function* () {
335 const name = "opencode2-worktree-move";
336 const before = yield* checkpointWorkspace(`${name}-before`);
337 const after = yield* checkpointWorkspace(`${name}-after`);
338 const thread = threadCommands({ name, worktreePath: before });
339 const projection = yield* runScenario({
340 name,
341 threadId: thread.threadId,
342 entries: [
343 ...createdSession(before),
344 ...answeredPrompt("FIRST"),
345 ...directoryModels(after),
346 out("session.get", { sessionID: SESSION }),
347 reply("session.get", sessionInfo(before)),
348 // The worktree change detached the thread, so its session is loaded afresh.
349 ...noOpenRequests,
350 out("session.move", { sessionID: SESSION, directory: after }),
351 reply("session.move", null),
352 ...answeredPrompt("SECOND"),
353 ],
354 commands: [
355 thread.create,
356 thread.message("first"),
357 {
358 type: "thread.metadata.update",
359 commandId: thread.command("worktree"),
360 threadId: thread.threadId,
361 worktreePath: after,
362 },
363 thread.message("second"),
364 ],
365 });
366 assert.deepEqual(
367 projection.runs.map((run) => run.status),
368 ["completed", "completed"],
369 );
370 assert.lengthOf(projection.providerThreads, 1);
371 }).pipe(Effect.scoped),
372 );
373
374 it.effect("gives a session made with older rules T3's rules before its next prompt", () =>
375 Effect.gen(function* () {
376 const name = "opencode2-resume-rules";
377 const before = yield* checkpointWorkspace(`${name}-before`);
378 const after = yield* checkpointWorkspace(`${name}-after`);
379 const thread = threadCommands({ name, worktreePath: before });
380 const projection = yield* runScenario({
381 name,
382 threadId: thread.threadId,
383 entries: [
384 ...createdSession(before),
385 ...answeredPrompt("FIRST"),
386 ...directoryModels(after),
387 // Reopened after a worktree change, the session reports the rules an
388 // older build gave it; they are replaced before anything runs.
389 out("session.get", { sessionID: SESSION }),
390 reply(
391 "session.get",
392 sessionInfo(before, [{ action: "*", resource: "*", effect: "allow" }]),
393 ),
394 ...noOpenRequests,
395 out("session.update", { sessionID: SESSION, permissions: T3_RULES }),
396 reply("session.update", null),
397 out("session.move", { sessionID: SESSION, directory: after }),
398 reply("session.move", null),
399 ...answeredPrompt("SECOND"),
400 ],
401 commands: [
402 thread.create,
403 thread.message("first"),
404 {
405 type: "thread.metadata.update",
406 commandId: thread.command("worktree"),
407 threadId: thread.threadId,
408 worktreePath: after,
409 },
410 thread.message("second"),
411 ],
412 });
413 assert.deepEqual(
414 projection.runs.map((run) => run.status),
415 ["completed", "completed"],
416 );
417 }).pipe(Effect.scoped),
418 );
419
420 it.effect(
421 "creates a Supervised thread's session with rules that ask before shell and edits",
422 () =>
423 Effect.gen(function* () {
424 const name = "opencode2-supervised-rules";
425 const cwd = yield* checkpointWorkspace(name);
426 const thread = threadCommands({
427 name,
428 worktreePath: cwd,
429 runtimeMode: "approval-required",
430 });
431 const projection = yield* runScenario({
432 name,
433 threadId: thread.threadId,
434 entries: [...createdSession(cwd, SUPERVISED_RULES), ...answeredPrompt("FIRST")],
435 commands: [thread.create, thread.message("first")],
436 });
437 assert.deepEqual(
438 projection.runs.map((run) => run.status),
439 ["completed"],
440 );
441 }).pipe(Effect.scoped),
442 );
443
444 it.effect("rewrites the session's rules when the thread's mode changes between turns", () =>
445 Effect.gen(function* () {
446 const name = "opencode2-mode-change";
447 const cwd = yield* checkpointWorkspace(name);
448 const thread = threadCommands({ name, worktreePath: cwd });
449 const setMode = (key: string, runtimeMode: RuntimeMode) =>
450 ({
451 type: "thread.runtime-mode.set",
452 commandId: thread.command(key),
453 threadId: thread.threadId,
454 runtimeMode,
455 }) satisfies OrchestrationV2Command;
456 const projection = yield* runScenario({
457 name,
458 threadId: thread.threadId,
459 entries: [
460 ...createdSession(cwd),
461 ...answeredPrompt("FIRST"),
462 // A mode change detaches nothing: the same session is resumed with the new rules.
463 out("session.get", { sessionID: SESSION }),
464 reply("session.get", sessionInfo(cwd)),
465 out("agent.list", "<any>"),
466 reply("agent.list", agentList(cwd)),
467 out("session.update", { sessionID: SESSION, permissions: AUTO_EDIT_RULES }),
468 reply("session.update", null),
469 ...answeredPrompt("SECOND"),
470 // Back to Full access: the narrowing rules go.
471 out("session.get", { sessionID: SESSION }),
472 reply("session.get", sessionInfo(cwd, AUTO_EDIT_RULES)),
473 out("session.update", { sessionID: SESSION, permissions: T3_RULES }),
474 reply("session.update", null),
475 ...answeredPrompt("THIRD"),
476 ],
477 commands: [
478 thread.create,
479 thread.message("first"),
480 setMode("auto-edit", "auto-accept-edits"),
481 thread.message("second"),
482 setMode("full", "full-access"),
483 thread.message("third"),
484 ],
485 });
486 assert.deepEqual(
487 projection.runs.map((run) => run.status),
488 ["completed", "completed", "completed"],
489 );
490 assert.lengthOf(projection.providerThreads, 1);
491 }).pipe(Effect.scoped),
492 );
493
494 it.effect("denies edits outside the plan directory in plan mode and lifts it after", () =>
495 Effect.gen(function* () {
496 const name = "opencode2-plan-rules";
497 const cwd = yield* checkpointWorkspace(name);
498 const thread = threadCommands({ name, worktreePath: cwd, interactionMode: "plan" });
499 const projection = yield* runScenario({
500 name,
501 threadId: thread.threadId,
502 entries: [
503 ...createdSession(cwd, PLAN_RULES),
504 ...answeredPrompt("PLANNED"),
505 out("session.get", { sessionID: SESSION }),
506 reply("session.get", sessionInfo(cwd, PLAN_RULES)),
507 out("session.update", { sessionID: SESSION, permissions: T3_RULES }),
508 reply("session.update", null),
509 ...answeredPrompt("BUILT"),
510 ],
511 commands: [
512 thread.create,
513 thread.message("plan"),
514 {
515 type: "thread.interaction-mode.set",
516 commandId: thread.command("default"),
517 threadId: thread.threadId,
518 interactionMode: "default",
519 },
520 thread.message("build"),
521 ],
522 });
523 assert.deepEqual(
524 projection.runs.map((run) => run.status),
525 ["completed", "completed"],
526 );
527 }).pipe(Effect.scoped),
528 );
529});