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

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

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