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

OpenCodeAdapterV2.testkit.ts

474 lines16.2 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/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 }
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" && (key === "id" || key === "messageID" || key === "parentID")
123 ? (messageIds.get(entry) ?? entry)
124 : materializeMessageIds(entry, messageIds),
125 ]),
126 );
128​
129/**
130 * Replays one transcript at a client boundary: each outbound call must match the
131 * next `expect_outbound`, then answers with its `sdk.response`; `sdk.event`
132 * frames feed the event stream. Shared by the 1.x SDK and 2.x HTTP transports.
133 */
134export class OpenCodeReplayController {
135 private cursor = 0;
136 private readonly waiters = new Set<() => void>();
137 private failure: unknown = null;
138 private readonly transcript: ProviderReplayTranscript;
139 private messageIds = new Map<string, string>();
140​
141 constructor(transcript: ProviderReplayTranscript) {
142 this.transcript = transcript;
143 }
144​
145 async expectOutbound(actual: unknown): Promise<void> {
146 try {
147 const entry = this.transcript.entries[this.cursor];
148 const expectedFrame = entry?.type === "expect_outbound" ? frameRecord(entry.frame) : null;
149 const actualFrame = frameRecord(actual);
150 const messageIds = new Map(this.messageIds);
151 let conflictingMessageId = false;
152 if (
153 expectedFrame?.type === "session.promptAsync" &&
154 actualFrame?.type === expectedFrame.type
155 ) {
156 const recordedId = frameRecord(expectedFrame.input)?.messageID;
157 const actualId = frameRecord(actualFrame.input)?.messageID;
158 if (
159 typeof recordedId === "string" &&
160 typeof actualId === "string" &&
161 recordedId !== "<any>" &&
162 recordedId !== "<workspace>" &&
163 !messageIds.has(recordedId)
164 ) {
165 conflictingMessageId = [...messageIds.values()].includes(actualId);
166 if (!conflictingMessageId) messageIds.set(recordedId, actualId);
167 }
168 }
169 const expected =
170 entry?.type === "expect_outbound"
171 ? materializeMessageIds(entry.frame, messageIds)
172 : (entry ?? null);
173 if (
174 conflictingMessageId ||
175 entry?.type !== "expect_outbound" ||
176 !replayValueMatches(expected, actual)
177 ) {
178 throw new OpenCodeReplayMismatchError({
179 scenario: this.transcript.scenario,
180 cursor: this.cursor,
181 expected,
182 actual,
183 });
184 }
185 this.messageIds = messageIds;
186 this.advance();
187 } catch (cause) {
188 this.fail(cause);
189 throw cause;
190 }
191 }
192​
193 async response(operation: string): Promise<unknown> {
194 while (true) {
195 this.throwFailure();
196 const entry = this.transcript.entries[this.cursor];
197 if (entry?.type === "emit_inbound") {
198 const frame = frameRecord(entry.frame);
199 if (frame?.type === "sdk.response" && frame.operation === operation) {
200 if (entry.afterMs !== undefined && entry.afterMs > 0) {
201 await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs)));
202 }
203 const data = materializeMessageIds(frame.data, this.messageIds);
204 this.advance();
205 return data;
206 }
207 }
208 if (entry?.type === "runtime_exit") {
209 const mismatch = new OpenCodeReplayMismatchError({
210 scenario: this.transcript.scenario,
211 cursor: this.cursor,
212 expected: { type: "sdk.response", operation },
213 actual: entry,
214 });
215 this.fail(mismatch);
216 throw mismatch;
217 }
218 await this.changed();
219 }
220 }
221​
222 /**
223 * Resolves once the server events recorded before the next entry have been
224 * delivered. For transports whose events and requests travel separately, a
225 * request is matched at its recorded point instead of racing those events.
226 */
227 async untilEventsDelivered(): Promise<void> {
228 while (true) {
229 this.throwFailure();
230 const entry = this.transcript.entries[this.cursor];
231 if (entry?.type !== "emit_inbound" || frameRecord(entry.frame)?.type !== "sdk.event") return;
232 await this.changed();
233 }
234 }
235​
236 async *events(signal?: AbortSignal): AsyncIterable<unknown> {
237 while (true) {
238 if (signal?.aborted === true) return;
239 this.throwFailure();
240 const entry = this.transcript.entries[this.cursor];
241 if (entry?.type === "emit_inbound") {
242 const frame = frameRecord(entry.frame);
243 if (frame?.type === "sdk.event") {
244 if (entry.afterMs !== undefined && entry.afterMs > 0) {
245 await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs)));
246 }
247 const event = materializeMessageIds(frame.event, this.messageIds);
248 this.advance();
249 yield event;
250 continue;
251 }
252 }
253 if (entry?.type === "runtime_exit") {
254 this.advance();
255 if (entry.status === "success") return;
256 const mismatch = new OpenCodeReplayMismatchError({
257 scenario: this.transcript.scenario,
258 cursor: this.cursor - 1,
259 expected: { status: "success" },
260 actual: entry,
261 });
262 this.fail(mismatch);
263 throw mismatch;
264 }
265 await this.changed(signal);
266 }
267 }
268​
269 assertComplete(): void {
270 while (this.transcript.entries[this.cursor]?.type === "runtime_exit") {
271 const exit = this.transcript.entries[this.cursor];
272 if (exit?.type !== "runtime_exit" || exit.status !== "success") break;
273 this.cursor += 1;
274 }
275 this.throwFailure();
276 if (this.cursor !== this.transcript.entries.length) {
277 throw new OpenCodeReplayIncompleteError({
278 scenario: this.transcript.scenario,
279 cursor: this.cursor,
280 remaining: this.transcript.entries.length - this.cursor,
281 });
282 }
283 }
284​
285 private advance(): void {
286 this.cursor += 1;
287 for (const waiter of this.waiters) waiter();
288 this.waiters.clear();
289 }
290​
291 private fail(cause: unknown): void {
292 this.failure = cause;
293 for (const waiter of this.waiters) waiter();
294 this.waiters.clear();
295 }
296​
297 private throwFailure(): void {
298 if (this.failure !== null) throw this.failure;
299 }
300​
301 private changed(signal?: AbortSignal): Promise<void> {
302 return new Promise((resolve) => {
303 let settled = false;
304 const done = () => {
305 if (settled) return;
306 settled = true;
307 signal?.removeEventListener("abort", done);
308 this.waiters.delete(done);
309 resolve();
310 };
311 this.waiters.add(done);
312 signal?.addEventListener("abort", done, { once: true });
313 if (signal?.aborted === true) done();
314 });
315 }
317​
318function makeReplayClient(controller: OpenCodeReplayController): OpencodeClient {
319 const request = async (operation: string, input: unknown) => {
320 await controller.expectOutbound({ type: operation, input });
321 return { data: await controller.response(operation) };
322 };
323 return {
324 event: {
325 subscribe: async (_input?: unknown, options?: { readonly signal?: AbortSignal }) => {
326 await controller.expectOutbound({ type: "event.subscribe" });
327 return { stream: controller.events(options?.signal) };
328 },
329 },
330 session: {
331 create: (input: unknown) => request("session.create", input),
332 get: (input: unknown) => request("session.get", input),
333 children: (input: unknown) => request("session.children", input),
334 update: (input: unknown) => request("session.update", input),
335 messages: (input: unknown) => request("session.messages", input),
336 promptAsync: (input: unknown) => request("session.promptAsync", input),
337 abort: (input: unknown) => request("session.abort", input),
338 revert: (input: unknown) => request("session.revert", input),
339 unrevert: (input: unknown) => request("session.unrevert", input),
340 fork: (input: unknown) => request("session.fork", input),
341 },
342 permission: {
343 reply: (input: unknown) => request("permission.reply", input),
344 },
345 question: {
346 reply: (input: unknown) => request("question.reply", input),
347 },
348 mcp: {
349 add: (input: unknown) => request("mcp.add", input),
350 },
351 } as unknown as OpencodeClient;
353​
354function makeOpenCodeReplayRuntimeLayer(transcript: OpenCodeSdkReplayTranscript) {
355 return Layer.effect(
356 OpenCodeRuntime.OpenCodeRuntime,
357 Effect.gen(function* () {
358 const controller = new OpenCodeReplayController(transcript);
359 yield* Effect.addFinalizer(() =>
360 Effect.sync(() => {
361 controller.assertComplete();
362 }),
363 );
364 const client = makeReplayClient(controller);
365 return OpenCodeRuntime.OpenCodeRuntime.of({
366 startOpenCodeServerProcess: () =>
367 Effect.fail(
368 new OpenCodeRuntime.OpenCodeRuntimeError({
369 operation: "startOpenCodeServerProcess",
370 detail: "OpenCode replay uses an external in-memory SDK boundary.",
371 }),
372 ),
373 connectToOpenCodeServer: () =>
374 Effect.succeed({
375 url: "replay://opencode",
376 version: "0.0.0-replay",
377 exitCode: null,
378 external: true,
379 }),
380 runOpenCodeCommand: () =>
381 Effect.fail(
382 new OpenCodeRuntime.OpenCodeRuntimeError({
383 operation: "runOpenCodeCommand",
384 detail: "OpenCode replay does not execute commands.",
385 }),
386 ),
387 createOpenCodeSdkClient: () => client,
388 loadOpenCodeInventory: () =>
389 Effect.fail(
390 new OpenCodeRuntime.OpenCodeRuntimeError({
391 operation: "loadOpenCodeInventory",
392 detail: "OpenCode replay does not load inventory.",
393 }),
394 ),
395 loadInventoryFromCli: () =>
396 Effect.fail(
397 new OpenCodeRuntime.OpenCodeRuntimeError({
398 operation: "loadInventoryFromCli",
399 detail: "OpenCode replay does not load inventory.",
400 }),
401 ),
402 loadOpenCodeSkills: () =>
403 Effect.fail(
404 new OpenCodeRuntime.OpenCodeRuntimeError({
405 operation: "loadOpenCodeSkills",
406 detail: "OpenCode replay does not load skills.",
407 }),
408 ),
409 loadSkillsFromCli: () =>
410 Effect.fail(
411 new OpenCodeRuntime.OpenCodeRuntimeError({
412 operation: "loadSkillsFromCli",
413 detail: "OpenCode replay does not load skills.",
414 }),
415 ),
416 } satisfies OpenCodeRuntime.OpenCodeRuntimeShape);
417 }),
418 );
420​
421function makeOpenCodeProviderAdapterRegistryReplayLayer(transcript: OpenCodeSdkReplayTranscript) {
422 const serverConfigLayer = Layer.effect(
423 ServerConfig.ServerConfig,
424 makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie),
425 ).pipe(Layer.provide(NodeServices.layer));
426 return ProviderAdapterRegistry.makeDriverLayer({
427 drivers: [OpenCodeAdapterV2Driver],
428 configMap: {
429 [OPENCODE_DEFAULT_INSTANCE_ID]: {
430 driver: OPENCODE_PROVIDER,
431 config: { serverUrl: "replay://opencode" },
432 },
433 },
434 }).pipe(
435 Layer.provide(
436 Layer.mergeAll(
437 makeOpenCodeReplayRuntimeLayer(transcript),
438 serverConfigLayer,
439 NodeServices.layer,
440 IdAllocator.layer,
441 Layer.succeed(
442 ProviderEventLoggers.ProviderEventLoggers,
443 ProviderEventLoggers.NoOpProviderEventLoggers,
444 ),
445 ),
446 ),
447 );
449​
450function transcriptMetadata(transcript: ProviderReplayTranscript) {
451 return {
452 provider: transcript.provider,
453 protocol: transcript.protocol,
454 scenario: transcript.scenario,
455 };
457​
458export const OpenCodeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
459 OpenCodeSdkReplayTranscript,
460 OpenCodeOrchestratorReplayHarnessError
461> = {
462 driver: OPENCODE_PROVIDER,
463 decodeTranscript: (transcript) =>
464 decodeOpenCodeSdkReplayTranscript(transcript).pipe(
465 Effect.mapError(
466 (cause) =>
467 new OpenCodeReplayTranscriptDecodeError({
468 ...transcriptMetadata(transcript),
469 cause,
470 }),
471 ),
472 ),
473 makeProviderAdapterRegistryLayer: makeOpenCodeProviderAdapterRegistryReplayLayer,
474};