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

OpenCode2AdapterV2.testkit.ts

407 lines16.7 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import {
4 ProviderInstanceId,
5 ProviderReplayEntry,
6 ProviderSessionId,
7 ThreadId,
8 type ProviderReplayTranscript,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Schema from "effect/Schema";
14import * as Stream from "effect/Stream";
15import * as HttpClient from "effect/http/HttpClient";
16import * as HttpClientError from "effect/http/HttpClientError";
17import * as HttpClientResponse from "effect/http/HttpClientResponse";
18import * as UrlParams from "effect/http/UrlParams";
19​
20import * as OpenCode2Client from "@t3tools/provider-opencode/server/v2/OpenCode2Client";
21import * as OpenCode2Server from "@t3tools/provider-opencode/server/v2/OpenCode2Server";
22import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
23import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
24import { resolveAttachmentPath } from "../../attachmentStore.ts";
25import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
26import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate";
27import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
28import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
29import { OPENCODE_PROVIDER } from "@t3tools/provider-opencode/testing";
30import {
31 OpenCodeReplayController,
32 OpenCodeReplayTranscriptDecodeError,
33} from "./OpenCodeAdapterV2.testkit.ts";
34import * as OpenCode2Adapter from "@t3tools/provider-opencode/server/v2/adapter";
35​
36export const OPENCODE2_HTTP_PROTOCOL = "opencode2-http.sse" as const;
37const BASE_URL = "http://opencode2.replay";
38const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
39const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
40​
41const OpenCode2ReplayTranscript = Schema.Struct({
42 provider: Schema.Literal(OPENCODE_PROVIDER),
43 protocol: Schema.Literal(OPENCODE2_HTTP_PROTOCOL),
44 version: Schema.String,
45 scenario: Schema.String,
46 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
47 entries: Schema.Array(ProviderReplayEntry),
48});
49type OpenCode2ReplayTranscript = typeof OpenCode2ReplayTranscript.Type;
50const decodeOpenCode2ReplayTranscript = Schema.decodeUnknownEffect(OpenCode2ReplayTranscript);
51​
52const operationOf = (
53 method: string,
54 path: string,
55 query: Record<string, unknown>,
56 body: unknown,
57) => {
58 if (method === "GET" && path === "/api/experimental/job" && query.kind === "image")
59 return { type: "imageJobs", input: query };
60 if (method === "GET" && path.startsWith("/api/fs/read/"))
61 return { type: "image.read", input: { path, ...query } };
62 const rpc = /^\/api\/rpc\/([^/]+)\/([^/]+)$/.exec(path);
63 if (method === "POST" && rpc !== null)
64 return {
65 type: "rpc.call",
66 input: { rpcID: rpc[1], method: rpc[2], ...query, ...(body as object) },
67 };
68 if (method === "GET" && path === "/api/experimental/job")
69 return { type: "job.list", input: query };
70 const shell = /^\/api\/shell(?:\/([^/]+)(\/output)?)?$/.exec(path);
71 if (shell !== null) {
72 const input = { ...(shell[1] === undefined ? {} : { id: shell[1] }), ...query };
73 return {
74 type: `shell.${method === "DELETE" ? "remove" : shell[2] ? "output" : shell[1] ? "get" : "list"}`,
75 input,
76 };
77 }
78 const session = /^\/api\/session\/([^/]+)(\/.*)?$/.exec(path);
79 if (method === "GET" && path === "/api/event") return { type: "event.subscribe" };
80 if (method === "GET" && path === "/api/model") return { type: "model.list", input: query };
81 if (method === "GET" && path === "/api/agent") return { type: "agent.list", input: query };
82 if (method === "POST" && path === "/api/session") return { type: "session.create", input: body };
83 if (method === "GET" && path === "/api/session/active") return { type: "session.active" };
84 if (method === "GET" && path === "/api/command") return { type: "command.list", input: query };
85 const mcp = /^\/api\/experimental\/mcp\/([^/]+)$/.exec(path);
86 if (mcp !== null && method === "PUT") {
87 return { type: "mcp.add", input: { server: mcp[1], ...query, ...(body as object) } };
88 }
89 if (mcp !== null && method === "DELETE") {
90 return { type: "mcp.remove", input: { server: mcp[1], ...query } };
91 }
92 const entry = /^\/api\/experimental\/session\/([^/]+)\/instructions\/entries\/([^/]+)$/.exec(
93 path,
94 );
95 if (entry !== null && method === "PUT") {
96 return {
97 type: "session.instructions.entry.put",
98 input: { sessionID: entry[1], key: entry[2], ...(body as object) },
99 };
100 }
101 if (method === "GET" && path === "/api/skill") return { type: "skill.list", input: query };
102 if (session !== null) {
103 const [, sessionID, rest = ""] = session;
104 // The client sends absent optional fields as `null`; recordings omit them.
105 const fields = Object.entries((body ?? {}) as Record<string, unknown>).filter(
106 ([, value]) => value !== null,
107 );
108 const input = { sessionID, ...query, ...Object.fromEntries(fields) };
109 if (method === "GET" && rest === "") return { type: "session.get", input };
110 if (method === "DELETE" && rest === "") return { type: "session.remove", input };
111 if (method === "PATCH" && rest === "") return { type: "session.update", input };
112 if (method === "POST" && rest === "/prompt") return { type: "session.prompt", input };
113 if (method === "POST" && rest === "/command") return { type: "session.command", input };
114 if (method === "POST" && rest === "/compact") return { type: "session.compact", input };
115 if (method === "POST" && rest === "/interrupt") return { type: "session.interrupt", input };
116 if (method === "POST" && rest === "/model") return { type: "session.switchModel", input };
117 if (method === "POST" && rest === "/agent") return { type: "session.switchAgent", input };
118 if (method === "POST" && rest === "/move") return { type: "session.move", input };
119 if (method === "POST" && rest === "/synthetic") return { type: "session.synthetic", input };
120 if (method === "POST" && rest === "/fork") return { type: "session.fork", input };
121 if (method === "POST" && rest === "/revert/stage") {
122 return { type: "session.revert.stage", input };
123 }
124 if (method === "POST" && rest === "/revert/commit") {
125 return { type: "session.revert.commit", input };
126 }
127 if (method === "DELETE" && rest === "/revert") return { type: "session.revert.clear", input };
128 const inbox = /^\/inbox\/([^/]+)$/.exec(rest);
129 if (method === "DELETE" && inbox !== null) {
130 const inboxID = decodeURIComponent(inbox[1] ?? "");
131 return { type: "session.inbox.cancel", input: { ...input, inboxID } };
132 }
133 if (method === "GET" && rest === "/message") return { type: "message.list", input };
134 if (method === "GET" && rest === "/permission") return { type: "permission.list", input };
135 if (method === "GET" && rest === "/form") return { type: "session.form.list", input };
136 const form = /^\/form\/([^/]+)(\/reply)?$/.exec(rest);
137 if (form !== null) {
138 const formInput = { ...input, formID: form[1] };
139 if (method === "POST" && form[2] !== undefined) {
140 return { type: "session.form.reply", input: formInput };
141 }
142 if (method === "DELETE") return { type: "session.form.cancel", input: formInput };
143 }
144 const permission = /^\/permission\/([^/]+)\/reply$/.exec(rest);
145 if (method === "POST" && permission !== null) {
146 return { type: "permission.reply", input: { ...input, requestID: permission[1] } };
147 }
148 }
149 return { type: `${method} ${path}`, input: { ...query, body } };
150};
151​
152const replayHttpClient = (
153 controller: OpenCodeReplayController,
154 replayGate: ProviderReplayGate | undefined,
155 onPrompt: ((input: unknown) => void) | undefined,
156 beforeResponse: ((path: string) => Effect.Effect<void>) | undefined,
157) =>
158 HttpClient.make((request, url) =>
159 Effect.tryPromise({
160 try: async () => {
161 if (controller.exited && controller.finished) {
162 throw new Error("The replayed OpenCode server has exited.");
163 }
164 const raw =
165 request.body._tag === "Uint8Array"
166 ? new TextDecoder().decode(request.body.body)
167 : undefined;
168 const query = UrlParams.toRecord(UrlParams.fromInput(url.searchParams));
169 const operation = operationOf(
170 request.method,
171 url.pathname,
172 query,
173 raw === undefined ? undefined : decodeJson(raw),
174 );
175 // HTTP streams and requests use separate connections; deliver prior recorded inbound data before matching requests.
176 if (operation.type !== "event.subscribe") await controller.untilInboundDelivered();
177 if (operation.type === "session.prompt") onPrompt?.(operation.input);
178 await controller.expectOutbound(operation);
179 if (operation.type === "event.subscribe") {
180 controller.exited = false;
181 const encoder = new TextEncoder();
182 const events = controller.events(undefined, replayGate?.beforeEmit);
183 const frames = events[Symbol.asyncIterator]();
184 const body = new ReadableStream<Uint8Array>({
185 async pull(stream) {
186 const next = await frames.next();
187 if (next.done === true) stream.close();
188 else stream.enqueue(encoder.encode(`data: ${encodeJson(next.value)}\n\n`));
189 },
190 });
191 return new Response(body, { headers: { "content-type": "text/event-stream" } });
192 }
193 // Recorded responses are the raw HTTP bodies; `null` is an empty 204.
194 const body = await controller.response(operation.type);
195 if (typeof body === "object" && body !== null && "imageBase64" in body) {
196 return new Response(Buffer.from(String(body.imageBase64), "base64"), {
197 headers: { "content-type": "image/png" },
198 });
199 }
200 if (body === "<hang>") return new Promise<Response>(() => {});
201 if (typeof body === "object" && body !== null && "status" in body && "body" in body) {
202 return new Response(encodeJson(body.body), {
203 status: Number(body.status),
204 headers: { "content-type": "application/json" },
205 });
206 }
207 return body === null
208 ? new Response(null, { status: 204 })
209 : new Response(encodeJson(body), { headers: { "content-type": "application/json" } });
210 },
211 catch: (cause) =>
212 new HttpClientError.HttpClientError({
213 reason: new HttpClientError.TransportError({ request, cause }),
214 }),
215 }).pipe(
216 Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
217 Effect.tap(() => beforeResponse?.(url.pathname) ?? Effect.void),
218 ),
219 );
220​
221export const replayServer = (
222 transcript: ProviderReplayTranscript,
223 options?: {
224 readonly external?: boolean;
225 readonly processExit?: Effect.Effect<void>;
226 readonly beforeResponse?: (path: string) => Effect.Effect<void>;
227 readonly onPrompt?: (input: unknown) => void;
228 readonly replayGate?: ProviderReplayGate;
229 readonly borrowers?: { current: number };
230 },
231) =>
232 Effect.gen(function* () {
233 const controller = new OpenCodeReplayController(transcript);
234 yield* Effect.addFinalizer(() =>
235 Effect.sync(() => {
236 options?.replayGate?.releaseAll();
237 controller.assertComplete();
238 }),
239 );
240 const opencode = yield* OpenCode2Client.make.pipe(
241 Effect.provideService(
242 HttpClient.HttpClient,
243 replayHttpClient(
244 controller,
245 options?.replayGate,
246 options?.onPrompt,
247 options?.beforeResponse,
248 ),
249 ),
250 );
251 const connection = {
252 ...(yield* opencode.connect({ baseUrl: BASE_URL, password: "replay" })),
253 url: BASE_URL,
254 version: transcript.version,
255 external: options?.external ?? false,
256 ...(options?.external ? {} : { processExit: options?.processExit ?? Effect.never }),
257 };
258 const borrowers = options?.borrowers;
259 return OpenCode2Server.OpenCode2Server.of({
260 withConnection: (use) =>
261 borrowers === undefined
262 ? use(connection)
263 : Effect.acquireUseRelease(
264 Effect.sync(() => {
265 borrowers.current += 1;
266 }),
267 () => use(connection),
268 () =>
269 Effect.sync(() => {
270 borrowers.current -= 1;
271 }),
272 ),
273 forget: Effect.void,
274 connections: Stream.never,
275 });
276 });
277​
278const makeReplayAdapter = (
279 transcript: ProviderReplayTranscript,
280 options?: {
281 readonly external?: boolean;
282 readonly processExit?: Effect.Effect<void>;
283 readonly beforeResponse?: (path: string) => Effect.Effect<void>;
284 readonly onPrompt?: (input: unknown) => void;
285 readonly replayGate?: ProviderReplayGate;
286 readonly borrowers?: { current: number };
287 },
288) =>
289 Effect.gen(function* () {
290 const server = yield* replayServer(transcript, options);
291 return yield* OpenCode2Adapter.make(ProviderInstanceId.make("opencode")).pipe(
292 Effect.provideService(OpenCode2Server.OpenCode2Server, server),
293 );
294 });
295​
296const layerReplayHost = TestProviderHost.layer().pipe(
297 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
298);
299​
300const layerReplayHostWithAttachments = (
301 attachmentsDir: string,
302 resolveExtractedTextPath?: (path: string) => Effect.Effect<string | undefined>,
303) =>
304 Layer.effect(
305 ProviderHost.ProviderHost,
306 Effect.gen(function* () {
307 const host = yield* ProviderHost.ProviderHost;
308 return ProviderHost.ProviderHost.of({
309 ...host,
310 paths: { ...host.paths, attachmentsDir },
311 resolveAttachmentPath: (attachment) =>
312 resolveAttachmentPath({ attachmentsDir, attachment }),
313 ...(resolveExtractedTextPath === undefined ? {} : { resolveExtractedTextPath }),
314 });
315 }),
316 ).pipe(Layer.provide(layerReplayHost));
317​
318function layerRegistry(
319 transcript: OpenCode2ReplayTranscript,
320 options?: { readonly replayGate?: ProviderReplayGate },
321) {
322 return Layer.unwrap(
323 makeReplayAdapter(transcript, { external: true, ...options }).pipe(
324 Effect.map((adapter) => ProviderAdapterRegistry.layerFromAdapters([adapter])),
325 ),
326 ).pipe(
327 Layer.provide(
328 Layer.mergeAll(layerReplayHost, IdAllocator.layer, NodeServices.layer, NodeCrypto.layer),
329 ),
330 );
332​
333export const openCode2ReplayRuntime = (
334 entries: ReadonlyArray<ProviderReplayEntry>,
335 options?: {
336 readonly external?: boolean;
337 readonly processExit?: Effect.Effect<void>;
338 readonly beforeResponse?: (path: string) => Effect.Effect<void>;
339 readonly version?: string;
340 readonly onPrompt?: (input: unknown) => void;
341 readonly borrowers?: { current: number };
342 readonly replayGate?: ProviderReplayGate;
343 readonly attachmentsDir?: string;
344 readonly resolveExtractedTextPath?: (path: string) => Effect.Effect<string | undefined>;
345 readonly fileSystem?: FileSystem.FileSystem;
346 },
347) =>
348 Effect.gen(function* () {
349 const fileSystem = options?.fileSystem ?? (yield* FileSystem.FileSystem);
350 const adapter = yield* makeReplayAdapter(
351 {
352 provider: OPENCODE_PROVIDER,
353 protocol: OPENCODE2_HTTP_PROTOCOL,
354 version: options?.version ?? "2.0.18",
355 scenario: "opencode2_adapter",
356 entries,
357 },
358 options,
359 ).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));
360 return yield* adapter.openSession({
361 threadId: ThreadId.make("thread:opencode2-adapter"),
362 providerSessionId: ProviderSessionId.make("provider-session:opencode2-adapter"),
363 modelSelection: {
364 instanceId: ProviderInstanceId.make("opencode"),
365 model: "opencode/big-pickle",
366 },
367 runtimePolicy: {
368 runtimeMode: "full-access",
369 interactionMode: "default",
370 cwd: "/work/opencode2",
371 },
372 });
373 }).pipe(
374 Effect.provide(
375 Layer.mergeAll(
376 options?.attachmentsDir === undefined
377 ? layerReplayHost
378 : layerReplayHostWithAttachments(
379 options.attachmentsDir,
380 options.resolveExtractedTextPath,
381 ),
382 IdAllocator.layer,
383 NodeServices.layer,
384 NodeCrypto.layer,
385 ),
386 ),
387 );
388​
389export const OpenCode2OrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
390 OpenCode2ReplayTranscript,
391 OpenCodeReplayTranscriptDecodeError
392> = {
393 driver: OPENCODE_PROVIDER,
394 decodeTranscript: (transcript: ProviderReplayTranscript) =>
395 decodeOpenCode2ReplayTranscript(transcript).pipe(
396 Effect.mapError(
397 (cause) =>
398 new OpenCodeReplayTranscriptDecodeError({
399 driver: transcript.provider,
400 protocol: transcript.protocol,
401 scenario: transcript.scenario,
402 cause,
403 }),
404 ),
405 ),
406 makeProviderAdapterRegistryLayer: layerRegistry,
407};