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

OpenCodeAdapterV2.testkit.ts

512 lines17.6 KB

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/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 }
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 }
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 }
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);
110​
111function frameRecord(frame: unknown): Record<string, unknown> | null {
112 return typeof frame === "object" && frame !== null ? (frame as Record<string, unknown>) : null;
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 );
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 }
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 status: () => request("mcp.status", {}),
387 add: (input: unknown) => request("mcp.add", input),
388 },
389 } as unknown as OpencodeClient;
391​
392function layerOpenCodeReplayRuntime(transcript: OpenCodeSdkReplayTranscript) {
393 return Layer.effect(
394 OpenCodeRuntime.OpenCodeRuntime,
395 Effect.gen(function* () {
396 const controller = new OpenCodeReplayController(transcript);
397 yield* Effect.addFinalizer(() =>
398 Effect.sync(() => {
399 controller.assertComplete();
400 }),
401 );
402 const client = makeReplayClient(controller);
403 return OpenCodeRuntime.OpenCodeRuntime.of({
404 startOpenCodeServerProcess: () =>
405 Effect.fail(
406 new OpenCodeRuntime.OpenCodeRuntimeError({
407 operation: "startOpenCodeServerProcess",
408 detail: "OpenCode replay uses an external in-memory SDK boundary.",
409 }),
410 ),
411 connectToOpenCodeServer: () =>
412 Effect.succeed({
413 url: "replay://opencode",
414 version: "0.0.0-replay",
415 exitCode: null,
416 external: true,
417 }),
418 runOpenCodeCommand: () =>
419 Effect.fail(
420 new OpenCodeRuntime.OpenCodeRuntimeError({
421 operation: "runOpenCodeCommand",
422 detail: "OpenCode replay does not execute commands.",
423 }),
424 ),
425 createOpenCodeSdkClient: () => client,
426 loadOpenCodeInventory: () =>
427 Effect.fail(
428 new OpenCodeRuntime.OpenCodeRuntimeError({
429 operation: "loadOpenCodeInventory",
430 detail: "OpenCode replay does not load inventory.",
431 }),
432 ),
433 loadInventoryFromCli: () =>
434 Effect.fail(
435 new OpenCodeRuntime.OpenCodeRuntimeError({
436 operation: "loadInventoryFromCli",
437 detail: "OpenCode replay does not load inventory.",
438 }),
439 ),
440 loadOpenCodeSkills: () =>
441 Effect.fail(
442 new OpenCodeRuntime.OpenCodeRuntimeError({
443 operation: "loadOpenCodeSkills",
444 detail: "OpenCode replay does not load skills.",
445 }),
446 ),
447 loadSkillsFromCli: () =>
448 Effect.fail(
449 new OpenCodeRuntime.OpenCodeRuntimeError({
450 operation: "loadSkillsFromCli",
451 detail: "OpenCode replay does not load skills.",
452 }),
453 ),
454 } satisfies OpenCodeRuntime.OpenCodeRuntimeShape);
455 }),
456 );
458​
459function layerOpenCodeProviderAdapterRegistryReplay(transcript: OpenCodeSdkReplayTranscript) {
460 const layerServerConfig = Layer.effect(
461 ServerConfig.ServerConfig,
462 makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),
463 ).pipe(Layer.provide(NodeServices.layer));
464 return ProviderAdapterRegistry.layerFromDrivers({
465 drivers: [OpenCodeAdapterV2Driver],
466 configMap: {
467 [OPENCODE_DEFAULT_INSTANCE_ID]: {
468 driver: OPENCODE_PROVIDER,
469 config: { serverUrl: "replay://opencode" },
470 },
471 },
472 }).pipe(
473 Layer.provide(
474 Layer.mergeAll(
475 layerOpenCodeReplayRuntime(transcript),
476 layerServerConfig,
477 NodeServices.layer,
478 IdAllocator.layer,
479 Layer.succeed(
480 ProviderEventLoggers.ProviderEventLoggers,
481 ProviderEventLoggers.NoOpProviderEventLoggers,
482 ),
483 ),
484 ),
485 );
487​
488function transcriptMetadata(transcript: ProviderReplayTranscript) {
489 return {
490 provider: transcript.provider,
491 protocol: transcript.protocol,
492 scenario: transcript.scenario,
493 };
495​
496export const OpenCodeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
497 OpenCodeSdkReplayTranscript,
498 OpenCodeOrchestratorReplayHarnessError
499> = {
500 driver: OPENCODE_PROVIDER,
501 decodeTranscript: (transcript) =>
502 decodeOpenCodeSdkReplayTranscript(transcript).pipe(
503 Effect.mapError(
504 (cause) =>
505 new OpenCodeReplayTranscriptDecodeError({
506 ...transcriptMetadata(transcript),
507 cause,
508 }),
509 ),
510 ),
511 makeProviderAdapterRegistryLayer: layerOpenCodeProviderAdapterRegistryReplay,
512};