Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

replay.ts

562 lines18.5 KB

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