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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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}
148
149const encoder = new TextEncoder();
150const decoder = new TextDecoder();
151
152function stableStringify(value: unknown): string {
153 if (Array.isArray(value)) {
154 return `[${value.map(stableStringify).join(",")}]`;
155 }
156 if (typeof value === "object" && value !== null) {
157 const record = value as Record<string, unknown>;
158 return `{${Object.keys(record)
159 .toSorted()
160 .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
161 .join(",")}}`;
162 }
163 return JSON.stringify(value);
164}
165
166function normalizeContextHandoffText(value: string): string {
167 if (!value.startsWith("Context handoff (")) {
168 return value;
169 }
170 const userMessageMarker = "\n\nUser message:\n";
171 const userMessageIndex = value.indexOf(userMessageMarker);
172 const headerEndIndex = value.indexOf(":\n");
173 if (headerEndIndex === -1 || userMessageIndex === -1 || headerEndIndex >= userMessageIndex) {
174 return value;
175 }
176 return `${value.slice(0, headerEndIndex + 2)}<dynamic-summary>${value.slice(userMessageIndex)}`;
177}
178
179function normalizeReplayFrame(value: unknown): unknown {
180 if (typeof value === "string") {
181 return normalizeContextHandoffText(value);
182 }
183 if (typeof value !== "object" || value === null) {
184 return value;
185 }
186 if (Array.isArray(value)) {
187 return value.map(normalizeReplayFrame);
188 }
189
190 const record = value as Record<string, unknown>;
191 const normalized = Object.fromEntries(
192 Object.entries(record).map(([key, entry]) => [key, normalizeReplayFrame(entry)]),
193 );
194
195 if (
196 normalized.method === "initialize" &&
197 typeof normalized.params === "object" &&
198 normalized.params !== null
199 ) {
200 const params = normalized.params as Record<string, unknown>;
201 if (typeof params.clientInfo === "object" && params.clientInfo !== null) {
202 normalized.params = {
203 ...params,
204 clientInfo: {
205 ...(params.clientInfo as Record<string, unknown>),
206 version: "<ignored>",
207 },
208 };
209 }
210 }
211
212 if (
213 normalized.method === "turn/start" &&
214 typeof normalized.params === "object" &&
215 normalized.params !== null
216 ) {
217 const params = { ...(normalized.params as Record<string, unknown>) };
218 if (params.approvalPolicy === "never") {
219 delete params.approvalPolicy;
220 }
221 if (
222 typeof params.sandboxPolicy === "object" &&
223 params.sandboxPolicy !== null &&
224 (params.sandboxPolicy as Record<string, unknown>).type === "dangerFullAccess"
225 ) {
226 delete params.sandboxPolicy;
227 }
228 if (typeof params.collaborationMode === "object" && params.collaborationMode !== null) {
229 const collaborationMode = {
230 ...(params.collaborationMode as Record<string, unknown>),
231 };
232 if (typeof collaborationMode.settings === "object" && collaborationMode.settings !== null) {
233 collaborationMode.settings = {
234 ...(collaborationMode.settings as Record<string, unknown>),
235 developer_instructions: "<ignored>",
236 };
237 }
238 params.collaborationMode = collaborationMode;
239 }
240 normalized.params = params;
241 }
242
243 if (
244 (normalized.method === "thread/start" ||
245 normalized.method === "thread/resume" ||
246 normalized.method === "thread/fork") &&
247 typeof normalized.params === "object" &&
248 normalized.params !== null
249 ) {
250 // Runtime-scoped thread settings are supplied by the host and commonly
251 // contain machine-local cwd and short-lived MCP authorization headers.
252 // They are orthogonal to the recorded provider protocol behavior.
253 const params = { ...(normalized.params as Record<string, unknown>) };
254 delete params.cwd;
255 delete params.model;
256 delete params.config;
257 normalized.params = params;
258 }
259
260 return normalized;
261}
262
263function sameFrame(left: unknown, right: unknown): boolean {
264 return (
265 stableStringify(normalizeReplayFrame(left)) === stableStringify(normalizeReplayFrame(right))
266 );
267}
268
269function normalizeLegacyInboundFrame(value: unknown): unknown {
270 if (Array.isArray(value)) {
271 return value.map(normalizeLegacyInboundFrame);
272 }
273 if (typeof value !== "object" || value === null) {
274 return value;
275 }
276 const record = value as Record<string, unknown>;
277 const normalized = Object.fromEntries(
278 Object.entries(record).map(([key, entry]) => [key, normalizeLegacyInboundFrame(entry)]),
279 );
280 if (
281 typeof normalized.id === "string" &&
282 normalized.sessionId === undefined &&
283 "modelProvider" in normalized &&
284 "status" in normalized
285 ) {
286 normalized.sessionId = normalized.id;
287 }
288 if (
289 (normalized.method === "item/started" || normalized.method === "item/completed") &&
290 typeof normalized.params === "object" &&
291 normalized.params !== null
292 ) {
293 const params = { ...(normalized.params as Record<string, unknown>) };
294 if (normalized.method === "item/started" && params.startedAtMs === undefined) {
295 params.startedAtMs = 0;
296 }
297 if (normalized.method === "item/completed" && params.completedAtMs === undefined) {
298 params.completedAtMs = 0;
299 }
300 normalized.params = params;
301 }
302 if (
303 typeof normalized.method === "string" &&
304 normalized.method.endsWith("/requestApproval") &&
305 typeof normalized.params === "object" &&
306 normalized.params !== null
307 ) {
308 const params = { ...(normalized.params as Record<string, unknown>) };
309 if (params.startedAtMs === undefined) {
310 params.startedAtMs = 0;
311 }
312 normalized.params = params;
313 }
314 return normalized;
315}
316
317function encodeInboundFrame(frame: unknown): Uint8Array {
318 return encoder.encode(`${JSON.stringify(normalizeLegacyInboundFrame(frame))}\n`);
319}
320
321function replayTransportError(
322 error: CodexAppServerReplayError,
323): CodexError.CodexAppServerTransportError {
324 return new CodexError.CodexAppServerTransportError({
325 operation: "read-input-stream",
326 cause: error,
327 });
328}
329
330export function layerReplay(
331 transcript: CodexAppServerReplayTranscript,
332): Layer.Layer<CodexAppServerClient, CodexAppServerReplayError> {
333 return Layer.effect(CodexAppServerClient, makeReplayClient(transcript));
334}
335
336export const makeReplayDriver = Effect.fn("effect-codex-app-server/replay.makeReplayDriver")(
337 function* (transcript: CodexAppServerReplayTranscript) {
338 return {
339 transcript,
340 state: yield* Ref.make<CodexAppServerReplayState>({ cursor: 0, failure: null }),
341 } satisfies CodexAppServerReplayDriver;
342 },
343);
344
345export function layerReplayWithDriver(
346 driver: CodexAppServerReplayDriver,
347): Layer.Layer<CodexAppServerClient, CodexAppServerReplayError> {
348 return Layer.effect(CodexAppServerClient, makeReplayClientWithState(driver));
349}
350
351export const makeReplayClient = Effect.fn("effect-codex-app-server/replay.makeReplayClient")(
352 function* (
353 transcript: CodexAppServerReplayTranscript,
354 options: CodexClient.CodexAppServerClientOptions = {},
355 ) {
356 const driver = yield* makeReplayDriver(transcript);
357 return yield* makeReplayClientWithState(driver, options);
358 },
359);
360
361const makeReplayClientWithState = Effect.fn(
362 "effect-codex-app-server/replay.makeReplayClientWithState",
363)(function* (
364 driver: CodexAppServerReplayDriver,
365 options: CodexClient.CodexAppServerClientOptions = {},
366) {
367 const transcript = driver.transcript;
368 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
369 const state = driver.state;
370 const outboundRemainder = yield* Ref.make("");
371
372 const failReplay = (error: CodexAppServerReplayError) =>
373 Ref.update(state, (current) => ({
374 ...current,
375 failure: current.failure ?? error,
376 })).pipe(Effect.andThen(Queue.end(input)));
377
378 const drainInbound = Effect.fn("effect-codex-app-server/replay.drainInbound")(function* () {
379 while (true) {
380 const current = yield* Ref.get(state);
381 if (current.failure) {
382 return;
383 }
384
385 const entry = transcript.entries[current.cursor];
386 if (!entry) {
387 return;
388 }
389
390 if (entry.type === "emit_inbound") {
391 if (entry.afterMs !== undefined && entry.afterMs > 0) {
392 yield* Effect.sleep(Duration.millis(entry.afterMs));
393 }
394 yield* Queue.offer(input, encodeInboundFrame(entry.frame));
395 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
396 continue;
397 }
398
399 if (entry.type === "runtime_exit") {
400 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
401 if (entry.status === "success") {
402 yield* Queue.end(input);
403 return;
404 }
405 yield* failReplay(
406 new CodexAppServerReplayRuntimeExitError({
407 scenario: transcript.scenario,
408 cursor: current.cursor,
409 status: entry.status,
410 ...(entry.error === undefined ? {} : { error: entry.error }),
411 }),
412 );
413 return;
414 }
415
416 return;
417 }
418 });
419
420 const processOutboundFrame = (actual: unknown) =>
421 drainInbound().pipe(
422 Effect.andThen(
423 Effect.gen(function* () {
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 yield* failReplay(
432 new CodexAppServerReplayExhaustedError({
433 scenario: transcript.scenario,
434 cursor: current.cursor,
435 actual,
436 }),
437 );
438 return;
439 }
440
441 if (entry.type !== "expect_outbound") {
442 yield* failReplay(
443 new CodexAppServerReplayUnexpectedOutboundError({
444 scenario: transcript.scenario,
445 cursor: current.cursor,
446 expectedType: entry.type,
447 actual,
448 }),
449 );
450 return;
451 }
452
453 if (!sameFrame(entry.frame, actual)) {
454 yield* failReplay(
455 new CodexAppServerReplayFrameMismatchError({
456 scenario: transcript.scenario,
457 cursor: current.cursor,
458 ...(entry.label === undefined ? {} : { label: entry.label }),
459 expected: entry.frame,
460 actual,
461 }),
462 );
463 return;
464 }
465
466 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
467 yield* drainInbound();
468 }),
469 ),
470 );
471
472 const processOutboundLine = (line: string) => {
473 const trimmed = line.trim();
474 if (trimmed.length === 0) {
475 return Effect.void;
476 }
477 return Effect.try({
478 try: () => decodeOutboundJsonFrame(trimmed),
479 catch: (cause) =>
480 new CodexAppServerReplayJsonParseError({
481 scenario: transcript.scenario,
482 line: trimmed,
483 cause,
484 }),
485 }).pipe(
486 Effect.matchEffect({
487 onFailure: failReplay,
488 onSuccess: processOutboundFrame,
489 }),
490 );
491 };
492
493 const processOutboundChunk = (chunk: string | Uint8Array) =>
494 Ref.modify(outboundRemainder, (current) => {
495 const text = typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
496 const combined = current + text;
497 const lines = combined.split("\n");
498 const nextRemainder = lines.pop() ?? "";
499 return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
500 }).pipe(
501 Effect.flatMap((lines) => Effect.forEach(lines, processOutboundLine, { discard: true })),
502 );
503
504 const terminationError: Effect.Effect<CodexError.CodexAppServerError> = Ref.get(state).pipe(
505 Effect.map((current) =>
506 current.failure
507 ? replayTransportError(current.failure)
508 : new CodexError.CodexAppServerProcessExitedError({ code: 0 }),
509 ),
510 );
511
512 const stdio = Stdio.make({
513 args: Effect.succeed([]),
514 stdin: Stream.fromQueue(input),
515 stdout: () => Sink.forEach(processOutboundChunk),
516 stderr: () => Sink.drain,
517 });
518
519 yield* drainInbound();
520
521 return yield* CodexClient.make(stdio, options, terminationError);
522});