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

main
ts 578 lines 18.9 KB
Raw
1 import { pipe } from "effect/Function";
2 import * as Cause from "effect/Cause";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as Queue from "effect/Queue";
7 import * as Ref from "effect/Ref";
8 import * as Schema from "effect/Schema";
9 import * as Sink from "effect/Sink";
10 import * as Stdio from "effect/Stdio";
11 import * as Stream from "effect/Stream";
12
13 import * as CodexClient from "./client.ts";
14 import * as CodexError from "./errors.ts";
15
16 export const CodexAppServerReplayEntry = Schema.Union([
17 Schema.Struct({
18 type: Schema.Literal("expect_outbound"),
19 label: Schema.optional(Schema.String),
20 frame: Schema.Unknown,
21 }),
22 Schema.Struct({
23 type: Schema.Literal("emit_inbound"),
24 label: Schema.optional(Schema.String),
25 frame: Schema.Unknown,
26 afterMs: Schema.optional(Schema.Number),
27 }),
28 Schema.Struct({
29 type: Schema.Literal("runtime_exit"),
30 status: Schema.Literals(["success", "error", "cancelled"]),
31 error: Schema.optional(Schema.Unknown),
32 }),
33 ]);
34 export type CodexAppServerReplayEntry = typeof CodexAppServerReplayEntry.Type;
35
36 export const CodexAppServerReplayTranscript = Schema.Struct({
37 provider: Schema.Literal("codex"),
38 protocol: Schema.Literal("codex.app-server"),
39 version: Schema.String,
40 scenario: Schema.String,
41 metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
42 entries: Schema.Array(CodexAppServerReplayEntry),
43 });
44 export type CodexAppServerReplayTranscript = typeof CodexAppServerReplayTranscript.Type;
45 const decodeOutboundJsonFrame = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
46
47 export class CodexAppServerReplayJsonParseError extends Schema.TaggedError<CodexAppServerReplayJsonParseError>()(
48 "CodexAppServerReplayJsonParseError",
49 {
50 scenario: Schema.String,
51 line: Schema.String,
52 cause: Schema.Defect(),
53 },
54 ) {
55 override get message(): string {
56 return `Failed to parse outbound Codex app-server replay frame for scenario ${this.scenario}.`;
57 }
58 }
59
60 export class CodexAppServerReplayExhaustedError extends Schema.TaggedError<CodexAppServerReplayExhaustedError>()(
61 "CodexAppServerReplayExhaustedError",
62 {
63 scenario: Schema.String,
64 cursor: Schema.Number,
65 actual: Schema.Unknown,
66 },
67 ) {
68 override get message(): string {
69 return `Codex app-server replay transcript exhausted before outbound frame ${this.cursor} in scenario ${this.scenario}.`;
70 }
71 }
72
73 export class CodexAppServerReplayUnexpectedOutboundError extends Schema.TaggedError<CodexAppServerReplayUnexpectedOutboundError>()(
74 "CodexAppServerReplayUnexpectedOutboundError",
75 {
76 scenario: Schema.String,
77 cursor: Schema.Number,
78 expectedType: Schema.String,
79 actual: Schema.Unknown,
80 },
81 ) {
82 override get message(): string {
83 return `Unexpected outbound Codex app-server frame at replay cursor ${this.cursor} in scenario ${this.scenario}.`;
84 }
85 }
86
87 export class CodexAppServerReplayFrameMismatchError extends Schema.TaggedError<CodexAppServerReplayFrameMismatchError>()(
88 "CodexAppServerReplayFrameMismatchError",
89 {
90 scenario: Schema.String,
91 cursor: Schema.Number,
92 label: Schema.optional(Schema.String),
93 expected: Schema.Unknown,
94 actual: Schema.Unknown,
95 },
96 ) {
97 override get message(): string {
98 return `Outbound Codex app-server frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}. Expected ${JSON.stringify(this.expected)}, received ${JSON.stringify(this.actual)}.`;
99 }
100 }
101
102 export class CodexAppServerReplayRuntimeExitError extends Schema.TaggedError<CodexAppServerReplayRuntimeExitError>()(
103 "CodexAppServerReplayRuntimeExitError",
104 {
105 scenario: Schema.String,
106 cursor: Schema.Number,
107 status: Schema.Literals(["error", "cancelled"]),
108 error: Schema.optional(Schema.Unknown),
109 },
110 ) {
111 override get message(): string {
112 return `Codex app-server replay exited with status ${this.status} at cursor ${this.cursor} in scenario ${this.scenario}.`;
113 }
114 }
115
116 export const CodexAppServerReplayError = Schema.Union([
117 CodexAppServerReplayJsonParseError,
118 CodexAppServerReplayExhaustedError,
119 CodexAppServerReplayUnexpectedOutboundError,
120 CodexAppServerReplayFrameMismatchError,
121 CodexAppServerReplayRuntimeExitError,
122 ]);
123 export type CodexAppServerReplayError = typeof CodexAppServerReplayError.Type;
124
125 export interface CodexAppServerReplayState {
126 readonly cursor: number;
127 readonly failure: CodexAppServerReplayError | null;
128 }
129
130 export interface CodexAppServerReplayDriver {
131 readonly transcript: CodexAppServerReplayTranscript;
132 readonly state: Ref.Ref<CodexAppServerReplayState>;
133 readonly beforeEmitInbound?: (
134 entry: Extract<CodexAppServerReplayEntry, { readonly type: "emit_inbound" }>,
135 ) => Effect.Effect<void>;
136 }
137
138 const encoder = new TextEncoder();
139
140 function stableStringify(value: unknown): string {
141 if (Array.isArray(value)) {
142 return `[${value.map(stableStringify).join(",")}]`;
143 }
144 if (typeof value === "object" && value !== null) {
145 const record = value as Record<string, unknown>;
146 return `{${Object.keys(record)
147 .toSorted()
148 .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
149 .join(",")}}`;
150 }
151 return JSON.stringify(value);
152 }
153
154 function normalizeContextHandoffText(value: string): string {
155 if (!value.startsWith("Context handoff (")) {
156 return value;
157 }
158 const userMessageMarker = "\n\nUser message:\n";
159 const userMessageIndex = value.indexOf(userMessageMarker);
160 const headerEndIndex = value.indexOf(":\n");
161 if (headerEndIndex === -1 || userMessageIndex === -1 || headerEndIndex >= userMessageIndex) {
162 return value;
163 }
164 return `${value.slice(0, headerEndIndex + 2)}<dynamic-summary>${value.slice(userMessageIndex)}`;
165 }
166
167 function normalizeReplayFrame(value: unknown): unknown {
168 if (typeof value === "string") {
169 return normalizeContextHandoffText(value);
170 }
171 if (typeof value !== "object" || value === null) {
172 return value;
173 }
174 if (Array.isArray(value)) {
175 return value.map(normalizeReplayFrame);
176 }
177
178 const record = value as Record<string, unknown>;
179 const normalized = Object.fromEntries(
180 Object.entries(record).map(([key, entry]) => [key, normalizeReplayFrame(entry)]),
181 );
182
183 if (
184 normalized.method === "initialize" &&
185 typeof normalized.params === "object" &&
186 normalized.params !== null
187 ) {
188 const params = normalized.params as Record<string, unknown>;
189 if (typeof params.clientInfo === "object" && params.clientInfo !== null) {
190 normalized.params = {
191 ...params,
192 clientInfo: {
193 ...(params.clientInfo as Record<string, unknown>),
194 version: "<ignored>",
195 },
196 };
197 }
198 }
199
200 if (
201 normalized.method === "turn/start" &&
202 typeof normalized.params === "object" &&
203 normalized.params !== null
204 ) {
205 const params = { ...(normalized.params as Record<string, unknown>) };
206 // Older recordings used `never` for full access, before MCP prompts were kept interactive.
207 if (
208 params.approvalPolicy === "never" ||
209 stableStringify(params.approvalPolicy) ===
210 stableStringify({
211 granular: {
212 mcp_elicitations: true,
213 request_permissions: false,
214 rules: false,
215 sandbox_approval: false,
216 skill_approval: false,
217 },
218 })
219 ) {
220 delete params.approvalPolicy;
221 }
222 if (
223 typeof params.sandboxPolicy === "object" &&
224 params.sandboxPolicy !== null &&
225 (params.sandboxPolicy as Record<string, unknown>).type === "dangerFullAccess"
226 ) {
227 delete params.sandboxPolicy;
228 }
229 if (typeof params.collaborationMode === "object" && params.collaborationMode !== null) {
230 const collaborationMode = {
231 ...(params.collaborationMode as Record<string, unknown>),
232 };
233 if (typeof collaborationMode.settings === "object" && collaborationMode.settings !== null) {
234 collaborationMode.settings = {
235 ...(collaborationMode.settings as Record<string, unknown>),
236 developer_instructions: "<ignored>",
237 };
238 }
239 params.collaborationMode = collaborationMode;
240 }
241 normalized.params = params;
242 }
243
244 return normalized;
245 }
246
247 function recorderThreadConfigKeys(transcript: CodexAppServerReplayTranscript): ReadonlySet<string> {
248 const keys = transcript.metadata?.recorderThreadConfigKeys;
249 return new Set(Array.isArray(keys) ? keys.filter((key) => typeof key === "string") : []);
250 }
251
252 /**
253 * `cwd`, `model`, host-supplied MCP servers (machine-local URLs, short-lived
254 * authorization headers) and the T3 thread id vary per machine or run, and
255 * recorder-only keys are not the client's. The config read before a thread
256 * request carries the same `cwd`.
257 */
258 function normalizeThreadRequest(frame: unknown, ignoredConfigKeys: ReadonlySet<string>): unknown {
259 if (typeof frame !== "object" || frame === null) return frame;
260 const record = frame as Record<string, unknown>;
261 if (
262 record.method === "config/read" &&
263 typeof record.params === "object" &&
264 record.params !== null
265 ) {
266 const { cwd: _cwd, ...params } = record.params as Record<string, unknown>;
267 return { ...record, params };
268 }
269 if (
270 (record.method !== "thread/start" &&
271 record.method !== "thread/resume" &&
272 record.method !== "thread/fork") ||
273 typeof record.params !== "object" ||
274 record.params === null
275 ) {
276 return frame;
277 }
278 const { cwd: _cwd, model: _model, config, ...params } = record.params as Record<string, unknown>;
279 if (typeof config !== "object" || config === null) return { ...record, params };
280 const owned = Object.fromEntries(
281 Object.entries(config as Record<string, unknown>).filter(
282 ([key]) =>
283 key !== "mcp_servers" &&
284 !key.startsWith("mcp_servers.") &&
285 key !== "shell_environment_policy.set.T3CODE_THREAD_ID",
286 ),
287 );
288 for (const key of ignoredConfigKeys) delete owned[key];
289 return { ...record, params: { ...params, config: owned } };
290 }
291
292 function sameFrame(
293 left: unknown,
294 right: unknown,
295 ignoredConfigKeys: ReadonlySet<string> = new Set(),
296 ): boolean {
297 const normalize = (frame: unknown) =>
298 pipe(
299 normalizeReplayFrame(frame),
300 (request) => normalizeThreadRequest(request, ignoredConfigKeys),
301 stableStringify,
302 );
303 return normalize(left) === normalize(right);
304 }
305
306 function normalizeLegacyInboundFrame(value: unknown): unknown {
307 if (Array.isArray(value)) {
308 return value.map(normalizeLegacyInboundFrame);
309 }
310 if (typeof value !== "object" || value === null) {
311 return value;
312 }
313 const record = value as Record<string, unknown>;
314 const normalized = Object.fromEntries(
315 Object.entries(record).map(([key, entry]) => [key, normalizeLegacyInboundFrame(entry)]),
316 );
317 if (
318 typeof normalized.id === "string" &&
319 "modelProvider" in normalized &&
320 "status" in normalized
321 ) {
322 if (normalized.sessionId === undefined) normalized.sessionId = normalized.id;
323 if (normalized.projectId === undefined) normalized.projectId = null;
324 }
325 if (
326 (normalized.method === "item/started" || normalized.method === "item/completed") &&
327 typeof normalized.params === "object" &&
328 normalized.params !== null
329 ) {
330 const params = { ...(normalized.params as Record<string, unknown>) };
331 if (normalized.method === "item/started" && params.startedAtMs === undefined) {
332 params.startedAtMs = 0;
333 }
334 if (normalized.method === "item/completed" && params.completedAtMs === undefined) {
335 params.completedAtMs = 0;
336 }
337 normalized.params = params;
338 }
339 if (
340 typeof normalized.method === "string" &&
341 normalized.method.endsWith("/requestApproval") &&
342 typeof normalized.params === "object" &&
343 normalized.params !== null
344 ) {
345 const params = { ...(normalized.params as Record<string, unknown>) };
346 if (params.startedAtMs === undefined) {
347 params.startedAtMs = 0;
348 }
349 normalized.params = params;
350 }
351 if (
352 normalized.method === "item/tool/requestUserInput" &&
353 typeof normalized.params === "object" &&
354 normalized.params !== null
355 ) {
356 const params = { ...(normalized.params as Record<string, unknown>) };
357 // Codex treats a legacy request without `isBlocking` as blocking.
358 if (params.isBlocking === undefined) {
359 params.isBlocking = true;
360 }
361 normalized.params = params;
362 }
363 return normalized;
364 }
365
366 function encodeInboundFrame(frame: unknown): Uint8Array {
367 return encoder.encode(`${JSON.stringify(normalizeLegacyInboundFrame(frame))}\n`);
368 }
369
370 function replayTransportError(
371 error: CodexAppServerReplayError,
372 ): CodexError.CodexAppServerTransportError {
373 return new CodexError.CodexAppServerTransportError({
374 operation: "read-input-stream",
375 cause: error,
376 });
377 }
378
379 export function layerReplay(
380 transcript: CodexAppServerReplayTranscript,
381 ): Layer.Layer<CodexClient.CodexAppServerClient, CodexAppServerReplayError> {
382 return Layer.effect(CodexClient.CodexAppServerClient, makeReplayClient(transcript));
383 }
384
385 export const makeReplayDriver = Effect.fn("effect-codex-app-server/replay.makeReplayDriver")(
386 function* (
387 transcript: CodexAppServerReplayTranscript,
388 options: Pick<CodexAppServerReplayDriver, "beforeEmitInbound"> = {},
389 ) {
390 return {
391 transcript,
392 state: yield* Ref.make<CodexAppServerReplayState>({ cursor: 0, failure: null }),
393 ...options,
394 } satisfies CodexAppServerReplayDriver;
395 },
396 );
397
398 export function layerReplayWithDriver(
399 driver: CodexAppServerReplayDriver,
400 ): Layer.Layer<CodexClient.CodexAppServerClient, CodexAppServerReplayError> {
401 return Layer.effect(CodexClient.CodexAppServerClient, makeReplayClientWithState(driver));
402 }
403
404 const makeReplayClient = Effect.fn("effect-codex-app-server/replay.makeReplayClient")(function* (
405 transcript: CodexAppServerReplayTranscript,
406 options: CodexClient.CodexAppServerClientOptions = {},
407 ) {
408 const driver = yield* makeReplayDriver(transcript);
409 return yield* makeReplayClientWithState(driver, options);
410 });
411
412 const makeReplayClientWithState = Effect.fn(
413 "effect-codex-app-server/replay.makeReplayClientWithState",
414 )(function* (
415 driver: CodexAppServerReplayDriver,
416 options: CodexClient.CodexAppServerClientOptions = {},
417 ) {
418 const transcript = driver.transcript;
419 const ignoredThreadConfigKeys = recorderThreadConfigKeys(transcript);
420 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
421 const state = driver.state;
422 const outboundRemainder = yield* Ref.make("");
423 const decoder = new TextDecoder();
424
425 const failReplay = (error: CodexAppServerReplayError) =>
426 Ref.update(state, (current) => ({
427 ...current,
428 failure: current.failure ?? error,
429 })).pipe(Effect.andThen(Queue.end(input)));
430
431 const drainInbound = Effect.fn("effect-codex-app-server/replay.drainInbound")(function* () {
432 while (true) {
433 const current = yield* Ref.get(state);
434 if (current.failure) {
435 return;
436 }
437
438 const entry = transcript.entries[current.cursor];
439 if (!entry) {
440 return;
441 }
442
443 if (entry.type === "emit_inbound") {
444 if (driver.beforeEmitInbound !== undefined) {
445 yield* driver.beforeEmitInbound(entry);
446 }
447 if (entry.afterMs !== undefined && entry.afterMs > 0) {
448 yield* Effect.sleep(Duration.millis(entry.afterMs));
449 }
450 yield* Queue.offer(input, encodeInboundFrame(entry.frame));
451 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
452 continue;
453 }
454
455 if (entry.type === "runtime_exit") {
456 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
457 if (entry.status === "success") {
458 yield* Queue.end(input);
459 return;
460 }
461 yield* failReplay(
462 new CodexAppServerReplayRuntimeExitError({
463 scenario: transcript.scenario,
464 cursor: current.cursor,
465 status: entry.status,
466 ...(entry.error === undefined ? {} : { error: entry.error }),
467 }),
468 );
469 return;
470 }
471
472 return;
473 }
474 });
475
476 const processOutboundFrame = (actual: unknown) =>
477 drainInbound().pipe(
478 Effect.andThen(
479 Effect.gen(function* () {
480 const current = yield* Ref.get(state);
481 if (current.failure) {
482 return;
483 }
484
485 const entry = transcript.entries[current.cursor];
486 if (!entry) {
487 yield* failReplay(
488 new CodexAppServerReplayExhaustedError({
489 scenario: transcript.scenario,
490 cursor: current.cursor,
491 actual,
492 }),
493 );
494 return;
495 }
496
497 if (entry.type !== "expect_outbound") {
498 yield* failReplay(
499 new CodexAppServerReplayUnexpectedOutboundError({
500 scenario: transcript.scenario,
501 cursor: current.cursor,
502 expectedType: entry.type,
503 actual,
504 }),
505 );
506 return;
507 }
508
509 if (!sameFrame(entry.frame, actual, ignoredThreadConfigKeys)) {
510 yield* failReplay(
511 new CodexAppServerReplayFrameMismatchError({
512 scenario: transcript.scenario,
513 cursor: current.cursor,
514 ...(entry.label === undefined ? {} : { label: entry.label }),
515 expected: entry.frame,
516 actual,
517 }),
518 );
519 return;
520 }
521
522 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
523 yield* drainInbound();
524 }),
525 ),
526 );
527
528 const processOutboundLine = (line: string) => {
529 const trimmed = line.trim();
530 if (trimmed.length === 0) {
531 return Effect.void;
532 }
533 return Effect.try({
534 try: () => decodeOutboundJsonFrame(trimmed),
535 catch: (cause) =>
536 new CodexAppServerReplayJsonParseError({
537 scenario: transcript.scenario,
538 line: trimmed,
539 cause,
540 }),
541 }).pipe(
542 Effect.matchEffect({
543 onFailure: failReplay,
544 onSuccess: processOutboundFrame,
545 }),
546 );
547 };
548
549 const processOutboundChunk = (chunk: string | Uint8Array) =>
550 Ref.modify(outboundRemainder, (current) => {
551 const text = typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
552 const combined = current + text;
553 const lines = combined.split("\n");
554 const nextRemainder = lines.pop() ?? "";
555 return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
556 }).pipe(
557 Effect.flatMap((lines) => Effect.forEach(lines, processOutboundLine, { discard: true })),
558 );
559
560 const terminationError: Effect.Effect<CodexError.CodexAppServerError> = Ref.get(state).pipe(
561 Effect.map((current) =>
562 current.failure
563 ? replayTransportError(current.failure)
564 : new CodexError.CodexAppServerProcessExitedError({ code: 0 }),
565 ),
566 );
567
568 const stdio = Stdio.make({
569 args: Effect.succeed([]),
570 stdin: Stream.fromQueue(input),
571 stdout: () => Sink.forEach(processOutboundChunk),
572 stderr: () => Sink.drain,
573 });
574
575 yield* drainInbound();
576
577 return yield* CodexClient.make(stdio, options, terminationError);
578 });