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