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

replay.ts

530 lines17.1 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 { 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 }
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 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 }
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;
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>;
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);
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)}`;
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 if (
246 (normalized.method === "thread/start" ||
247 normalized.method === "thread/resume" ||
248 normalized.method === "thread/fork") &&
249 typeof normalized.params === "object" &&
250 normalized.params !== null
251 ) {
252 // Runtime-scoped thread settings are supplied by the host and commonly
253 // contain machine-local cwd and short-lived MCP authorization headers.
254 // They are orthogonal to the recorded provider protocol behavior.
255 const params = { ...(normalized.params as Record<string, unknown>) };
256 delete params.cwd;
257 delete params.model;
258 delete params.config;
259 normalized.params = params;
260 }
261​
262 return normalized;
264​
265function sameFrame(left: unknown, right: unknown): boolean {
266 return (
267 stableStringify(normalizeReplayFrame(left)) === stableStringify(normalizeReplayFrame(right))
268 );
270​
271function normalizeLegacyInboundFrame(value: unknown): unknown {
272 if (Array.isArray(value)) {
273 return value.map(normalizeLegacyInboundFrame);
274 }
275 if (typeof value !== "object" || value === null) {
276 return value;
277 }
278 const record = value as Record<string, unknown>;
279 const normalized = Object.fromEntries(
280 Object.entries(record).map(([key, entry]) => [key, normalizeLegacyInboundFrame(entry)]),
281 );
282 if (
283 typeof normalized.id === "string" &&
284 normalized.sessionId === undefined &&
285 "modelProvider" in normalized &&
286 "status" in normalized
287 ) {
288 normalized.sessionId = normalized.id;
289 }
290 if (
291 (normalized.method === "item/started" || normalized.method === "item/completed") &&
292 typeof normalized.params === "object" &&
293 normalized.params !== null
294 ) {
295 const params = { ...(normalized.params as Record<string, unknown>) };
296 if (normalized.method === "item/started" && params.startedAtMs === undefined) {
297 params.startedAtMs = 0;
298 }
299 if (normalized.method === "item/completed" && params.completedAtMs === undefined) {
300 params.completedAtMs = 0;
301 }
302 normalized.params = params;
303 }
304 if (
305 typeof normalized.method === "string" &&
306 normalized.method.endsWith("/requestApproval") &&
307 typeof normalized.params === "object" &&
308 normalized.params !== null
309 ) {
310 const params = { ...(normalized.params as Record<string, unknown>) };
311 if (params.startedAtMs === undefined) {
312 params.startedAtMs = 0;
313 }
314 normalized.params = params;
315 }
316 return normalized;
318​
319function encodeInboundFrame(frame: unknown): Uint8Array {
320 return encoder.encode(`${JSON.stringify(normalizeLegacyInboundFrame(frame))}\n`);
322​
323function replayTransportError(
324 error: CodexAppServerReplayError,
325): CodexError.CodexAppServerTransportError {
326 return new CodexError.CodexAppServerTransportError({
327 operation: "read-input-stream",
328 cause: error,
329 });
331​
332export function layerReplay(
333 transcript: CodexAppServerReplayTranscript,
334): Layer.Layer<CodexAppServerClient, CodexAppServerReplayError> {
335 return Layer.effect(CodexAppServerClient, makeReplayClient(transcript));
337​
338export const makeReplayDriver = Effect.fn("effect-codex-app-server/replay.makeReplayDriver")(
339 function* (
340 transcript: CodexAppServerReplayTranscript,
341 options: Pick<CodexAppServerReplayDriver, "beforeEmitInbound"> = {},
342 ) {
343 return {
344 transcript,
345 state: yield* Ref.make<CodexAppServerReplayState>({ cursor: 0, failure: null }),
346 ...options,
347 } satisfies CodexAppServerReplayDriver;
348 },
349);
350​
351export function layerReplayWithDriver(
352 driver: CodexAppServerReplayDriver,
353): Layer.Layer<CodexAppServerClient, CodexAppServerReplayError> {
354 return Layer.effect(CodexAppServerClient, makeReplayClientWithState(driver));
356​
357const makeReplayClient = Effect.fn("effect-codex-app-server/replay.makeReplayClient")(function* (
358 transcript: CodexAppServerReplayTranscript,
359 options: CodexClient.CodexAppServerClientOptions = {},
360) {
361 const driver = yield* makeReplayDriver(transcript);
362 return yield* makeReplayClientWithState(driver, options);
363});
364​
365const makeReplayClientWithState = Effect.fn(
366 "effect-codex-app-server/replay.makeReplayClientWithState",
367)(function* (
368 driver: CodexAppServerReplayDriver,
369 options: CodexClient.CodexAppServerClientOptions = {},
370) {
371 const transcript = driver.transcript;
372 const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();
373 const state = driver.state;
374 const outboundRemainder = yield* Ref.make("");
375 const decoder = new TextDecoder();
376​
377 const failReplay = (error: CodexAppServerReplayError) =>
378 Ref.update(state, (current) => ({
379 ...current,
380 failure: current.failure ?? error,
381 })).pipe(Effect.andThen(Queue.end(input)));
382​
383 const drainInbound = Effect.fn("effect-codex-app-server/replay.drainInbound")(function* () {
384 while (true) {
385 const current = yield* Ref.get(state);
386 if (current.failure) {
387 return;
388 }
389​
390 const entry = transcript.entries[current.cursor];
391 if (!entry) {
392 return;
393 }
394​
395 if (entry.type === "emit_inbound") {
396 if (driver.beforeEmitInbound !== undefined) {
397 yield* driver.beforeEmitInbound(entry);
398 }
399 if (entry.afterMs !== undefined && entry.afterMs > 0) {
400 yield* Effect.sleep(Duration.millis(entry.afterMs));
401 }
402 yield* Queue.offer(input, encodeInboundFrame(entry.frame));
403 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
404 continue;
405 }
406​
407 if (entry.type === "runtime_exit") {
408 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
409 if (entry.status === "success") {
410 yield* Queue.end(input);
411 return;
412 }
413 yield* failReplay(
414 new CodexAppServerReplayRuntimeExitError({
415 scenario: transcript.scenario,
416 cursor: current.cursor,
417 status: entry.status,
418 ...(entry.error === undefined ? {} : { error: entry.error }),
419 }),
420 );
421 return;
422 }
423​
424 return;
425 }
426 });
427​
428 const processOutboundFrame = (actual: unknown) =>
429 drainInbound().pipe(
430 Effect.andThen(
431 Effect.gen(function* () {
432 const current = yield* Ref.get(state);
433 if (current.failure) {
434 return;
435 }
436​
437 const entry = transcript.entries[current.cursor];
438 if (!entry) {
439 yield* failReplay(
440 new CodexAppServerReplayExhaustedError({
441 scenario: transcript.scenario,
442 cursor: current.cursor,
443 actual,
444 }),
445 );
446 return;
447 }
448​
449 if (entry.type !== "expect_outbound") {
450 yield* failReplay(
451 new CodexAppServerReplayUnexpectedOutboundError({
452 scenario: transcript.scenario,
453 cursor: current.cursor,
454 expectedType: entry.type,
455 actual,
456 }),
457 );
458 return;
459 }
460​
461 if (!sameFrame(entry.frame, actual)) {
462 yield* failReplay(
463 new CodexAppServerReplayFrameMismatchError({
464 scenario: transcript.scenario,
465 cursor: current.cursor,
466 ...(entry.label === undefined ? {} : { label: entry.label }),
467 expected: entry.frame,
468 actual,
469 }),
470 );
471 return;
472 }
473​
474 yield* Ref.update(state, (latest) => ({ ...latest, cursor: latest.cursor + 1 }));
475 yield* drainInbound();
476 }),
477 ),
478 );
479​
480 const processOutboundLine = (line: string) => {
481 const trimmed = line.trim();
482 if (trimmed.length === 0) {
483 return Effect.void;
484 }
485 return Effect.try({
486 try: () => decodeOutboundJsonFrame(trimmed),
487 catch: (cause) =>
488 new CodexAppServerReplayJsonParseError({
489 scenario: transcript.scenario,
490 line: trimmed,
491 cause,
492 }),
493 }).pipe(
494 Effect.matchEffect({
495 onFailure: failReplay,
496 onSuccess: processOutboundFrame,
497 }),
498 );
499 };
500​
501 const processOutboundChunk = (chunk: string | Uint8Array) =>
502 Ref.modify(outboundRemainder, (current) => {
503 const text = typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
504 const combined = current + text;
505 const lines = combined.split("\n");
506 const nextRemainder = lines.pop() ?? "";
507 return [lines.map((line) => line.replace(/\r$/, "")), nextRemainder] as const;
508 }).pipe(
509 Effect.flatMap((lines) => Effect.forEach(lines, processOutboundLine, { discard: true })),
510 );
511​
512 const terminationError: Effect.Effect<CodexError.CodexAppServerError> = Ref.get(state).pipe(
513 Effect.map((current) =>
514 current.failure
515 ? replayTransportError(current.failure)
516 : new CodexError.CodexAppServerProcessExitedError({ code: 0 }),
517 ),
518 );
519​
520 const stdio = Stdio.make({
521 args: Effect.succeed([]),
522 stdin: Stream.fromQueue(input),
523 stdout: () => Sink.forEach(processOutboundChunk),
524 stderr: () => Sink.drain,
525 });
526​
527 yield* drainInbound();
528​
529 return yield* CodexClient.make(stdio, options, terminationError);
530});