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