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 { CodexAppServerClient } from "./client.ts";
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 class CodexAppServerReplayIncompleteError extends Schema.TaggedError<CodexAppServerReplayIncompleteError>()(
117 "CodexAppServerReplayIncompleteError",
118 {
119 scenario: Schema.String,
120 cursor: Schema.Number,
121 remaining: Schema.Number,
122 },
123) {
124 override get message(): string {
125 return `Codex app-server replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`;
126 }
127}
128
129export const CodexAppServerReplayError = Schema.Union([
130 CodexAppServerReplayJsonParseError,
131 CodexAppServerReplayExhaustedError,
132 CodexAppServerReplayUnexpectedOutboundError,
133 CodexAppServerReplayFrameMismatchError,
134 CodexAppServerReplayRuntimeExitError,
135 CodexAppServerReplayIncompleteError,
136]);
137export type CodexAppServerReplayError = typeof CodexAppServerReplayError.Type;
138
139export interface CodexAppServerReplayState {
140 readonly cursor: number;
141 readonly failure: CodexAppServerReplayError | null;
142}
143
144export interface CodexAppServerReplayDriver {
145 readonly transcript: CodexAppServerReplayTranscript;
146 readonly state: Ref.Ref<CodexAppServerReplayState>;
147 readonly beforeEmitInbound?: (
148 entry: Extract<CodexAppServerReplayEntry, { readonly type: "emit_inbound" }>,
149 ) => Effect.Effect<void>;
150}
151
152const encoder = new TextEncoder();
153
154function stableStringify(value: unknown): string {
155 if (Array.isArray(value)) {
156 return `[${value.map(stableStringify).join(",")}]`;
157 }
158 if (typeof value === "object" && value !== null) {
159 const record = value as Record<string, unknown>;
160 return `{${Object.keys(record)
161 .toSorted()
162 .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
163 .join(",")}}`;
164 }
165 return JSON.stringify(value);
166}
167
168function normalizeContextHandoffText(value: string): string {
169 if (!value.startsWith("Context handoff (")) {
170 return value;
171 }
172 const userMessageMarker = "\n\nUser message:\n";
173 const userMessageIndex = value.indexOf(userMessageMarker);
174 const headerEndIndex = value.indexOf(":\n");
175 if (headerEndIndex === -1 || userMessageIndex === -1 || headerEndIndex >= userMessageIndex) {
176 return value;
177 }
178 return `${value.slice(0, headerEndIndex + 2)}<dynamic-summary>${value.slice(userMessageIndex)}`;
179}
180
181function normalizeReplayFrame(value: unknown): unknown {
182 if (typeof value === "string") {
183 return normalizeContextHandoffText(value);
184 }
185 if (typeof value !== "object" || value === null) {
186 return value;
187 }
188 if (Array.isArray(value)) {
189 return value.map(normalizeReplayFrame);
190 }
191
192 const record = value as Record<string, unknown>;
193 const normalized = Object.fromEntries(
194 Object.entries(record).map(([key, entry]) => [key, normalizeReplayFrame(entry)]),
195 );
196
197 if (
198 normalized.method === "initialize" &&
199 typeof normalized.params === "object" &&
200 normalized.params !== null
201 ) {
202 const params = normalized.params as Record<string, unknown>;
203 if (typeof params.clientInfo === "object" && params.clientInfo !== null) {
204 normalized.params = {
205 ...params,
206 clientInfo: {
207 ...(params.clientInfo as Record<string, unknown>),
208 version: "<ignored>",
209 },
210 };
211 }
212 }
213
214 if (
215 normalized.method === "turn/start" &&
216 typeof normalized.params === "object" &&
217 normalized.params !== null
218 ) {
219 const params = { ...(normalized.params as Record<string, unknown>) };
220 if (params.approvalPolicy === "never") {
221 delete params.approvalPolicy;
222 }
223 if (
224 typeof params.sandboxPolicy === "object" &&
225 params.sandboxPolicy !== null &&
226 (params.sandboxPolicy as Record<string, unknown>).type === "dangerFullAccess"
227 ) {
228 delete params.sandboxPolicy;
229 }
230 if (typeof params.collaborationMode === "object" && params.collaborationMode !== null) {
231 const collaborationMode = {
232 ...(params.collaborationMode as Record<string, unknown>),
233 };
234 if (typeof collaborationMode.settings === "object" && collaborationMode.settings !== null) {
235 collaborationMode.settings = {
236 ...(collaborationMode.settings as Record<string, unknown>),
237 developer_instructions: "<ignored>",
238 };
239 }
240 params.collaborationMode = collaborationMode;
241 }
242 normalized.params = params;
243 }
244
245 return normalized;
246}
247
248/**
249 * `config` keys a recorder sent on thread requests that the client under test
250 * never sends, such as `agents.max_depth`. Recorders list them in the
251 * transcript header as `metadata.recorderThreadConfigKeys`.
252 */
253function recorderThreadConfigKeys(transcript: CodexAppServerReplayTranscript): ReadonlySet<string> {
254 const keys = transcript.metadata?.recorderThreadConfigKeys;
255 return new Set(Array.isArray(keys) ? keys.filter((key) => typeof key === "string") : []);
256}
257
258/**
259 * Thread requests must match on the `config` the client owns. `cwd`, `model`
260 * and host-supplied MCP servers (machine-local URLs, short-lived authorization
261 * headers) vary per machine, and recorder-only keys are not the client's.
262 */
263function normalizeThreadRequest(frame: unknown, ignoredConfigKeys: ReadonlySet<string>): unknown {
264 if (typeof frame !== "object" || frame === null) return frame;
265 const record = frame as Record<string, unknown>;
266 if (
267 (record.method !== "thread/start" &&
268 record.method !== "thread/resume" &&
269 record.method !== "thread/fork") ||
270 typeof record.params !== "object" ||
271 record.params === null
272 ) {
273 return frame;
274 }
275 const { cwd: _cwd, model: _model, config, ...params } = record.params as Record<string, unknown>;
276 if (typeof config !== "object" || config === null) return { ...record, params };
277 const { mcp_servers: _mcpServers, ...owned } = config as Record<string, unknown>;
278 for (const key of ignoredConfigKeys) delete owned[key];
279 return { ...record, params: { ...params, config: owned } };
280}
281
282function sameFrame(
283 left: unknown,
284 right: unknown,
285 ignoredConfigKeys: ReadonlySet<string> = new Set(),
286): boolean {
287 const normalize = (frame: unknown) =>
288 stableStringify(normalizeThreadRequest(normalizeReplayFrame(frame), ignoredConfigKeys));
289 return normalize(left) === normalize(right);
290}
291
292function normalizeLegacyInboundFrame(value: unknown): unknown {
293 if (Array.isArray(value)) {
294 return value.map(normalizeLegacyInboundFrame);
295 }
296 if (typeof value !== "object" || value === null) {
297 return value;
298 }
299 const record = value as Record<string, unknown>;
300 const normalized = Object.fromEntries(
301 Object.entries(record).map(([key, entry]) => [key, normalizeLegacyInboundFrame(entry)]),
302 );
303 if (
304 typeof normalized.id === "string" &&
305 "modelProvider" in normalized &&
306 "status" in normalized
307 ) {
308 if (normalized.sessionId === undefined) normalized.sessionId = normalized.id;
309 if (normalized.projectId === undefined) normalized.projectId = null;
310 }
311 if (
312 (normalized.method === "item/started" || normalized.method === "item/completed") &&
313 typeof normalized.params === "object" &&
314 normalized.params !== null
315 ) {
316 const params = { ...(normalized.params as Record<string, unknown>) };
317 if (normalized.method === "item/started" && params.startedAtMs === undefined) {
318 params.startedAtMs = 0;
319 }
320 if (normalized.method === "item/completed" && params.completedAtMs === undefined) {
321 params.completedAtMs = 0;
322 }
323 normalized.params = params;
324 }
325 if (
326 typeof normalized.method === "string" &&
327 normalized.method.endsWith("/requestApproval") &&
328 typeof normalized.params === "object" &&
329 normalized.params !== null
330 ) {
331 const params = { ...(normalized.params as Record<string, unknown>) };
332 if (params.startedAtMs === undefined) {
333 params.startedAtMs = 0;
334 }
335 normalized.params = params;
336 }
337 if (
338 normalized.method === "item/tool/requestUserInput" &&
339 typeof normalized.params === "object" &&
340 normalized.params !== null
341 ) {
342 const params = { ...(normalized.params as Record<string, unknown>) };
343 // Codex treats a legacy request without `isBlocking` as blocking.
344 if (params.isBlocking === undefined) {
345 params.isBlocking = true;
346 }
347 normalized.params = params;
348 }
349 return normalized;
350}
351
352function encodeInboundFrame(frame: unknown): Uint8Array {
353 return encoder.encode(`${JSON.stringify(normalizeLegacyInboundFrame(frame))}\n`);
354}
355
356function replayTransportError(
357 error: CodexAppServerReplayError,
358): CodexError.CodexAppServerTransportError {
359 return new CodexError.CodexAppServerTransportError({
360 operation: "read-input-stream",
361 cause: error,
362 });
363}
364
365export function layerReplay(
366 transcript: CodexAppServerReplayTranscript,
367): Layer.Layer<CodexAppServerClient, CodexAppServerReplayError> {
368 return Layer.effect(CodexAppServerClient, makeReplayClient(transcript));
369}
370
371export const makeReplayDriver = Effect.fn("effect-codex-app-server/replay.makeReplayDriver")(
372 function* (
373 transcript: CodexAppServerReplayTranscript,
374 options: Pick<CodexAppServerReplayDriver, "beforeEmitInbound"> = {},
375 ) {
376 return {
377 transcript,
378 state: yield* Ref.make<CodexAppServerReplayState>({ cursor: 0, failure: null }),
379 ...options,
380 } satisfies CodexAppServerReplayDriver;
381 },
382);
383
384export function layerReplayWithDriver(
385 driver: CodexAppServerReplayDriver,
386): Layer.Layer<CodexAppServerClient, CodexAppServerReplayError> {
387 return Layer.effect(CodexAppServerClient, makeReplayClientWithState(driver));
388}
389
390const makeReplayClient = Effect.fn("effect-codex-app-server/replay.makeReplayClient")(function* (
391 transcript: CodexAppServerReplayTranscript,
392 options: CodexClient.CodexAppServerClientOptions = {},
393) {
394 const driver = yield* makeReplayDriver(transcript);
395 return yield* makeReplayClientWithState(driver, options);
396});
397
398const makeReplayClientWithState = Effect.fn(
399 "effect-codex-app-server/replay.makeReplayClientWithState",
400)(function* (
401 driver: CodexAppServerReplayDriver,
402 options: CodexClient.CodexAppServerClientOptions = {},
403) {
404 const transcript = driver.transcript;
405 const ignoredThreadConfigKeys = recorderThreadConfigKeys(transcript);
406 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
407 const state = driver.state;
408 const outboundRemainder = yield* Ref.make("");
409 const decoder = new TextDecoder();
410
411 const failReplay = (error: CodexAppServerReplayError) =>
412 Ref.update(state, (current) => ({
413 ...current,
414 failure: current.failure ?? error,
415 })).pipe(Effect.andThen(Queue.end(input)));
416
417 const drainInbound = Effect.fn("effect-codex-app-server/replay.drainInbound")(function* () {
418 while (true) {
419 const current = yield* Ref.get(state);
420 if (current.failure) {
421 return;
422 }
423
424 const entry = transcript.entries[current.cursor];
425 if (!entry) {
426 return;
427 }
428
429 if (entry.type === "emit_inbound") {
430 if (driver.beforeEmitInbound !== undefined) {
431 yield* driver.beforeEmitInbound(entry);
432 }
433 if (entry.afterMs !== undefined && entry.afterMs > 0) {
434 yield* Effect.sleep(Duration.millis(entry.afterMs));
435 }
436 yield* Queue.offer(input, encodeInboundFrame(entry.frame));
437 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
438 continue;
439 }
440
441 if (entry.type === "runtime_exit") {
442 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
443 if (entry.status === "success") {
444 yield* Queue.end(input);
445 return;
446 }
447 yield* failReplay(
448 new CodexAppServerReplayRuntimeExitError({
449 scenario: transcript.scenario,
450 cursor: current.cursor,
451 status: entry.status,
452 ...(entry.error === undefined ? {} : { error: entry.error }),
453 }),
454 );
455 return;
456 }
457
458 return;
459 }
460 });
461
462 const processOutboundFrame = (actual: unknown) =>
463 drainInbound().pipe(
464 Effect.andThen(
465 Effect.gen(function* () {
466 const current = yield* Ref.get(state);
467 if (current.failure) {
468 return;
469 }
470
471 const entry = transcript.entries[current.cursor];
472 if (!entry) {
473 yield* failReplay(
474 new CodexAppServerReplayExhaustedError({
475 scenario: transcript.scenario,
476 cursor: current.cursor,
477 actual,
478 }),
479 );
480 return;
481 }
482
483 if (entry.type !== "expect_outbound") {
484 yield* failReplay(
485 new CodexAppServerReplayUnexpectedOutboundError({
486 scenario: transcript.scenario,
487 cursor: current.cursor,
488 expectedType: entry.type,
489 actual,
490 }),
491 );
492 return;
493 }
494
495 if (!sameFrame(entry.frame, actual, ignoredThreadConfigKeys)) {
496 yield* failReplay(
497 new CodexAppServerReplayFrameMismatchError({
498 scenario: transcript.scenario,
499 cursor: current.cursor,
500 ...(entry.label === undefined ? {} : { label: entry.label }),
501 expected: entry.frame,
502 actual,
503 }),
504 );
505 return;
506 }
507
508 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
509 yield* drainInbound();
510 }),
511 ),
512 );
513
514 const processOutboundLine = (line: string) => {
515 const trimmed = line.trim();
516 if (trimmed.length === 0) {
517 return Effect.void;
518 }
519 return Effect.try({
520 try: () => decodeOutboundJsonFrame(trimmed),
521 catch: (cause) =>
522 new CodexAppServerReplayJsonParseError({
523 scenario: transcript.scenario,
524 line: trimmed,
525 cause,
526 }),
527 }).pipe(
528 Effect.matchEffect({
529 onFailure: failReplay,
530 onSuccess: processOutboundFrame,
531 }),
532 );
533 };
534
535 const processOutboundChunk = (chunk: string | Uint8Array) =>
536 Ref.modify(outboundRemainder, (current) => {
537 const text = typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
538 const combined = current + text;
539 const lines = combined.split("\n");
540 const nextRemainder = lines.pop() ?? "";
541 return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
542 }).pipe(
543 Effect.flatMap((lines) => Effect.forEach(lines, processOutboundLine, { discard: true })),
544 );
545
546 const terminationError: Effect.Effect<CodexError.CodexAppServerError> = Ref.get(state).pipe(
547 Effect.map((current) =>
548 current.failure
549 ? replayTransportError(current.failure)
550 : new CodexError.CodexAppServerProcessExitedError({ code: 0 }),
551 ),
552 );
553
554 const stdio = Stdio.make({
555 args: Effect.succeed([]),
556 stdin: Stream.fromQueue(input),
557 stdout: () => Sink.forEach(processOutboundChunk),
558 stderr: () => Sink.drain,
559 });
560
561 yield* drainInbound();
562
563 return yield* CodexClient.make(stdio, options, terminationError);
564});