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

record-codex-app-server-replay-fixture.ts

1,310 lines40.8 KB

1import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
4import { resolveSpawnCommand } from "@t3tools/shared/shell";
5import * as Console from "effect/Console";
6import * as Deferred from "effect/Deferred";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as Effect from "effect/Effect";
12import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13​
14import * as CodexClient from "effect-codex-app-server/client";
15import type * as CodexSchema from "effect-codex-app-server/schema";
16​
17import {
18 MESSAGE_STEERING_INITIAL_PROMPT,
19 MESSAGE_STEERING_STEER_PROMPT,
20 MULTI_TURN_FIRST_PROMPT,
21 MULTI_TURN_SECOND_PROMPT,
22 PLAN_QUESTIONS_PROMPT,
23 PROPOSED_PLAN_PROMPT,
24 PROVIDER_THREAD_RESUME_FIRST_PROMPT,
25 PROVIDER_THREAD_RESUME_SECOND_PROMPT,
26 SIMPLE_PROMPT,
27 SUBAGENT_CONTINUE_PARENT_PROMPT,
28 SUBAGENT_CONTINUE_PROMPT,
29 SUBAGENT_PROMPT,
30 THREAD_ROLLBACK_AFTER_PROMPT,
31 THREAD_ROLLBACK_FIRST_PROMPT,
32 THREAD_ROLLBACK_SECOND_PROMPT,
33 THREAD_FORK_NATIVE_CONTINUE_FIRST_PROMPT,
34 THREAD_FORK_NATIVE_CONTINUE_SECOND_PROMPT,
35 THREAD_FORK_NATIVE_CONTINUE_SOURCE_PROMPT,
36 THREAD_FORK_NATIVE_SIBLINGS_FIRST_PROMPT,
37 THREAD_FORK_NATIVE_SIBLINGS_SECOND_PROMPT,
38 THREAD_FORK_NATIVE_SIBLINGS_SOURCE_PROMPT,
39 THREAD_MERGE_BACK_FORK_PROMPT,
40 THREAD_MERGE_BACK_HANDOFF_PROMPT,
41 THREAD_MERGE_BACK_RECALL_PROMPT,
42 THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT,
43 THREAD_MERGE_BACK_SIBLINGS_FIRST_HANDOFF_PROMPT,
44 THREAD_MERGE_BACK_SIBLINGS_RECALL_PROMPT,
45 THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT,
46 THREAD_MERGE_BACK_SIBLINGS_SECOND_HANDOFF_PROMPT,
47 THREAD_MERGE_BACK_SIBLINGS_SOURCE_PROMPT,
48 THREAD_MERGE_BACK_SOURCE_PROMPT,
49 TODO_LIST_PROMPT,
50 TOOL_CALL_WRITE_PROMPT,
51 TURN_INTERRUPT_MID_TOOL_PROMPT,
52 TURN_INTERRUPT_PROMPT,
53} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
54import { codexReplayRecordingOutputRecords } from "./codexReplayRecordingRecords.ts";
55import { makeReplayRecorderDeferredRegistry } from "./replayRecorderDeferredRegistry.ts";
56​
57const CODEX_REPLAY_PLAN_MODE_DEVELOPER_INSTRUCTIONS =
58 process.env.T3_CODEX_REPLAY_PLAN_DEVELOPER_INSTRUCTIONS ??
59 "You are in Plan mode. Prefer request_user_input for clarifying questions. When presenting a complete plan, wrap it in <proposed_plan> and </proposed_plan>.";
60const CODEX_CLIENT_INFO = {
61 name: "t3code_desktop",
62 title: "T3 Code Desktop",
63 version: "0.1.0",
64} as const;
65const CODEX_CLIENT_CAPABILITIES = {
66 experimentalApi: true,
67} as const;
68​
69const SCENARIO_NAMES = [
70 "simple",
71 "tool_call_read_only_on_request",
72 "tool_call_workspace_never",
73 "tool_call_restricted_granular",
74 "subagent",
75 "subagent_continue",
76 "multi_turn",
77 "provider_thread_resume",
78 "todo_list",
79 "plan_questions",
80 "proposed_plan",
81 "message_steering",
82 "turn_interrupt",
83 "turn_interrupt_mid_tool",
84 "thread_rollback",
85 "thread_fork_native_continue",
86 "thread_fork_native_siblings",
87 "thread_merge_back_continue",
88 "thread_merge_back_siblings",
89] as const;
90​
91type ScenarioName = (typeof SCENARIO_NAMES)[number];
92type TurnStartParams = CodexSchema.ClientRequestParamsByMethod["turn/start"] & {
93 readonly collaborationMode?: CodexSchema.V2TurnStartParams__CollaborationMode;
94};
95type TurnStartInput = TurnStartParams["input"];
96type TurnStartResponse = CodexSchema.ClientRequestResponsesByMethod["turn/start"];
97type SandboxPolicy = NonNullable<TurnStartParams["sandboxPolicy"]>;
98type ApprovalPolicy = NonNullable<TurnStartParams["approvalPolicy"]>;
99​
100interface ReplayRun {
101 readonly name: string;
102 readonly prompt?: string;
103 readonly description: string;
104 readonly steps: ReadonlyArray<ReplayStep>;
105 readonly turnDefaults?: Omit<TurnStartParams, "input" | "threadId">;
107​
108type ReplayStep =
109 | {
110 readonly type: "turn";
111 readonly label: string;
112 readonly prompt: string;
113 readonly thread?: string;
114 readonly turnOverrides?: Omit<TurnStartParams, "input" | "threadId">;
115 }
116 | {
117 readonly type: "steeredTurn";
118 readonly label: string;
119 readonly prompt: string;
120 readonly steer: string;
121 readonly turnOverrides?: Omit<TurnStartParams, "input" | "threadId">;
122 }
123 | {
124 readonly type: "interruptedTurn";
125 readonly label: string;
126 readonly prompt: string;
127 readonly interruptAfterMs?: number;
128 readonly interruptAfterCommandExecutionStarted?: boolean;
129 readonly turnOverrides?: Omit<TurnStartParams, "input" | "threadId">;
130 }
131 | {
132 readonly type: "rollback";
133 readonly label: string;
134 readonly numTurns: number;
135 }
136 | {
137 readonly type: "fork";
138 readonly label: string;
139 readonly from?: string;
140 readonly as?: string;
141 };
142type TurnReplayStep = Exclude<
143 ReplayStep,
144 { readonly type: "rollback" } | { readonly type: "fork" }
145>;
146​
147interface ReplayScenario {
148 readonly name: ScenarioName;
149 readonly fileName: `${ScenarioName}.ndjson`;
150 readonly description: string;
151 readonly runs: ReadonlyArray<ReplayRun>;
153​
154interface Recorder {
155 readonly path: string;
156 readonly setVersion: (version: string) => Effect.Effect<void>;
157 readonly writeRecord: (
158 record: Record<string, unknown>,
159 ) => Effect.Effect<void, PlatformError.PlatformError>;
160 readonly flush: () => Effect.Effect<void, PlatformError.PlatformError>;
162​
163function readArgValue(name: string): string | undefined {
164 const args = process.argv.slice(2);
165 const index = args.indexOf(name);
166 return index >= 0 ? args[index + 1] : undefined;
168​
169function readArgValues(name: string): ReadonlyArray<string> {
170 const args = process.argv.slice(2);
171 return args.flatMap((arg, index) => (arg === name && args[index + 1] ? [args[index + 1]!] : []));
173​
174function defaultTranscriptUrl(scenario: ReplayScenario): URL {
175 return new URL(
176 `../src/orchestration-v2/testkit/fixtures/${scenario.name}/codex_transcript.ndjson`,
177 import.meta.url,
178 );
180​
181function isRecord(value: unknown): value is Record<string, unknown> {
182 return typeof value === "object" && value !== null;
184​
185function parseScenarios(): ReadonlyArray<ScenarioName> {
186 const rawValues = [
187 ...readArgValues("--scenario"),
188 ...(process.env.T3_CODEX_REPLAY_SCENARIOS ? [process.env.T3_CODEX_REPLAY_SCENARIOS] : []),
189 ];
190 const requested = rawValues.length > 0 ? rawValues : ["simple"];
191 const names = requested.flatMap((value) =>
192 value
193 .split(",")
194 .map((part) => part.trim())
195 .filter((part) => part.length > 0),
196 );
197​
198 if (names.includes("all")) {
199 return SCENARIO_NAMES;
200 }
201​
202 const expandedNames = names.flatMap((name) =>
203 name === "tool_call"
204 ? [
205 "tool_call_read_only_on_request",
206 "tool_call_workspace_never",
207 "tool_call_restricted_granular",
208 ]
209 : [name],
210 );
211​
212 const invalid = expandedNames.filter(
213 (name): name is string => !SCENARIO_NAMES.includes(name as ScenarioName),
214 );
215 if (invalid.length > 0) {
216 throw new Error(`Unknown scenario(s): ${invalid.join(", ")}`);
217 }
218​
219 return [...new Set(expandedNames)] as ReadonlyArray<ScenarioName>;
221​
222function classifyJsonRpcPayload(payload: unknown): string {
223 if (!isRecord(payload)) {
224 return "unknown";
225 }
226 if (typeof payload.method === "string" && "id" in payload) {
227 return "request";
228 }
229 if (typeof payload.method === "string") {
230 return "notification";
231 }
232 if ("id" in payload && "error" in payload) {
233 return "error_response";
234 }
235 if ("id" in payload && "result" in payload) {
236 return "response";
237 }
238 return "unknown";
240​
241function protocolMethod(payload: unknown): string | undefined {
242 return isRecord(payload) && typeof payload.method === "string" ? payload.method : undefined;
244​
245function protocolId(payload: unknown): string | number | undefined {
246 if (!isRecord(payload)) {
247 return undefined;
248 }
249 return typeof payload.id === "string" || typeof payload.id === "number" ? payload.id : undefined;
251​
252function protocolResult(payload: unknown): unknown {
253 return isRecord(payload) && "result" in payload ? payload.result : undefined;
255​
256function inferCodexVersion(payload: unknown): string | undefined {
257 const result = protocolResult(payload);
258 if (!isRecord(result)) {
259 return undefined;
260 }
261​
262 if (typeof result.userAgent === "string") {
263 const match = result.userAgent.match(/\/([0-9][^\s)]*)/u);
264 if (match?.[1]) {
265 return match[1];
266 }
267 }
268​
269 const thread = result.thread;
270 return isRecord(thread) && typeof thread.cliVersion === "string" ? thread.cliVersion : undefined;
272​
273function turnInput(prompt: string): TurnStartInput {
274 return [{ type: "text", text: prompt }];
276​
277function getTurnId(response: TurnStartResponse): string {
278 return response.turn.id;
280​
281function readOnlyFullAccessSandbox(): SandboxPolicy {
282 return {
283 networkAccess: false,
284 type: "readOnly",
285 };
287​
288function readOnlyRestrictedSandbox(): SandboxPolicy {
289 return {
290 networkAccess: false,
291 type: "readOnly",
292 };
294​
295function workspaceWriteSandbox(): SandboxPolicy {
296 return {
297 networkAccess: false,
298 type: "workspaceWrite",
299 writableRoots: [],
300 };
302​
303function granularApprovalPolicy(): ApprovalPolicy {
304 return {
305 granular: {
306 mcp_elicitations: true,
307 request_permissions: true,
308 rules: true,
309 sandbox_approval: true,
310 skill_approval: true,
311 },
312 };
314​
315function collaborationMode(
316 mode: Extract<CodexSchema.V2TurnStartParams__ModeKind, "plan">,
317): CodexSchema.V2TurnStartParams__CollaborationMode {
318 return {
319 mode,
320 settings: {
321 developer_instructions: CODEX_REPLAY_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
322 model: "gpt-5.4",
323 reasoning_effort: "medium",
324 },
325 };
327​
328function scenarios(): ReadonlyArray<ReplayScenario> {
329 return [
330 {
331 name: "simple",
332 fileName: "simple.ndjson",
333 description: "One thread and one turn with a deterministic text-only response.",
334 runs: [
335 {
336 name: "simple",
337 description: "Single text-only turn.",
338 prompt: SIMPLE_PROMPT,
339 steps: [{ type: "turn", label: "simple", prompt: SIMPLE_PROMPT }],
340 },
341 ],
342 },
343 {
344 name: "tool_call_read_only_on_request",
345 fileName: "tool_call_read_only_on_request.ndjson",
346 description:
347 "Write a small fixture file with read-only full filesystem visibility and on-request approvals.",
348 runs: [
349 {
350 name: "read-only-on-request",
351 description:
352 "Write action under read-only full filesystem visibility with on-request approvals.",
353 prompt: TOOL_CALL_WRITE_PROMPT,
354 turnDefaults: {
355 approvalPolicy: "on-request",
356 sandboxPolicy: readOnlyFullAccessSandbox(),
357 },
358 steps: [{ type: "turn", label: "write-fixture-file", prompt: TOOL_CALL_WRITE_PROMPT }],
359 },
360 ],
361 },
362 {
363 name: "tool_call_workspace_never",
364 fileName: "tool_call_workspace_never.ndjson",
365 description:
366 "Write a small fixture file with workspace-write sandbox policy and never approvals.",
367 runs: [
368 {
369 name: "workspace-never",
370 description:
371 "Write action under workspace-write policy with never approvals for baseline no-prompt behavior.",
372 prompt: TOOL_CALL_WRITE_PROMPT,
373 turnDefaults: {
374 approvalPolicy: "never",
375 sandboxPolicy: workspaceWriteSandbox(),
376 },
377 steps: [{ type: "turn", label: "write-fixture-file", prompt: TOOL_CALL_WRITE_PROMPT }],
378 },
379 ],
380 },
381 {
382 name: "tool_call_restricted_granular",
383 fileName: "tool_call_restricted_granular.ndjson",
384 description:
385 "Write a small fixture file with restricted read access and granular approval flags enabled.",
386 runs: [
387 {
388 name: "restricted-granular",
389 description:
390 "Write action under restricted read access with granular approval flags enabled, intended to capture permission request flows when Codex escalates.",
391 prompt: TOOL_CALL_WRITE_PROMPT,
392 turnDefaults: {
393 approvalPolicy: granularApprovalPolicy(),
394 sandboxPolicy: readOnlyRestrictedSandbox(),
395 },
396 steps: [
397 {
398 type: "turn",
399 label: "write-fixture-file",
400 prompt: TOOL_CALL_WRITE_PROMPT,
401 },
402 ],
403 },
404 ],
405 },
406 {
407 name: "subagent",
408 fileName: "subagent.ndjson",
409 description: "One root turn that asks Codex to spawn two collab agents.",
410 runs: [
411 {
412 name: "two-subagents",
413 description: "Root turn asks for two subagents reading different files.",
414 prompt: SUBAGENT_PROMPT,
415 turnDefaults: {
416 approvalPolicy: "on-request",
417 sandboxPolicy: readOnlyFullAccessSandbox(),
418 },
419 steps: [{ type: "turn", label: "spawn-two-subagents", prompt: SUBAGENT_PROMPT }],
420 },
421 ],
422 },
423 {
424 name: "subagent_continue",
425 fileName: "subagent_continue.ndjson",
426 description:
427 "A root turn spawns one native Codex subagent, then a later root turn resumes and messages the same child thread.",
428 runs: [
429 {
430 name: "continued-subagent",
431 description:
432 "The second root turn asks Codex to continue the subagent created by the first root turn.",
433 steps: [
434 {
435 type: "turn",
436 label: "spawn-subagent",
437 prompt: SUBAGENT_CONTINUE_PROMPT,
438 },
439 {
440 type: "turn",
441 label: "continue-subagent",
442 prompt: SUBAGENT_CONTINUE_PARENT_PROMPT,
443 },
444 ],
445 },
446 ],
447 },
448 {
449 name: "multi_turn",
450 fileName: "multi_turn.ndjson",
451 description: "One thread with two sequential user turns.",
452 runs: [
453 {
454 name: "two-turns-same-thread",
455 description: "Second turn starts after the first root turn completes.",
456 steps: [
457 {
458 type: "turn",
459 label: "first",
460 prompt: MULTI_TURN_FIRST_PROMPT,
461 },
462 {
463 type: "turn",
464 label: "second",
465 prompt: MULTI_TURN_SECOND_PROMPT,
466 },
467 ],
468 },
469 ],
470 },
471 {
472 name: "provider_thread_resume",
473 fileName: "provider_thread_resume.ndjson",
474 description:
475 "One provider-native thread is started, completed, then resumed by thread id in a fresh app-server session.",
476 runs: [
477 {
478 name: "resume-provider-thread",
479 description:
480 "First turn completes, the app-server runtime is restarted, thread/resume loads the existing provider thread, then a second turn completes.",
481 steps: [
482 {
483 type: "turn",
484 label: "first-before-resume",
485 prompt: PROVIDER_THREAD_RESUME_FIRST_PROMPT,
486 },
487 {
488 type: "turn",
489 label: "second-after-resume",
490 prompt: PROVIDER_THREAD_RESUME_SECOND_PROMPT,
491 },
492 ],
493 },
494 ],
495 },
496 {
497 name: "todo_list",
498 fileName: "todo_list.ndjson",
499 description: "One turn that asks Codex to emit progress through update_plan.",
500 runs: [
501 {
502 name: "todo-list",
503 description: "Default-mode turn that should surface turn/plan/updated notifications.",
504 prompt: TODO_LIST_PROMPT,
505 turnDefaults: {
506 approvalPolicy: "never",
507 sandboxPolicy: readOnlyFullAccessSandbox(),
508 },
509 steps: [{ type: "turn", label: "todo-list", prompt: TODO_LIST_PROMPT }],
510 },
511 ],
512 },
513 {
514 name: "plan_questions",
515 fileName: "plan_questions.ndjson",
516 description: "One plan-mode turn that asks a structured clarifying question.",
517 runs: [
518 {
519 name: "plan-questions",
520 description: "Plan-mode turn intended to surface item/tool/requestUserInput.",
521 prompt: PLAN_QUESTIONS_PROMPT,
522 turnDefaults: {
523 approvalPolicy: "never",
524 collaborationMode: collaborationMode("plan"),
525 sandboxPolicy: readOnlyFullAccessSandbox(),
526 },
527 steps: [{ type: "turn", label: "plan-questions", prompt: PLAN_QUESTIONS_PROMPT }],
528 },
529 ],
530 },
531 {
532 name: "proposed_plan",
533 fileName: "proposed_plan.ndjson",
534 description: "One plan-mode turn that emits a proposed plan document.",
535 runs: [
536 {
537 name: "proposed-plan",
538 description:
539 "Plan-mode turn intended to surface item/plan/delta and completed plan item.",
540 prompt: PROPOSED_PLAN_PROMPT,
541 turnDefaults: {
542 approvalPolicy: "never",
543 collaborationMode: collaborationMode("plan"),
544 sandboxPolicy: readOnlyFullAccessSandbox(),
545 },
546 steps: [{ type: "turn", label: "proposed-plan", prompt: PROPOSED_PLAN_PROMPT }],
547 },
548 ],
549 },
550 {
551 name: "message_steering",
552 fileName: "message_steering.ndjson",
553 description: "One active turn receives an immediate turn/steer request.",
554 runs: [
555 {
556 name: "immediate-steer",
557 description: "Start a turn, then immediately steer the active root turn.",
558 steps: [
559 {
560 type: "steeredTurn",
561 label: "steered",
562 prompt: MESSAGE_STEERING_INITIAL_PROMPT,
563 steer: MESSAGE_STEERING_STEER_PROMPT,
564 },
565 ],
566 },
567 ],
568 },
569 {
570 name: "turn_interrupt",
571 fileName: "turn_interrupt.ndjson",
572 description: "One active turn is interrupted before it finishes naturally.",
573 runs: [
574 {
575 name: "interrupt-active-turn",
576 description: "Start a long-running turn, then send turn/interrupt.",
577 prompt: TURN_INTERRUPT_PROMPT,
578 turnDefaults: {
579 approvalPolicy: "never",
580 sandboxPolicy: workspaceWriteSandbox(),
581 },
582 steps: [
583 {
584 type: "interruptedTurn",
585 label: "interrupt-active-turn",
586 prompt: TURN_INTERRUPT_PROMPT,
587 interruptAfterMs: 1_500,
588 },
589 ],
590 },
591 ],
592 },
593 {
594 name: "turn_interrupt_mid_tool",
595 fileName: "turn_interrupt_mid_tool.ndjson",
596 description:
597 "One active turn is interrupted after Codex has already executed a local command.",
598 runs: [
599 {
600 name: "interrupt-after-command-execution",
601 description: "Start a turn, wait for command execution, then send turn/interrupt.",
602 prompt: TURN_INTERRUPT_MID_TOOL_PROMPT,
603 turnDefaults: {
604 approvalPolicy: "never",
605 sandboxPolicy: workspaceWriteSandbox(),
606 },
607 steps: [
608 {
609 type: "interruptedTurn",
610 label: "interrupt-after-command-execution",
611 prompt: TURN_INTERRUPT_MID_TOOL_PROMPT,
612 interruptAfterCommandExecutionStarted: true,
613 },
614 ],
615 },
616 ],
617 },
618 {
619 name: "thread_rollback",
620 fileName: "thread_rollback.ndjson",
621 description:
622 "One thread completes two turns, rolls back the most recent turn, then starts another turn.",
623 runs: [
624 {
625 name: "rollback-one-turn",
626 description:
627 "Two completed turns, thread/rollback numTurns=1, then a post-rollback turn.",
628 steps: [
629 {
630 type: "turn",
631 label: "first-before-rollback",
632 prompt: THREAD_ROLLBACK_FIRST_PROMPT,
633 },
634 {
635 type: "turn",
636 label: "second-before-rollback",
637 prompt: THREAD_ROLLBACK_SECOND_PROMPT,
638 },
639 {
640 type: "rollback",
641 label: "rollback-latest-turn",
642 numTurns: 1,
643 },
644 {
645 type: "turn",
646 label: "post-rollback",
647 prompt: THREAD_ROLLBACK_AFTER_PROMPT,
648 },
649 ],
650 },
651 ],
652 },
653 {
654 name: "thread_fork_native_continue",
655 fileName: "thread_fork_native_continue.ndjson",
656 description:
657 "One source marker turn, a native thread fork, a fork-local marker turn, and a recall turn that requires both contexts.",
658 runs: [
659 {
660 name: "continue-native-fork",
661 description:
662 "Proves the native fork inherits source context and retains its own first turn into a second fork-local turn.",
663 steps: [
664 {
665 type: "turn",
666 label: "source",
667 prompt: THREAD_FORK_NATIVE_CONTINUE_SOURCE_PROMPT,
668 },
669 {
670 type: "fork",
671 label: "fork-source",
672 },
673 {
674 type: "turn",
675 label: "fork-first-delta",
676 prompt: THREAD_FORK_NATIVE_CONTINUE_FIRST_PROMPT,
677 },
678 {
679 type: "turn",
680 label: "fork-second-delta",
681 prompt: THREAD_FORK_NATIVE_CONTINUE_SECOND_PROMPT,
682 },
683 ],
684 },
685 ],
686 },
687 {
688 name: "thread_fork_native_siblings",
689 fileName: "thread_fork_native_siblings.ndjson",
690 description:
691 "One source marker turn and two independent native forks that each recall the source plus only their own fork marker.",
692 runs: [
693 {
694 name: "native-sibling-forks",
695 description:
696 "Creates two native forks from the same source provider thread and proves their contexts remain isolated.",
697 steps: [
698 {
699 type: "turn",
700 label: "source",
701 prompt: THREAD_FORK_NATIVE_SIBLINGS_SOURCE_PROMPT,
702 thread: "source",
703 },
704 {
705 type: "fork",
706 label: "fork-first",
707 from: "source",
708 as: "first",
709 },
710 {
711 type: "turn",
712 label: "first-recall",
713 prompt: THREAD_FORK_NATIVE_SIBLINGS_FIRST_PROMPT,
714 thread: "first",
715 },
716 {
717 type: "fork",
718 label: "fork-second",
719 from: "source",
720 as: "second",
721 },
722 {
723 type: "turn",
724 label: "second-recall",
725 prompt: THREAD_FORK_NATIVE_SIBLINGS_SECOND_PROMPT,
726 thread: "second",
727 },
728 ],
729 },
730 ],
731 },
732 {
733 name: "thread_merge_back_continue",
734 fileName: "thread_merge_back_continue.ndjson",
735 description:
736 "A source thread consumes one fork-delta handoff and later recalls source and transferred context.",
737 runs: [
738 {
739 name: "merge-native-fork",
740 description:
741 "Proves a merge-back handoff becomes durable context on the original provider thread.",
742 steps: [
743 {
744 type: "turn",
745 label: "source",
746 prompt: THREAD_MERGE_BACK_SOURCE_PROMPT,
747 thread: "source",
748 },
749 {
750 type: "fork",
751 label: "fork",
752 from: "source",
753 as: "fork",
754 },
755 {
756 type: "turn",
757 label: "fork-delta",
758 prompt: THREAD_MERGE_BACK_FORK_PROMPT,
759 thread: "fork",
760 },
761 {
762 type: "turn",
763 label: "merge-back",
764 prompt: THREAD_MERGE_BACK_HANDOFF_PROMPT,
765 thread: "source",
766 },
767 {
768 type: "turn",
769 label: "source-recall",
770 prompt: THREAD_MERGE_BACK_RECALL_PROMPT,
771 thread: "source",
772 },
773 ],
774 },
775 ],
776 },
777 {
778 name: "thread_merge_back_siblings",
779 fileName: "thread_merge_back_siblings.ndjson",
780 description:
781 "Two sibling fork deltas are merged sequentially into one source provider thread and recalled together.",
782 runs: [
783 {
784 name: "merge-native-sibling-forks",
785 description:
786 "Proves repeated merge-back handoffs accumulate on the source while native sibling forks remain independent.",
787 steps: [
788 {
789 type: "turn",
790 label: "source",
791 prompt: THREAD_MERGE_BACK_SIBLINGS_SOURCE_PROMPT,
792 thread: "source",
793 },
794 {
795 type: "fork",
796 label: "fork-first",
797 from: "source",
798 as: "first",
799 },
800 {
801 type: "turn",
802 label: "first-fork-delta",
803 prompt: THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT,
804 thread: "first",
805 },
806 {
807 type: "fork",
808 label: "fork-second",
809 from: "source",
810 as: "second",
811 },
812 {
813 type: "turn",
814 label: "second-fork-delta",
815 prompt: THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT,
816 thread: "second",
817 },
818 {
819 type: "turn",
820 label: "merge-first",
821 prompt: THREAD_MERGE_BACK_SIBLINGS_FIRST_HANDOFF_PROMPT,
822 thread: "source",
823 },
824 {
825 type: "turn",
826 label: "merge-second",
827 prompt: THREAD_MERGE_BACK_SIBLINGS_SECOND_HANDOFF_PROMPT,
828 thread: "source",
829 },
830 {
831 type: "turn",
832 label: "source-recall",
833 prompt: THREAD_MERGE_BACK_SIBLINGS_RECALL_PROMPT,
834 thread: "source",
835 },
836 ],
837 },
838 ],
839 },
840 ];
842​
843function makeRecorder({
844 outPath,
845 scenario,
846}: {
847 readonly outPath: string;
848 readonly scenario: ReplayScenario;
849}): Effect.Effect<Recorder, PlatformError.PlatformError, FileSystem.FileSystem> {
850 return Effect.gen(function* () {
851 const fs = yield* FileSystem.FileSystem;
852 let version = "unknown";
853 const records: Array<Record<string, unknown>> = [];
854 const setVersion = (nextVersion: string) =>
855 Effect.sync(() => {
856 version = nextVersion;
857 });
858 const writeRecord = (record: Record<string, unknown>) =>
859 Effect.sync(() => {
860 records.push(record);
861 });
862 const flush = () => {
863 const outputRecords = codexReplayRecordingOutputRecords(records);
864 return fs.writeFileString(
865 outPath,
866 `${[
867 {
868 type: "transcript_start",
869 provider: "codex",
870 protocol: "codex.app-server",
871 version,
872 scenario: scenario.name,
873 metadata: {
874 source: "record-codex-app-server-replay-fixture",
875 fileName: scenario.fileName,
876 description: scenario.description,
877 },
878 },
879 ...outputRecords,
880 ]
881 .map((record) => JSON.stringify(record))
882 .join("\n")}\n`,
883 );
884 };
885​
886 return { path: outPath, setVersion, writeRecord, flush };
887 });
889​
890function makeCodexLayer({ recorder }: { readonly recorder: Recorder }) {
891 const clientRequestMethodById = new Map<string, string>();
892 const serverRequestMethodById = new Map<string, string>();
893 const clientOptions: CodexClient.CodexAppServerClientOptions = {
894 logIncoming: true,
895 logOutgoing: true,
896 logger: (event) => {
897 if (event.stage === "raw") {
898 return Effect.void;
899 }
900​
901 const id = protocolId(event.payload);
902 const idKey = id === undefined ? undefined : String(id);
903 const method = protocolMethod(event.payload);
904 const messageKind = classifyJsonRpcPayload(event.payload);
905 let correlatedRequestMethod: string | undefined;
906​
907 if (messageKind === "request" && idKey && method) {
908 if (event.direction === "outgoing") {
909 clientRequestMethodById.set(idKey, method);
910 } else {
911 serverRequestMethodById.set(idKey, method);
912 }
913 }
914​
915 if (messageKind === "response" || messageKind === "error_response") {
916 if (event.direction === "incoming" && idKey) {
917 correlatedRequestMethod = clientRequestMethodById.get(idKey);
918 clientRequestMethodById.delete(idKey);
919 }
920 if (event.direction === "outgoing" && idKey) {
921 correlatedRequestMethod = serverRequestMethodById.get(idKey);
922 serverRequestMethodById.delete(idKey);
923 }
924 }
925​
926 const version = inferCodexVersion(event.payload);
927 const updateVersion = version ? recorder.setVersion(version) : Effect.void;
928​
929 const label = method ?? correlatedRequestMethod;
930 const record =
931 event.direction === "outgoing"
932 ? {
933 type: "expect_outbound",
934 ...(label ? { label } : {}),
935 frame: event.payload,
936 }
937 : {
938 type: "emit_inbound",
939 ...(label ? { label } : {}),
940 frame: event.payload,
941 };
942​
943 return Effect.gen(function* () {
944 yield* updateVersion;
945 yield* recorder.writeRecord(record);
946 }).pipe(Effect.ignore);
947 },
948 };
949​
950 return Layer.effect(
951 CodexClient.CodexAppServerClient,
952 Effect.gen(function* () {
953 const environment = yield* HostProcessEnvironment;
954 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
955 const commandName = environment.T3_CODEX_BIN ?? environment.CODEX_BIN ?? "codex";
956 const spawnCommand = yield* resolveSpawnCommand(commandName, ["app-server"], {
957 env: environment,
958 });
959 const handle = yield* spawner.spawn(
960 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
961 cwd: process.cwd(),
962 env: environment,
963 shell: spawnCommand.shell,
964 }),
965 );
966 const context = yield* Layer.build(CodexClient.layerChildProcess(handle, clientOptions));
967 return yield* Effect.service(CodexClient.CodexAppServerClient).pipe(Effect.provide(context));
968 }),
969 );
971​
972function installReplayHandlers({
973 client,
974 startTurn,
975 completeTurn,
976 startCommandExecution,
977 beforeApprovalResponse,
978}: {
979 readonly client: CodexClient.CodexAppServerClient["Service"];
980 readonly startTurn: (turnId: string) => Effect.Effect<void>;
981 readonly completeTurn: (turnId: string) => Effect.Effect<void>;
982 readonly startCommandExecution: (turnId: string) => Effect.Effect<void>;
983 readonly beforeApprovalResponse: () => Effect.Effect<void>;
984}) {
985 return Effect.all(
986 [
987 client.handleServerRequest("item/tool/requestUserInput", (payload) =>
988 Effect.succeed({
989 answers: Object.fromEntries(
990 payload.questions.map((question) => [
991 question.id,
992 {
993 answers:
994 question.options && question.options.length > 0
995 ? [question.options[0]!.label]
996 : ["ok"],
997 },
998 ]),
999 ),
1000 }),
1001 ),
1002 client.handleServerRequest("item/commandExecution/requestApproval", () =>
1003 beforeApprovalResponse().pipe(Effect.as({ decision: "accept" })),
1004 ),
1005 client.handleServerRequest("item/fileChange/requestApproval", () =>
1006 beforeApprovalResponse().pipe(Effect.as({ decision: "accept" })),
1007 ),
1008 client.handleServerRequest("item/permissions/requestApproval", (payload) =>
1009 beforeApprovalResponse().pipe(
1010 Effect.as({
1011 permissions: payload.permissions,
1012 scope: "turn" as const,
1013 }),
1014 ),
1015 ),
1016 client.handleServerRequest("mcpServer/elicitation/request", () =>
1017 Effect.succeed({ action: "accept" }),
1018 ),
1019 client.handleServerRequest("item/tool/call", (payload) =>
1020 Effect.succeed({
1021 contentItems: [
1023 text: `Replay dynamic tool handler did not execute external tool: ${payload.tool}`,
1024 type: "inputText" as const,
1025 },
1026 ],
1027 success: false,
1028 }),
1029 ),
1030 client.handleServerRequest("applyPatchApproval", () =>
1031 Effect.succeed({ decision: "approved" }),
1032 ),
1033 client.handleServerRequest("execCommandApproval", () =>
1034 Effect.succeed({ decision: "approved" }),
1035 ),
1036 client.handleUnknownServerRequest((method) =>
1037 Effect.die(new Error(`Unhandled Codex app-server request in replay recorder: ${method}`)),
1038 ),
1039 client.handleServerNotification("turn/started", (payload) =>
1040 startTurn(payload.turn.id).pipe(Effect.ignore),
1041 ),
1042 client.handleServerNotification("turn/completed", (payload) =>
1043 completeTurn(payload.turn.id).pipe(Effect.ignore),
1044 ),
1045 client.handleServerNotification("item/completed", (payload) =>
1046 isRecord(payload.item) && payload.item.type === "commandExecution"
1047 ? startCommandExecution(payload.turnId).pipe(Effect.ignore)
1048 : Effect.void,
1049 ),
1050 client.handleServerNotification("item/started", (payload) =>
1051 isRecord(payload.item) && payload.item.type === "commandExecution"
1052 ? startCommandExecution(payload.turnId).pipe(Effect.ignore)
1053 : Effect.void,
1054 ),
1055 ],
1056 { discard: true },
1057 );
1059​
1060function runReplaySession({
1061 scenario,
1062 run,
1063 recorder,
1064}: {
1065 readonly scenario: ReplayScenario;
1066 readonly run: ReplayRun;
1067 readonly recorder: Recorder;
1068}) {
1069 return Effect.gen(function* () {
1070 const startedTurns = yield* makeReplayRecorderDeferredRegistry();
1071 const completedTurns = yield* makeReplayRecorderDeferredRegistry();
1072 const startedCommandExecutions = yield* makeReplayRecorderDeferredRegistry();
1073 let approvalGate: Deferred.Deferred<void> | undefined;
1074 const getStarted = startedTurns.getOrCreate;
1075 const getCompletion = completedTurns.getOrCreate;
1076 const getCommandExecutionStarted = startedCommandExecutions.getOrCreate;
1077 const startTurn = startedTurns.succeed;
1078 const completeTurn = completedTurns.succeed;
1079 const startCommandExecution = startedCommandExecutions.succeed;
1080 const beforeApprovalResponse = () =>
1081 approvalGate ? Deferred.await(approvalGate) : Effect.void;
1082​
1083 const initializeClient = Effect.gen(function* () {
1084 const client = yield* CodexClient.CodexAppServerClient;
1085​
1086 yield* installReplayHandlers({
1087 client,
1088 startTurn,
1089 completeTurn,
1090 startCommandExecution,
1091 beforeApprovalResponse,
1092 });
1093​
1094 yield* client.request("initialize", {
1095 clientInfo: CODEX_CLIENT_INFO,
1096 capabilities: CODEX_CLIENT_CAPABILITIES,
1097 });
1098​
1099 yield* client.notify("initialized", undefined);
1100​
1101 return client;
1102 });
1103​
1104 const runTurnStep = (
1105 client: CodexClient.CodexAppServerClient["Service"],
1106 threadId: string,
1107 step: TurnReplayStep,
1108 ) =>
1109 Effect.gen(function* () {
1110 const turnParams: TurnStartParams = {
1111 ...run.turnDefaults,
1112 ...step.turnOverrides,
1113 input: turnInput(step.prompt),
1114 threadId,
1115 };
1116​
1117 if (step.type === "steeredTurn") {
1118 approvalGate = yield* Deferred.make<void>();
1120​
1121 const turn = yield* client.request("turn/start", turnParams);
1122 const turnId = getTurnId(turn);
1123 const started = yield* getStarted(turnId);
1124 yield* getCompletion(turnId);
1125​
1126 if (step.type === "steeredTurn") {
1127 yield* Deferred.await(started);
1128 yield* client.request("turn/steer", {
1129 expectedTurnId: turnId,
1130 input: turnInput(step.steer),
1131 threadId,
1132 });
1133 if (approvalGate) {
1134 yield* Deferred.succeed(approvalGate, void 0);
1135 approvalGate = undefined;
1138​
1139 if (step.type === "interruptedTurn") {
1140 if (step.interruptAfterCommandExecutionStarted === true) {
1141 const commandExecutionStarted = yield* getCommandExecutionStarted(turnId);
1142 yield* Deferred.await(commandExecutionStarted);
1143 } else {
1144 yield* Effect.sleep(`${step.interruptAfterMs ?? 1_500} millis`);
1146 yield* client.request("turn/interrupt", {
1147 threadId,
1148 turnId,
1149 });
1151​
1152 const completed = yield* getCompletion(turnId);
1153 yield* Deferred.await(completed);
1154 });
1155​
1156 if (scenario.name === "provider_thread_resume") {
1157 const firstStep = run.steps[0];
1158 const secondStep = run.steps[1];
1159 if (
1160 !firstStep ||
1161 !secondStep ||
1162 firstStep.type === "rollback" ||
1163 firstStep.type === "fork" ||
1164 secondStep.type === "rollback" ||
1165 secondStep.type === "fork"
1166 ) {
1167 throw new Error("provider_thread_resume replay recording requires two turn steps.");
1169​
1170 const firstThread = yield* Effect.gen(function* () {
1171 const client = yield* initializeClient;
1172 const thread = yield* client.request("thread/start", {});
1173 yield* runTurnStep(client, thread.thread.id, firstStep);
1174 return thread;
1175 }).pipe(
1176 Effect.provide(
1177 makeCodexLayer({
1178 recorder,
1179 }),
1180 ),
1181 );
1182​
1183 yield* recorder.writeRecord({
1184 type: "runtime_exit",
1185 status: "success",
1186 });
1187​
1188 yield* Effect.gen(function* () {
1189 const client = yield* initializeClient;
1190 const thread = yield* client.request("thread/resume", {
1191 threadId: firstThread.thread.id,
1192 });
1193 yield* runTurnStep(client, thread.thread.id, secondStep);
1194 }).pipe(
1195 Effect.provide(
1196 makeCodexLayer({
1197 recorder,
1198 }),
1199 ),
1200 );
1201 return;
1203​
1204 yield* Effect.gen(function* () {
1205 const client = yield* initializeClient;
1206 const thread = yield* client.request("thread/start", {});
1207 let activeThreadId = thread.thread.id;
1208 const threadIds = new Map<string, string>([["source", thread.thread.id]]);
1209​
1210 for (const [stepIndex, step] of run.steps.entries()) {
1211 if (step.type === "rollback") {
1212 yield* client.request("thread/rollback", {
1213 threadId: activeThreadId,
1214 numTurns: step.numTurns,
1215 });
1216 continue;
1218 if (step.type === "fork") {
1219 const sourceThreadId =
1220 step.from === undefined ? activeThreadId : threadIds.get(step.from);
1221 if (sourceThreadId === undefined) {
1222 throw new Error(`Unknown replay thread alias '${step.from}'.`);
1224 const forked = yield* client.request("thread/fork", {
1225 threadId: sourceThreadId,
1226 });
1227 activeThreadId = forked.thread.id;
1228 if (step.as !== undefined) {
1229 threadIds.set(step.as, forked.thread.id);
1231 continue;
1233​
1234 const threadAlias = "thread" in step ? step.thread : undefined;
1235 const turnThreadId =
1236 threadAlias === undefined ? activeThreadId : threadIds.get(threadAlias);
1237 if (turnThreadId === undefined) {
1238 throw new Error(`Unknown replay thread alias '${threadAlias}'.`);
1240 yield* runTurnStep(client, turnThreadId, step);
1241 void stepIndex;
1243 }).pipe(
1244 Effect.provide(
1245 makeCodexLayer({
1246 recorder,
1247 }),
1248 ),
1249 );
1250 });
1252​
1253function runScenario({
1254 scenario,
1255 outPath,
1256}: {
1257 readonly scenario: ReplayScenario;
1258 readonly outPath: string;
1259}) {
1260 return Effect.gen(function* () {
1261 const fs = yield* FileSystem.FileSystem;
1262 const path = yield* Path.Path;
1263 const recorder = yield* makeRecorder({ outPath, scenario });
1264​
1265 yield* fs.makeDirectory(path.dirname(outPath), { recursive: true });
1266 yield* Console.log(`Writing ${scenario.name} Codex replay events to ${recorder.path}`);
1267​
1268 yield* Effect.forEach(scenario.runs, (run) => runReplaySession({ scenario, run, recorder }), {
1269 concurrency: 1,
1270 });
1271​
1272 yield* recorder.writeRecord({
1273 type: "runtime_exit",
1274 status: "success",
1275 });
1276 yield* recorder.flush();
1277 });
1279​
1280const program = Effect.gen(function* () {
1281 const path = yield* Path.Path;
1282 const requestedScenarios = parseScenarios();
1283 const allScenarios = scenarios();
1284 const outDir = readArgValue("--out-dir") ?? process.env.T3_CODEX_REPLAY_OUT_DIR;
1285 const singleOutPath = readArgValue("--out") ?? process.env.T3_CODEX_REPLAY_OUT;
1286 const selected = allScenarios.filter((scenario) => requestedScenarios.includes(scenario.name));
1287​
1288 if (selected.length === 0) {
1289 throw new Error("No replay scenarios selected.");
1291 if (singleOutPath && selected.length !== 1) {
1292 throw new Error("--out / T3_CODEX_REPLAY_OUT can only be used with exactly one --scenario.");
1294​
1295 yield* Effect.forEach(
1296 selected,
1297 (scenario) =>
1298 Effect.gen(function* () {
1299 const defaultOutPath = yield* path.fromFileUrl(defaultTranscriptUrl(scenario));
1300 yield* runScenario({
1301 scenario,
1302 outPath:
1303 singleOutPath ?? (outDir ? path.join(outDir, scenario.fileName) : defaultOutPath),
1304 });
1305 }),
1306 { concurrency: 1 },
1307 );
1308});
1309​
1310program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);