Open History to see the last commit
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 type { ProviderReplayGate } from "../testkit/ProviderReplayGate.testkit.ts";
29import {
30 makeReplayServerConfig,
31 type OrchestratorV2ProviderReplayHarness,
32} from "../testkit/ProviderReplayHarness.ts";
33import { OPENCODE_PROVIDER } from "./OpenCodeAdapterV2.ts";
34import {
35 OpenCodeReplayController,
36 OpenCodeReplayTranscriptDecodeError,
37} from "./OpenCodeAdapterV2.testkit.ts";
38import * as OpenCode2AdapterV2 from "./OpenCode2AdapterV2.ts";
39
40export const OPENCODE2_HTTP_PROTOCOL = "opencode2-http.sse" as const;
41const BASE_URL = "http://opencode2.replay";
42const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
43const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
44
45const OpenCode2ReplayTranscript = Schema.Struct({
46 provider: Schema.Literal(OPENCODE_PROVIDER),
47 protocol: Schema.Literal(OPENCODE2_HTTP_PROTOCOL),
48 version: Schema.String,
49 scenario: Schema.String,
50 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
51 entries: Schema.Array(ProviderReplayEntry),
52});
53type OpenCode2ReplayTranscript = typeof OpenCode2ReplayTranscript.Type;
54const decodeOpenCode2ReplayTranscript = Schema.decodeUnknownEffect(OpenCode2ReplayTranscript);
55
56/** Names a request the way the recordings do: the client operation and its JSON input. */
57const operationOf = (
58 method: string,
59 path: string,
60 query: Record<string, unknown>,
61 body: unknown,
62) => {
63 const session = /^\/api\/session\/([^/]+)(\/.*)?$/.exec(path);
64 if (method === "GET" && path === "/api/event") return { type: "event.subscribe" };
65 if (method === "GET" && path === "/api/model") return { type: "model.list", input: query };
66 if (method === "GET" && path === "/api/agent") return { type: "agent.list", input: query };
67 if (method === "POST" && path === "/api/session") return { type: "session.create", input: body };
68 if (method === "GET" && path === "/api/session/active") return { type: "session.active" };
69 if (method === "GET" && path === "/api/command") return { type: "command.list", input: query };
70 const mcp = /^\/api\/experimental\/mcp\/([^/]+)$/.exec(path);
71 if (mcp !== null && method === "PUT") {
72 return { type: "mcp.add", input: { server: mcp[1], ...query, ...(body as object) } };
73 }
74 if (mcp !== null && method === "DELETE") {
75 return { type: "mcp.remove", input: { server: mcp[1], ...query } };
76 }
77 const entry = /^\/api\/experimental\/session\/([^/]+)\/instructions\/entries\/([^/]+)$/.exec(
78 path,
79 );
80 if (entry !== null && method === "PUT") {
81 return {
82 type: "session.instructions.entry.put",
83 input: { sessionID: entry[1], key: entry[2], ...(body as object) },
84 };
85 }
86 if (method === "GET" && path === "/api/skill") return { type: "skill.list", input: query };
87 if (session !== null) {
88 const [, sessionID, rest = ""] = session;
89 // The client sends absent optional fields as `null`; recordings omit them.
90 const fields = Object.entries((body ?? {}) as Record<string, unknown>).filter(
91 ([, value]) => value !== null,
92 );
93 const input = { sessionID, ...query, ...Object.fromEntries(fields) };
94 if (method === "GET" && rest === "") return { type: "session.get", input };
95 if (method === "DELETE" && rest === "") return { type: "session.remove", input };
96 if (method === "PATCH" && rest === "") return { type: "session.update", input };
97 if (method === "POST" && rest === "/prompt") return { type: "session.prompt", input };
98 if (method === "POST" && rest === "/command") return { type: "session.command", input };
99 if (method === "POST" && rest === "/compact") return { type: "session.compact", input };
100 if (method === "POST" && rest === "/interrupt") return { type: "session.interrupt", input };
101 if (method === "POST" && rest === "/model") return { type: "session.switchModel", input };
102 if (method === "POST" && rest === "/agent") return { type: "session.switchAgent", input };
103 if (method === "POST" && rest === "/move") return { type: "session.move", input };
104 if (method === "POST" && rest === "/synthetic") return { type: "session.synthetic", input };
105 if (method === "POST" && rest === "/fork") return { type: "session.fork", input };
106 if (method === "POST" && rest === "/revert/stage") {
107 return { type: "session.revert.stage", input };
108 }
109 if (method === "POST" && rest === "/revert/commit") {
110 return { type: "session.revert.commit", input };
111 }
112 if (method === "DELETE" && rest === "/revert") return { type: "session.revert.clear", input };
113 const inbox = /^\/inbox\/([^/]+)$/.exec(rest);
114 if (method === "DELETE" && inbox !== null) {
115 // T3's steer ids carry `:`, which the path encodes.
116 const inboxID = decodeURIComponent(inbox[1] ?? "");
117 return { type: "session.inbox.cancel", input: { ...input, inboxID } };
118 }
119 if (method === "GET" && rest === "/message") return { type: "message.list", input };
120 if (method === "GET" && rest === "/permission") return { type: "permission.list", input };
121 if (method === "GET" && rest === "/form") return { type: "session.form.list", input };
122 const form = /^\/form\/([^/]+)(\/reply)?$/.exec(rest);
123 if (form !== null) {
124 const formInput = { ...input, formID: form[1] };
125 if (method === "POST" && form[2] !== undefined) {
126 return { type: "session.form.reply", input: formInput };
127 }
128 if (method === "DELETE") return { type: "session.form.cancel", input: formInput };
129 }
130 const permission = /^\/permission\/([^/]+)\/reply$/.exec(rest);
131 if (method === "POST" && permission !== null) {
132 return { type: "permission.reply", input: { ...input, requestID: permission[1] } };
133 }
134 }
135 return { type: `${method} ${path}`, input: { ...query, body } };
136};
137
138/**
139 * An `HttpClient` that answers every request from the transcript. A successful
140 * `runtime_exit` ends the event stream: the server has stopped. When entries
141 * follow it, the server was restarted and the next `event.subscribe` opens its
142 * new stream; a transcript that ends there stays down, so every later request
143 * fails to connect as it would against a stopped server.
144 */
145const replayHttpClient = (
146 controller: OpenCodeReplayController,
147 replayGate: ProviderReplayGate | undefined,
148) =>
149 HttpClient.make((request, url) =>
150 Effect.tryPromise({
151 try: async () => {
152 if (controller.exited && controller.finished) {
153 throw new Error("The replayed OpenCode server has exited.");
154 }
155 const raw =
156 request.body._tag === "Uint8Array"
157 ? new TextDecoder().decode(request.body.body)
158 : undefined;
159 const query = UrlParams.toRecord(UrlParams.fromInput(url.searchParams));
160 const operation = operationOf(
161 request.method,
162 url.pathname,
163 query,
164 raw === undefined ? undefined : decodeJson(raw),
165 );
166 // The event stream and requests are separate connections: a request
167 // is matched only once what was recorded before it was delivered.
168 if (operation.type !== "event.subscribe") await controller.untilInboundDelivered();
169 await controller.expectOutbound(operation);
170 if (operation.type === "event.subscribe") {
171 controller.exited = false;
172 const encoder = new TextEncoder();
173 const events = controller.events(undefined, replayGate?.beforeEmit);
174 const frames = events[Symbol.asyncIterator]();
175 const body = new ReadableStream<Uint8Array>({
176 async pull(stream) {
177 const next = await frames.next();
178 if (next.done === true) stream.close();
179 else stream.enqueue(encoder.encode(`data: ${encodeJson(next.value)}\n\n`));
180 },
181 });
182 return new Response(body, { headers: { "content-type": "text/event-stream" } });
183 }
184 // Recorded responses are the raw HTTP bodies; `null` is an empty 204.
185 // `{ status, body }` replays an error status and `"<hang>"` never answers.
186 const body = await controller.response(operation.type);
187 if (body === "<hang>") return new Promise<Response>(() => {});
188 if (typeof body === "object" && body !== null && "status" in body && "body" in body) {
189 return new Response(encodeJson(body.body), {
190 status: Number(body.status),
191 headers: { "content-type": "application/json" },
192 });
193 }
194 return body === null
195 ? new Response(null, { status: 204 })
196 : new Response(encodeJson(body), { headers: { "content-type": "application/json" } });
197 },
198 catch: (cause) =>
199 new HttpClientError.HttpClientError({
200 reason: new HttpClientError.TransportError({ request, cause }),
201 }),
202 }).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response))),
203 );
204
205/**
206 * An OpenCode 2 server that answers from `transcript`, checking at scope close
207 * that the transcript ran out.
208 */
209export const replayServer = (
210 transcript: ProviderReplayTranscript,
211 options?: {
212 readonly external?: boolean;
213 readonly replayGate?: ProviderReplayGate;
214 /** Counts the connections currently lent out, as the server owner's borrowers. */
215 readonly borrowers?: { current: number };
216 },
217) =>
218 Effect.gen(function* () {
219 const controller = new OpenCodeReplayController(transcript);
220 yield* Effect.addFinalizer(() =>
221 Effect.sync(() => {
222 options?.replayGate?.releaseAll();
223 controller.assertComplete();
224 }),
225 );
226 const opencode = yield* OpenCode2Client.make.pipe(
227 Effect.provideService(
228 HttpClient.HttpClient,
229 replayHttpClient(controller, options?.replayGate),
230 ),
231 );
232 const connection = {
233 ...(yield* opencode.connect({ baseUrl: BASE_URL, password: "replay" })),
234 url: BASE_URL,
235 version: transcript.version,
236 external: options?.external ?? false,
237 };
238 const borrowers = options?.borrowers;
239 return OpenCode2Server.OpenCode2Server.of({
240 withConnection: (use) =>
241 borrowers === undefined
242 ? use(connection)
243 : Effect.acquireUseRelease(
244 Effect.sync(() => {
245 borrowers.current += 1;
246 }),
247 () => use(connection),
248 () =>
249 Effect.sync(() => {
250 borrowers.current -= 1;
251 }),
252 ),
253 });
254 });
255
256/** The 2.x adapter over a replayed server. */
257const makeReplayAdapter = (
258 transcript: ProviderReplayTranscript,
259 options?: {
260 readonly external?: boolean;
261 readonly replayGate?: ProviderReplayGate;
262 /** Counts the connections currently lent out, as the server owner's borrowers. */
263 readonly borrowers?: { current: number };
264 },
265) =>
266 Effect.gen(function* () {
267 const server = yield* replayServer(transcript, options);
268 return yield* OpenCode2AdapterV2.make(ProviderInstanceId.make("opencode")).pipe(
269 Effect.provideService(OpenCode2Server.OpenCode2Server, server),
270 );
271 });
272
273const replayServerConfig = (scenario: string) =>
274 Layer.effect(ServerConfig.ServerConfig, makeReplayServerConfig(scenario).pipe(Effect.orDie)).pipe(
275 Layer.provide(NodeServices.layer),
276 );
277
278function makeRegistryLayer(
279 transcript: OpenCode2ReplayTranscript,
280 options?: { readonly replayGate?: ProviderReplayGate },
281) {
282 return Layer.unwrap(
283 makeReplayAdapter(transcript, { external: true, ...options }).pipe(
284 Effect.map((adapter) => ProviderAdapterRegistry.makeLayer([adapter])),
285 ),
286 ).pipe(Layer.provide(Layer.mergeAll(replayServerConfig(transcript.scenario), IdAllocator.layer)));
287}
288
289/**
290 * An open 2.x session runtime whose server answers from `entries`, for
291 * adapter-level tests of failures a real server cannot produce on demand.
292 */
293export const openCode2ReplayRuntime = (
294 entries: ReadonlyArray<ProviderReplayEntry>,
295 options?: { readonly external?: boolean; readonly borrowers?: { current: number } },
296) =>
297 Effect.gen(function* () {
298 const adapter = yield* makeReplayAdapter(
299 {
300 provider: OPENCODE_PROVIDER,
301 protocol: OPENCODE2_HTTP_PROTOCOL,
302 version: "2.0.18",
303 scenario: "opencode2_adapter",
304 entries,
305 },
306 options,
307 );
308 return yield* adapter.openSession({
309 threadId: ThreadId.make("thread:opencode2-adapter"),
310 providerSessionId: ProviderSessionId.make("provider-session:opencode2-adapter"),
311 modelSelection: {
312 instanceId: ProviderInstanceId.make("opencode"),
313 model: "opencode/big-pickle",
314 },
315 // Opened where the adapter tests' threads run, as T3 opens a session for its first thread.
316 runtimePolicy: {
317 runtimeMode: "full-access",
318 interactionMode: "default",
319 cwd: "/work/opencode2",
320 },
321 });
322 }).pipe(
323 Effect.provide(Layer.mergeAll(replayServerConfig("opencode2_adapter"), IdAllocator.layer)),
324 );
325
326export const OpenCode2OrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
327 OpenCode2ReplayTranscript,
328 OpenCodeReplayTranscriptDecodeError
329> = {
330 driver: OPENCODE_PROVIDER,
331 decodeTranscript: (transcript: ProviderReplayTranscript) =>
332 decodeOpenCode2ReplayTranscript(transcript).pipe(
333 Effect.mapError(
334 (cause) =>
335 new OpenCodeReplayTranscriptDecodeError({
336 driver: transcript.provider,
337 protocol: transcript.protocol,
338 scenario: transcript.scenario,
339 cause,
340 }),
341 ),
342 ),
343 makeProviderAdapterRegistryLayer: makeRegistryLayer,
344};