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

replay.ts

553 lines18.1 KB

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