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