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