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

OpenCode2AdapterV2.test.ts

1,311 lines50.0 KB

1/**
2 * Failures and settings a live OpenCode 2 server cannot produce on demand,
3 * driven through the real adapter and `@opencode/client` against a replayed
4 * HTTP server. Frames reuse the shapes recorded against 2.0.18.
5 */
6import { assert, it } from "@effect/vitest";
7import {
8 MessageId,
9 NodeId,
10 ProviderInstanceId,
11 ProviderSessionId,
12 ProviderThreadId,
13 RunAttemptId,
14 RunId,
15 ThreadId,
16 type ModelSelection,
17 type OrchestrationV2AppThread,
18 type OrchestrationV2ProviderThread,
19 type ProviderReplayEntry,
20} from "@t3tools/contracts";
21import * as DateTime from "effect/DateTime";
22import * as Effect from "effect/Effect";
23import * as Fiber from "effect/Fiber";
24import * as Option from "effect/Option";
25import * as Scope from "effect/Scope";
26import * as Stream from "effect/Stream";
27import * as Exit from "effect/Exit";
28import { TestClock } from "effect/testing";
29import { describe } from "vite-plus/test";
30​
31import type {
32 ProviderAdapterV2Event,
33 ProviderAdapterV2SessionRuntime,
34} from "../ProviderAdapter.ts";
35import * as IdAllocator from "../IdAllocator.ts";
36import { OPENCODE_PROVIDER } from "./OpenCodeAdapterV2.ts";
37import { OPENCODE_2_STILL_STOPPING } from "./OpenCode2AdapterV2.ts";
38import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts";
39​
40const SESSION = "ses_f148ca2deffeJcwCnRQtb0YFNX";
41const WORK = "/work/opencode2";
42const instanceId = ProviderInstanceId.make("opencode");
43const threadId = ThreadId.make("thread:opencode2-adapter");
44​
45const out = (type: string, input?: unknown): ProviderReplayEntry => ({
46 type: "expect_outbound",
47 frame: input === undefined ? { type } : { type, input },
48});
49/** A recorded response body; `{ data }` is the server's envelope, `null` an empty 204. */
50const reply = (operation: string, data: unknown): ProviderReplayEntry => ({
51 type: "emit_inbound",
52 frame: { type: "sdk.response", operation, data },
53});
54const replyData = (operation: string, data: unknown) => reply(operation, { data });
55const event = (type: string, data: Record<string, unknown>): ProviderReplayEntry => ({
56 type: "emit_inbound",
57 frame: {
58 type: "sdk.event",
59 event: { id: `evt_${type.replaceAll(".", "")}0000`, created: 1, type, data, ...durable },
60 },
61});
62const durable = { durable: { aggregateID: SESSION, seq: 1, version: 1 } };
63​
64/** The rules T3 gives every session it runs. */
65const t3Rules = [
66 { action: "*", resource: "*", effect: "allow" },
67 { action: "subagent", resource: "*", effect: "deny" },
68];
69const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
70 id: SESSION,
71 permissions: t3Rules,
72 projectID: "global",
73 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
74 cost: 0,
75 tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
76 time: { created: 1790656601394, updated: 1790656601394 },
77 location: { directory: WORK },
78 ...overrides,
79});
80// `/api/model` as 2.0.18 lists big-pickle: its 160k input limit is the usable window.
81const modelCatalog = {
82 location: { directory: WORK },
83 data: [
84 {
85 id: "big-pickle",
86 modelID: "big-pickle",
87 providerID: "opencode",
88 family: "big-pickle",
89 name: "Big Pickle",
90 compatibility: { reasoningField: "reasoning_content" },
91 package: "@opencode/ai/providers/openai-compatible",
92 settings: { apiKey: "public", baseURL: "https://opencode.ai/zen/v1", provider: "opencode" },
93 capabilities: { tools: true, input: ["text"], output: ["text"] },
94 variants: [],
95 time: { released: 1760659200000 },
96 cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
97 status: "active",
98 enabled: true,
99 limit: { context: 200000, input: 160000, output: 32000 },
100 },
101 ],
102};
103​
104const promptAccepted = replyData("session.prompt", {
105 id: "msg_0eb735d41001NJee1EvVePJAK5",
106 sessionID: SESSION,
107 time: { created: 1790656601410 },
108 type: "user",
109 payload: { text: "hi" },
110 delivery: "steer",
111});
112​
113/** A resumed session that waits on nothing. */
114const noOpenRequests: ReadonlyArray<ProviderReplayEntry> = [
115 out("permission.list", { sessionID: SESSION }),
116 replyData("permission.list", []),
117 out("session.form.list", { sessionID: SESSION }),
118 replyData("session.form.list", []),
119];
120​
121/** What every session sends when it opens: the event stream, then the model list. */
122const opening: ReadonlyArray<ProviderReplayEntry> = [
123 out("event.subscribe"),
124 out("model.list", "<any>"),
125 reply("model.list", modelCatalog),
126];
127/** The model list read the first time a thread runs in `directory`. */
128const directoryModels = (directory: string): ReadonlyArray<ProviderReplayEntry> => [
129 out("model.list", { "location[directory]": directory }),
130 reply("model.list", { ...modelCatalog, location: { directory } }),
131];
132​
133const bigPickle: ModelSelection = { instanceId, model: "opencode/big-pickle" };
134const policy = (runtimeMode: "full-access" | "approval-required" = "full-access") => ({
135 runtimeMode,
136 interactionMode: "default" as const,
137 cwd: WORK,
138});
139​
140const providerThread = (now: DateTime.Utc): OrchestrationV2ProviderThread => ({
141 id: ProviderThreadId.make("provider-thread:opencode2-adapter"),
142 driver: OPENCODE_PROVIDER,
143 providerInstanceId: instanceId,
144 providerSessionId: ProviderSessionId.make("provider-session:opencode2-adapter"),
145 appThreadId: threadId,
146 ownerNodeId: null,
147 nativeThreadRef: { driver: OPENCODE_PROVIDER, nativeId: SESSION, strength: "strong" },
148 nativeConversationHeadRef: null,
149 status: "idle",
150 firstRunOrdinal: null,
151 lastRunOrdinal: null,
152 handoffIds: [],
153 forkedFrom: null,
154 createdAt: now,
155 updatedAt: now,
156});
157​
158const turnInput = (
159 thread: OrchestrationV2ProviderThread,
160 modelSelection: ModelSelection = bigPickle,
161 runtimeMode: "full-access" | "approval-required" = "full-access",
162) => ({
163 appThread: {} as OrchestrationV2AppThread,
164 threadId,
165 runId: RunId.make("run:opencode2-adapter"),
166 runOrdinal: 1,
167 providerTurnOrdinal: 1,
168 attemptId: RunAttemptId.make("attempt:opencode2-adapter"),
169 rootNodeId: NodeId.make("node:opencode2-adapter"),
170 providerThread: thread,
171 message: {
172 messageId: MessageId.make("message:opencode2-adapter"),
173 text: "hi",
174 attachments: [],
175 createdBy: "user" as const,
176 creationSource: "web" as const,
177 scheduledTaskId: undefined,
178 senderThreadId: undefined,
179 },
180 modelSelection,
181 runtimePolicy: policy(runtimeMode),
182});
183​
184/** The agents' own path rules, as `/api/agent` lists them for build. */
185const buildPaths = [
186 {
187 action: "external_directory",
188 resource: "/home/.local/share/opencode/tool-output/*",
189 effect: "allow",
190 },
191];
192const agentList = {
193 location: { directory: WORK },
194 data: [
195 {
196 id: "build",
197 name: "Build",
198 request: { settings: {}, headers: {}, body: {} },
199 description: "The default agent.",
200 mode: "primary",
201 hidden: false,
202 permissions: [{ action: "*", resource: "*", effect: "allow" }, ...buildPaths],
203 },
204 ],
205};
206/** Supervised: shell, edits and other directories ask. */
207const supervisedRules = [
208 { action: "shell", resource: "*", effect: "ask" },
209 { action: "edit", resource: "*", effect: "ask" },
210 { action: "external_directory", resource: "*", effect: "ask" },
211 ...buildPaths,
212 { action: "subagent", resource: "*", effect: "deny" },
213];
214​
215// The first ask and question form the spike recorded (recordings/permission, question).
216const shellAsk = {
217 data: {
218 id: "per_0eb7c4d7e001Pyt8o50Vi4KrOO",
219 sessionID: SESSION,
220 action: "shell",
221 resources: ["echo FIRST"],
222 save: ["echo *"],
223 source: { type: "tool", messageID: "msg_0eb7c4330001dYFQKuTpfD780v", id: "call_1" },
224 },
225};
226const shellAskEvent = event("permission.asked", shellAsk.data);
227const colorForm = {
228 id: "frm_0eb79ab35001fkvFECSh3wYNVD",
229 sessionID: SESSION,
230 title: "Questions",
231 metadata: { kind: "question" },
232 fields: [
233 {
234 key: "q0",
235 title: "Color preference",
236 description: "Which color do you prefer?",
237 type: "string",
238 options: [{ value: "Red", label: "Red" }],
239 custom: true,
240 },
241 ],
242};
243​
244/**
245 * Resumes the recorded session and returns the runtime and the thread. A
246 * supervised resume gives the session Supervised rules first.
247 */
248const resumed = (
249 entries: ReadonlyArray<ProviderReplayEntry>,
250 options?: { readonly external?: boolean; readonly supervised?: boolean },
251) =>
252 Effect.gen(function* () {
253 const runtime = yield* openCode2ReplayRuntime(
254 [
255 ...opening,
256 out("session.get", { sessionID: SESSION }),
257 replyData("session.get", sessionInfo()),
258 ...noOpenRequests,
259 ...(options?.supervised === true
260 ? [
261 out("agent.list", "<any>"),
262 reply("agent.list", agentList),
263 out("session.update", { sessionID: SESSION, permissions: supervisedRules }),
264 reply("session.update", null),
265 ]
266 : []),
267 ...entries,
268 ],
269 options?.external === undefined ? undefined : { external: options.external },
270 );
271 const thread = yield* runtime.resumeThread({
272 providerThread: providerThread(yield* DateTime.now),
273 threadId,
274 modelSelection: bigPickle,
275 runtimePolicy: policy(options?.supervised === true ? "approval-required" : "full-access"),
276 });
277 return { runtime, thread };
278 });
279​
280const requestOf = (runtime: ProviderAdapterV2SessionRuntime) =>
281 runtime.events.pipe(
282 Stream.filter(
283 (event): event is Extract<ProviderAdapterV2Event, { type: "runtime_request.updated" }> =>
284 event.type === "runtime_request.updated",
285 ),
286 Stream.map((event) => event.runtimeRequest),
287 Stream.runHead,
288 Effect.map(Option.getOrUndefined),
289 );
290​
291const terminalOf = (runtime: ProviderAdapterV2SessionRuntime) =>
292 runtime.events.pipe(
293 Stream.filter(
294 (event): event is Extract<ProviderAdapterV2Event, { type: "turn.terminal" }> =>
295 event.type === "turn.terminal",
296 ),
297 Stream.runHead,
298 Effect.map(Option.getOrUndefined),
299 );
300​
301// The history the spike read back after its `simple` turn (recordings/simple.ndjson).
302const history = {
303 data: [
304 {
305 id: "msg_0eb732081001RntUJfRtTXOAjd",
306 time: { created: 1790656585885 },
307 text: "Think carefully step by step about whether 391 is prime, showing your reasoning, then answer in one short sentence.",
308 type: "user",
309 },
310 {
311 id: "msg_0eb7320a9001vve3OV5uNi2HRT",
312 time: { created: 1790656585925, streamed: 1790656590719, completed: 1790656590736 },
313 type: "assistant",
314 agent: "build",
315 model: { id: "space-bunny-free", providerID: "opencode", variant: "high" },
316 content: [
317 { type: "reasoning", text: "Check divisibility up to sqrt(391)." },
318 { type: "text", text: "391 is not prime: it's the product 17 × 23." },
319 ],
320 finish: "stop",
321 cost: 0,
322 tokens: { input: 8701, output: 113, reasoning: 147, cache: { read: 489, write: 0 } },
323 },
324 {
325 id: "msg_0eb733399001NhwTrB32UU6d6H",
326 time: { created: 1790656590745 },
327 type: "idle",
328 outcome: "succeeded",
329 },
330 ],
331 cursor: {},
332};
333​
334describe("OpenCode2 adapter", () => {
335 it.effect("switches the session's model and variant before a turn that changed them", () =>
336 Effect.gen(function* () {
337 const { runtime, thread } = yield* resumed([
338 out("session.switchModel", {
339 sessionID: SESSION,
340 model: { providerID: "openrouter", id: "deepseek/deepseek-v4-flash", variant: "high" },
341 }),
342 reply("session.switchModel", null),
343 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
344 promptAccepted,
345 event("session.execution.succeeded", { sessionID: SESSION }),
346 ]);
347 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
348 yield* runtime.startTurn(
349 turnInput(thread, {
350 instanceId,
351 model: "openrouter/deepseek/deepseek-v4-flash",
352 options: [{ id: "variant", value: "high" }],
353 }),
354 );
355 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
356 }).pipe(Effect.scoped),
357 );
358​
359 it.effect("ends the turn when its terminal event is one this build cannot decode", () =>
360 Effect.gen(function* () {
361 const { runtime, thread } = yield* resumed([
362 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
363 promptAccepted,
364 // A reason added after 2.0.18: the full schema rejects the frame.
365 event("session.execution.interrupted", { sessionID: SESSION, reason: "budget" }),
366 ]);
367 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
368 yield* runtime.startTurn(turnInput(thread));
369 assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
370 }).pipe(Effect.scoped),
371 );
372​
373 it.effect("keeps a turn running through a start event this build cannot decode", () =>
374 Effect.gen(function* () {
375 const { runtime, thread } = yield* resumed([
376 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
377 promptAccepted,
378 {
379 type: "emit_inbound",
380 frame: {
381 type: "sdk.event",
382 event: {
383 id: "evt_executionstartedx",
384 created: 1,
385 type: "session.execution.started",
386 data: { sessionID: SESSION },
387 durable: "not-an-envelope",
388 },
389 },
390 },
391 event("session.text.started", {
392 sessionID: SESSION,
393 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
394 ordinal: 0,
395 }),
396 event("session.text.ended", {
397 sessionID: SESSION,
398 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
399 ordinal: 0,
400 text: "DONE",
401 }),
402 event("session.execution.succeeded", { sessionID: SESSION }),
403 ]);
404 const collected = yield* runtime.events.pipe(
405 Stream.takeUntil((event) => event.type === "turn.terminal"),
406 Stream.runCollect,
407 Effect.forkScoped,
408 );
409 yield* runtime.startTurn(turnInput(thread));
410 const seen = yield* Fiber.join(collected);
411 const terminals = seen.filter((event) => event.type === "turn.terminal");
412 assert.deepEqual(
413 terminals.map((event) => event.type === "turn.terminal" && event.status),
414 ["completed"],
415 );
416 // The reply after the malformed start still reached the turn.
417 assert.isTrue(
418 seen.some(
419 (event) =>
420 event.type === "turn_item.updated" &&
421 event.turnItem.type === "assistant_message" &&
422 event.turnItem.text === "DONE",
423 ),
424 );
425 }).pipe(Effect.scoped),
426 );
427​
428 it.effect("denies the subagent tool on the sessions it creates", () =>
429 Effect.gen(function* () {
430 const runtime = yield* openCode2ReplayRuntime([
431 ...opening,
432 out("session.create", {
433 location: { directory: WORK },
434 model: { providerID: "opencode", id: "big-pickle" },
435 permissions: t3Rules,
436 }),
437 replyData("session.create", sessionInfo()),
438 ]);
439 const thread = yield* runtime.ensureThread({
440 threadId,
441 modelSelection: bigPickle,
442 runtimePolicy: policy(),
443 });
444 assert.equal(thread.nativeThreadRef?.nativeId, SESSION);
445 }).pipe(Effect.scoped),
446 );
447​
448 it.effect("stops running turns on an external server when the session closes", () =>
449 Effect.gen(function* () {
450 const scope = yield* Scope.make();
451 const { runtime, thread } = yield* resumed(
452 [
453 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
454 promptAccepted,
455 out("session.interrupt", { sessionID: SESSION }),
456 reply("session.interrupt", { interrupted: true }),
457 ],
458 { external: true },
459 ).pipe(Scope.provide(scope));
460 yield* runtime.startTurn(turnInput(thread));
461 yield* Scope.close(scope, Exit.void);
462 }),
463 );
464​
465 it.effect("ends a turn locally when a stuck server never answers Stop", () =>
466 Effect.gen(function* () {
467 const { runtime, thread } = yield* resumed([
468 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
469 promptAccepted,
470 out("session.interrupt", { sessionID: SESSION }),
471 reply("session.interrupt", "<hang>"),
472 ]);
473 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
474 yield* runtime.startTurn(turnInput(thread));
475 const interrupt = yield* runtime
476 .interruptTurn({
477 providerThread: thread,
478 providerTurnId: yield* providerTurnId,
479 })
480 .pipe(Effect.forkScoped);
481 yield* TestClock.adjust("11 seconds");
482 yield* Fiber.join(interrupt);
483 assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
484 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
485 );
486​
487 /** A prompt accepted, then a Stop the server never answers, advanced past its timeout. */
488 const stopTimedOut: ReadonlyArray<ProviderReplayEntry> = [
489 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
490 promptAccepted,
491 out("session.interrupt", { sessionID: SESSION }),
492 reply("session.interrupt", "<hang>"),
493 ];
494 const secondTurn = (thread: OrchestrationV2ProviderThread) => ({
495 ...turnInput(thread),
496 runId: RunId.make("run:opencode2-adapter:2"),
497 runOrdinal: 2,
498 providerTurnOrdinal: 2,
499 attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
500 });
501 const stopFirstTurn = (
502 runtime: ProviderAdapterV2SessionRuntime,
503 thread: OrchestrationV2ProviderThread,
504 ) =>
505 Effect.gen(function* () {
506 yield* runtime.startTurn(turnInput(thread));
507 const interrupt = yield* runtime
508 .interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
509 .pipe(Effect.forkScoped);
510 yield* TestClock.adjust("11 seconds");
511 yield* Fiber.join(interrupt);
512 });
513 const terminals = (runtime: ProviderAdapterV2SessionRuntime, count: number) =>
514 runtime.events.pipe(
515 Stream.filter(
516 (event): event is Extract<ProviderAdapterV2Event, { type: "turn.terminal" }> =>
517 event.type === "turn.terminal",
518 ),
519 Stream.take(count),
520 Stream.runCollect,
521 Effect.forkScoped,
522 );
523​
524 it.effect("never lets a timed-out Stop's late end finish the next turn", () =>
525 Effect.gen(function* () {
526 const { runtime, thread } = yield* resumed([
527 ...stopTimedOut,
528 // The server no longer runs the stopped execution, so the next turn goes ahead.
529 out("session.active"),
530 reply("session.active", { data: {} }),
531 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
532 promptAccepted,
533 // The stopped execution's end arrives late, then the new turn's own.
534 event("session.execution.succeeded", { sessionID: SESSION }),
535 event("session.execution.started", { sessionID: SESSION }),
536 event("session.execution.failed", {
537 sessionID: SESSION,
538 error: { type: "provider", message: "second turn failed" },
539 }),
540 ]);
541 const ended = yield* terminals(runtime, 2);
542 yield* stopFirstTurn(runtime, thread);
543 yield* runtime.startTurn(secondTurn(thread));
544 const [first, second] = yield* Fiber.join(ended);
545 assert.equal(first?.status, "interrupted");
546 // Only the second turn's own end finishes it.
547 assert.equal(second?.status, "failed");
548 assert.equal(second?.failure?.message, "second turn failed");
549 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
550 );
551​
552 it.effect(
553 "starts the next turn once the server no longer runs a timed-out Stop's execution",
554 () =>
555 Effect.gen(function* () {
556 const { runtime, thread } = yield* resumed([
557 ...stopTimedOut,
558 out("session.active"),
559 reply("session.active", { data: {} }),
560 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
561 promptAccepted,
562 event("session.execution.started", { sessionID: SESSION }),
563 event("session.execution.succeeded", { sessionID: SESSION }),
564 ]);
565 const ended = yield* terminals(runtime, 2);
566 yield* stopFirstTurn(runtime, thread);
567 yield* runtime.startTurn(secondTurn(thread));
568 const [, second] = yield* Fiber.join(ended);
569 assert.equal(second?.status, "completed");
570 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
571 );
572​
573 it.effect("reads a timed-out Stop's next turn from an execution start it cannot decode", () =>
574 Effect.gen(function* () {
575 const { runtime, thread } = yield* resumed([
576 ...stopTimedOut,
577 out("session.active"),
578 reply("session.active", { data: {} }),
579 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
580 promptAccepted,
581 // A newer server's start: the full schema rejects it, but it still opens the turn.
582 {
583 type: "emit_inbound",
584 frame: {
585 type: "sdk.event",
586 event: {
587 id: "evt_executionstartednewer",
588 created: 1,
589 type: "session.execution.started",
590 data: { sessionID: SESSION },
591 durable: "not-an-envelope",
592 },
593 },
594 },
595 event("session.text.ended", {
596 sessionID: SESSION,
597 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
598 ordinal: 0,
599 text: "DONE",
600 }),
601 event("session.execution.succeeded", { sessionID: SESSION }),
602 ]);
603 const ended = yield* terminals(runtime, 2);
604 yield* stopFirstTurn(runtime, thread);
605 yield* runtime.startTurn(secondTurn(thread));
606 const [, second] = yield* Fiber.join(ended);
607 assert.equal(second?.status, "completed");
608 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
609 );
610​
611 it.effect("checks the server before prompting again after a prompt request failed", () =>
612 Effect.gen(function* () {
613 const { runtime, thread } = yield* resumed([
614 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
615 // The request failed, but the server may have taken the prompt.
616 reply("session.prompt", {
617 status: 502,
618 body: { _tag: "UnknownError", message: "bad gateway" },
619 }),
620 out("session.active"),
621 reply("session.active", { data: { [SESSION]: { type: "running" } } }),
622 out("session.interrupt", { sessionID: SESSION }),
623 reply("session.interrupt", { interrupted: true }),
624 ]);
625 const ended = yield* terminals(runtime, 2);
626 yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
627 yield* runtime.startTurn(secondTurn(thread));
628 const [first, second] = yield* Fiber.join(ended);
629 assert.equal(first?.status, "failed");
630 assert.equal(second?.failure?.message, OPENCODE_2_STILL_STOPPING);
631 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
632 );
633​
634 it.effect("prompts again without a check after the server refused a prompt", () =>
635 Effect.gen(function* () {
636 const { runtime, thread } = yield* resumed([
637 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
638 reply("session.prompt", {
639 status: 400,
640 body: { _tag: "InvalidRequestError", message: "bad prompt" },
641 }),
642 // A clear refusal: nothing runs, so the next turn prompts directly.
643 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
644 promptAccepted,
645 event("session.execution.succeeded", { sessionID: SESSION }),
646 ]);
647 const ended = yield* terminals(runtime, 2);
648 yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
649 yield* runtime.startTurn(secondTurn(thread));
650 const [first, second] = yield* Fiber.join(ended);
651 assert.deepEqual([first?.status, second?.status], ["failed", "completed"]);
652 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
653 );
654​
655 it.effect("stops a timed-out Stop's execution again and fails the turn while it runs", () =>
656 Effect.gen(function* () {
657 const { runtime, thread } = yield* resumed([
658 ...stopTimedOut,
659 out("session.active"),
660 reply("session.active", { data: { [SESSION]: { type: "running" } } }),
661 // Stopped again, and the turn fails without a prompt.
662 out("session.interrupt", { sessionID: SESSION }),
663 reply("session.interrupt", { interrupted: true }),
664 ]);
665 const ended = yield* terminals(runtime, 2);
666 yield* stopFirstTurn(runtime, thread);
667 yield* runtime.startTurn(secondTurn(thread));
668 const [, second] = yield* Fiber.join(ended);
669 assert.equal(second?.status, "failed");
670 assert.equal(second?.failure?.message, OPENCODE_2_STILL_STOPPING);
671 }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
672 );
673​
674 it.effect("does not report a Stop the server says did nothing", () =>
675 Effect.gen(function* () {
676 const { runtime, thread } = yield* resumed([
677 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
678 promptAccepted,
679 out("session.interrupt", { sessionID: SESSION }),
680 reply("session.interrupt", { interrupted: false }),
681 ]);
682 yield* runtime.startTurn(turnInput(thread));
683 const failed = yield* runtime
684 .interruptTurn({
685 providerThread: thread,
686 providerTurnId: yield* providerTurnId,
687 })
688 .pipe(Effect.flip);
689 assert.equal(failed._tag, "ProviderAdapterProtocolError");
690 }).pipe(Effect.scoped),
691 );
692​
693 it.effect("reports a turn as completed when its Stop request failed", () =>
694 Effect.gen(function* () {
695 const { runtime, thread } = yield* resumed([
696 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
697 promptAccepted,
698 out("session.interrupt", { sessionID: SESSION }),
699 reply("session.interrupt", {
700 status: 500,
701 body: { _tag: "UnknownError", message: "interrupt failed" },
702 }),
703 event("session.execution.succeeded", { sessionID: SESSION }),
704 ]);
705 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
706 yield* runtime.startTurn(turnInput(thread));
707 const failed = yield* runtime
708 .interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
709 .pipe(Effect.flip);
710 assert.equal(failed._tag, "ProviderAdapterInterruptError");
711 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
712 }).pipe(Effect.scoped),
713 );
714​
715 it.effect("refuses to resume a thread without an OpenCode session as a protocol error", () =>
716 Effect.gen(function* () {
717 const runtime = yield* openCode2ReplayRuntime(opening);
718 const failed = yield* runtime
719 .resumeThread({
720 providerThread: { ...providerThread(yield* DateTime.now), nativeThreadRef: null },
721 })
722 .pipe(Effect.flip);
723 assert.equal(failed._tag, "ProviderAdapterProtocolError");
724 }).pipe(Effect.scoped),
725 );
726​
727 it.effect("gives a resumed session T3's rules when it was made with others", () =>
728 Effect.gen(function* () {
729 const runtime = yield* openCode2ReplayRuntime([
730 ...opening,
731 out("session.get", { sessionID: SESSION }),
732 // Made before the subagent rule: it still allows everything.
733 replyData(
734 "session.get",
735 sessionInfo({ permissions: [{ action: "*", resource: "*", effect: "allow" }] }),
736 ),
737 ...noOpenRequests,
738 out("session.update", { sessionID: SESSION, permissions: t3Rules }),
739 reply("session.update", null),
740 ]);
741 yield* runtime.resumeThread({
742 providerThread: providerThread(yield* DateTime.now),
743 threadId,
744 modelSelection: bigPickle,
745 runtimePolicy: policy(),
746 });
747 }).pipe(Effect.scoped),
748 );
749​
750 it.effect("moves the session when the thread's worktree changed", () =>
751 Effect.gen(function* () {
752 const runtime = yield* openCode2ReplayRuntime([
753 ...opening,
754 ...directoryModels("/work/opencode2-feature"),
755 out("session.get", { sessionID: SESSION }),
756 replyData("session.get", sessionInfo()),
757 ...noOpenRequests,
758 out("session.move", { sessionID: SESSION, directory: "/work/opencode2-feature" }),
759 reply("session.move", null),
760 ]);
761 yield* runtime.resumeThread({
762 providerThread: providerThread(yield* DateTime.now),
763 threadId,
764 modelSelection: bigPickle,
765 runtimePolicy: { ...policy(), cwd: "/work/opencode2-feature" },
766 });
767 }).pipe(Effect.scoped),
768 );
769​
770 it.effect(
771 "moves the session when a thread it resumes through ensureThread changed worktree",
772 () =>
773 Effect.gen(function* () {
774 const runtime = yield* openCode2ReplayRuntime([
775 ...opening,
776 ...directoryModels("/work/opencode2-feature"),
777 out("session.get", { sessionID: SESSION }),
778 replyData("session.get", sessionInfo()),
779 ...noOpenRequests,
780 out("session.move", { sessionID: SESSION, directory: "/work/opencode2-feature" }),
781 reply("session.move", null),
782 ]);
783 yield* runtime.ensureThread({
784 threadId,
785 modelSelection: bigPickle,
786 runtimePolicy: { ...policy(), cwd: "/work/opencode2-feature" },
787 existingProviderThread: providerThread(yield* DateTime.now),
788 });
789 }).pipe(Effect.scoped),
790 );
791​
792 it.effect("breaks the thread and forgets it when the session was deleted outside T3", () =>
793 Effect.gen(function* () {
794 const { runtime, thread } = yield* resumed([
795 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
796 reply("session.prompt", {
797 status: 404,
798 body: {
799 _tag: "SessionNotFoundError",
800 sessionID: SESSION,
801 message: `Session not found: ${SESSION}`,
802 },
803 }),
804 ]);
805 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
806 yield* runtime.startTurn(turnInput(thread)).pipe(Effect.ignore);
807 const ended = yield* Fiber.join(terminal);
808 assert.equal(ended?.status, "failed");
809 assert.equal(ended?.threadDisposition, "broken");
810 // The next turn must resume (and fail into a handoff), not reuse the dead session.
811 const again = yield* runtime.startTurn(turnInput(thread)).pipe(Effect.flip);
812 assert.equal(again._tag, "ProviderAdapterProtocolError");
813 assert.include(again.message, "not registered");
814 }).pipe(Effect.scoped),
815 );
816​
817 it.effect("refuses a model slug that is not provider/model before creating a session", () =>
818 Effect.gen(function* () {
819 // Nothing but the session's opening is expected: no create, no prompt.
820 const runtime = yield* openCode2ReplayRuntime([...opening]);
821 const created = yield* runtime
822 .ensureThread({
823 threadId,
824 modelSelection: { instanceId, model: "big-pickle" },
825 runtimePolicy: policy(),
826 })
827 .pipe(Effect.flip);
828 assert.equal(created._tag, "ProviderAdapterProtocolError");
829 assert.include(created.message, "OpenCode model 'big-pickle' must use provider/model format");
830 }).pipe(Effect.scoped),
831 );
832​
833 it.effect("refuses a turn whose model slug is not provider/model before prompting", () =>
834 Effect.gen(function* () {
835 const { runtime, thread } = yield* resumed([]);
836 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
837 yield* runtime.startTurn(turnInput(thread, { instanceId, model: "big-pickle" }));
838 const refused = yield* Fiber.join(terminal);
839 assert.equal(refused?.failure?.class, "validation_error");
840 assert.include(refused?.failure?.message, "must use provider/model format");
841 }).pipe(Effect.scoped),
842 );
843​
844 it.effect("stops the requests a session still waits on when a restarted T3 loads it", () =>
845 Effect.gen(function* () {
846 // T3 restarted while the server kept waiting on an ask T3 no longer shows.
847 const runtime = yield* openCode2ReplayRuntime(
848 [
849 ...opening,
850 out("session.get", { sessionID: SESSION }),
851 replyData("session.get", sessionInfo()),
852 out("permission.list", { sessionID: SESSION }),
853 replyData("permission.list", [shellAsk.data]),
854 out("session.form.list", { sessionID: SESSION }),
855 replyData("session.form.list", [colorForm]),
856 out("permission.reply", {
857 sessionID: SESSION,
858 requestID: shellAsk.data.id,
859 decision: "reject",
860 }),
861 reply("permission.reply", null),
862 out("session.form.cancel", { sessionID: SESSION, formID: colorForm.id }),
863 reply("session.form.cancel", null),
864 // The next turn checks that the stopped run is gone. Its end arrives
865 // late and is its own; the turn ends on its own execution's end.
866 out("session.active"),
867 reply("session.active", { data: {} }),
868 event("session.execution.interrupted", { sessionID: SESSION, reason: "user" }),
869 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
870 promptAccepted,
871 event("session.execution.started", { sessionID: SESSION }),
872 event("session.execution.succeeded", { sessionID: SESSION }),
873 ],
874 { external: true },
875 );
876 const thread = yield* runtime.resumeThread({
877 providerThread: providerThread(yield* DateTime.now),
878 threadId,
879 modelSelection: bigPickle,
880 runtimePolicy: policy(),
881 });
882 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
883 yield* runtime.startTurn(turnInput(thread));
884 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
885 }).pipe(Effect.scoped),
886 );
887​
888 it.effect("ends the turn when an answer to its request cannot be delivered", () =>
889 Effect.gen(function* () {
890 const failedReply = reply("permission.reply", {
891 status: 500,
892 body: { _tag: "UnknownError", message: "reply failed" },
893 });
894 const replyOut = out("permission.reply", {
895 sessionID: SESSION,
896 requestID: shellAsk.data.id,
897 decision: "once",
898 });
899 const { runtime, thread } = yield* resumed(
900 [
901 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
902 promptAccepted,
903 shellAskEvent,
904 // One try and one retry, then the turn ends and the session is stopped.
905 replyOut,
906 failedReply,
907 replyOut,
908 failedReply,
909 out("session.interrupt", { sessionID: SESSION }),
910 reply("session.interrupt", { interrupted: true }),
911 ],
912 { supervised: true },
913 );
914 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
915 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
916 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
917 const request = yield* Fiber.join(requested);
918 yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
919 const ended = yield* Fiber.join(terminal);
920 assert.equal(ended?.status, "failed");
921 assert.equal(
922 ended?.status === "failed" ? ended.failure.message : undefined,
923 "OpenCode is waiting on a request T3 Code couldn't answer.",
924 );
925 }).pipe(Effect.scoped),
926 );
927​
928 it.effect("counts an answer to a request OpenCode already dropped as delivered", () =>
929 Effect.gen(function* () {
930 const { runtime, thread } = yield* resumed(
931 [
932 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
933 promptAccepted,
934 shellAskEvent,
935 // The execution ended first, so OpenCode no longer knows the request.
936 out("permission.reply", {
937 sessionID: SESSION,
938 requestID: shellAsk.data.id,
939 decision: "once",
940 }),
941 reply("permission.reply", {
942 status: 404,
943 body: {
944 _tag: "PermissionNotFoundError",
945 requestID: shellAsk.data.id,
946 message: "Permission request not found",
947 },
948 }),
949 event("session.execution.succeeded", { sessionID: SESSION }),
950 ],
951 { supervised: true },
952 );
953 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
954 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
955 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
956 const request = yield* Fiber.join(requested);
957 yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
958 // Not "waiting on a request T3 Code couldn't answer": nothing waits on it.
959 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
960 }).pipe(Effect.scoped),
961 );
962​
963 it.effect("declines a form T3 cannot show with the reason, instead of leaving it open", () =>
964 Effect.gen(function* () {
965 const { runtime, thread } = yield* resumed([
966 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
967 promptAccepted,
968 event("form.created", {
969 form: {
970 id: "frm_0eb79ab35001fkvFECSh3wYNVD",
971 sessionID: SESSION,
972 title: "MCP authorization",
973 metadata: { kind: "mcp" },
974 fields: [
975 {
976 key: "authorization",
977 type: "external",
978 url: "https://example.com/authorize",
979 title: "Authorize",
980 },
981 ],
982 },
983 }),
984 out("session.form.cancel", {
985 sessionID: SESSION,
986 formID: "frm_0eb79ab35001fkvFECSh3wYNVD",
987 }),
988 reply("session.form.cancel", null),
989 ]);
990 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
991 yield* runtime.startTurn(turnInput(thread));
992 const ended = yield* Fiber.join(terminal);
993 assert.equal(ended?.status, "failed");
994 assert.include(
995 ended?.status === "failed" ? ended.failure.message : "",
996 "asked for a link to open",
997 );
998 }).pipe(Effect.scoped),
999 );
1000​
1001 it.effect("asks a subagent's permission request on the parent thread's turn", () =>
1002 Effect.gen(function* () {
1003 const child = "ses_f0e5aa64cffelFnoQRL0DAA9BH";
1004 const { runtime, thread } = yield* resumed(
1006 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1007 promptAccepted,
1008 // As 2.0.18 announced the child the live probe's parent started.
1009 event("session.created", {
1010 sessionID: child,
1011 slug: "stellar-garden",
1012 version: "2.0.18",
1013 projectID: "global",
1014 parentID: SESSION,
1015 location: { directory: WORK },
1016 subpath: "",
1017 title: "Echo test command",
1018 agent: "general",
1019 permissions: supervisedRules,
1020 model: { id: "big-pickle", providerID: "opencode", variant: "default" },
1021 }),
1022 event("permission.asked", { ...shellAsk.data, sessionID: child }),
1023 out("permission.reply", {
1024 sessionID: child,
1025 requestID: shellAsk.data.id,
1026 decision: "once",
1027 }),
1028 reply("permission.reply", null),
1029 event("permission.replied", {
1030 sessionID: child,
1031 requestID: shellAsk.data.id,
1032 reply: "once",
1033 }),
1034 event("session.execution.succeeded", { sessionID: SESSION }),
1035 ],
1036 { supervised: true },
1037 );
1038 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
1039 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
1040 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
1041 const request = yield* Fiber.join(requested);
1042 assert.equal(request?.nativeRequestRef?.nativeId, shellAsk.data.id);
1043 yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
1044 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
1045 }).pipe(Effect.scoped),
1046 );
1047​
1048 it.effect("keeps 'allow this session' in the session's rules, not OpenCode's saved grants", () =>
1049 Effect.gen(function* () {
1050 const { runtime, thread } = yield* resumed(
1052 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1053 promptAccepted,
1054 shellAskEvent,
1055 // The grant goes into this session's rules; the reply is only `once`.
1056 out("session.update", {
1057 sessionID: SESSION,
1058 permissions: [
1059 ...supervisedRules.slice(0, 3),
1060 { action: "shell", resource: "echo *", effect: "allow" },
1061 ...supervisedRules.slice(3),
1062 ],
1063 }),
1064 reply("session.update", null),
1065 out("permission.reply", {
1066 sessionID: SESSION,
1067 requestID: shellAsk.data.id,
1068 decision: "once",
1069 }),
1070 reply("permission.reply", null),
1071 event("session.execution.succeeded", { sessionID: SESSION }),
1072 ],
1073 { supervised: true },
1074 );
1075 const requested = yield* requestOf(runtime).pipe(Effect.forkScoped);
1076 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
1077 yield* runtime.startTurn(turnInput(thread, bigPickle, "approval-required"));
1078 const request = yield* Fiber.join(requested);
1079 yield* runtime.respondToRuntimeRequest({
1080 requestId: request!.id,
1081 decision: "acceptForSession",
1082 });
1083 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
1084 }).pipe(Effect.scoped),
1085 );
1086​
1087 it.effect("reads the agents again while a fresh server still lists none", () =>
1088 Effect.gen(function* () {
1089 // 2.0.18 answers `/api/agent` with `[]` for a moment after it starts;
1090 // rules written from that would drop the agents' own paths.
1091 const runtime = yield* openCode2ReplayRuntime([
1092 ...opening,
1093 out("agent.list", "<any>"),
1094 reply("agent.list", { location: { directory: WORK }, data: [] }),
1095 out("agent.list", "<any>"),
1096 reply("agent.list", agentList),
1097 out("session.create", {
1098 location: { directory: WORK },
1099 model: { providerID: "opencode", id: "big-pickle" },
1100 permissions: supervisedRules,
1101 }),
1102 replyData("session.create", sessionInfo({ permissions: supervisedRules })),
1103 ]);
1104 const created = yield* runtime
1105 .ensureThread({
1106 threadId,
1107 modelSelection: bigPickle,
1108 runtimePolicy: policy("approval-required"),
1109 })
1110 .pipe(Effect.forkScoped);
1111 yield* TestClock.adjust("250 millis");
1112 assert.equal((yield* Fiber.join(created)).nativeThreadRef?.nativeId, SESSION);
1113 }).pipe(Effect.scoped),
1114 );
1115​
1116 it.effect("refuses a turn after the event stream is gone instead of prompting", () =>
1117 Effect.gen(function* () {
1118 // The stream ends with no turn running; no prompt is expected after it.
1119 const { runtime, thread } = yield* resumed([{ type: "runtime_exit", status: "success" }]);
1120 // The runtime ends its own events once the lost stream is settled.
1121 yield* runtime.events.pipe(Stream.runDrain);
1122 const refused = yield* runtime
1123 .startTurn(turnInput(thread))
1124 .pipe(Effect.flip, Effect.timeout("5 seconds"));
1125 assert.equal(refused._tag, "ProviderAdapterEventStreamError");
1126 }).pipe(Effect.scoped),
1127 );
1128​
1129 it.effect("reports the session as failed after a lost stream settles its turns", () =>
1130 Effect.gen(function* () {
1131 const { runtime, thread } = yield* resumed([
1132 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1133 promptAccepted,
1134 { type: "runtime_exit", status: "success" },
1135 ]);
1136 // The runtime's event stream has one consumer.
1137 const events = yield* runtime.events.pipe(Stream.runCollect, Effect.forkScoped);
1138 yield* runtime.startTurn(turnInput(thread));
1139 const collected = yield* Fiber.join(events);
1140 const last = collected.findLast((event) => event.type === "provider_session.updated");
1141 assert.equal(
1142 last?.type === "provider_session.updated" ? last.providerSession.status : undefined,
1143 "error",
1144 );
1145 }).pipe(Effect.scoped),
1146 );
1147 it.effect("reads user and assistant text from the session's message list", () =>
1148 Effect.gen(function* () {
1149 const runtime = yield* openCode2ReplayRuntime([
1150 ...opening,
1151 out("message.list", { sessionID: SESSION, order: "asc", limit: "100" }),
1152 reply("message.list", history),
1153 ]);
1154 const snapshot = yield* runtime.readThreadSnapshot({
1155 providerThread: providerThread(yield* DateTime.now),
1156 });
1157 assert.deepEqual(
1158 snapshot.messages.map((message) => [message.role, message.text]),
1160 ["user", history.data[0]!.text],
1161 ["assistant", "391 is not prime: it's the product 17 × 23."],
1162 ],
1163 );
1164 assert.equal(
1165 snapshot.providerThread.nativeConversationHeadRef?.nativeId,
1166 history.data[0]!.id,
1167 );
1168 }).pipe(Effect.scoped),
1169 );
1170​
1171 it.effect("ends a turn before re-reading a model list that never answers", () =>
1172 Effect.gen(function* () {
1173 // The session opened before the catalog loaded, so the turn's model has no window.
1174 const runtime = yield* openCode2ReplayRuntime([
1175 out("event.subscribe"),
1176 out("model.list", "<any>"),
1177 reply("model.list", { location: { directory: WORK }, data: [] }),
1178 out("session.get", { sessionID: SESSION }),
1179 replyData("session.get", sessionInfo()),
1180 ...noOpenRequests,
1181 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1182 promptAccepted,
1183 event("session.execution.succeeded", { sessionID: SESSION }),
1184 out("model.list", "<any>"),
1185 reply("model.list", "<hang>"),
1186 ]);
1187 const thread = yield* runtime.resumeThread({
1188 providerThread: providerThread(yield* DateTime.now),
1189 threadId,
1190 modelSelection: bigPickle,
1191 runtimePolicy: policy(),
1192 });
1193 const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
1194 yield* runtime.startTurn(turnInput(thread));
1195 assert.equal((yield* Fiber.join(terminal))?.status, "completed");
1196 // The terminal did not wait on the re-read, which is still in flight.
1197 for (let i = 0; i < 20; i++) yield* Effect.yieldNow;
1198 }).pipe(Effect.scoped),
1199 );
1200​
1201 it.effect("reports cache writes as cache creation, not only as input", () =>
1202 Effect.gen(function* () {
1203 const { runtime, thread } = yield* resumed([
1204 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1205 promptAccepted,
1206 // A step from a provider that reports prompt-cache writes.
1207 event("session.step.ended", {
1208 sessionID: SESSION,
1209 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
1210 finish: "stop",
1211 cost: 0,
1212 tokens: { input: 1200, output: 40, reasoning: 0, cache: { read: 300, write: 2500 } },
1213 }),
1214 event("session.execution.succeeded", { sessionID: SESSION }),
1215 ]);
1216 const turn = yield* runtime.events.pipe(
1217 Stream.filter(
1218 (event) =>
1219 event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null,
1220 ),
1221 Stream.runHead,
1222 Effect.forkScoped,
1223 );
1224 yield* runtime.startTurn(turnInput(thread));
1225 const settled = Option.getOrUndefined(yield* Fiber.join(turn));
1226 assert.deepInclude(
1227 settled?.type === "provider_turn.updated" ? settled.providerTurn.turnTokenUsage : undefined,
1229 inputTokens: 1200 + 300 + 2500,
1230 cachedInputTokens: 300,
1231 cacheCreationTokens: 2500,
1232 outputTokens: 40,
1233 },
1234 );
1235 }).pipe(Effect.scoped),
1236 );
1237​
1238 it.effect("reports a model's input limit as its context window", () =>
1239 Effect.gen(function* () {
1240 const runtime = yield* openCode2ReplayRuntime([...opening]);
1241 assert.equal(runtime.getModelContextWindow?.(bigPickle), 160000);
1242 }).pipe(Effect.scoped),
1243 );
1244​
1245 it.effect("reports each directory's own limit for a model its project config changed", () =>
1246 Effect.gen(function* () {
1247 // 2.0.18 lists big-pickle at 48k input for a project whose opencode.json
1248 // sets that limit, and at its catalog 160k everywhere else.
1249 const custom = "/work/opencode2-custom";
1250 const runtime = yield* openCode2ReplayRuntime([
1251 ...opening,
1252 out("model.list", { "location[directory]": custom }),
1253 reply("model.list", {
1254 location: { directory: custom },
1255 data: modelCatalog.data.map((model) => ({
1256 ...model,
1257 limit: { context: 64000, input: 48000, output: 8000 },
1258 })),
1259 }),
1260 out("session.create", {
1261 location: { directory: custom },
1262 model: { providerID: "opencode", id: "big-pickle" },
1263 permissions: t3Rules,
1264 }),
1265 replyData("session.create", sessionInfo({ location: { directory: custom } })),
1266 out("session.prompt", { sessionID: SESSION, text: "<any>" }),
1267 promptAccepted,
1268 event("session.step.ended", {
1269 sessionID: SESSION,
1270 assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z",
1271 finish: "stop",
1272 cost: 0,
1273 tokens: { input: 1200, output: 40, reasoning: 0, cache: { read: 0, write: 0 } },
1274 }),
1275 event("session.execution.succeeded", { sessionID: SESSION }),
1276 ]);
1277 const customPolicy = { ...policy(), cwd: custom };
1278 const thread = yield* runtime.ensureThread({
1279 threadId,
1280 modelSelection: bigPickle,
1281 runtimePolicy: customPolicy,
1282 });
1283 // Each directory keeps its own limit, whichever was read last.
1284 assert.equal(runtime.getModelContextWindow?.(bigPickle, WORK), 160000);
1285 assert.equal(runtime.getModelContextWindow?.(bigPickle, custom), 48000);
1286 const settled = yield* runtime.events.pipe(
1287 Stream.filter(
1288 (event) =>
1289 event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null,
1290 ),
1291 Stream.runHead,
1292 Effect.forkScoped,
1293 );
1294 yield* runtime.startTurn({ ...turnInput(thread), runtimePolicy: customPolicy });
1295 const turn = Option.getOrUndefined(yield* Fiber.join(settled));
1296 assert.equal(
1297 turn?.type === "provider_turn.updated" ? turn.providerTurn.tokenUsage?.maxTokens : null,
1298 48000,
1299 );
1300 }).pipe(Effect.scoped),
1301 );
1302});
1303​
1304/** The provider turn the adapter derives for `turnInput`'s attempt. */
1305const providerTurnId = Effect.gen(function* () {
1306 const ids = yield* IdAllocator.IdAllocatorV2;
1307 return ids.derive.providerTurn({
1308 driver: OPENCODE_PROVIDER,
1309 nativeTurnId: `${SESSION}:attempt:attempt:opencode2-adapter`,
1310 });
1311}).pipe(Effect.provide(IdAllocator.layer));