Open History to see the last commit
1import type { OpencodeClient } from "@opencode-ai/sdk/v2";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { ProviderReplayEntry, type ProviderReplayTranscript } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Duration from "effect/Duration";
6import * as Layer from "effect/Layer";
7import * as Schema from "effect/Schema";
8
9import * as ServerConfig from "../../config.ts";
10import * as OpenCodeRuntime from "../../provider/opencodeRuntime.ts";
11import * as ProviderEventLoggers from "../../provider/Layers/ProviderEventLoggers.ts";
12import * as IdAllocator from "../IdAllocator.ts";
13import { ProviderAdapterDriverCreateError } from "../ProviderAdapterDriver.ts";
14import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
15import {
16 makeReplayServerConfig,
17 type OrchestratorV2ProviderReplayHarness,
18} from "../testkit/ProviderReplayHarness.ts";
19import {
20 OPENCODE_DEFAULT_INSTANCE_ID,
21 OPENCODE_PROVIDER,
22 OPENCODE_SDK_PROTOCOL,
23 OpenCodeAdapterV2Driver,
24} from "./OpenCodeAdapterV2.ts";
25
26const OPENCODE_SDK_REPLAY_PROTOCOL = OPENCODE_SDK_PROTOCOL;
27
28const OpenCodeSdkReplayTranscript = Schema.Struct({
29 provider: Schema.Literal(OPENCODE_PROVIDER),
30 protocol: Schema.Literal(OPENCODE_SDK_REPLAY_PROTOCOL),
31 version: Schema.String,
32 scenario: Schema.String,
33 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
34 entries: Schema.Array(ProviderReplayEntry),
35});
36export type OpenCodeSdkReplayTranscript = typeof OpenCodeSdkReplayTranscript.Type;
37const decodeOpenCodeSdkReplayTranscript = Schema.decodeUnknownEffect(OpenCodeSdkReplayTranscript);
38
39export class OpenCodeReplayTranscriptDecodeError extends Schema.TaggedError<OpenCodeReplayTranscriptDecodeError>()(
40 "OpenCodeReplayTranscriptDecodeError",
41 {
42 driver: Schema.optional(Schema.String),
43 protocol: Schema.optional(Schema.String),
44 scenario: Schema.optional(Schema.String),
45 cause: Schema.Defect(),
46 },
47) {
48 override get message(): string {
49 return `Failed to decode OpenCode replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
50 }
51}
52
53export class OpenCodeReplayMismatchError extends Schema.TaggedError<OpenCodeReplayMismatchError>()(
54 "OpenCodeReplayMismatchError",
55 {
56 scenario: Schema.String,
57 cursor: Schema.Number,
58 expected: Schema.Unknown,
59 actual: Schema.Unknown,
60 },
61) {
62 override get message(): string {
63 return `OpenCode replay frame mismatch at cursor ${this.cursor} in scenario ${this.scenario}.`;
64 }
65}
66
67export class OpenCodeReplayIncompleteError extends Schema.TaggedError<OpenCodeReplayIncompleteError>()(
68 "OpenCodeReplayIncompleteError",
69 {
70 scenario: Schema.String,
71 cursor: Schema.Number,
72 remaining: Schema.Number,
73 },
74) {
75 override get message(): string {
76 return `OpenCode replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`;
77 }
78}
79
80export const OpenCodeReplayError = Schema.Union([
81 OpenCodeReplayTranscriptDecodeError,
82 OpenCodeReplayMismatchError,
83 OpenCodeReplayIncompleteError,
84]);
85export type OpenCodeReplayError = typeof OpenCodeReplayError.Type;
86export const OpenCodeOrchestratorReplayHarnessError = Schema.Union([
87 OpenCodeReplayError,
88 ProviderAdapterDriverCreateError,
89]);
90export type OpenCodeOrchestratorReplayHarnessError =
91 typeof OpenCodeOrchestratorReplayHarnessError.Type;
92
93function replayValueMatches(expected: unknown, actual: unknown): boolean {
94 if (expected === "<any>" || expected === "<workspace>") return true;
95 if (Array.isArray(expected)) {
96 return (
97 Array.isArray(actual) &&
98 expected.length === actual.length &&
99 expected.every((entry, index) => replayValueMatches(entry, actual[index]))
100 );
101 }
102 if (typeof expected === "object" && expected !== null) {
103 if (typeof actual !== "object" || actual === null) return false;
104 return Object.entries(expected).every(([key, value]) =>
105 replayValueMatches(value, (actual as Record<string, unknown>)[key]),
106 );
107 }
108 return Object.is(expected, actual);
109}
110
111function frameRecord(frame: unknown): Record<string, unknown> | null {
112 return typeof frame === "object" && frame !== null ? (frame as Record<string, unknown>) : null;
113}
114
115function materializeMessageIds(value: unknown, messageIds: ReadonlyMap<string, string>): unknown {
116 if (Array.isArray(value)) return value.map((entry) => materializeMessageIds(entry, messageIds));
117 const record = frameRecord(value);
118 if (record === null) return value;
119 return Object.fromEntries(
120 Object.entries(record).map(([key, entry]) => [
121 key,
122 typeof entry === "string" &&
123 (key === "id" ||
124 key === "messageID" ||
125 key === "parentID" ||
126 key === "inboxID" ||
127 key === "before")
128 ? (messageIds.get(entry) ?? entry)
129 : materializeMessageIds(entry, messageIds),
130 ]),
131 );
132}
133
134/**
135 * Replays one transcript at a client boundary: each outbound call must match the
136 * next `expect_outbound`, then answers with its `sdk.response`; `sdk.event`
137 * frames feed the event stream. Shared by the 1.x SDK and 2.x HTTP transports.
138 */
139export class OpenCodeReplayController {
140 private cursor = 0;
141 /** Set once the event stream reached a successful `runtime_exit`: the server is gone. */
142 exited = false;
143
144 /** Whether every entry has been used, so a stopped server is not coming back. */
145 get finished(): boolean {
146 return this.cursor >= this.transcript.entries.length;
147 }
148 private readonly waiters = new Set<() => void>();
149 private failure: unknown = null;
150 private readonly transcript: ProviderReplayTranscript;
151 private messageIds = new Map<string, string>();
152
153 constructor(transcript: ProviderReplayTranscript) {
154 this.transcript = transcript;
155 }
156
157 async expectOutbound(actual: unknown): Promise<void> {
158 try {
159 const entry = this.transcript.entries[this.cursor];
160 const expectedFrame = entry?.type === "expect_outbound" ? frameRecord(entry.frame) : null;
161 const actualFrame = frameRecord(actual);
162 const messageIds = new Map(this.messageIds);
163 let conflictingMessageId = false;
164 // A message id the client picks (1.x prompts, 2.x steers) replaces the
165 // recorded one everywhere after it, so replies and events carry the live id.
166 const idKey = expectedFrame?.type === "session.promptAsync" ? "messageID" : "id";
167 if (
168 (expectedFrame?.type === "session.promptAsync" ||
169 expectedFrame?.type === "session.prompt") &&
170 actualFrame?.type === expectedFrame.type
171 ) {
172 const recordedId = frameRecord(expectedFrame.input)?.[idKey];
173 const actualId = frameRecord(actualFrame.input)?.[idKey];
174 if (
175 typeof recordedId === "string" &&
176 typeof actualId === "string" &&
177 recordedId !== "<any>" &&
178 recordedId !== "<workspace>" &&
179 !messageIds.has(recordedId)
180 ) {
181 conflictingMessageId = [...messageIds.values()].includes(actualId);
182 if (!conflictingMessageId) messageIds.set(recordedId, actualId);
183 }
184 }
185 const expected =
186 entry?.type === "expect_outbound"
187 ? materializeMessageIds(entry.frame, messageIds)
188 : (entry ?? null);
189 if (
190 conflictingMessageId ||
191 entry?.type !== "expect_outbound" ||
192 !replayValueMatches(expected, actual)
193 ) {
194 throw new OpenCodeReplayMismatchError({
195 scenario: this.transcript.scenario,
196 cursor: this.cursor,
197 expected,
198 actual,
199 });
200 }
201 this.messageIds = messageIds;
202 this.advance();
203 } catch (cause) {
204 this.fail(cause);
205 throw cause;
206 }
207 }
208
209 async response(operation: string): Promise<unknown> {
210 while (true) {
211 this.throwFailure();
212 const entry = this.transcript.entries[this.cursor];
213 if (entry?.type === "emit_inbound") {
214 const frame = frameRecord(entry.frame);
215 if (frame?.type === "sdk.response" && frame.operation === operation) {
216 if (entry.afterMs !== undefined && entry.afterMs > 0) {
217 await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs)));
218 }
219 const data = materializeMessageIds(frame.data, this.messageIds);
220 this.advance();
221 return data;
222 }
223 }
224 if (entry?.type === "runtime_exit") {
225 const mismatch = new OpenCodeReplayMismatchError({
226 scenario: this.transcript.scenario,
227 cursor: this.cursor,
228 expected: { type: "sdk.response", operation },
229 actual: entry,
230 });
231 this.fail(mismatch);
232 throw mismatch;
233 }
234 await this.changed();
235 }
236 }
237
238 /**
239 * Resolves once the server events recorded before the next entry have been
240 * delivered. For transports whose events and requests travel separately, a
241 * request is matched at its recorded point instead of racing those events.
242 */
243 async untilEventsDelivered(): Promise<void> {
244 while (true) {
245 this.throwFailure();
246 const entry = this.transcript.entries[this.cursor];
247 if (entry?.type !== "emit_inbound" || frameRecord(entry.frame)?.type !== "sdk.event") return;
248 await this.changed();
249 }
250 }
251
252 /**
253 * Like {@link untilEventsDelivered}, but also waits for recorded responses to
254 * be taken: over HTTP a request can start while an earlier one's answer is
255 * still in flight, and must not be matched against that answer.
256 */
257 async untilInboundDelivered(): Promise<void> {
258 while (true) {
259 this.throwFailure();
260 if (this.transcript.entries[this.cursor]?.type !== "emit_inbound") return;
261 await this.changed();
262 }
263 }
264
265 async *events(
266 signal?: AbortSignal,
267 beforeEmit?: (label: string | undefined) => Promise<void>,
268 ): AsyncIterable<unknown> {
269 while (true) {
270 if (signal?.aborted === true) return;
271 this.throwFailure();
272 const entry = this.transcript.entries[this.cursor];
273 if (entry?.type === "emit_inbound") {
274 const frame = frameRecord(entry.frame);
275 if (frame?.type === "sdk.event") {
276 // A scenario can hold an event until it has done what happened meanwhile.
277 if (beforeEmit !== undefined) await beforeEmit(entry.label);
278 if (entry.afterMs !== undefined && entry.afterMs > 0) {
279 await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs)));
280 }
281 const event = materializeMessageIds(frame.event, this.messageIds);
282 this.advance();
283 yield event;
284 continue;
285 }
286 }
287 if (entry?.type === "runtime_exit") {
288 this.advance();
289 if (entry.status === "success") {
290 this.exited = true;
291 return;
292 }
293 const mismatch = new OpenCodeReplayMismatchError({
294 scenario: this.transcript.scenario,
295 cursor: this.cursor - 1,
296 expected: { status: "success" },
297 actual: entry,
298 });
299 this.fail(mismatch);
300 throw mismatch;
301 }
302 await this.changed(signal);
303 }
304 }
305
306 assertComplete(): void {
307 while (this.transcript.entries[this.cursor]?.type === "runtime_exit") {
308 const exit = this.transcript.entries[this.cursor];
309 if (exit?.type !== "runtime_exit" || exit.status !== "success") break;
310 this.cursor += 1;
311 }
312 this.throwFailure();
313 if (this.cursor !== this.transcript.entries.length) {
314 throw new OpenCodeReplayIncompleteError({
315 scenario: this.transcript.scenario,
316 cursor: this.cursor,
317 remaining: this.transcript.entries.length - this.cursor,
318 });
319 }
320 }
321
322 private advance(): void {
323 this.cursor += 1;
324 for (const waiter of this.waiters) waiter();
325 this.waiters.clear();
326 }
327
328 private fail(cause: unknown): void {
329 this.failure = cause;
330 for (const waiter of this.waiters) waiter();
331 this.waiters.clear();
332 }
333
334 private throwFailure(): void {
335 if (this.failure !== null) throw this.failure;
336 }
337
338 private changed(signal?: AbortSignal): Promise<void> {
339 return new Promise((resolve) => {
340 let settled = false;
341 const done = () => {
342 if (settled) return;
343 settled = true;
344 signal?.removeEventListener("abort", done);
345 this.waiters.delete(done);
346 resolve();
347 };
348 this.waiters.add(done);
349 signal?.addEventListener("abort", done, { once: true });
350 if (signal?.aborted === true) done();
351 });
352 }
353}
354
355function makeReplayClient(controller: OpenCodeReplayController): OpencodeClient {
356 const request = async (operation: string, input: unknown) => {
357 await controller.expectOutbound({ type: operation, input });
358 return { data: await controller.response(operation) };
359 };
360 return {
361 event: {
362 subscribe: async (_input?: unknown, options?: { readonly signal?: AbortSignal }) => {
363 await controller.expectOutbound({ type: "event.subscribe" });
364 return { stream: controller.events(options?.signal) };
365 },
366 },
367 session: {
368 create: (input: unknown) => request("session.create", input),
369 get: (input: unknown) => request("session.get", input),
370 children: (input: unknown) => request("session.children", input),
371 update: (input: unknown) => request("session.update", input),
372 messages: (input: unknown) => request("session.messages", input),
373 promptAsync: (input: unknown) => request("session.promptAsync", input),
374 abort: (input: unknown) => request("session.abort", input),
375 revert: (input: unknown) => request("session.revert", input),
376 unrevert: (input: unknown) => request("session.unrevert", input),
377 fork: (input: unknown) => request("session.fork", input),
378 },
379 permission: {
380 reply: (input: unknown) => request("permission.reply", input),
381 },
382 question: {
383 reply: (input: unknown) => request("question.reply", input),
384 },
385 mcp: {
386 add: (input: unknown) => request("mcp.add", input),
387 },
388 } as unknown as OpencodeClient;
389}
390
391function makeOpenCodeReplayRuntimeLayer(transcript: OpenCodeSdkReplayTranscript) {
392 return Layer.effect(
393 OpenCodeRuntime.OpenCodeRuntime,
394 Effect.gen(function* () {
395 const controller = new OpenCodeReplayController(transcript);
396 yield* Effect.addFinalizer(() =>
397 Effect.sync(() => {
398 controller.assertComplete();
399 }),
400 );
401 const client = makeReplayClient(controller);
402 return OpenCodeRuntime.OpenCodeRuntime.of({
403 startOpenCodeServerProcess: () =>
404 Effect.fail(
405 new OpenCodeRuntime.OpenCodeRuntimeError({
406 operation: "startOpenCodeServerProcess",
407 detail: "OpenCode replay uses an external in-memory SDK boundary.",
408 }),
409 ),
410 connectToOpenCodeServer: () =>
411 Effect.succeed({
412 url: "replay://opencode",
413 version: "0.0.0-replay",
414 exitCode: null,
415 external: true,
416 }),
417 runOpenCodeCommand: () =>
418 Effect.fail(
419 new OpenCodeRuntime.OpenCodeRuntimeError({
420 operation: "runOpenCodeCommand",
421 detail: "OpenCode replay does not execute commands.",
422 }),
423 ),
424 createOpenCodeSdkClient: () => client,
425 loadOpenCodeInventory: () =>
426 Effect.fail(
427 new OpenCodeRuntime.OpenCodeRuntimeError({
428 operation: "loadOpenCodeInventory",
429 detail: "OpenCode replay does not load inventory.",
430 }),
431 ),
432 loadInventoryFromCli: () =>
433 Effect.fail(
434 new OpenCodeRuntime.OpenCodeRuntimeError({
435 operation: "loadInventoryFromCli",
436 detail: "OpenCode replay does not load inventory.",
437 }),
438 ),
439 loadOpenCodeSkills: () =>
440 Effect.fail(
441 new OpenCodeRuntime.OpenCodeRuntimeError({
442 operation: "loadOpenCodeSkills",
443 detail: "OpenCode replay does not load skills.",
444 }),
445 ),
446 loadSkillsFromCli: () =>
447 Effect.fail(
448 new OpenCodeRuntime.OpenCodeRuntimeError({
449 operation: "loadSkillsFromCli",
450 detail: "OpenCode replay does not load skills.",
451 }),
452 ),
453 } satisfies OpenCodeRuntime.OpenCodeRuntimeShape);
454 }),
455 );
456}
457
458function makeOpenCodeProviderAdapterRegistryReplayLayer(transcript: OpenCodeSdkReplayTranscript) {
459 const serverConfigLayer = Layer.effect(
460 ServerConfig.ServerConfig,
461 makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),
462 ).pipe(Layer.provide(NodeServices.layer));
463 return ProviderAdapterRegistry.makeDriverLayer({
464 drivers: [OpenCodeAdapterV2Driver],
465 configMap: {
466 [OPENCODE_DEFAULT_INSTANCE_ID]: {
467 driver: OPENCODE_PROVIDER,
468 config: { serverUrl: "replay://opencode" },
469 },
470 },
471 }).pipe(
472 Layer.provide(
473 Layer.mergeAll(
474 makeOpenCodeReplayRuntimeLayer(transcript),
475 serverConfigLayer,
476 NodeServices.layer,
477 IdAllocator.layer,
478 Layer.succeed(
479 ProviderEventLoggers.ProviderEventLoggers,
480 ProviderEventLoggers.NoOpProviderEventLoggers,
481 ),
482 ),
483 ),
484 );
485}
486
487function transcriptMetadata(transcript: ProviderReplayTranscript) {
488 return {
489 provider: transcript.provider,
490 protocol: transcript.protocol,
491 scenario: transcript.scenario,
492 };
493}
494
495export const OpenCodeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
496 OpenCodeSdkReplayTranscript,
497 OpenCodeOrchestratorReplayHarnessError
498> = {
499 driver: OPENCODE_PROVIDER,
500 decodeTranscript: (transcript) =>
501 decodeOpenCodeSdkReplayTranscript(transcript).pipe(
502 Effect.mapError(
503 (cause) =>
504 new OpenCodeReplayTranscriptDecodeError({
505 ...transcriptMetadata(transcript),
506 cause,
507 }),
508 ),
509 ),
510 makeProviderAdapterRegistryLayer: makeOpenCodeProviderAdapterRegistryReplayLayer,
511};