The best way to control Claude Code, Codex and more from any computer or phone

main
ts 473 lines 16.3 KB
Raw
1 import type { OpencodeClient } from "@opencode-ai/sdk/v2";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { ProviderReplayEntry, type ProviderReplayTranscript } from "@t3tools/contracts";
4 import * as Effect from "effect/Effect";
5 import * as Duration from "effect/Duration";
6 import * as Layer from "effect/Layer";
7 import * as Schema from "effect/Schema";
8
9 import { OpenCodeAdapterV2Driver } from "@t3tools/provider-opencode/server";
10 import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
11 import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
12 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
13 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
14 import { ProviderAdapterDriverCreateError } from "@t3tools/provider-core/server/adapterDriver";
15 import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
16 import { type OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
17 import {
18 OPENCODE_DEFAULT_INSTANCE_ID,
19 OPENCODE_PROVIDER,
20 OPENCODE_SDK_PROTOCOL,
21 } from "@t3tools/provider-opencode/testing";
22
23 const OPENCODE_SDK_REPLAY_PROTOCOL = OPENCODE_SDK_PROTOCOL;
24
25 const OpenCodeSdkReplayTranscript = Schema.Struct({
26 provider: Schema.Literal(OPENCODE_PROVIDER),
27 protocol: Schema.Literal(OPENCODE_SDK_REPLAY_PROTOCOL),
28 version: Schema.String,
29 scenario: Schema.String,
30 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
31 entries: Schema.Array(ProviderReplayEntry),
32 });
33 export type OpenCodeSdkReplayTranscript = typeof OpenCodeSdkReplayTranscript.Type;
34 const decodeOpenCodeSdkReplayTranscript = Schema.decodeUnknownEffect(OpenCodeSdkReplayTranscript);
35
36 export class OpenCodeReplayTranscriptDecodeError extends Schema.TaggedError<OpenCodeReplayTranscriptDecodeError>()(
37 "OpenCodeReplayTranscriptDecodeError",
38 {
39 driver: Schema.optional(Schema.String),
40 protocol: Schema.optional(Schema.String),
41 scenario: Schema.optional(Schema.String),
42 cause: Schema.Defect(),
43 },
44 ) {
45 override get message(): string {
46 return `Failed to decode OpenCode replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
47 }
48 }
49
50 export class OpenCodeReplayMismatchError extends Schema.TaggedError<OpenCodeReplayMismatchError>()(
51 "OpenCodeReplayMismatchError",
52 {
53 scenario: Schema.String,
54 cursor: Schema.Number,
55 expected: Schema.Unknown,
56 actual: Schema.Unknown,
57 },
58 ) {
59 override get message(): string {
60 return `OpenCode replay frame mismatch at cursor ${this.cursor} in scenario ${this.scenario}.`;
61 }
62 }
63
64 export class OpenCodeReplayIncompleteError extends Schema.TaggedError<OpenCodeReplayIncompleteError>()(
65 "OpenCodeReplayIncompleteError",
66 {
67 scenario: Schema.String,
68 cursor: Schema.Number,
69 remaining: Schema.Number,
70 },
71 ) {
72 override get message(): string {
73 return `OpenCode replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`;
74 }
75 }
76
77 export const OpenCodeReplayError = Schema.Union([
78 OpenCodeReplayTranscriptDecodeError,
79 OpenCodeReplayMismatchError,
80 OpenCodeReplayIncompleteError,
81 ]);
82 export type OpenCodeReplayError = typeof OpenCodeReplayError.Type;
83 export const OpenCodeOrchestratorReplayHarnessError = Schema.Union([
84 OpenCodeReplayError,
85 ProviderAdapterDriverCreateError,
86 ]);
87 export type OpenCodeOrchestratorReplayHarnessError =
88 typeof OpenCodeOrchestratorReplayHarnessError.Type;
89
90 function replayValueMatches(expected: unknown, actual: unknown): boolean {
91 if (expected === "<any>" || expected === "<workspace>") return true;
92 if (expected === "<string>") return typeof actual === "string" && actual.length > 0;
93 if (Array.isArray(expected)) {
94 return (
95 Array.isArray(actual) &&
96 expected.length === actual.length &&
97 expected.every((entry, index) => replayValueMatches(entry, actual[index]))
98 );
99 }
100 if (typeof expected === "object" && expected !== null) {
101 if (typeof actual !== "object" || actual === null) return false;
102 return Object.entries(expected).every(([key, value]) =>
103 replayValueMatches(value, (actual as Record<string, unknown>)[key]),
104 );
105 }
106 return Object.is(expected, actual);
107 }
108
109 function frameRecord(frame: unknown): Record<string, unknown> | null {
110 return typeof frame === "object" && frame !== null ? (frame as Record<string, unknown>) : null;
111 }
112
113 function materializeMessageIds(value: unknown, messageIds: ReadonlyMap<string, string>): unknown {
114 if (Array.isArray(value)) return value.map((entry) => materializeMessageIds(entry, messageIds));
115 const record = frameRecord(value);
116 if (record === null) return value;
117 return Object.fromEntries(
118 Object.entries(record).map(([key, entry]) => [
119 key,
120 typeof entry === "string" &&
121 (key === "id" ||
122 key === "messageID" ||
123 key === "parentID" ||
124 key === "inboxID" ||
125 key === "before")
126 ? (messageIds.get(entry) ?? entry)
127 : materializeMessageIds(entry, messageIds),
128 ]),
129 );
130 }
131
132 export class OpenCodeReplayController {
133 private cursor = 0;
134 exited = false;
135
136 get finished(): boolean {
137 return this.cursor >= this.transcript.entries.length;
138 }
139 private readonly waiters = new Set<() => void>();
140 private failure: unknown = null;
141 private readonly transcript: ProviderReplayTranscript;
142 private messageIds = new Map<string, string>();
143
144 constructor(transcript: ProviderReplayTranscript) {
145 this.transcript = transcript;
146 }
147
148 async expectOutbound(actual: unknown): Promise<void> {
149 try {
150 const entry = this.transcript.entries[this.cursor];
151 const expectedFrame = entry?.type === "expect_outbound" ? frameRecord(entry.frame) : null;
152 const actualFrame = frameRecord(actual);
153 const messageIds = new Map(this.messageIds);
154 let conflictingMessageId = false;
155 const idKey = expectedFrame?.type === "session.promptAsync" ? "messageID" : "id";
156 if (
157 (expectedFrame?.type === "session.promptAsync" ||
158 expectedFrame?.type === "session.prompt") &&
159 actualFrame?.type === expectedFrame.type
160 ) {
161 const recordedId = frameRecord(expectedFrame.input)?.[idKey];
162 const actualId = frameRecord(actualFrame.input)?.[idKey];
163 if (
164 typeof recordedId === "string" &&
165 typeof actualId === "string" &&
166 recordedId !== "<any>" &&
167 recordedId !== "<workspace>" &&
168 !messageIds.has(recordedId)
169 ) {
170 conflictingMessageId = [...messageIds.values()].includes(actualId);
171 if (!conflictingMessageId) messageIds.set(recordedId, actualId);
172 }
173 }
174 const expected =
175 entry?.type === "expect_outbound"
176 ? materializeMessageIds(entry.frame, messageIds)
177 : (entry ?? null);
178 if (
179 conflictingMessageId ||
180 entry?.type !== "expect_outbound" ||
181 !replayValueMatches(expected, actual)
182 ) {
183 throw new OpenCodeReplayMismatchError({
184 scenario: this.transcript.scenario,
185 cursor: this.cursor,
186 expected,
187 actual,
188 });
189 }
190 this.messageIds = messageIds;
191 this.advance();
192 } catch (cause) {
193 this.fail(cause);
194 throw cause;
195 }
196 }
197
198 async response(operation: string): Promise<unknown> {
199 while (true) {
200 this.throwFailure();
201 const entry = this.transcript.entries[this.cursor];
202 if (entry?.type === "emit_inbound") {
203 const frame = frameRecord(entry.frame);
204 if (frame?.type === "sdk.response" && frame.operation === operation) {
205 if (entry.afterMs !== undefined && entry.afterMs > 0) {
206 await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs)));
207 }
208 const data = materializeMessageIds(frame.data, this.messageIds);
209 this.advance();
210 return data;
211 }
212 }
213 if (entry?.type === "runtime_exit") {
214 const mismatch = new OpenCodeReplayMismatchError({
215 scenario: this.transcript.scenario,
216 cursor: this.cursor,
217 expected: { type: "sdk.response", operation },
218 actual: entry,
219 });
220 this.fail(mismatch);
221 throw mismatch;
222 }
223 await this.changed();
224 }
225 }
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 /** Waits for events and responses to be consumed so concurrent HTTP requests cannot match earlier answers. */
237 async untilInboundDelivered(): Promise<void> {
238 while (true) {
239 this.throwFailure();
240 if (this.transcript.entries[this.cursor]?.type !== "emit_inbound") return;
241 await this.changed();
242 }
243 }
244
245 async *events(
246 signal?: AbortSignal,
247 beforeEmit?: (label: string | undefined) => Promise<void>,
248 ): AsyncIterable<unknown> {
249 while (true) {
250 if (signal?.aborted === true) return;
251 this.throwFailure();
252 const entry = this.transcript.entries[this.cursor];
253 if (entry?.type === "emit_inbound") {
254 const frame = frameRecord(entry.frame);
255 if (frame?.type === "sdk.event") {
256 if (beforeEmit !== undefined) await beforeEmit(entry.label);
257 if (entry.afterMs !== undefined && entry.afterMs > 0) {
258 await Effect.runPromise(Effect.sleep(Duration.millis(entry.afterMs)));
259 }
260 const event = materializeMessageIds(frame.event, this.messageIds);
261 this.advance();
262 yield event;
263 continue;
264 }
265 }
266 if (entry?.type === "runtime_exit") {
267 this.advance();
268 if (entry.status === "success") {
269 this.exited = true;
270 return;
271 }
272 const mismatch = new OpenCodeReplayMismatchError({
273 scenario: this.transcript.scenario,
274 cursor: this.cursor - 1,
275 expected: { status: "success" },
276 actual: entry,
277 });
278 this.fail(mismatch);
279 throw mismatch;
280 }
281 await this.changed(signal);
282 }
283 }
284
285 assertComplete(): void {
286 while (this.transcript.entries[this.cursor]?.type === "runtime_exit") {
287 const exit = this.transcript.entries[this.cursor];
288 if (exit?.type !== "runtime_exit" || exit.status !== "success") break;
289 this.cursor += 1;
290 }
291 this.throwFailure();
292 if (this.cursor !== this.transcript.entries.length) {
293 throw new OpenCodeReplayIncompleteError({
294 scenario: this.transcript.scenario,
295 cursor: this.cursor,
296 remaining: this.transcript.entries.length - this.cursor,
297 });
298 }
299 }
300
301 private advance(): void {
302 this.cursor += 1;
303 for (const waiter of this.waiters) waiter();
304 this.waiters.clear();
305 }
306
307 private fail(cause: unknown): void {
308 this.failure = cause;
309 for (const waiter of this.waiters) waiter();
310 this.waiters.clear();
311 }
312
313 private throwFailure(): void {
314 if (this.failure !== null) throw this.failure;
315 }
316
317 private changed(signal?: AbortSignal): Promise<void> {
318 return new Promise((resolve) => {
319 let settled = false;
320 const done = () => {
321 if (settled) return;
322 settled = true;
323 signal?.removeEventListener("abort", done);
324 this.waiters.delete(done);
325 resolve();
326 };
327 this.waiters.add(done);
328 signal?.addEventListener("abort", done, { once: true });
329 if (signal?.aborted === true) done();
330 });
331 }
332 }
333
334 function makeReplayClient(controller: OpenCodeReplayController): OpencodeClient {
335 const request = async (operation: string, input: unknown) => {
336 await controller.expectOutbound({ type: operation, input });
337 return { data: await controller.response(operation) };
338 };
339 return {
340 event: {
341 subscribe: async (_input?: unknown, options?: { readonly signal?: AbortSignal }) => {
342 await controller.expectOutbound({ type: "event.subscribe" });
343 return { stream: controller.events(options?.signal) };
344 },
345 },
346 session: {
347 create: (input: unknown) => request("session.create", input),
348 get: (input: unknown) => request("session.get", input),
349 children: (input: unknown) => request("session.children", input),
350 update: (input: unknown) => request("session.update", input),
351 messages: (input: unknown) => request("session.messages", input),
352 promptAsync: (input: unknown) => request("session.promptAsync", input),
353 abort: (input: unknown) => request("session.abort", input),
354 revert: (input: unknown) => request("session.revert", input),
355 unrevert: (input: unknown) => request("session.unrevert", input),
356 fork: (input: unknown) => request("session.fork", input),
357 },
358 permission: {
359 reply: (input: unknown) => request("permission.reply", input),
360 },
361 question: {
362 reply: (input: unknown) => request("question.reply", input),
363 },
364 mcp: {
365 status: () => request("mcp.status", {}),
366 add: (input: unknown) => request("mcp.add", input),
367 },
368 } as unknown as OpencodeClient;
369 }
370
371 function layerOpenCodeReplayRuntime(transcript: OpenCodeSdkReplayTranscript) {
372 return Layer.effect(
373 OpenCodeRuntime.OpenCodeRuntime,
374 Effect.gen(function* () {
375 const controller = new OpenCodeReplayController(transcript);
376 yield* Effect.addFinalizer(() =>
377 Effect.sync(() => {
378 controller.assertComplete();
379 }),
380 );
381 const client = makeReplayClient(controller);
382 return OpenCodeRuntime.OpenCodeRuntime.of({
383 startOpenCodeServerProcess: () =>
384 Effect.fail(
385 new OpenCodeRuntime.OpenCodeRuntimeError({
386 operation: "startOpenCodeServerProcess",
387 detail: "OpenCode replay uses an external in-memory SDK boundary.",
388 }),
389 ),
390 connectToOpenCodeServer: () =>
391 Effect.succeed({
392 url: "replay://opencode",
393 version: "0.0.0-replay",
394 exitCode: null,
395 external: true,
396 }),
397 runOpenCodeCommand: () =>
398 Effect.fail(
399 new OpenCodeRuntime.OpenCodeRuntimeError({
400 operation: "runOpenCodeCommand",
401 detail: "OpenCode replay does not execute commands.",
402 }),
403 ),
404 createOpenCodeSdkClient: () => client,
405 loadOpenCodeInventory: () =>
406 Effect.fail(
407 new OpenCodeRuntime.OpenCodeRuntimeError({
408 operation: "loadOpenCodeInventory",
409 detail: "OpenCode replay does not load inventory.",
410 }),
411 ),
412 loadOpenCodeSkills: () =>
413 Effect.fail(
414 new OpenCodeRuntime.OpenCodeRuntimeError({
415 operation: "loadOpenCodeSkills",
416 detail: "OpenCode replay does not load skills.",
417 }),
418 ),
419 } satisfies OpenCodeRuntime.OpenCodeRuntime["Service"]);
420 }),
421 );
422 }
423
424 function layerOpenCodeProviderAdapterRegistryReplay(transcript: OpenCodeSdkReplayTranscript) {
425 return ProviderAdapterRegistry.layerFromAdaptersEffect(
426 OpenCodeAdapterV2Driver.create({
427 instanceId: OPENCODE_DEFAULT_INSTANCE_ID,
428 environment: [],
429 displayName: undefined,
430 enabled: true,
431 config: { ...OpenCodeAdapterV2Driver.defaultConfig(), serverUrl: "replay://opencode" },
432 }).pipe(Effect.map((adapter) => [adapter])),
433 ).pipe(
434 Layer.provide(
435 Layer.mergeAll(
436 layerOpenCodeReplayRuntime(transcript),
437 TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)),
438 NodeServices.layer,
439 IdAllocator.layer,
440 Layer.succeed(
441 ProviderEventLoggers.ProviderEventLoggers,
442 ProviderEventLoggers.NoOpProviderEventLoggers,
443 ),
444 ),
445 ),
446 );
447 }
448
449 function transcriptMetadata(transcript: ProviderReplayTranscript) {
450 return {
451 provider: transcript.provider,
452 protocol: transcript.protocol,
453 scenario: transcript.scenario,
454 };
455 }
456
457 export const OpenCodeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
458 OpenCodeSdkReplayTranscript,
459 OpenCodeOrchestratorReplayHarnessError
460 > = {
461 driver: OPENCODE_PROVIDER,
462 decodeTranscript: (transcript) =>
463 decodeOpenCodeSdkReplayTranscript(transcript).pipe(
464 Effect.mapError(
465 (cause) =>
466 new OpenCodeReplayTranscriptDecodeError({
467 ...transcriptMetadata(transcript),
468 cause,
469 }),
470 ),
471 ),
472 makeProviderAdapterRegistryLayer: layerOpenCodeProviderAdapterRegistryReplay,
473 };