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

OpenCode2AdapterV2.testkit.ts

243 lines10.5 KB

1/**
2 * Replays an OpenCode 2 transcript at the HTTP boundary: the real
3 * `@opencode/client` and the adapter's event reader run against an
4 * `HttpClient` that answers from the transcript, so request encoding and
5 * response decoding are both exercised.
6 */
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import {
9 ProviderInstanceId,
10 ProviderReplayEntry,
11 ProviderSessionId,
12 ThreadId,
13 type ProviderReplayTranscript,
14} from "@t3tools/contracts";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Schema from "effect/Schema";
18import * as HttpClient from "effect/unstable/http/HttpClient";
19import * as HttpClientError from "effect/unstable/http/HttpClientError";
20import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
21import * as UrlParams from "effect/unstable/http/UrlParams";
22​
23import * as ServerConfig from "../../config.ts";
24import * as OpenCode2Client from "../../provider/opencode2/OpenCode2Client.ts";
25import * as OpenCode2Server from "../../provider/opencode2/OpenCode2Server.ts";
26import * as IdAllocator from "../IdAllocator.ts";
27import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
28import {
29 makeReplayServerConfig,
30 type OrchestratorV2ProviderReplayHarness,
31} from "../testkit/ProviderReplayHarness.ts";
32import { OPENCODE_PROVIDER } from "./OpenCodeAdapterV2.ts";
33import {
34 OpenCodeReplayController,
35 OpenCodeReplayTranscriptDecodeError,
36} from "./OpenCodeAdapterV2.testkit.ts";
37import * as OpenCode2AdapterV2 from "./OpenCode2AdapterV2.ts";
38​
39export const OPENCODE2_HTTP_PROTOCOL = "opencode2-http.sse" as const;
40const BASE_URL = "http://opencode2.replay";
41const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
42const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
43​
44const OpenCode2ReplayTranscript = Schema.Struct({
45 provider: Schema.Literal(OPENCODE_PROVIDER),
46 protocol: Schema.Literal(OPENCODE2_HTTP_PROTOCOL),
47 version: Schema.String,
48 scenario: Schema.String,
49 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
50 entries: Schema.Array(ProviderReplayEntry),
51});
52type OpenCode2ReplayTranscript = typeof OpenCode2ReplayTranscript.Type;
53const decodeOpenCode2ReplayTranscript = Schema.decodeUnknownEffect(OpenCode2ReplayTranscript);
54​
55/** Names a request the way the recordings do: the client operation and its JSON input. */
56const operationOf = (
57 method: string,
58 path: string,
59 query: Record<string, unknown>,
60 body: unknown,
61) => {
62 const session = /^\/api\/session\/([^/]+)(\/.*)?$/.exec(path);
63 if (method === "GET" && path === "/api/event") return { type: "event.subscribe" };
64 if (method === "GET" && path === "/api/model") return { type: "model.list", input: query };
65 if (method === "GET" && path === "/api/agent") return { type: "agent.list", input: query };
66 if (method === "POST" && path === "/api/session") return { type: "session.create", input: body };
67 if (method === "GET" && path === "/api/session/active") return { type: "session.active" };
68 if (session !== null) {
69 const [, sessionID, rest = ""] = session;
70 const input = { sessionID, ...query, ...(body === undefined ? {} : (body as object)) };
71 if (method === "GET" && rest === "") return { type: "session.get", input };
72 if (method === "PATCH" && rest === "") return { type: "session.update", input };
73 if (method === "POST" && rest === "/prompt") return { type: "session.prompt", input };
74 if (method === "POST" && rest === "/interrupt") return { type: "session.interrupt", input };
75 if (method === "POST" && rest === "/model") return { type: "session.switchModel", input };
76 if (method === "POST" && rest === "/move") return { type: "session.move", input };
77 if (method === "POST" && rest === "/synthetic") return { type: "session.synthetic", input };
78 if (method === "GET" && rest === "/message") return { type: "message.list", input };
79 if (method === "GET" && rest === "/permission") return { type: "permission.list", input };
80 if (method === "GET" && rest === "/form") return { type: "session.form.list", input };
81 const form = /^\/form\/([^/]+)(\/reply)?$/.exec(rest);
82 if (form !== null) {
83 const formInput = { ...input, formID: form[1] };
84 if (method === "POST" && form[2] !== undefined) {
85 return { type: "session.form.reply", input: formInput };
86 }
87 if (method === "DELETE") return { type: "session.form.cancel", input: formInput };
88 }
89 const permission = /^\/permission\/([^/]+)\/reply$/.exec(rest);
90 if (method === "POST" && permission !== null) {
91 return { type: "permission.reply", input: { ...input, requestID: permission[1] } };
92 }
93 }
94 return { type: `${method} ${path}`, input: { ...query, body } };
95};
96​
97/** An `HttpClient` that answers every request from the transcript. */
98const replayHttpClient = (controller: OpenCodeReplayController) =>
99 HttpClient.make((request, url) =>
100 Effect.tryPromise({
101 try: async () => {
102 const raw =
103 request.body._tag === "Uint8Array"
104 ? new TextDecoder().decode(request.body.body)
105 : undefined;
106 const query = UrlParams.toRecord(UrlParams.fromInput(url.searchParams));
107 const operation = operationOf(
108 request.method,
109 url.pathname,
110 query,
111 raw === undefined ? undefined : decodeJson(raw),
112 );
113 // The event stream and requests are separate connections: a request
114 // is matched only once the events recorded before it were delivered.
115 if (operation.type !== "event.subscribe") await controller.untilEventsDelivered();
116 await controller.expectOutbound(operation);
117 if (operation.type === "event.subscribe") {
118 const encoder = new TextEncoder();
119 const frames = controller.events()[Symbol.asyncIterator]();
120 const body = new ReadableStream<Uint8Array>({
121 async pull(stream) {
122 const next = await frames.next();
123 if (next.done === true) stream.close();
124 else stream.enqueue(encoder.encode(`data: ${encodeJson(next.value)}\n\n`));
125 },
126 });
127 return new Response(body, { headers: { "content-type": "text/event-stream" } });
128 }
129 // Recorded responses are the raw HTTP bodies; `null` is an empty 204.
130 // `{ status, body }` replays an error status and `"<hang>"` never answers.
131 const body = await controller.response(operation.type);
132 if (body === "<hang>") return new Promise<Response>(() => {});
133 if (typeof body === "object" && body !== null && "status" in body && "body" in body) {
134 return new Response(encodeJson(body.body), {
135 status: Number(body.status),
136 headers: { "content-type": "application/json" },
137 });
138 }
139 return body === null
140 ? new Response(null, { status: 204 })
141 : new Response(encodeJson(body), { headers: { "content-type": "application/json" } });
142 },
143 catch: (cause) =>
144 new HttpClientError.HttpClientError({
145 reason: new HttpClientError.TransportError({ request, cause }),
146 }),
147 }).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response))),
148 );
149​
150/** The 2.x adapter over a replayed server, checking at scope close that the transcript ran out. */
151const makeReplayAdapter = (
152 transcript: ProviderReplayTranscript,
153 options?: { external?: boolean },
154) =>
155 Effect.gen(function* () {
156 const controller = new OpenCodeReplayController(transcript);
157 yield* Effect.addFinalizer(() => Effect.sync(() => controller.assertComplete()));
158 const opencode = yield* OpenCode2Client.make.pipe(
159 Effect.provideService(HttpClient.HttpClient, replayHttpClient(controller)),
160 );
161 const connection = {
162 ...(yield* opencode.connect({ baseUrl: BASE_URL, password: "replay" })),
163 url: BASE_URL,
164 version: transcript.version,
165 external: options?.external ?? false,
166 };
167 return yield* OpenCode2AdapterV2.make(ProviderInstanceId.make("opencode")).pipe(
168 Effect.provideService(
169 OpenCode2Server.OpenCode2Server,
170 OpenCode2Server.OpenCode2Server.of({ withConnection: (use) => use(connection) }),
171 ),
172 );
173 });
174​
175const replayServerConfig = (scenario: string) =>
176 Layer.effect(ServerConfig.ServerConfig, makeReplayServerConfig(scenario).pipe(Effect.orDie)).pipe(
177 Layer.provide(NodeServices.layer),
178 );
179​
180function makeRegistryLayer(transcript: OpenCode2ReplayTranscript) {
181 return Layer.unwrap(
182 makeReplayAdapter(transcript, { external: true }).pipe(
183 Effect.map((adapter) => ProviderAdapterRegistry.makeLayer([adapter])),
184 ),
185 ).pipe(Layer.provide(Layer.mergeAll(replayServerConfig(transcript.scenario), IdAllocator.layer)));
187​
188/**
189 * An open 2.x session runtime whose server answers from `entries`, for
190 * adapter-level tests of failures a real server cannot produce on demand.
191 */
192export const openCode2ReplayRuntime = (
193 entries: ReadonlyArray<ProviderReplayEntry>,
194 options?: { readonly external?: boolean },
195) =>
196 Effect.gen(function* () {
197 const adapter = yield* makeReplayAdapter(
198 {
199 provider: OPENCODE_PROVIDER,
200 protocol: OPENCODE2_HTTP_PROTOCOL,
201 version: "2.0.18",
202 scenario: "opencode2_adapter",
203 entries,
204 },
205 options,
206 );
207 return yield* adapter.openSession({
208 threadId: ThreadId.make("thread:opencode2-adapter"),
209 providerSessionId: ProviderSessionId.make("provider-session:opencode2-adapter"),
210 modelSelection: {
211 instanceId: ProviderInstanceId.make("opencode"),
212 model: "opencode/big-pickle",
213 },
214 // Opened where the adapter tests' threads run, as T3 opens a session for its first thread.
215 runtimePolicy: {
216 runtimeMode: "full-access",
217 interactionMode: "default",
218 cwd: "/work/opencode2",
219 },
220 });
221 }).pipe(
222 Effect.provide(Layer.mergeAll(replayServerConfig("opencode2_adapter"), IdAllocator.layer)),
223 );
224​
225export const OpenCode2OrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
226 OpenCode2ReplayTranscript,
227 OpenCodeReplayTranscriptDecodeError
228> = {
229 driver: OPENCODE_PROVIDER,
230 decodeTranscript: (transcript: ProviderReplayTranscript) =>
231 decodeOpenCode2ReplayTranscript(transcript).pipe(
232 Effect.mapError(
233 (cause) =>
234 new OpenCodeReplayTranscriptDecodeError({
235 driver: transcript.provider,
236 protocol: transcript.protocol,
237 scenario: transcript.scenario,
238 cause,
239 }),
240 ),
241 ),
242 makeProviderAdapterRegistryLayer: makeRegistryLayer,
243};