Open History to see the last commit
1import { pipe } from "effect/Function";
2import * as Cause from "effect/Cause";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Queue from "effect/Queue";
7import * as Ref from "effect/Ref";
8import * as Schema from "effect/Schema";
9import * as Sink from "effect/Sink";
10import * as Stdio from "effect/Stdio";
11import * as Stream from "effect/Stream";
12
13import * as CodexClient from "./client.ts";
14import * as CodexError from "./errors.ts";
15
16export 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]);
34export type CodexAppServerReplayEntry = typeof CodexAppServerReplayEntry.Type;
35
36export 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});
44export type CodexAppServerReplayTranscript = typeof CodexAppServerReplayTranscript.Type;
45const decodeOutboundJsonFrame = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
46
47export 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
60export 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
73export 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
87export 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
102export 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
116export const CodexAppServerReplayError = Schema.Union([
117 CodexAppServerReplayJsonParseError,
118 CodexAppServerReplayExhaustedError,
119 CodexAppServerReplayUnexpectedOutboundError,
120 CodexAppServerReplayFrameMismatchError,
121 CodexAppServerReplayRuntimeExitError,
122]);
123export type CodexAppServerReplayError = typeof CodexAppServerReplayError.Type;
124
125export interface CodexAppServerReplayState {
126 readonly cursor: number;
127 readonly failure: CodexAppServerReplayError | null;
128}
129
130export 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
138const encoder = new TextEncoder();
139
140function 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
154function 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
167function 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
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`, 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 */
258function 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 // Older recordings omitted the source for ordinary threads.
280 if (record.method === "thread/start" && params.threadSource === "user") {
281 delete params.threadSource;
282 }
283 if (typeof config !== "object" || config === null) return { ...record, params };
284 const owned = Object.fromEntries(
285 Object.entries(config as Record<string, unknown>).filter(
286 ([key]) =>
287 key !== "mcp_servers" &&
288 !key.startsWith("mcp_servers.") &&
289 key !== "shell_environment_policy.set.T3CODE_THREAD_ID",
290 ),
291 );
292 for (const key of ignoredConfigKeys) delete owned[key];
293 return { ...record, params: { ...params, config: owned } };
294}
295
296function sameFrame(
297 left: unknown,
298 right: unknown,
299 ignoredConfigKeys: ReadonlySet<string> = new Set(),
300): boolean {
301 const normalize = (frame: unknown) =>
302 pipe(
303 normalizeReplayFrame(frame),
304 (request) => normalizeThreadRequest(request, ignoredConfigKeys),
305 stableStringify,
306 );
307 return normalize(left) === normalize(right);
308}
309
310function normalizeLegacyInboundFrame(value: unknown): unknown {
311 if (Array.isArray(value)) {
312 return value.map(normalizeLegacyInboundFrame);
313 }
314 if (typeof value !== "object" || value === null) {
315 return value;
316 }
317 const record = value as Record<string, unknown>;
318 const normalized = Object.fromEntries(
319 Object.entries(record).map(([key, entry]) => [key, normalizeLegacyInboundFrame(entry)]),
320 );
321 if (
322 typeof normalized.id === "string" &&
323 "modelProvider" in normalized &&
324 "status" in normalized
325 ) {
326 if (normalized.sessionId === undefined) normalized.sessionId = normalized.id;
327 if (normalized.projectId === undefined) normalized.projectId = null;
328 }
329 if (
330 (normalized.method === "item/started" || normalized.method === "item/completed") &&
331 typeof normalized.params === "object" &&
332 normalized.params !== null
333 ) {
334 const params = { ...(normalized.params as Record<string, unknown>) };
335 if (normalized.method === "item/started" && params.startedAtMs === undefined) {
336 params.startedAtMs = 0;
337 }
338 if (normalized.method === "item/completed" && params.completedAtMs === undefined) {
339 params.completedAtMs = 0;
340 }
341 normalized.params = params;
342 }
343 if (
344 typeof normalized.method === "string" &&
345 normalized.method.endsWith("/requestApproval") &&
346 typeof normalized.params === "object" &&
347 normalized.params !== null
348 ) {
349 const params = { ...(normalized.params as Record<string, unknown>) };
350 if (params.startedAtMs === undefined) {
351 params.startedAtMs = 0;
352 }
353 normalized.params = params;
354 }
355 if (
356 normalized.method === "item/tool/requestUserInput" &&
357 typeof normalized.params === "object" &&
358 normalized.params !== null
359 ) {
360 const params = { ...(normalized.params as Record<string, unknown>) };
361 // Codex treats a legacy request without `isBlocking` as blocking.
362 if (params.isBlocking === undefined) {
363 params.isBlocking = true;
364 }
365 normalized.params = params;
366 }
367 return normalized;
368}
369
370function encodeInboundFrame(frame: unknown): Uint8Array {
371 return encoder.encode(`${JSON.stringify(normalizeLegacyInboundFrame(frame))}\n`);
372}
373
374function replayTransportError(
375 error: CodexAppServerReplayError,
376): CodexError.CodexAppServerTransportError {
377 return new CodexError.CodexAppServerTransportError({
378 operation: "read-input-stream",
379 cause: error,
380 });
381}
382
383export function layerReplay(
384 transcript: CodexAppServerReplayTranscript,
385): Layer.Layer<CodexClient.CodexAppServerClient, CodexAppServerReplayError> {
386 return Layer.effect(CodexClient.CodexAppServerClient, makeReplayClient(transcript));
387}
388
389export const makeReplayDriver = Effect.fn("effect-codex-app-server/replay.makeReplayDriver")(
390 function* (
391 transcript: CodexAppServerReplayTranscript,
392 options: Pick<CodexAppServerReplayDriver, "beforeEmitInbound"> = {},
393 ) {
394 return {
395 transcript,
396 state: yield* Ref.make<CodexAppServerReplayState>({ cursor: 0, failure: null }),
397 ...options,
398 } satisfies CodexAppServerReplayDriver;
399 },
400);
401
402export function layerReplayWithDriver(
403 driver: CodexAppServerReplayDriver,
404): Layer.Layer<CodexClient.CodexAppServerClient, CodexAppServerReplayError> {
405 return Layer.effect(CodexClient.CodexAppServerClient, makeReplayClientWithState(driver));
406}
407
408const makeReplayClient = Effect.fn("effect-codex-app-server/replay.makeReplayClient")(function* (
409 transcript: CodexAppServerReplayTranscript,
410 options: CodexClient.CodexAppServerClientOptions = {},
411) {
412 const driver = yield* makeReplayDriver(transcript);
413 return yield* makeReplayClientWithState(driver, options);
414});
415
416const makeReplayClientWithState = Effect.fn(
417 "effect-codex-app-server/replay.makeReplayClientWithState",
418)(function* (
419 driver: CodexAppServerReplayDriver,
420 options: CodexClient.CodexAppServerClientOptions = {},
421) {
422 const transcript = driver.transcript;
423 const ignoredThreadConfigKeys = recorderThreadConfigKeys(transcript);
424 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
425 const state = driver.state;
426 const outboundRemainder = yield* Ref.make("");
427 const decoder = new TextDecoder();
428
429 const failReplay = (error: CodexAppServerReplayError) =>
430 Ref.update(state, (current) => ({
431 ...current,
432 failure: current.failure ?? error,
433 })).pipe(Effect.andThen(Queue.end(input)));
434
435 const drainInbound = Effect.fn("effect-codex-app-server/replay.drainInbound")(function* () {
436 while (true) {
437 const current = yield* Ref.get(state);
438 if (current.failure) {
439 return;
440 }
441
442 const entry = transcript.entries[current.cursor];
443 if (!entry) {
444 return;
445 }
446
447 if (entry.type === "emit_inbound") {
448 if (driver.beforeEmitInbound !== undefined) {
449 yield* driver.beforeEmitInbound(entry);
450 }
451 if (entry.afterMs !== undefined && entry.afterMs > 0) {
452 yield* Effect.sleep(Duration.millis(entry.afterMs));
453 }
454 yield* Queue.offer(input, encodeInboundFrame(entry.frame));
455 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
456 continue;
457 }
458
459 if (entry.type === "runtime_exit") {
460 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
461 if (entry.status === "success") {
462 yield* Queue.end(input);
463 return;
464 }
465 yield* failReplay(
466 new CodexAppServerReplayRuntimeExitError({
467 scenario: transcript.scenario,
468 cursor: current.cursor,
469 status: entry.status,
470 ...(entry.error === undefined ? {} : { error: entry.error }),
471 }),
472 );
473 return;
474 }
475
476 return;
477 }
478 });
479
480 const processOutboundFrame = (actual: unknown) =>
481 drainInbound().pipe(
482 Effect.andThen(
483 Effect.gen(function* () {
484 const current = yield* Ref.get(state);
485 if (current.failure) {
486 return;
487 }
488
489 const entry = transcript.entries[current.cursor];
490 if (!entry) {
491 yield* failReplay(
492 new CodexAppServerReplayExhaustedError({
493 scenario: transcript.scenario,
494 cursor: current.cursor,
495 actual,
496 }),
497 );
498 return;
499 }
500
501 if (entry.type !== "expect_outbound") {
502 yield* failReplay(
503 new CodexAppServerReplayUnexpectedOutboundError({
504 scenario: transcript.scenario,
505 cursor: current.cursor,
506 expectedType: entry.type,
507 actual,
508 }),
509 );
510 return;
511 }
512
513 if (!sameFrame(entry.frame, actual, ignoredThreadConfigKeys)) {
514 yield* failReplay(
515 new CodexAppServerReplayFrameMismatchError({
516 scenario: transcript.scenario,
517 cursor: current.cursor,
518 ...(entry.label === undefined ? {} : { label: entry.label }),
519 expected: entry.frame,
520 actual,
521 }),
522 );
523 return;
524 }
525
526 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
527 yield* drainInbound();
528 }),
529 ),
530 );
531
532 const processOutboundLine = (line: string) => {
533 const trimmed = line.trim();
534 if (trimmed.length === 0) {
535 return Effect.void;
536 }
537 return Effect.try({
538 try: () => decodeOutboundJsonFrame(trimmed),
539 catch: (cause) =>
540 new CodexAppServerReplayJsonParseError({
541 scenario: transcript.scenario,
542 line: trimmed,
543 cause,
544 }),
545 }).pipe(
546 Effect.matchEffect({
547 onFailure: failReplay,
548 onSuccess: processOutboundFrame,
549 }),
550 );
551 };
552
553 const processOutboundChunk = (chunk: string | Uint8Array) =>
554 Ref.modify(outboundRemainder, (current) => {
555 const text = typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
556 const combined = current + text;
557 const lines = combined.split("\n");
558 const nextRemainder = lines.pop() ?? "";
559 return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
560 }).pipe(
561 Effect.flatMap((lines) => Effect.forEach(lines, processOutboundLine, { discard: true })),
562 );
563
564 const terminationError: Effect.Effect<CodexError.CodexAppServerError> = Ref.get(state).pipe(
565 Effect.map((current) =>
566 current.failure
567 ? replayTransportError(current.failure)
568 : new CodexError.CodexAppServerProcessExitedError({ code: 0 }),
569 ),
570 );
571
572 const stdio = Stdio.make({
573 args: Effect.succeed([]),
574 stdin: Stream.fromQueue(input),
575 stdout: () => Sink.forEach(processOutboundChunk),
576 stderr: () => Sink.drain,
577 });
578
579 yield* drainInbound();
580
581 return yield* CodexClient.make(stdio, options, terminationError);
582});