@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 12,742 lines 447 KB
Raw
1 import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget";
2 import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
3 import {
4 makeProviderTextDeltaCoalescer,
5 type ProviderTextDeltaUpdate,
6 } from "./ProviderTextDeltaCoalescer.ts";
7 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
8 import * as NodeServices from "@effect/platform-node/NodeServices";
9 import {
10 CommandId,
11 CheckpointId,
12 CodexSettings,
13 EnvironmentId,
14 MessageId,
15 type ModelSelection,
16 NodeId,
17 type OrchestrationV2AppThread,
18 type OrchestrationV2ProviderThread,
19 type OrchestrationV2ProviderTurn,
20 type OrchestrationV2RuntimeRequest,
21 type OrchestrationV2Subagent,
22 type OrchestrationV2TurnItem,
23 ProjectId,
24 type ProviderApprovalDecision,
25 ProviderInstanceId,
26 ProviderSessionId,
27 ProviderSetupError,
28 ProviderThreadId,
29 ProviderTurnId,
30 RunAttemptId,
31 RunId,
32 ThreadId,
33 TurnItemId,
34 type ServerProviderModel,
35 } from "@t3tools/contracts";
36 import { assert, describe, it } from "@effect/vitest";
37 import * as CodexClient from "effect-codex-app-server/client";
38 import * as CodexReplay from "effect-codex-app-server/replay";
39 import * as CodexError from "effect-codex-app-server/errors";
40 import type * as CodexSchema from "effect-codex-app-server/schema";
41 import * as DateTime from "effect/DateTime";
42 import * as Deferred from "effect/Deferred";
43 import * as Digest from "effect/crypto/Digest";
44 import * as Effect from "effect/Effect";
45 import * as Predicate from "effect/Predicate";
46 import * as FileSystem from "effect/FileSystem";
47 import { MCP_APP_OUTPUT_KEY, readMcpAppReference } from "@t3tools/shared/mcpApp";
48 import { toolOutputImages } from "@t3tools/shared/toolOutput";
49 import { resolveAttachmentPathById } from "../../attachmentStore.ts";
50 import * as Fiber from "effect/Fiber";
51 import * as Layer from "effect/Layer";
52 import * as PubSub from "effect/PubSub";
53 import * as Queue from "effect/Queue";
54 import * as Ref from "effect/Ref";
55 import * as Schema from "effect/Schema";
56 import * as Option from "effect/Option";
57 import * as Stream from "effect/Stream";
58 import * as Sink from "effect/Sink";
59 import * as Stdio from "effect/Stdio";
60 import * as Exit from "effect/Exit";
61 import * as Cause from "effect/Cause";
62 import * as PlatformError from "effect/PlatformError";
63 import { TestClock } from "effect/testing";
64 import { ChildProcess, ChildProcessSpawner } from "effect/process";
65 import * as Scope from "effect/Scope";
66 import * as HostProcess from "@t3tools/shared/HostProcess";
67
68 import packageJson from "../../../package.json" with { type: "json" };
69 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
70 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
71 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
72 import * as EffectWorker from "../EffectWorker.ts";
73 import * as Orchestrator from "../Orchestrator.ts";
74 import * as ProviderReplayHarness from "../testkit/ProviderReplayHarness.ts";
75 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
76 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
77 import * as ModelManifest from "../../provider/ModelManifest.ts";
78 import * as PortScanner from "../../preview/PortScanner.ts";
79 import { resolveProviderCompatibility } from "../../provider/providerCompatibility.ts";
80 import * as CodexAdapterV2 from "./CodexAdapterV2.ts";
81 import { withCodexReplayChildMetadata } from "./CodexAdapterV2.testkit.ts";
82 import * as CodexAdapterV2Testkit from "./CodexAdapterV2.testkit.ts";
83
84 const replayTranscriptJson = Schema.fromJsonString(CodexReplay.CodexAppServerReplayTranscript);
85 const encodeReplayTranscriptJson = Schema.encodeEffect(replayTranscriptJson);
86 const decodeReplayTranscriptJson = Schema.decodeUnknownEffect(replayTranscriptJson);
87 const encodeStringJson = Schema.encodeEffect(Schema.fromJsonString(Schema.String));
88 const isProviderAdapterEventStreamError = Schema.is(
89 ProviderAdapter.ProviderAdapterEventStreamError,
90 );
91 const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
92
93 describe("CodexAdapterV2 context usage", () => {
94 it("uses the current context rather than cumulative processed tokens", () => {
95 const usage = CodexAdapterV2.codexProviderTurnTokenUsage(
96 {
97 total: {
98 totalTokens: 180_000,
99 inputTokens: 160_000,
100 cachedInputTokens: 20_000,
101 outputTokens: 20_000,
102 reasoningOutputTokens: 5_000,
103 },
104 last: {
105 totalTokens: 50_000,
106 inputTokens: 45_000,
107 cachedInputTokens: 10_000,
108 outputTokens: 5_000,
109 reasoningOutputTokens: 1_000,
110 },
111 modelContextWindow: 200_000,
112 },
113 "2026-08-29T00:00:00.000Z",
114 );
115
116 assert.deepEqual(usage, {
117 usedTokens: 50_000,
118 maxTokens: 200_000,
119 inputTokens: 45_000,
120 cachedInputTokens: 10_000,
121 outputTokens: 5_000,
122 reasoningOutputTokens: 1_000,
123 updatedAt: "2026-08-29T00:00:00.000Z",
124 });
125 });
126 });
127
128 describe("CodexAdapterV2 assistant message streaming", () => {
129 it.effect("flushes buffered text synchronously before item and turn completion", () =>
130 Effect.gen(function* () {
131 const updates = yield* Ref.make<ReadonlyArray<ProviderTextDeltaUpdate>>([]);
132 const coalescer = yield* makeProviderTextDeltaCoalescer({
133 flushIntervalMs: 50,
134 emit: (update) => Ref.update(updates, (current) => [...current, update]),
135 });
136
137 yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "item final" });
138 const completedText = yield* coalescer.complete({
139 turnId: "turn-1",
140 itemId: "message-1",
141 });
142 yield* coalescer.append({ turnId: "turn-1", itemId: "message-2", delta: "turn final" });
143 yield* coalescer.flushTurn("turn-1");
144
145 assert.equal(completedText, "item final");
146 assert.deepEqual(yield* Ref.get(updates), [
147 { turnId: "turn-1", itemId: "message-1", text: "item final", completed: true },
148 { turnId: "turn-1", itemId: "message-2", text: "turn final", completed: true },
149 ]);
150 yield* Effect.yieldNow;
151 yield* TestClock.adjust("50 millis");
152 yield* Effect.yieldNow;
153 assert.equal((yield* Ref.get(updates)).length, 2);
154 }),
155 );
156 });
157
158 describe("CodexAdapterV2 runtime policy", () => {
159 it.effect.each([undefined, false, true])(
160 "selects native collaboration modes without prompt overrides with hasT3Mcp=%s",
161 (hasT3Mcp) =>
162 Effect.gen(function* () {
163 for (const interactionMode of ["plan", "default"] as const) {
164 for (const reasoningEffort of [undefined, "high"] as const) {
165 const params = yield* CodexAdapterV2.buildCodexTurnStartParams({
166 nativeThreadId: "native-mode-switch",
167 codexInput: [{ type: "text", text: "test" }],
168 runtimePolicy: { runtimeMode: "full-access", interactionMode, cwd: null },
169 modelSelection: {
170 instanceId: ProviderInstanceId.make("codex"),
171 model: "gpt-5.4",
172 ...(reasoningEffort === undefined
173 ? {}
174 : { options: [{ id: "reasoningEffort", value: reasoningEffort }] }),
175 },
176 ...(hasT3Mcp === undefined ? {} : { hasT3Mcp }),
177 });
178
179 assert.deepEqual(params.collaborationMode, {
180 mode: interactionMode,
181 settings: {
182 model: "gpt-5.4",
183 ...(reasoningEffort === undefined ? {} : { reasoning_effort: reasoningEffort }),
184 },
185 });
186 assert.equal(params.effort, reasoningEffort);
187 // Some Responses providers reject `detailed`; `auto` is the most detailed a model supports.
188 assert.equal(params.summary, "auto");
189 assert.equal(params.additionalContext !== undefined, hasT3Mcp === true);
190 }
191 }
192 }),
193 );
194
195 it.effect("derives concrete Codex turn policies from every T3 runtime mode", () =>
196 Effect.gen(function* () {
197 const build = (
198 runtimeMode: "approval-required" | "auto-accept-edits" | "auto" | "full-access",
199 ) =>
200 CodexAdapterV2.buildCodexTurnStartParams({
201 nativeThreadId: `native-${runtimeMode}`,
202 codexInput: [{ type: "text", text: "test" }],
203 runtimePolicy: {
204 runtimeMode,
205 interactionMode: "default",
206 cwd: null,
207 },
208 modelSelection: {
209 instanceId: ProviderInstanceId.make("codex"),
210 model: "gpt-5.4",
211 },
212 });
213
214 const approvalRequired = yield* build("approval-required");
215 const autoAcceptEdits = yield* build("auto-accept-edits");
216 const auto = yield* build("auto");
217 const fullAccess = yield* build("full-access");
218
219 assert.equal(approvalRequired.approvalPolicy, "untrusted");
220 assert.equal(approvalRequired.approvalsReviewer, "user");
221 assert.equal(approvalRequired.sandboxPolicy?.type, "readOnly");
222 assert.equal(autoAcceptEdits.approvalPolicy, "on-request");
223 assert.equal(autoAcceptEdits.approvalsReviewer, "user");
224 assert.equal(autoAcceptEdits.sandboxPolicy?.type, "workspaceWrite");
225 assert.equal(auto.approvalPolicy, "on-request");
226 assert.equal(auto.approvalsReviewer, "auto_review");
227 assert.equal(auto.sandboxPolicy?.type, "workspaceWrite");
228 assert.deepEqual(fullAccess.approvalPolicy, {
229 granular: {
230 mcp_elicitations: true,
231 request_permissions: false,
232 rules: false,
233 sandbox_approval: false,
234 skill_approval: false,
235 },
236 });
237 assert.equal(fullAccess.approvalsReviewer, "user");
238 assert.equal(fullAccess.sandboxPolicy?.type, "dangerFullAccess");
239 }),
240 );
241
242 it.effect("sends the chosen cyber access program, else the model's default", () =>
243 Effect.gen(function* () {
244 const build = (value?: string, cyberAccess?: { defaultProgram: string | undefined }) =>
245 CodexAdapterV2.buildCodexTurnStartParams({
246 nativeThreadId: "native-cyber",
247 codexInput: [{ type: "text", text: "test" }],
248 runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: null },
249 modelSelection: {
250 instanceId: ProviderInstanceId.make("codex"),
251 model: "gpt-5.4",
252 ...(value === undefined ? {} : { options: [{ id: "cyberAccessProgram", value }] }),
253 },
254 cyberAccess,
255 });
256
257 // Custom models offer no Cyber Access, so even an explicit choice is dropped.
258 assert.notProperty(yield* build(), "cyberAccessProgram");
259 assert.notProperty(yield* build("daybreakBlue"), "cyberAccessProgram");
260 const daybreak = { defaultProgram: "daybreakBlue" };
261 assert.equal((yield* build(undefined, daybreak)).cyberAccessProgram, "daybreakBlue");
262 assert.equal((yield* build("standard", daybreak)).cyberAccessProgram, "standard");
263 // An unread config leaves no default, but an explicit Standard still goes.
264 const unknown = { defaultProgram: undefined };
265 assert.notProperty(yield* build(undefined, unknown), "cyberAccessProgram");
266 assert.equal((yield* build("standard", unknown)).cyberAccessProgram, "standard");
267 }),
268 );
269
270 it.effect("sends MCP app model context as untrusted Codex context", () =>
271 Effect.gen(function* () {
272 const policy = { runtimeMode: "full-access", interactionMode: "default", cwd: null } as const;
273 const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };
274 const appContext = [{ key: "mcp_app_todos_list_todos_item-1", text: "Filtered to overdue" }];
275 const alone = yield* CodexAdapterV2.buildCodexTurnStartParams({
276 nativeThreadId: "native-app-context",
277 codexInput: [{ type: "text", text: "what's on my list?" }],
278 runtimePolicy: policy,
279 modelSelection,
280 appContext,
281 });
282 assert.deepEqual(alone.additionalContext, {
283 "mcp_app_todos_list_todos_item-1": { kind: "untrusted", value: "Filtered to overdue" },
284 });
285 const withT3 = yield* CodexAdapterV2.buildCodexTurnStartParams({
286 nativeThreadId: "native-app-context",
287 codexInput: [{ type: "text", text: "what's on my list?" }],
288 runtimePolicy: policy,
289 modelSelection,
290 hasT3Mcp: true,
291 appContext,
292 });
293 assert.deepEqual(withT3.additionalContext?.["mcp_app_todos_list_todos_item-1"], {
294 kind: "untrusted",
295 value: "Filtered to overdue",
296 });
297 assert.isDefined(withT3.additionalContext?.["t3_code_runtime"]);
298 }),
299 );
300 });
301
302 describe("CodexAdapterV2 native protocol logging", () => {
303 it.effect("logs decoded app-server frames once with credentials redacted", () =>
304 Effect.gen(function* () {
305 const writes: Array<{
306 readonly event: unknown;
307 readonly threadId: ThreadId | null;
308 }> = [];
309 const logger: ProviderEventLoggers.EventNdjsonLogger = {
310 filePath: "/tmp/events.log",
311 write: (event, threadId) =>
312 Effect.sync(() => {
313 writes.push({ event, threadId });
314 }),
315 close: () => Effect.void,
316 };
317 const threadId = ThreadId.make("thread-1");
318 const providerSessionId = ProviderSessionId.make("provider-session-1");
319 const protocolLogger = CodexAdapterV2.makeCodexAppServerProtocolLogger({
320 nativeEventLogger: logger,
321 providerSessionId,
322 });
323
324 assert.notEqual(protocolLogger, undefined);
325 if (protocolLogger === undefined) {
326 return;
327 }
328
329 const startThread = (requestId: number, appThreadId: string, nativeThreadId: string) =>
330 Effect.gen(function* () {
331 yield* protocolLogger({
332 direction: "outgoing",
333 stage: "decoded",
334 payload: {
335 id: requestId,
336 method: "thread/start",
337 params: { config: { "shell_environment_policy.set.T3CODE_THREAD_ID": appThreadId } },
338 },
339 });
340 yield* protocolLogger({
341 direction: "incoming",
342 stage: "decoded",
343 payload: { id: requestId, result: { thread: { id: nativeThreadId } } },
344 });
345 });
346 yield* startThread(1, "thread-1", "native-1");
347 yield* startThread(2, "thread-2", "native-2");
348 yield* protocolLogger({
349 direction: "outgoing",
350 stage: "decoded",
351 payload: { id: 3, method: "turn/start", params: { threadId: "native-2" } },
352 });
353 yield* protocolLogger({
354 direction: "incoming",
355 stage: "decoded",
356 payload: { id: 3, result: { turn: { id: "turn-2" } } },
357 });
358 yield* protocolLogger({
359 direction: "incoming",
360 stage: "decoded",
361 payload: { id: 4, result: { userAgent: "codex/1.0.0" } },
362 });
363 assert.deepEqual(
364 writes.splice(0).map((write) => write.threadId),
365 ["thread-1", "thread-1", "thread-2", "thread-2", "thread-2", "thread-2", null],
366 );
367
368 yield* protocolLogger({
369 direction: "incoming",
370 stage: "decoded",
371 payload: {
372 method: "thread/event",
373 params: {
374 threadId: "native-1",
375 id: "evt-1",
376 http_headers: { Authorization: "Bearer secret-codex-token" },
377 usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 },
378 },
379 },
380 });
381 yield* protocolLogger({
382 direction: "incoming",
383 stage: "raw",
384 payload:
385 '{"method":"thread/event","params":{"http_headers":{"Authorization":"Bearer secret-codex-token"}}}\n',
386 });
387
388 assert.equal(writes.length, 1);
389 assert.equal(writes[0]?.threadId, threadId);
390 assert.deepEqual(writes[0]?.event, {
391 provider: "codex",
392 protocol: "codex.app-server",
393 kind: "protocol",
394 providerSessionId,
395 event: {
396 direction: "incoming",
397 stage: "decoded",
398 payload: {
399 method: "thread/event",
400 params: {
401 threadId: "native-1",
402 id: "evt-1",
403 http_headers: { Authorization: "[REDACTED]" },
404 usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 },
405 },
406 },
407 },
408 });
409 }),
410 );
411 });
412
413 describe("CodexAdapterV2 rollback mapping", () => {
414 it.effect("derives native rollback count from durable provider turns", () =>
415 Effect.gen(function* () {
416 const now = yield* DateTime.now;
417 const providerThreadId = ProviderThreadId.make("provider-thread-codex-rollback");
418 const providerThread: OrchestrationV2ProviderThread = {
419 id: providerThreadId,
420 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
421 providerInstanceId: ProviderInstanceId.make("codex"),
422 providerSessionId: ProviderSessionId.make("provider-session-codex-rollback"),
423 appThreadId: ThreadId.make("thread-codex-rollback"),
424 ownerNodeId: null,
425 nativeThreadRef: {
426 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
427 nativeId: "native-thread-codex-rollback",
428 strength: "strong",
429 },
430 nativeConversationHeadRef: null,
431 status: "idle",
432 firstRunOrdinal: 1,
433 lastRunOrdinal: 3,
434 handoffIds: [],
435 forkedFrom: null,
436 createdAt: now,
437 updatedAt: now,
438 };
439 const providerTurn = (
440 id: string,
441 ordinal: number,
442 status: OrchestrationV2ProviderTurn["status"],
443 ): OrchestrationV2ProviderTurn => ({
444 id: ProviderTurnId.make(id),
445 providerThreadId,
446 nodeId: NodeId.make(`node-${id}`),
447 runAttemptId: RunAttemptId.make(`run-attempt-${id}`),
448 nativeTurnRef: {
449 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
450 nativeId: `native-${id}`,
451 strength: "strong",
452 },
453 ordinal,
454 status,
455 startedAt: now,
456 completedAt: status === "running" || status === "pending" ? null : now,
457 });
458 const firstTurn = providerTurn("provider-turn-first", 1, "completed");
459 const secondTurn = providerTurn("provider-turn-second", 2, "completed");
460 const runningTurn = providerTurn("provider-turn-running", 3, "running");
461 const interruptedTurn = providerTurn("provider-turn-interrupted", 4, "interrupted");
462 const goalCommandTurn = {
463 ...providerTurn("provider-turn-goal-command", 5, "completed"),
464 nativeTurnRef: null,
465 };
466
467 const numTurns = yield* CodexAdapterV2.resolveCodexRollbackTurnCount({
468 providerThread,
469 target: {
470 type: "provider_turn",
471 checkpointId: CheckpointId.make("checkpoint-first"),
472 appRunOrdinal: 1,
473 providerTurn: firstTurn,
474 },
475 providerThreadTurns: [goalCommandTurn, interruptedTurn, runningTurn, secondTurn, firstTurn],
476 });
477
478 assert.equal(numTurns, 2);
479 }),
480 );
481 });
482
483 describe("CodexAdapterV2 fork boundary", () => {
484 const providerThreadId = ProviderThreadId.make("provider-thread-codex-fork-boundary");
485 const makeProviderThread = (now: DateTime.Utc): OrchestrationV2ProviderThread => ({
486 id: providerThreadId,
487 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
488 providerInstanceId: ProviderInstanceId.make("codex"),
489 providerSessionId: ProviderSessionId.make("provider-session-codex-fork-boundary"),
490 appThreadId: ThreadId.make("thread-codex-fork-boundary"),
491 ownerNodeId: null,
492 nativeThreadRef: {
493 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
494 nativeId: "native-thread-codex-fork-boundary",
495 strength: "strong",
496 },
497 nativeConversationHeadRef: null,
498 status: "idle",
499 firstRunOrdinal: 1,
500 lastRunOrdinal: 2,
501 handoffIds: [],
502 forkedFrom: null,
503 createdAt: now,
504 updatedAt: now,
505 });
506 const makeProviderTurn = (
507 id: string,
508 ordinal: number,
509 nativeId: string | null,
510 now: DateTime.Utc,
511 ): OrchestrationV2ProviderTurn => ({
512 id: ProviderTurnId.make(id),
513 providerThreadId,
514 nodeId: NodeId.make(`node-${id}`),
515 runAttemptId: RunAttemptId.make(`run-attempt-${id}`),
516 nativeTurnRef:
517 nativeId === null
518 ? { driver: CodexAdapterV2.CODEX_DRIVER_KIND, nativeId: null, strength: "none" }
519 : { driver: CodexAdapterV2.CODEX_DRIVER_KIND, nativeId, strength: "strong" },
520 ordinal,
521 status: "completed",
522 startedAt: now,
523 completedAt: now,
524 });
525
526 it.effect("resolves the selected provider turn to an inclusive native fork boundary", () =>
527 Effect.gen(function* () {
528 const now = yield* DateTime.now;
529 const firstTurn = makeProviderTurn("provider-turn-first", 1, "native-turn-first", now);
530 const secondTurn = makeProviderTurn("provider-turn-second", 2, "native-turn-second", now);
531
532 const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({
533 sourceProviderThread: makeProviderThread(now),
534 sourceProviderTurns: [firstTurn, secondTurn],
535 providerTurnId: firstTurn.id,
536 targetThreadId: ThreadId.make("thread-codex-fork-target"),
537 });
538
539 assert.deepEqual(boundary, {
540 lastTurnId: "native-turn-first",
541 rollbackTurnCount: 0,
542 });
543 }),
544 );
545
546 it.effect("keeps the rollback-count fallback when the boundary turn lacks a native id", () =>
547 Effect.gen(function* () {
548 const now = yield* DateTime.now;
549 const firstTurn = makeProviderTurn("provider-turn-first", 1, null, now);
550 const secondTurn = makeProviderTurn("provider-turn-second", 2, "native-turn-second", now);
551
552 const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({
553 sourceProviderThread: makeProviderThread(now),
554 sourceProviderTurns: [firstTurn, secondTurn],
555 providerTurnId: firstTurn.id,
556 targetThreadId: ThreadId.make("thread-codex-fork-target"),
557 });
558
559 assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 1 });
560 }),
561 );
562 });
563
564 const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({});
565 const CHATGPT_SHARING_LIMIT_MESSAGE =
566 "stream disconnected before completion: The ChatGPT user has reached their Subscription Sharing usage limit. Ask the user to try again after their usage limit resets or use an API key instead.";
567 const CODEX_TEST_MODEL_SELECTION = {
568 instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
569 model: "gpt-5.4",
570 } satisfies ModelSelection;
571 const CODEX_TEST_RUNTIME_POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
572 runtimeMode: "full-access",
573 interactionMode: "default",
574 cwd: "/workspace",
575 });
576 const T3_THREAD_ENV_KEY = "shell_environment_policy.set.T3CODE_THREAD_ID";
577 const threadEnvOf = (params: unknown) =>
578 Predicate.hasProperty(params, "config") && Predicate.hasProperty(params.config, T3_THREAD_ENV_KEY)
579 ? params.config[T3_THREAD_ENV_KEY]
580 : undefined;
581
582 const CODEX_TEST_THREAD_TITLE = "Codex continuation test";
583
584 function makeCodexTestAppThread(input: {
585 readonly threadId: ThreadId;
586 readonly providerThread: OrchestrationV2ProviderThread;
587 readonly now: DateTime.Utc;
588 }): OrchestrationV2AppThread {
589 return {
590 createdBy: "user",
591 creationSource: "web",
592 id: input.threadId,
593 projectId: ProjectId.make(`project-${input.threadId}`),
594 title: CODEX_TEST_THREAD_TITLE,
595 providerInstanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
596 modelSelection: CODEX_TEST_MODEL_SELECTION,
597 runtimeMode: "full-access",
598 interactionMode: "default",
599 branch: null,
600 worktreePath: null,
601 activeProviderThreadId: input.providerThread.id,
602 lineage: {
603 parentThreadId: null,
604 relationshipToParent: null,
605 rootThreadId: input.threadId,
606 },
607 forkedFrom: null,
608 createdAt: input.now,
609 updatedAt: input.now,
610 archivedAt: null,
611 settledOverride: null,
612 settledAt: null,
613 lastVisitedAt: null,
614 deletedAt: null,
615 };
616 }
617
618 function makeCodexTestTurnInput(input: {
619 readonly threadId: ThreadId;
620 readonly providerThread: OrchestrationV2ProviderThread;
621 readonly now: DateTime.Utc;
622 readonly attemptId: RunAttemptId;
623 readonly text: string;
624 }): ProviderAdapter.ProviderAdapterV2TurnInput {
625 return {
626 appThread: makeCodexTestAppThread(input),
627 threadId: input.threadId,
628 runId: RunId.make(`run-${input.attemptId}`),
629 runOrdinal: 1,
630 providerTurnOrdinal: 1,
631 attemptId: input.attemptId,
632 rootNodeId: NodeId.make(`node-${input.attemptId}`),
633 providerThread: input.providerThread,
634 message: {
635 createdBy: "user",
636 creationSource: "web",
637 messageId: MessageId.make(`message-${input.attemptId}`),
638 text: input.text,
639 attachments: [],
640 },
641 modelSelection: CODEX_TEST_MODEL_SELECTION,
642 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
643 };
644 }
645
646 function makeCodexReplayTurn(input: {
647 readonly id: string;
648 readonly status: "inProgress" | "completed" | "interrupted" | "failed";
649 }): Record<string, unknown> {
650 const terminal =
651 input.status === "completed" || input.status === "interrupted" || input.status === "failed";
652 return {
653 id: input.id,
654 items: [],
655 itemsView: "notLoaded",
656 status: input.status,
657 error: null,
658 startedAt: 1782622440,
659 completedAt: terminal ? 1782622450 : null,
660 durationMs: null,
661 };
662 }
663
664 function codexReplayPreamble(input: {
665 readonly nativeThreadId: string;
666 readonly nativeTurnId: string;
667 readonly prompt: string;
668 readonly sentPrompt?: string;
669 readonly effort?: string;
670 readonly turnPolicy?: Pick<
671 typeof CodexClient.V2TurnStartParams.Type,
672 "approvalPolicy" | "sandboxPolicy"
673 >;
674 }): Array<CodexReplay.CodexAppServerReplayEntry> {
675 return [
676 {
677 type: "expect_outbound",
678 label: "initialize",
679 frame: {
680 id: 1,
681 method: "initialize",
682 params: {
683 clientInfo: { name: "T3 Code", title: "T3 Code", version: packageJson.version },
684 capabilities: {
685 experimentalApi: true,
686 optOutNotificationMethods: ["turn/diff/updated"],
687 extensions: {
688 "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] },
689 },
690 },
691 },
692 },
693 },
694 {
695 type: "emit_inbound",
696 label: "initialize",
697 frame: {
698 id: 1,
699 result: {
700 userAgent: "T3 Code/0.156.1",
701 codexHome: "/tmp/codex-home",
702 platformFamily: "unix",
703 platformOs: "macos",
704 },
705 },
706 },
707 { type: "expect_outbound", label: "initialized", frame: { method: "initialized" } },
708 {
709 type: "expect_outbound",
710 label: "thread/start",
711 frame: {
712 id: 2,
713 method: "thread/start",
714 params: { config: CodexAdapterV2.CODEX_THREAD_CONFIG },
715 },
716 },
717 {
718 type: "emit_inbound",
719 label: "thread/start",
720 frame: {
721 id: 2,
722 result: {
723 thread: {
724 id: input.nativeThreadId,
725 sessionId: input.nativeThreadId,
726 projectId: null,
727 forkedFromId: null,
728 preview: "",
729 ephemeral: false,
730 modelProvider: "openai",
731 createdAt: 1782622440,
732 updatedAt: 1782622440,
733 status: { type: "idle" },
734 path: `/tmp/${input.nativeThreadId}.jsonl`,
735 cwd: "/workspace",
736 cliVersion: "0.144.0",
737 source: "vscode",
738 threadSource: null,
739 agentNickname: null,
740 agentRole: null,
741 gitInfo: null,
742 name: null,
743 turns: [],
744 },
745 model: "gpt-5.4",
746 modelProvider: "openai",
747 serviceTier: null,
748 cwd: "/workspace",
749 instructionSources: [],
750 approvalPolicy: "on-request",
751 approvalsReviewer: "user",
752 sandbox: { type: "workspaceWrite", writableRoots: [], networkAccess: false },
753 reasoningEffort: "medium",
754 },
755 },
756 },
757 {
758 type: "expect_outbound",
759 label: "turn/start",
760 frame: {
761 id: 3,
762 method: "turn/start",
763 params: {
764 threadId: input.nativeThreadId,
765 input: [{ type: "text", text: input.sentPrompt ?? input.prompt }],
766 cwd: "/workspace",
767 model: "gpt-5.4",
768 approvalPolicy: "never",
769 approvalsReviewer: "user",
770 sandboxPolicy: { type: "dangerFullAccess" },
771 ...input.turnPolicy,
772 summary: "auto",
773 ...(input.effort === undefined ? {} : { effort: input.effort }),
774 collaborationMode: {
775 mode: "default",
776 settings: {
777 model: "gpt-5.4",
778 ...(input.effort === undefined ? {} : { reasoning_effort: input.effort }),
779 },
780 },
781 },
782 },
783 },
784 {
785 type: "emit_inbound",
786 label: "turn/start",
787 frame: {
788 id: 3,
789 result: { turn: makeCodexReplayTurn({ id: input.nativeTurnId, status: "inProgress" }) },
790 },
791 },
792 {
793 type: "emit_inbound",
794 label: "turn/started",
795 frame: {
796 method: "turn/started",
797 params: {
798 threadId: input.nativeThreadId,
799 turn: makeCodexReplayTurn({ id: input.nativeTurnId, status: "inProgress" }),
800 },
801 },
802 },
803 ];
804 }
805
806 /**
807 * Every turn/start follows a config/read, and a thread's first turn on a connection names it
808 * unless the transcript names it itself. A thread start, resume or fork follows a config/read
809 * unless it retries a failed request or the transcript reads config itself. Inserts those
810 * exchanges and shifts later client ids.
811 */
812 function withConfigReadBeforeTurnStart(
813 entries: ReadonlyArray<CodexReplay.CodexAppServerReplayEntry>,
814 threadName = CODEX_TEST_THREAD_TITLE,
815 ): Array<CodexReplay.CodexAppServerReplayEntry> {
816 const result: Array<CodexReplay.CodexAppServerReplayEntry> = [];
817 let offset = 0;
818 let clientIds = new Map<number, number>();
819 let namedThreads = new Set<unknown>();
820 let transcriptReads = 0;
821 let previousOutbound: { readonly method: string; readonly id: number } | undefined;
822 let failedMethod: string | undefined;
823 for (const entry of entries) {
824 const frame = entry.type === "runtime_exit" ? undefined : entry.frame;
825 if (!Predicate.isObject(frame) || typeof frame.id !== "number") {
826 result.push(entry);
827 continue;
828 }
829 if (entry.type === "expect_outbound" && typeof frame.method === "string") {
830 const params = Predicate.isObject(frame.params) ? frame.params : {};
831 if (frame.method === "initialize") {
832 offset = 0;
833 clientIds = new Map();
834 namedThreads = new Set();
835 }
836 if (frame.method === "thread/name/set") namedThreads.add(params.threadId);
837 const exchanges: Array<readonly [string, unknown, unknown]> = [];
838 const isThreadRequest =
839 frame.method === "thread/start" ||
840 frame.method === "thread/resume" ||
841 frame.method === "thread/fork";
842 if (frame.method === "config/read") transcriptReads += 1;
843 else if (isThreadRequest && transcriptReads > 0) transcriptReads -= 1;
844 else if (
845 isThreadRequest &&
846 failedMethod !== frame.method &&
847 previousOutbound?.method !== "thread/unarchive"
848 ) {
849 exchanges.push([
850 "config/read",
851 { ...(params.cwd === undefined ? {} : { cwd: params.cwd }), includeLayers: false },
852 { config: {}, origins: {} },
853 ]);
854 }
855 if (frame.method === "turn/start") {
856 if (!namedThreads.has(params.threadId)) {
857 namedThreads.add(params.threadId);
858 exchanges.push(["thread/name/set", { threadId: params.threadId, name: threadName }, {}]);
859 }
860 exchanges.push([
861 "config/read",
862 { cwd: params.cwd, includeLayers: false },
863 { config: {}, origins: {} },
864 ]);
865 }
866 for (const [method, requestParams, response] of exchanges) {
867 const id = frame.id + offset;
868 result.push(
869 {
870 type: "expect_outbound",
871 label: method,
872 frame: { id, method, params: requestParams },
873 },
874 { type: "emit_inbound", label: method, frame: { id, result: response } },
875 );
876 offset += 1;
877 }
878 previousOutbound = { method: frame.method, id: frame.id };
879 failedMethod = undefined;
880 clientIds.set(frame.id, frame.id + offset);
881 result.push(withReplayRequestId(entry, frame.id + offset));
882 continue;
883 }
884 if (entry.type === "emit_inbound" && frame.id === previousOutbound?.id && "error" in frame) {
885 failedMethod = previousOutbound.method;
886 }
887 const mapped = clientIds.get(frame.id);
888 result.push(
889 entry.type === "emit_inbound" && frame.method === undefined && mapped !== undefined
890 ? withReplayRequestId(entry, mapped)
891 : entry,
892 );
893 }
894 return result;
895 }
896
897 function withConfigReads(
898 transcript: CodexReplay.CodexAppServerReplayTranscript,
899 threadName?: string,
900 ): CodexReplay.CodexAppServerReplayTranscript {
901 return { ...transcript, entries: withConfigReadBeforeTurnStart(transcript.entries, threadName) };
902 }
903
904 function makeCodexReplayTranscript(input: {
905 readonly scenario: string;
906 readonly entries: ReadonlyArray<CodexReplay.CodexAppServerReplayEntry>;
907 }): CodexReplay.CodexAppServerReplayTranscript {
908 return {
909 provider: "codex",
910 protocol: "codex.app-server",
911 version: "0.144.0",
912 scenario: input.scenario,
913 entries: input.entries,
914 };
915 }
916
917 function withReplayRequestId(
918 entry: CodexReplay.CodexAppServerReplayEntry,
919 id: number,
920 ): CodexReplay.CodexAppServerReplayEntry {
921 return entry.type !== "runtime_exit" && Predicate.isObject(entry.frame)
922 ? { ...entry, frame: { ...entry.frame, id } }
923 : entry;
924 }
925
926 describe("CodexAdapterV2 process exit", () => {
927 it.effect.each([
928 { exit: "numeric", active: false },
929 { exit: "SIGKILL", active: false },
930 { exit: "numeric", active: true },
931 { exit: "SIGKILL", active: true },
932 ] as const)("retires the shared session after $exit (active turn: $active)", ({ exit, active }) =>
933 Effect.gen(function* () {
934 const scenario = `process-exit-${exit}-${active}`;
935 const nativeThreadId = `native-${scenario}`;
936 const nativeTurnId = `turn-${scenario}`;
937 const input = yield* Queue.unbounded<Uint8Array, Cause.Done>();
938 const emit = (frame: unknown) =>
939 Queue.offer(input, new TextEncoder().encode(JSON.stringify(frame) + "\n"));
940 const outputEnded = yield* Deferred.make<void>();
941 const turnStarted = yield* Deferred.make<void>();
942 const turnCompleted = yield* Deferred.make<void>();
943 const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
944 const preamble = withConfigReadBeforeTurnStart(
945 codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" }),
946 );
947 const terminationError =
948 exit === "numeric"
949 ? new CodexError.CodexAppServerProcessExitedError({ code: 17, pid: 52 })
950 : new CodexError.CodexAppServerTransportError({
951 operation: "read-process-exit-status",
952 pid: 52,
953 cause: PlatformError.systemError({
954 _tag: "Unknown",
955 module: "ChildProcess",
956 method: "exitCode",
957 cause: new Error("Process terminated by SIGKILL"),
958 }),
959 });
960 const client = yield* CodexClient.make(
961 Stdio.make({
962 args: Effect.succeed([]),
963 stdin: Stream.fromQueue(input),
964 stdout: () =>
965 Sink.forEach((chunk: string | Uint8Array) =>
966 Effect.gen(function* () {
967 const frame = JSON.parse(
968 typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk),
969 ) as { readonly id?: number; readonly method: string };
970 const response = preamble.find(
971 (entry) =>
972 entry.type === "emit_inbound" &&
973 entry.label === frame.method &&
974 Predicate.isObject(entry.frame) &&
975 "id" in entry.frame,
976 );
977 if (response?.type === "emit_inbound" && Predicate.isObject(response.frame)) {
978 yield* emit({ ...response.frame, id: frame.id });
979 }
980 }),
981 ).pipe(Sink.ensuring(Deferred.succeed(outputEnded, undefined))),
982 stderr: () => Sink.drain,
983 }),
984 {},
985 Effect.succeed(terminationError),
986 );
987 const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({
988 instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
989 settings: DEFAULT_CODEX_SETTINGS,
990 environment: {},
991 clientFactory: { open: () => Effect.succeed(client) },
992 digest: yield* Digest.Digest,
993 fileSystem: yield* FileSystem.FileSystem,
994 idAllocator: yield* IdAllocator.IdAllocatorV2,
995 serverConfig: yield* ProviderReplayHarness.makeReplayServerConfig(scenario).pipe(
996 Effect.orDie,
997 ),
998 });
999 const threadId = ThreadId.make(`thread-${scenario}`);
1000 const runtime = yield* adapter.openSession({
1001 threadId,
1002 providerSessionId: ProviderSessionId.make(`session-${scenario}`),
1003 modelSelection: CODEX_TEST_MODEL_SELECTION,
1004 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
1005 });
1006 const eventReader = yield* runtime.events.pipe(
1007 Stream.runForEach((event) =>
1008 Effect.sync(() => events.push(event)).pipe(
1009 Effect.andThen(
1010 event.type === "provider_turn.updated" && event.providerTurn.status === "running"
1011 ? Deferred.succeed(turnStarted, undefined)
1012 : event.type === "turn.terminal"
1013 ? Deferred.succeed(turnCompleted, undefined)
1014 : Effect.void,
1015 ),
1016 ),
1017 ),
1018 Effect.forkScoped,
1019 );
1020 const providerThread = yield* runtime.ensureThread({
1021 threadId,
1022 modelSelection: CODEX_TEST_MODEL_SELECTION,
1023 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
1024 });
1025 yield* runtime.startTurn(
1026 makeCodexTestTurnInput({
1027 threadId,
1028 providerThread,
1029 now: yield* DateTime.now,
1030 attemptId: RunAttemptId.make(`attempt-${scenario}`),
1031 text: "work",
1032 }),
1033 );
1034 yield* emit({
1035 method: "turn/started",
1036 params: {
1037 threadId: nativeThreadId,
1038 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }),
1039 },
1040 });
1041 yield* Deferred.await(turnStarted);
1042 if (!active) {
1043 yield* emit({
1044 method: "turn/completed",
1045 params: {
1046 threadId: nativeThreadId,
1047 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
1048 },
1049 });
1050 yield* Deferred.await(turnCompleted);
1051 assert.isTrue(
1052 events.some((event) => event.type === "turn.terminal" && event.status === "completed"),
1053 );
1054 }
1055
1056 yield* Queue.end(input);
1057 // Output closes only after the protocol records the process termination.
1058 yield* Deferred.await(outputEnded);
1059 const rpcError = yield* client.request("thread/list", {}).pipe(Effect.flip);
1060 assert.strictEqual(rpcError, terminationError);
1061 // Without the fix the stream never ends, so this waits until the project timeout.
1062 const readerExit = yield* Fiber.await(eventReader);
1063 // A failure, not a clean end, carries the Codex error into the session's lastError.
1064 assert.isTrue(
1065 Exit.isFailure(readerExit) &&
1066 isProviderAdapterEventStreamError(Cause.squash(readerExit.cause)),
1067 "the session manager must receive process death so it can retire the shared process",
1068 );
1069 }).pipe(
1070 Effect.scoped,
1071 Effect.provide(
1072 Layer.mergeAll(
1073 IdAllocator.layer,
1074 McpProviderSessions.layer,
1075 NodeServices.layer,
1076 NodeCrypto.layer,
1077 ),
1078 ),
1079 ),
1080 );
1081
1082 it.effect("counts the app-server as a running agent until its session closes", () => {
1083 let runningAgents = 0;
1084 const factoryLayer = CodexAdapterV2.layerAppServerClientFactory.pipe(
1085 Layer.provide(
1086 Layer.mock(PortScanner.PortDiscovery)({
1087 trackAgent: () => {
1088 runningAgents += 1;
1089 return () => {
1090 runningAgents -= 1;
1091 };
1092 },
1093 }),
1094 ),
1095 Layer.provide(
1096 Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, {
1097 native: undefined,
1098 canonical: undefined,
1099 }),
1100 ),
1101 Layer.provide(
1102 Layer.succeed(
1103 ChildProcessSpawner.ChildProcessSpawner,
1104 ChildProcessSpawner.make(() =>
1105 Effect.succeed(
1106 ChildProcessSpawner.makeHandle({
1107 pid: ChildProcessSpawner.ProcessId(999_999_999),
1108 exitCode: Effect.never,
1109 isRunning: Effect.succeed(true),
1110 kill: () => Effect.void,
1111 unref: Effect.succeed(Effect.void),
1112 stdin: Sink.drain,
1113 stdout: Stream.never,
1114 stderr: Stream.empty,
1115 all: Stream.empty,
1116 getInputFd: () => Sink.drain,
1117 getOutputFd: () => Stream.empty,
1118 }),
1119 ),
1120 ),
1121 ),
1122 ),
1123 );
1124 return Effect.gen(function* () {
1125 const factory = yield* CodexAdapterV2.CodexAppServerClientFactory;
1126 yield* Effect.scoped(
1127 factory
1128 .open({
1129 instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
1130 threadId: ThreadId.make("thread-codex-agent"),
1131 providerSessionId: ProviderSessionId.make("session-codex-agent"),
1132 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
1133 settings: DEFAULT_CODEX_SETTINGS,
1134 environment: {},
1135 })
1136 .pipe(Effect.tap(() => Effect.sync(() => assert.equal(runningAgents, 1)))),
1137 );
1138 assert.equal(runningAgents, 0);
1139 }).pipe(Effect.provide(factoryLayer));
1140 });
1141 });
1142
1143 describe("CodexAdapterV2 session initialize", () => {
1144 const openReplaySession = (
1145 transcript: CodexReplay.CodexAppServerReplayTranscript,
1146 beforeEmitInbound?: CodexReplay.CodexAppServerReplayDriver["beforeEmitInbound"],
1147 compatibility?: CodexAdapterV2.CodexAdapterV2Options["compatibility"],
1148 ) =>
1149 Effect.gen(function* () {
1150 const driver = yield* CodexReplay.makeReplayDriver(
1151 withConfigReads(transcript),
1152 beforeEmitInbound === undefined ? {} : { beforeEmitInbound },
1153 );
1154 let initializeRequests = 0;
1155 const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({
1156 instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
1157 settings: DEFAULT_CODEX_SETTINGS,
1158 environment: {},
1159 ...(compatibility === undefined ? {} : { compatibility }),
1160 clientFactory: {
1161 open: (openInput) =>
1162 Layer.build(CodexReplay.layerReplayWithDriver(driver)).pipe(
1163 Effect.flatMap((context) =>
1164 Effect.service(CodexClient.CodexAppServerClient).pipe(Effect.provide(context)),
1165 ),
1166 Effect.map(
1167 (client) =>
1168 ({
1169 ...client,
1170 request: (method, params) =>
1171 Effect.sync(() => {
1172 if (method === "initialize") initializeRequests++;
1173 }).pipe(Effect.andThen(client.request(method, params))),
1174 }) satisfies CodexClient.CodexAppServerClient["Service"],
1175 ),
1176 Effect.mapError(
1177 (cause) =>
1178 new ProviderAdapter.ProviderAdapterOpenSessionError({
1179 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
1180 providerSessionId: openInput.providerSessionId,
1181 cause,
1182 }),
1183 ),
1184 ),
1185 },
1186 digest: yield* Digest.Digest,
1187 fileSystem: yield* FileSystem.FileSystem,
1188 idAllocator: yield* IdAllocator.IdAllocatorV2,
1189 serverConfig: yield* ProviderReplayHarness.makeReplayServerConfig(transcript.scenario).pipe(
1190 Effect.orDie,
1191 ),
1192 });
1193 const runtime = yield* adapter.openSession({
1194 threadId: ThreadId.make(`thread-${transcript.scenario}`),
1195 providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`),
1196 modelSelection: CODEX_TEST_MODEL_SELECTION,
1197 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
1198 });
1199 return {
1200 ensureThread: (threadId: string) =>
1201 runtime.ensureThread({
1202 threadId: ThreadId.make(threadId),
1203 modelSelection: CODEX_TEST_MODEL_SELECTION,
1204 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
1205 }),
1206 initializeRequests: () => initializeRequests,
1207 events: runtime.events,
1208 };
1209 });
1210
1211 const replayPreamble = (nativeThreadId: string) =>
1212 codexReplayPreamble({ nativeThreadId, nativeTurnId: "unused", prompt: "unused" });
1213
1214 it.effect("sends one initialize when two threads start on a fresh session at once", () =>
1215 Effect.gen(function* () {
1216 const initializeAwaitingResponse = yield* Deferred.make<void>();
1217 const releaseInitialize = yield* Deferred.make<void>();
1218 // Codex rejects a second initialize; the replay permits one handshake.
1219 const session = yield* openReplaySession(
1220 makeCodexReplayTranscript({
1221 scenario: "concurrent-initialize",
1222 entries: [
1223 ...replayPreamble("concurrent-first").slice(0, 3),
1224 ...[2, 3].flatMap((id): Array<CodexReplay.CodexAppServerReplayEntry> => [
1225 {
1226 type: "expect_outbound",
1227 label: "config/read",
1228 frame: { id, method: "config/read", params: { includeLayers: false } },
1229 },
1230 {
1231 type: "emit_inbound",
1232 label: "config/read",
1233 frame: { id, result: { config: {}, origins: {} } },
1234 },
1235 ]),
1236 ...replayPreamble("concurrent-first")
1237 .slice(3, 5)
1238 .map((entry) => withReplayRequestId(entry, 4)),
1239 ...replayPreamble("concurrent-second")
1240 .slice(3, 5)
1241 .map((entry) => withReplayRequestId(entry, 5)),
1242 ],
1243 }),
1244 (entry) =>
1245 entry.label === "initialize"
1246 ? Deferred.succeed(initializeAwaitingResponse, undefined).pipe(
1247 Effect.andThen(Deferred.await(releaseInitialize)),
1248 )
1249 : Effect.void,
1250 );
1251
1252 const first = yield* session
1253 .ensureThread("thread-concurrent-first")
1254 .pipe(Effect.forkChild({ startImmediately: true }));
1255 yield* Deferred.await(initializeAwaitingResponse);
1256 const second = yield* session
1257 .ensureThread("thread-concurrent-second")
1258 .pipe(Effect.forkChild({ startImmediately: true }));
1259 yield* Deferred.succeed(releaseInitialize, undefined);
1260
1261 const providerThreads = [yield* Fiber.join(first), yield* Fiber.join(second)];
1262 assert.equal(session.initializeRequests(), 1);
1263 assert.sameMembers(
1264 providerThreads.map((providerThread) => providerThread.nativeThreadRef?.nativeId),
1265 ["concurrent-first", "concurrent-second"],
1266 );
1267 }).pipe(
1268 Effect.scoped,
1269 Effect.provide(
1270 Layer.mergeAll(
1271 IdAllocator.layer,
1272 McpProviderSessions.layer,
1273 NodeServices.layer,
1274 NodeCrypto.layer,
1275 ),
1276 ),
1277 ),
1278 );
1279
1280 // regression: #16260 one-shot initializers raced; a failed handshake must be retried
1281 it.effect("retries initialize after a failed handshake", () =>
1282 Effect.gen(function* () {
1283 const preamble = replayPreamble("initialize-retry");
1284 const entries: Array<CodexReplay.CodexAppServerReplayEntry> = [
1285 ...preamble.slice(0, 1),
1286 {
1287 type: "emit_inbound",
1288 label: "initialize",
1289 frame: { id: 1, error: { code: -32603, message: "Codex is not ready." } },
1290 },
1291 ...preamble.slice(0, 2).map((entry) => withReplayRequestId(entry, 2)),
1292 ...preamble.slice(2, 3),
1293 ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)),
1294 ];
1295 const session = yield* openReplaySession(
1296 makeCodexReplayTranscript({ scenario: "initialize-retry", entries }),
1297 );
1298
1299 const failure = yield* session.ensureThread("thread-initialize-retry").pipe(Effect.flip);
1300 assert.equal(failure._tag, "ProviderAdapterEnsureThreadError");
1301 const providerThread = yield* session.ensureThread("thread-initialize-retry");
1302 assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-retry");
1303 assert.equal(session.initializeRequests(), 2);
1304 }).pipe(
1305 Effect.scoped,
1306 Effect.provide(
1307 Layer.mergeAll(
1308 IdAllocator.layer,
1309 McpProviderSessions.layer,
1310 NodeServices.layer,
1311 NodeCrypto.layer,
1312 ),
1313 ),
1314 ),
1315 );
1316
1317 it.effect("refuses to open a session on a Codex version marked broken", () =>
1318 Effect.gen(function* () {
1319 const [initialize] = replayPreamble("broken-version");
1320 const failure = yield* openReplaySession(
1321 makeCodexReplayTranscript({
1322 scenario: "broken-version",
1323 entries: [
1324 initialize!,
1325 {
1326 type: "emit_inbound",
1327 label: "initialize",
1328 frame: {
1329 id: 1,
1330 result: {
1331 userAgent: "T3 Code/0.144.3 (Mac OS 15.5.0; x86_64) unknown (T3 Code; 0.1.5)",
1332 codexHome: "/tmp/codex-home",
1333 platformFamily: "unix",
1334 platformOs: "macos",
1335 },
1336 },
1337 },
1338 ],
1339 }),
1340 undefined,
1341 (version) =>
1342 Effect.succeed(
1343 resolveProviderCompatibility(
1344 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
1345 CodexAdapterV2.CODEX_DRIVER_KIND,
1346 version,
1347 ),
1348 ),
1349 ).pipe(Effect.flip);
1350
1351 assert.instanceOf(failure, ProviderAdapter.ProviderAdapterOpenSessionError);
1352 assert.instanceOf(failure.cause, ProviderSetupError);
1353 assert.equal(
1354 failure.cause.message,
1355 "Codex 0.144.3 does not work with this T3 Code release. Update Codex to >=0.159.0, then retry.",
1356 );
1357 }).pipe(
1358 Effect.scoped,
1359 Effect.provide(
1360 Layer.mergeAll(
1361 IdAllocator.layer,
1362 McpProviderSessions.layer,
1363 NodeServices.layer,
1364 NodeCrypto.layer,
1365 ),
1366 ),
1367 ),
1368 );
1369
1370 it.effect("fails the open when initialize never answers during open", () =>
1371 Effect.gen(function* () {
1372 const initializeAwaitingResponse = yield* Deferred.make<void>();
1373 const opened = yield* openReplaySession(
1374 makeCodexReplayTranscript({
1375 scenario: "initialize-hung-open",
1376 entries: replayPreamble("initialize-hung-open").slice(0, 2),
1377 }),
1378 (entry) =>
1379 entry.label === "initialize"
1380 ? Deferred.succeed(initializeAwaitingResponse, undefined).pipe(
1381 Effect.andThen(Effect.never),
1382 )
1383 : Effect.void,
1384 () => Effect.die("initialize never answers"),
1385 ).pipe(Effect.flip, Effect.forkChild({ startImmediately: true }));
1386 yield* Deferred.await(initializeAwaitingResponse);
1387 yield* TestClock.adjust("30 seconds");
1388
1389 // The session manager discards a session whose open fails.
1390 assert.instanceOf(yield* Fiber.join(opened), ProviderAdapter.ProviderAdapterOpenSessionError);
1391 }).pipe(
1392 Effect.scoped,
1393 Effect.provide(
1394 Layer.mergeAll(
1395 IdAllocator.layer,
1396 McpProviderSessions.layer,
1397 NodeServices.layer,
1398 NodeCrypto.layer,
1399 ),
1400 ),
1401 ),
1402 );
1403
1404 it.effect("retires the shared session when initialize never answers", () =>
1405 Effect.gen(function* () {
1406 const initializeAwaitingResponse = yield* Deferred.make<void>();
1407 const session = yield* openReplaySession(
1408 makeCodexReplayTranscript({
1409 scenario: "initialize-hung",
1410 entries: replayPreamble("initialize-hung").slice(0, 2),
1411 }),
1412 (entry) =>
1413 entry.label === "initialize"
1414 ? Deferred.succeed(initializeAwaitingResponse, undefined).pipe(
1415 Effect.andThen(Effect.never),
1416 )
1417 : Effect.void,
1418 );
1419 const eventsExit = yield* Stream.runDrain(session.events).pipe(
1420 Effect.exit,
1421 Effect.forkChild({ startImmediately: true }),
1422 );
1423
1424 const ensured = yield* session
1425 .ensureThread("thread-initialize-hung")
1426 .pipe(Effect.flip, Effect.forkChild({ startImmediately: true }));
1427 yield* Deferred.await(initializeAwaitingResponse);
1428 const waiting = yield* session
1429 .ensureThread("thread-initialize-hung-waiting")
1430 .pipe(Effect.flip, Effect.forkChild({ startImmediately: true }));
1431 yield* TestClock.adjust("30 seconds");
1432
1433 assert.equal((yield* Fiber.join(ensured))._tag, "ProviderAdapterEnsureThreadError");
1434 // A waiter fails at once instead of re-sending initialize to the hung app-server.
1435 assert.equal((yield* Fiber.join(waiting))._tag, "ProviderAdapterEnsureThreadError");
1436 assert.equal(session.initializeRequests(), 1);
1437 // The session manager retires a session whose event stream fails.
1438 const exit = yield* Fiber.join(eventsExit);
1439 assert.isTrue(Exit.isFailure(exit));
1440 }).pipe(
1441 Effect.scoped,
1442 Effect.provide(
1443 Layer.mergeAll(
1444 IdAllocator.layer,
1445 McpProviderSessions.layer,
1446 NodeServices.layer,
1447 NodeCrypto.layer,
1448 ),
1449 ),
1450 ),
1451 );
1452
1453 it.effect("completes the handshake after a caller is interrupted mid-initialize", () =>
1454 Effect.gen(function* () {
1455 const initializeAwaitingResponse = yield* Deferred.make<void>();
1456 const releaseInitialize = yield* Deferred.make<void>();
1457 const preamble = replayPreamble("initialize-interrupted");
1458 const session = yield* openReplaySession(
1459 makeCodexReplayTranscript({
1460 scenario: "initialize-interrupted",
1461 entries: [
1462 ...preamble.slice(0, 2),
1463 ...preamble.slice(0, 1).map((entry) => withReplayRequestId(entry, 2)),
1464 {
1465 type: "emit_inbound",
1466 label: "initialize-rejected",
1467 frame: { id: 2, error: { code: -32600, message: "Already initialized" } },
1468 },
1469 ...preamble.slice(2, 3),
1470 ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)),
1471 ],
1472 }),
1473 (entry) =>
1474 entry.label === "initialize"
1475 ? Deferred.succeed(initializeAwaitingResponse, undefined).pipe(
1476 Effect.andThen(Deferred.await(releaseInitialize)),
1477 )
1478 : Effect.void,
1479 );
1480
1481 const interrupted = yield* session
1482 .ensureThread("thread-initialize-interrupted")
1483 .pipe(Effect.forkChild({ startImmediately: true }));
1484 yield* Deferred.await(initializeAwaitingResponse);
1485 yield* Fiber.interrupt(interrupted);
1486 yield* Deferred.succeed(releaseInitialize, undefined);
1487
1488 const providerThread = yield* session.ensureThread("thread-initialize-interrupted");
1489 assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-interrupted");
1490 assert.equal(session.initializeRequests(), 2);
1491 }).pipe(
1492 Effect.scoped,
1493 Effect.provide(
1494 Layer.mergeAll(
1495 IdAllocator.layer,
1496 McpProviderSessions.layer,
1497 NodeServices.layer,
1498 NodeCrypto.layer,
1499 ),
1500 ),
1501 ),
1502 );
1503 });
1504
1505 describe("CodexAdapterV2 post-settle continuation", () => {
1506 // The harness notifies after every recorded event or continuation, so a wait
1507 // re-checks exactly when the state it reads changes. Subscribing before the
1508 // first check means a change that lands in between is not lost.
1509 const makeChangeSignal = Effect.gen(function* () {
1510 const changes = yield* PubSub.unbounded<void>();
1511 const until = (predicate: () => boolean): Effect.Effect<void> =>
1512 Effect.scoped(
1513 Effect.gen(function* () {
1514 const subscription = yield* PubSub.subscribe(changes);
1515 while (!predicate()) yield* PubSub.take(subscription);
1516 }),
1517 );
1518 return { notify: PubSub.publish(changes, undefined), until };
1519 });
1520
1521 const makeCodexReplayHarness = (
1522 transcript: CodexReplay.CodexAppServerReplayTranscript,
1523 onEvent: (event: ProviderAdapter.ProviderAdapterV2Event) => Effect.Effect<unknown> = () =>
1524 Effect.void,
1525 onRequest: (method: string, params: unknown) => Effect.Effect<void> = () => Effect.void,
1526 readChildMetadata?: Parameters<typeof withCodexReplayChildMetadata>[2],
1527 beforeEmitInbound?: CodexReplay.CodexAppServerReplayDriver["beforeEmitInbound"],
1528 onUsageLimits?: CodexAdapterV2.CodexAdapterV2Options["onUsageLimits"],
1529 promptSuggestions: Effect.Effect<boolean> = Effect.succeed(false),
1530 onNotification: (method: string) => Effect.Effect<void> = () => Effect.void,
1531 models?: CodexAdapterV2.CodexAdapterV2Options["models"],
1532 ) =>
1533 Effect.gen(function* () {
1534 const fileSystem = yield* FileSystem.FileSystem;
1535 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1536 const serverConfig = yield* ProviderReplayHarness.makeReplayServerConfig(
1537 transcript.scenario,
1538 ).pipe(Effect.orDie);
1539 const changes = yield* makeChangeSignal;
1540 const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
1541 [];
1542 const commandStopWatchers: Array<PortScanner.AgentCommandStopWatcher> = [];
1543 const driver = yield* CodexReplay.makeReplayDriver(
1544 withConfigReads(transcript),
1545 beforeEmitInbound === undefined ? {} : { beforeEmitInbound },
1546 );
1547 const clientFactory: CodexAdapterV2.CodexAppServerClientFactoryShape = {
1548 open: (openInput) =>
1549 Layer.build(CodexReplay.layerReplayWithDriver(driver)).pipe(
1550 Effect.mapError(
1551 (cause) =>
1552 new ProviderAdapter.ProviderAdapterOpenSessionError({
1553 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
1554 providerSessionId: openInput.providerSessionId,
1555 cause,
1556 }),
1557 ),
1558 Effect.flatMap((context) =>
1559 Effect.service(CodexClient.CodexAppServerClient).pipe(
1560 Effect.map((client) =>
1561 withCodexReplayChildMetadata(client, transcript, readChildMetadata),
1562 ),
1563 Effect.map(
1564 (client) =>
1565 ({
1566 ...client,
1567 request: (method, params) =>
1568 onRequest(method, params).pipe(
1569 Effect.andThen(client.request(method, params)),
1570 ),
1571 handleServerNotification: (method, handler) =>
1572 client.handleServerNotification(method, (payload) =>
1573 onNotification(method).pipe(Effect.andThen(handler(payload))),
1574 ),
1575 raw: {
1576 ...client.raw,
1577 request: (method, params) =>
1578 onRequest(method, params).pipe(
1579 Effect.andThen(client.raw.request(method, params)),
1580 ),
1581 },
1582 }) satisfies CodexClient.CodexAppServerClient["Service"],
1583 ),
1584 Effect.provide(context),
1585 ),
1586 ),
1587 ),
1588 };
1589 const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({
1590 instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID,
1591 settings: DEFAULT_CODEX_SETTINGS,
1592 environment: {},
1593 clientFactory,
1594 ...(onUsageLimits ? { onUsageLimits } : {}),
1595 ...(models ? { models } : {}),
1596 digest: yield* Digest.Digest,
1597 fileSystem,
1598 idAllocator,
1599 serverConfig,
1600 continuationRequests: {
1601 offer: (request) =>
1602 Effect.sync(() => {
1603 continuationRequests.push(request);
1604 }).pipe(Effect.andThen(changes.notify)),
1605 },
1606 watchCommandStops: (watcher) =>
1607 Effect.sync(() => {
1608 commandStopWatchers.push(watcher);
1609 }),
1610 });
1611 const threadId = ThreadId.make(`thread-${transcript.scenario}`);
1612 const runtime = yield* adapter.openSession({
1613 threadId,
1614 providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`),
1615 modelSelection: CODEX_TEST_MODEL_SELECTION,
1616 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
1617 promptSuggestions,
1618 });
1619 const providerThread = yield* runtime.ensureThread({
1620 threadId,
1621 modelSelection: CODEX_TEST_MODEL_SELECTION,
1622 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
1623 });
1624 const events: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
1625 const firstTerminal = yield* Deferred.make<void>();
1626 yield* runtime.events.pipe(
1627 Stream.runForEach((event) =>
1628 Effect.sync(() => {
1629 events.push(event);
1630 }).pipe(
1631 Effect.andThen(
1632 event.type === "turn.terminal"
1633 ? Deferred.succeed(firstTerminal, undefined)
1634 : Effect.void,
1635 ),
1636 Effect.andThen(changes.notify),
1637 Effect.andThen(onEvent(event)),
1638 ),
1639 ),
1640 Effect.forkScoped,
1641 );
1642 if (runtime.hasPendingBackgroundWork === undefined) {
1643 return yield* Effect.die("Codex adapter runtime must expose hasPendingBackgroundWork.");
1644 }
1645 const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork;
1646 const terminalEvents = () =>
1647 events.filter(
1648 (
1649 event,
1650 ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }> =>
1651 event.type === "turn.terminal",
1652 );
1653 const subagentUpdates = () =>
1654 events.filter(
1655 (
1656 event,
1657 ): event is Extract<
1658 ProviderAdapter.ProviderAdapterV2Event,
1659 { type: "subagent.updated" }
1660 > => event.type === "subagent.updated",
1661 );
1662 return {
1663 runtime,
1664 providerThread,
1665 threadId,
1666 serverConfig,
1667 events,
1668 continuationRequests,
1669 commandStopWatchers,
1670 terminalEvents,
1671 subagentUpdates,
1672 hasPendingBackgroundWork,
1673 firstTerminal: Deferred.await(firstTerminal),
1674 until: changes.until,
1675 awaitTerminal: (count: number) => changes.until(() => terminalEvents().length >= count),
1676 };
1677 });
1678
1679 it.effect.each([
1680 { runtimeMode: "full-access", turnIdKind: "present" },
1681 { runtimeMode: "auto-accept-edits", turnIdKind: "null" },
1682 ] as const)(
1683 "handles MCP access approvals in $runtimeMode with a $turnIdKind turn id",
1684 ({ runtimeMode, turnIdKind }) =>
1685 Effect.gen(function* () {
1686 const nativeThreadId = "mcp-approval-thread";
1687 const nativeTurnId = "mcp-approval-turn";
1688 const prompt = "Read the dashboard in Chrome.";
1689 const pending = yield* Queue.unbounded<OrchestrationV2RuntimeRequest>();
1690 const harness = yield* makeCodexReplayHarness(
1691 makeCodexReplayTranscript({
1692 scenario: `mcp-approval-${turnIdKind}`,
1693 entries: [
1694 ...codexReplayPreamble({
1695 nativeThreadId,
1696 nativeTurnId,
1697 prompt,
1698 ...(runtimeMode === "full-access"
1699 ? {}
1700 : {
1701 turnPolicy: {
1702 approvalPolicy: "on-request",
1703 sandboxPolicy: { type: "workspaceWrite" },
1704 },
1705 }),
1706 }),
1707 {
1708 type: "emit_inbound",
1709 frame: {
1710 id: 0,
1711 method: "mcpServer/elicitation/request",
1712 params: {
1713 threadId: nativeThreadId,
1714 turnId: turnIdKind === "null" ? null : nativeTurnId,
1715 serverName: "browser",
1716 mode: "form",
1717 message: "Allow ChatGPT to use Google Chrome?",
1718 requestedSchema: {
1719 type: "object",
1720 properties: { approval: { type: "string", enum: ["once", "always"] } },
1721 required: ["approval"],
1722 },
1723 },
1724 },
1725 },
1726 {
1727 type: "expect_outbound",
1728 frame: { id: 0, result: { action: "accept", content: { approval: "once" } } },
1729 },
1730 {
1731 type: "emit_inbound",
1732 frame: {
1733 method: "turn/completed",
1734 params: {
1735 threadId: nativeThreadId,
1736 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
1737 },
1738 },
1739 },
1740 ],
1741 }),
1742 (event) =>
1743 event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending"
1744 ? Queue.offer(pending, event.runtimeRequest)
1745 : Effect.void,
1746 );
1747 const turnInput = makeCodexTestTurnInput({
1748 threadId: harness.threadId,
1749 providerThread: harness.providerThread,
1750 now: yield* DateTime.now,
1751 attemptId: RunAttemptId.make(`mcp-approval-${turnIdKind}-attempt`),
1752 text: prompt,
1753 });
1754 yield* harness.runtime.startTurn({
1755 ...turnInput,
1756 runtimePolicy: { ...turnInput.runtimePolicy, runtimeMode },
1757 });
1758 if (runtimeMode === "full-access") {
1759 const request = yield* Effect.raceFirst(
1760 harness.firstTerminal.pipe(Effect.as(undefined)),
1761 Queue.take(pending),
1762 );
1763 assert.isUndefined(request, "Full access must not wait for an MCP approval");
1764 assert.deepEqual(
1765 harness.terminalEvents().map((event) => event.status),
1766 ["completed"],
1767 );
1768 return;
1769 }
1770 const request = yield* Effect.raceFirst(
1771 Queue.take(pending),
1772 harness.firstTerminal.pipe(Effect.andThen(Effect.die("MCP approval was not presented"))),
1773 );
1774 assert.equal(request.kind, "mcp-elicitation");
1775 const approvals = harness.events.flatMap((event) =>
1776 event.type === "turn_item.updated" &&
1777 event.turnItem.type === "approval_request" &&
1778 event.turnItem.requestId === request.id
1779 ? [event.turnItem]
1780 : [],
1781 );
1782 assert.deepEqual(
1783 approvals.map((approval) => [approval.threadId, approval.appName, approval.prompt]),
1784 [[harness.threadId, "Google Chrome", "Allow ChatGPT to use Google Chrome?"]],
1785 );
1786 yield* harness.runtime.respondToRuntimeRequest({
1787 requestId: request.id,
1788 decision: "accept",
1789 });
1790 yield* harness.firstTerminal;
1791 assert.deepEqual(
1792 harness.terminalEvents().map((event) => event.status),
1793 ["completed"],
1794 );
1795 }).pipe(
1796 Effect.scoped,
1797 Effect.provide(
1798 Layer.mergeAll(
1799 IdAllocator.layer,
1800 McpProviderSessions.layer,
1801 NodeServices.layer,
1802 NodeCrypto.layer,
1803 ),
1804 ),
1805 ),
1806 );
1807
1808 it.effect.each(["native", "ordinary"] as const)(
1809 "resumes Codex without a prompt only for an existing conversation (%s)",
1810 (mode) =>
1811 Effect.gen(function* () {
1812 const nativeThreadId = `resume-${mode}`;
1813 const nativeTurnId = `resume-turn-${mode}`;
1814 const preamble = codexReplayPreamble({
1815 nativeThreadId,
1816 nativeTurnId,
1817 prompt: "Hello",
1818 });
1819 const harness = yield* makeCodexReplayHarness(
1820 makeCodexReplayTranscript({
1821 scenario: `manual-resume-${mode}`,
1822 entries: [
1823 ...preamble.map((entry) =>
1824 mode === "native" &&
1825 entry.type === "expect_outbound" &&
1826 Predicate.isObject(entry.frame) &&
1827 Predicate.isObject(entry.frame.params) &&
1828 entry.frame.method === "turn/start"
1829 ? {
1830 ...entry,
1831 frame: {
1832 ...entry.frame,
1833 params: {
1834 ...entry.frame.params,
1835 input: [],
1836 },
1837 },
1838 }
1839 : entry,
1840 ),
1841 {
1842 type: "emit_inbound",
1843 frame: {
1844 method: "turn/completed",
1845 params: {
1846 threadId: nativeThreadId,
1847 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
1848 },
1849 },
1850 },
1851 ],
1852 }),
1853 );
1854 const input = {
1855 ...makeCodexTestTurnInput({
1856 threadId: harness.threadId,
1857 providerThread: harness.providerThread,
1858 now: yield* DateTime.now,
1859 attemptId: RunAttemptId.make(`resume-${mode}`),
1860 text: "Hello",
1861 }),
1862 nativeThreadHasTurns: true,
1863 };
1864 const { message, ...resumeInput } = input;
1865 if (mode === "native")
1866 yield* harness.runtime.resumeTurn!({ ...resumeInput, messageId: message.messageId });
1867 else yield* harness.runtime.startTurn(input);
1868 yield* harness.firstTerminal;
1869 assert.equal(harness.terminalEvents()[0]?.status, "completed");
1870 }).pipe(
1871 Effect.scoped,
1872 Effect.provide(
1873 Layer.mergeAll(
1874 IdAllocator.layer,
1875 McpProviderSessions.layer,
1876 NodeServices.layer,
1877 NodeCrypto.layer,
1878 ),
1879 ),
1880 ),
1881 );
1882
1883 it.effect.each([
1884 { codex: "accepts", reply: { result: {} } },
1885 { codex: "rejects", reply: { error: { code: -32601, message: "Method not found" } } },
1886 ] as const)(
1887 "a steer that changes the service tier still steers when Codex $codex the settings update",
1888 ({ codex, reply }) =>
1889 Effect.gen(function* () {
1890 const nativeThreadId = `steer-tier-thread-${codex}`;
1891 const nativeTurnId = `steer-tier-turn-${codex}`;
1892 const harness = yield* makeCodexReplayHarness(
1893 makeCodexReplayTranscript({
1894 scenario: `steer-service-tier-${codex}`,
1895 entries: [
1896 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }),
1897 {
1898 type: "expect_outbound",
1899 label: "thread/settings/update",
1900 frame: {
1901 id: 4,
1902 method: "thread/settings/update",
1903 params: { threadId: nativeThreadId, serviceTier: "fast" },
1904 },
1905 },
1906 { type: "emit_inbound", frame: { id: 4, ...reply } },
1907 {
1908 type: "expect_outbound",
1909 label: "turn/steer",
1910 frame: {
1911 id: 5,
1912 method: "turn/steer",
1913 params: {
1914 threadId: nativeThreadId,
1915 expectedTurnId: nativeTurnId,
1916 input: [{ type: "text", text: "Hurry up." }],
1917 },
1918 },
1919 },
1920 { type: "emit_inbound", frame: { id: 5, result: { turnId: nativeTurnId } } },
1921 {
1922 type: "emit_inbound",
1923 frame: {
1924 method: "turn/completed",
1925 params: {
1926 threadId: nativeThreadId,
1927 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
1928 },
1929 },
1930 },
1931 ],
1932 }),
1933 );
1934 const turnInput = makeCodexTestTurnInput({
1935 threadId: harness.threadId,
1936 providerThread: harness.providerThread,
1937 now: yield* DateTime.now,
1938 attemptId: RunAttemptId.make("steer-tier-attempt"),
1939 text: "Work.",
1940 });
1941 yield* harness.runtime.startTurn(turnInput);
1942 yield* harness.until(() =>
1943 harness.events.some(
1944 (event) =>
1945 event.type === "provider_turn.updated" &&
1946 event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId,
1947 ),
1948 );
1949 const providerTurnId = harness.events.flatMap((event) =>
1950 event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
1951 )[0];
1952 assert.isDefined(providerTurnId);
1953 if (providerTurnId === undefined) return;
1954 yield* harness.runtime.steerTurn({
1955 ...turnInput,
1956 providerTurnId,
1957 modelSelection: {
1958 ...CODEX_TEST_MODEL_SELECTION,
1959 options: [{ id: "serviceTier", value: "fast" }],
1960 },
1961 message: { ...turnInput.message, text: "Hurry up." },
1962 });
1963 yield* harness.firstTerminal;
1964 assert.equal(harness.terminalEvents()[0]?.status, "completed");
1965 }).pipe(
1966 Effect.scoped,
1967 Effect.provide(
1968 Layer.mergeAll(
1969 IdAllocator.layer,
1970 McpProviderSessions.layer,
1971 NodeServices.layer,
1972 NodeCrypto.layer,
1973 ),
1974 ),
1975 ),
1976 );
1977
1978 // regression: #38541 an MCP app note that changes mid-turn reaches the next steer, once.
1979 it.effect("steers carry MCP app notes Codex has not been sent", () =>
1980 Effect.gen(function* () {
1981 const nativeThreadId = "steer-app-context-thread";
1982 const nativeTurnId = "steer-app-context-turn";
1983 const note = "<external_mcp_app_item-1>Pressed: blue</external_mcp_app_item-1>";
1984 const steerFrame = (id: number, input: ReadonlyArray<string>) =>
1985 [
1986 {
1987 type: "expect_outbound",
1988 label: "turn/steer",
1989 frame: {
1990 id,
1991 method: "turn/steer",
1992 params: {
1993 threadId: nativeThreadId,
1994 expectedTurnId: nativeTurnId,
1995 input: input.map((text) => ({ type: "text", text })),
1996 },
1997 },
1998 },
1999 { type: "emit_inbound", frame: { id, result: { turnId: nativeTurnId } } },
2000 ] as const;
2001 const harness = yield* makeCodexReplayHarness(
2002 makeCodexReplayTranscript({
2003 scenario: "steer-app-context",
2004 entries: [
2005 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }),
2006 ...steerFrame(4, [note, "What did the app report?"]),
2007 ...steerFrame(5, ["And now?"]),
2008 {
2009 type: "emit_inbound",
2010 frame: {
2011 method: "turn/completed",
2012 params: {
2013 threadId: nativeThreadId,
2014 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2015 },
2016 },
2017 },
2018 ],
2019 }),
2020 );
2021 const turnInput = makeCodexTestTurnInput({
2022 threadId: harness.threadId,
2023 providerThread: harness.providerThread,
2024 now: yield* DateTime.now,
2025 attemptId: RunAttemptId.make("steer-app-context-attempt"),
2026 text: "Work.",
2027 });
2028 yield* harness.runtime.startTurn(turnInput);
2029 yield* harness.until(() =>
2030 harness.events.some(
2031 (event) =>
2032 event.type === "provider_turn.updated" &&
2033 event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId,
2034 ),
2035 );
2036 const providerTurnId = harness.events.flatMap((event) =>
2037 event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
2038 )[0];
2039 assert.isDefined(providerTurnId);
2040 if (providerTurnId === undefined) return;
2041 const appContext = [{ key: "mcp_app_item-1", text: "Pressed: blue" }];
2042 yield* harness.runtime.steerTurn({
2043 ...turnInput,
2044 providerTurnId,
2045 appContext,
2046 message: { ...turnInput.message, text: "What did the app report?" },
2047 });
2048 yield* harness.runtime.steerTurn({
2049 ...turnInput,
2050 providerTurnId,
2051 appContext,
2052 message: { ...turnInput.message, text: "And now?" },
2053 });
2054 yield* harness.firstTerminal;
2055 assert.equal(harness.terminalEvents()[0]?.status, "completed");
2056 }).pipe(
2057 Effect.scoped,
2058 Effect.provide(
2059 Layer.mergeAll(
2060 IdAllocator.layer,
2061 McpProviderSessions.layer,
2062 NodeServices.layer,
2063 NodeCrypto.layer,
2064 ),
2065 ),
2066 ),
2067 );
2068
2069 it.effect("a speed change with no message updates Codex's next-turn settings", () =>
2070 Effect.gen(function* () {
2071 const nativeThreadId = "picker-tier-thread";
2072 const nativeTurnId = "picker-tier-turn";
2073 const harness = yield* makeCodexReplayHarness(
2074 makeCodexReplayTranscript({
2075 scenario: "picker-service-tier",
2076 entries: [
2077 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }),
2078 {
2079 type: "expect_outbound",
2080 label: "thread/settings/update",
2081 frame: {
2082 id: 4,
2083 method: "thread/settings/update",
2084 params: { threadId: nativeThreadId, serviceTier: "default" },
2085 },
2086 },
2087 { type: "emit_inbound", frame: { id: 4, result: {} } },
2088 {
2089 type: "emit_inbound",
2090 frame: {
2091 method: "turn/completed",
2092 params: {
2093 threadId: nativeThreadId,
2094 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2095 },
2096 },
2097 },
2098 ],
2099 }),
2100 );
2101 yield* harness.runtime.startTurn(
2102 makeCodexTestTurnInput({
2103 threadId: harness.threadId,
2104 providerThread: harness.providerThread,
2105 now: yield* DateTime.now,
2106 attemptId: RunAttemptId.make("picker-tier-attempt"),
2107 text: "Work.",
2108 }),
2109 );
2110 yield* harness.until(() =>
2111 harness.events.some(
2112 (event) =>
2113 event.type === "provider_turn.updated" &&
2114 event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId,
2115 ),
2116 );
2117 assert.isDefined(harness.runtime.applyModelSelection);
2118 yield* (
2119 harness.runtime.applyModelSelection?.({
2120 providerThread: harness.providerThread,
2121 modelSelection: {
2122 ...CODEX_TEST_MODEL_SELECTION,
2123 options: [{ id: "serviceTier", value: "default" }],
2124 },
2125 }) ?? Effect.void
2126 );
2127 yield* harness.firstTerminal;
2128 assert.equal(harness.terminalEvents()[0]?.status, "completed");
2129 }).pipe(
2130 Effect.scoped,
2131 Effect.provide(
2132 Layer.mergeAll(
2133 IdAllocator.layer,
2134 McpProviderSessions.layer,
2135 NodeServices.layer,
2136 NodeCrypto.layer,
2137 ),
2138 ),
2139 ),
2140 );
2141
2142 it.effect("keeps native image views available to the clients", () =>
2143 Effect.gen(function* () {
2144 const nativeThreadId = "image-view-thread";
2145 const nativeTurnId = "image-view-turn";
2146 const imagePath = "file:///workspace/reference.png";
2147 const harness = yield* makeCodexReplayHarness(
2148 makeCodexReplayTranscript({
2149 scenario: "image-view",
2150 entries: [
2151 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Show the reference." }),
2152 ...(["started", "completed"] as const).map((phase) => ({
2153 type: "emit_inbound" as const,
2154 label: `image ${phase}`,
2155 frame: {
2156 method: `item/${phase}`,
2157 params: {
2158 threadId: nativeThreadId,
2159 turnId: nativeTurnId,
2160 item: { type: "imageView", id: "image-view", path: imagePath },
2161 ...(phase === "started" ? { startedAtMs: 1 } : { completedAtMs: 2 }),
2162 },
2163 },
2164 })),
2165 {
2166 type: "emit_inbound",
2167 label: "turn completed",
2168 frame: {
2169 method: "turn/completed",
2170 params: {
2171 threadId: nativeThreadId,
2172 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2173 },
2174 },
2175 },
2176 ],
2177 }),
2178 );
2179 yield* harness.runtime.startTurn(
2180 makeCodexTestTurnInput({
2181 threadId: harness.threadId,
2182 providerThread: harness.providerThread,
2183 now: yield* DateTime.now,
2184 attemptId: RunAttemptId.make("image-view-attempt"),
2185 text: "Show the reference.",
2186 }),
2187 );
2188 yield* harness.firstTerminal;
2189 const images = harness.events.flatMap((event) =>
2190 event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
2191 ? [event.turnItem]
2192 : [],
2193 );
2194 assert.lengthOf(images, 1);
2195 assert.equal(images[0]?.viewedImagePath, imagePath);
2196 assert.equal(images[0]?.status, "completed");
2197 }).pipe(
2198 Effect.scoped,
2199 Effect.provide(
2200 Layer.mergeAll(
2201 IdAllocator.layer,
2202 McpProviderSessions.layer,
2203 NodeServices.layer,
2204 NodeCrypto.layer,
2205 ),
2206 ),
2207 ),
2208 );
2209
2210 it.effect.each(["before", "after"] as const)(
2211 "rejects a previous run's native turn when it completes %s the new start response",
2212 (completionOrder) =>
2213 Effect.gen(function* () {
2214 const nativeThreadId = "reused-turn-thread";
2215 const nativeTurnId = "reused-turn";
2216 const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" });
2217 const retry = codexReplayPreamble({
2218 nativeThreadId,
2219 nativeTurnId: "retry-turn",
2220 prompt: "work",
2221 });
2222 const completion: CodexReplay.CodexAppServerReplayEntry = {
2223 type: "emit_inbound",
2224 label: "original turn completed",
2225 frame: {
2226 method: "turn/completed",
2227 params: {
2228 threadId: nativeThreadId,
2229 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2230 },
2231 },
2232 };
2233 const harness = yield* makeCodexReplayHarness(
2234 makeCodexReplayTranscript({
2235 scenario: `reused-turn-${completionOrder}`,
2236 entries: [
2237 ...preamble,
2238 withReplayRequestId(preamble[5]!, 4),
2239 ...(completionOrder === "before" ? [completion] : []),
2240 withReplayRequestId(preamble[6]!, 4),
2241 ...(completionOrder === "after" ? [completion] : []),
2242 ...retry.slice(5, 7).map((entry) => withReplayRequestId(entry, 5)),
2243 {
2244 type: "emit_inbound",
2245 label: "retry completed",
2246 frame: {
2247 method: "turn/completed",
2248 params: {
2249 threadId: nativeThreadId,
2250 turn: makeCodexReplayTurn({ id: "retry-turn", status: "completed" }),
2251 },
2252 },
2253 },
2254 ],
2255 }),
2256 );
2257 const first = makeCodexTestTurnInput({
2258 threadId: harness.threadId,
2259 providerThread: harness.providerThread,
2260 now: yield* DateTime.now,
2261 attemptId: RunAttemptId.make("original"),
2262 text: "work",
2263 });
2264 yield* harness.runtime.startTurn(first);
2265 const result = yield* harness.runtime
2266 .startTurn({
2267 ...first,
2268 runId: RunId.make("replacement"),
2269 attemptId: RunAttemptId.make("replacement"),
2270 rootNodeId: NodeId.make("replacement"),
2271 runOrdinal: 2,
2272 providerTurnOrdinal: 2,
2273 })
2274 .pipe(Effect.result);
2275 assert.equal(result._tag, "Failure", "a different run must not adopt the original turn");
2276 if (result._tag !== "Failure") return;
2277 const failure = result.failure;
2278 assert.equal(failure._tag, "ProviderAdapterTurnStartError");
2279 assert.instanceOf(failure.cause, ProviderAdapter.ProviderAdapterProtocolError);
2280 yield* harness.firstTerminal;
2281 assert.deepEqual(
2282 harness.terminalEvents().map((event) => event.runOrdinal),
2283 [1],
2284 );
2285 yield* harness.runtime.startTurn({
2286 ...first,
2287 runId: RunId.make("retry"),
2288 attemptId: RunAttemptId.make("retry"),
2289 rootNodeId: NodeId.make("retry"),
2290 runOrdinal: 3,
2291 providerTurnOrdinal: 3,
2292 });
2293 yield* harness.awaitTerminal(2);
2294 assert.deepEqual(
2295 harness.terminalEvents().map((event) => [event.runOrdinal, event.status]),
2296 [
2297 [1, "completed"],
2298 [3, "completed"],
2299 ],
2300 );
2301 }).pipe(
2302 Effect.scoped,
2303 Effect.provide(
2304 Layer.mergeAll(
2305 IdAllocator.layer,
2306 McpProviderSessions.layer,
2307 NodeServices.layer,
2308 NodeCrypto.layer,
2309 ),
2310 ),
2311 ),
2312 );
2313
2314 it.effect.each(["supported", "unsupported", "invalid"] as const)(
2315 "delivers native history with %s app-server protocol",
2316 (response) =>
2317 Effect.gen(function* () {
2318 const nativeThreadId = `inject-${response}`;
2319 const prompt = "Only the current request";
2320 const history: ProviderAdapter.ProviderAdapterV2HistoricalContext = {
2321 context: "Historical conversation",
2322 messages: (["user", "assistant"] as const).map((role) => ({
2323 role,
2324 text:
2325 role === "user"
2326 ? "Original request\n" + "界".repeat(300)
2327 : "Partial interrupted work",
2328 threadId: ThreadId.make("source"),
2329 runId: RunId.make("source-run"),
2330 itemId: TurnItemId.make(`source-${role}`),
2331 providerThreadId: null,
2332 kind: `${role}_message`,
2333 status: "interrupted",
2334 })),
2335 };
2336 const items = historyResponseItems(history.messages, history.context);
2337 const preamble = codexReplayPreamble({
2338 nativeThreadId,
2339 nativeTurnId: "current-turn",
2340 prompt,
2341 });
2342 const transcript = makeCodexReplayTranscript({
2343 scenario: `inject-${response}`,
2344 entries: [
2345 ...preamble.slice(0, -3),
2346 {
2347 type: "expect_outbound",
2348 label: "inject",
2349 frame: {
2350 id: 3,
2351 method: "thread/inject_items",
2352 params: { threadId: nativeThreadId, items },
2353 },
2354 },
2355 {
2356 type: "emit_inbound",
2357 label: "inject-result",
2358 frame:
2359 response === "supported"
2360 ? { id: 3, result: {} }
2361 : {
2362 id: 3,
2363 error: {
2364 code: response === "unsupported" ? -32601 : -32602,
2365 message: "Injection rejected",
2366 },
2367 },
2368 },
2369 ...(response === "invalid"
2370 ? []
2371 : preamble
2372 .slice(-3)
2373 .map((entry) =>
2374 "frame" in entry && Predicate.isObject(entry.frame) && "id" in entry.frame
2375 ? { ...entry, frame: { ...entry.frame, id: 4 } }
2376 : entry,
2377 )),
2378 ],
2379 });
2380 const requests: string[] = [];
2381 const harness = yield* makeCodexReplayHarness(
2382 transcript,
2383 () => Effect.void,
2384 (method) =>
2385 Effect.sync(() => {
2386 requests.push(method);
2387 }),
2388 );
2389 const injection = yield* harness.runtime.injectHistory!({
2390 providerThread: harness.providerThread,
2391 ...history,
2392 }).pipe(Effect.result);
2393 if (response === "invalid") {
2394 assert.equal(injection._tag, "Failure");
2395 if (injection._tag === "Failure") {
2396 assert.equal(injection.failure._tag, "ProviderAdapterProtocolError");
2397 assert.propertyVal(injection.failure.cause, "code", -32602);
2398 assert.notProperty(injection.failure, "payload");
2399 }
2400 assert.notInclude(requests, "turn/start");
2401 return;
2402 }
2403 assert.equal(injection._tag, "Success");
2404 if (injection._tag === "Success") assert.equal(injection.success, response === "supported");
2405 yield* harness.runtime.startTurn(
2406 makeCodexTestTurnInput({
2407 threadId: harness.threadId,
2408 providerThread: harness.providerThread,
2409 now: yield* DateTime.now,
2410 attemptId: RunAttemptId.make("inject-attempt"),
2411 text: prompt,
2412 }),
2413 );
2414 assert.equal(requests.filter((method) => method === "turn/start").length, 1);
2415 assert.isBelow(requests.indexOf("thread/inject_items"), requests.indexOf("turn/start"));
2416 }).pipe(
2417 Effect.scoped,
2418 Effect.provide(
2419 Layer.mergeAll(
2420 IdAllocator.layer,
2421 McpProviderSessions.layer,
2422 NodeServices.layer,
2423 NodeCrypto.layer,
2424 ),
2425 ),
2426 ),
2427 );
2428
2429 it.effect("adds the session MCP server and gives stdio servers the thread id", () =>
2430 Effect.gen(function* () {
2431 const scenario = "launch-mcp-servers";
2432 yield* (yield* McpProviderSessions.McpProviderSessions).set({
2433 environmentId: EnvironmentId.make("environment-codex-mcp"),
2434 threadId: ThreadId.make(`thread-${scenario}`),
2435 providerSessionId: `provider-session-${scenario}`,
2436 providerInstanceId: ProviderInstanceId.make("codex"),
2437 endpoint: "http://127.0.0.1:43123/mcp",
2438 authorizationHeader: "Bearer secret-codex-token",
2439 browserToolsAvailable: true,
2440 });
2441 const requests: Array<unknown> = [];
2442 const preamble = codexReplayPreamble({
2443 nativeThreadId: "launch-mcp-thread",
2444 nativeTurnId: "unused",
2445 prompt: "unused",
2446 });
2447 yield* makeCodexReplayHarness(
2448 makeCodexReplayTranscript({
2449 scenario,
2450 entries: [
2451 ...preamble.slice(0, 3),
2452 {
2453 type: "expect_outbound",
2454 label: "config/read",
2455 frame: { id: 2, method: "config/read", params: { includeLayers: false } },
2456 },
2457 {
2458 type: "emit_inbound",
2459 label: "config/read",
2460 frame: {
2461 id: 2,
2462 result: {
2463 config: {
2464 mcp_servers: {
2465 envprobe: { command: "python3", env: { FOO: "bar" } },
2466 remote: { url: "https://example.com/mcp" },
2467 "dotted.name": { command: "node" },
2468 },
2469 },
2470 origins: {},
2471 },
2472 },
2473 },
2474 ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)),
2475 ],
2476 }),
2477 () => Effect.void,
2478 (method, params) =>
2479 Effect.sync(() => {
2480 if (method === "thread/start") requests.push(params);
2481 }),
2482 );
2483 assert.deepEqual(requests, [
2484 {
2485 cwd: "/workspace",
2486 model: "gpt-5.4",
2487 config: {
2488 "tools.update_plan.enabled": true,
2489 mcp_optional_startup_grace_ms: 10_000,
2490 "features.concurrent_reasoning_summaries": true,
2491 "shell_environment_policy.set.T3CODE_THREAD_ID": `thread-${scenario}`,
2492 "mcp_servers.envprobe.env.T3CODE_THREAD_ID": `thread-${scenario}`,
2493 "mcp_servers.t3-code": {
2494 url: "http://127.0.0.1:43123/mcp",
2495 tool_timeout_sec: 3_900,
2496 http_headers: { Authorization: "Bearer secret-codex-token" },
2497 disabled_tools: ["t3_thread_wait", "delegate_task"],
2498 },
2499 "mcp_servers.t3-code-direct": {
2500 url: "http://127.0.0.1:43123/mcp",
2501 tool_timeout_sec: 3_900,
2502 http_headers: { Authorization: "Bearer secret-codex-token" },
2503 enabled_tools: ["t3_thread_wait", "delegate_task"],
2504 omit_tools_from: ["code_mode", "deferred"],
2505 },
2506 },
2507 },
2508 ]);
2509 }).pipe(
2510 Effect.scoped,
2511 Effect.provide(
2512 Layer.mergeAll(
2513 IdAllocator.layer,
2514 McpProviderSessions.layer,
2515 NodeServices.layer,
2516 NodeCrypto.layer,
2517 ),
2518 ),
2519 ),
2520 );
2521
2522 // regression: #36520 MCP servers can tell a delegate_task child from a user thread
2523 it.effect("starts delegate_task children with the subagent thread source", () =>
2524 Effect.gen(function* () {
2525 const scenario = "delegated-thread-source";
2526 const preamble = codexReplayPreamble({
2527 nativeThreadId: "delegated-parent-thread",
2528 nativeTurnId: "unused",
2529 prompt: "unused",
2530 }).slice(0, 5);
2531 const childStart = codexReplayPreamble({
2532 nativeThreadId: "delegated-child-thread",
2533 nativeTurnId: "unused",
2534 prompt: "unused",
2535 })
2536 .slice(3, 5)
2537 .map((entry) => withReplayRequestId(entry, 3))
2538 .map((entry) =>
2539 entry.type === "expect_outbound" &&
2540 Predicate.isObject(entry.frame) &&
2541 Predicate.isObject(entry.frame["params"])
2542 ? {
2543 ...entry,
2544 frame: {
2545 ...entry.frame,
2546 params: { ...entry.frame["params"], threadSource: "subagent" },
2547 },
2548 }
2549 : entry,
2550 );
2551 const threadSources: Array<unknown> = [];
2552 const harness = yield* makeCodexReplayHarness(
2553 makeCodexReplayTranscript({ scenario, entries: [...preamble, ...childStart] }),
2554 () => Effect.void,
2555 (method, params) =>
2556 Effect.sync(() => {
2557 if (method === "thread/start" && Predicate.isObject(params)) {
2558 threadSources.push(params["threadSource"]);
2559 }
2560 }),
2561 );
2562 const childThreadId = (yield* IdAllocator.IdAllocatorV2).derive.delegatedTaskThread({
2563 commandId: CommandId.make(`mcp:${scenario}:delegate-task:child`),
2564 });
2565 yield* harness.runtime.ensureThread({
2566 threadId: childThreadId,
2567 modelSelection: CODEX_TEST_MODEL_SELECTION,
2568 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
2569 });
2570 assert.deepEqual(threadSources, [undefined, "subagent"]);
2571 }).pipe(
2572 Effect.scoped,
2573 Effect.provide(
2574 Layer.mergeAll(
2575 IdAllocator.layer,
2576 McpProviderSessions.layer,
2577 NodeServices.layer,
2578 NodeCrypto.layer,
2579 ),
2580 ),
2581 ),
2582 );
2583
2584 // regression: #15839 launch-arg MCP servers survive the thread's t3-code server
2585 it.effect("replays historical and dotted MCP config while enforcing other thread config", () =>
2586 Effect.gen(function* () {
2587 const recordedServer = {
2588 url: "http://127.0.0.1:41000/mcp",
2589 http_headers: { Authorization: "Bearer recorded-token" },
2590 };
2591 const currentConfig = {
2592 "tools.update_plan.enabled": true,
2593 "mcp_servers.t3-code": {
2594 url: "http://127.0.0.1:42000/mcp",
2595 http_headers: { Authorization: "Bearer current-token" },
2596 },
2597 "mcp_servers.extra.command": "cat",
2598 };
2599 for (const recordedMcp of [
2600 { mcp_servers: { "t3-code": recordedServer } },
2601 { "mcp_servers.t3-code": recordedServer, "mcp_servers.extra.command": "echo" },
2602 ]) {
2603 const entries = codexReplayPreamble({
2604 nativeThreadId: "replayed-mcp-thread",
2605 nativeTurnId: "unused",
2606 prompt: "unused",
2607 })
2608 .slice(3, 5)
2609 .map((entry) => withReplayRequestId(entry, 1));
2610 entries[0] = {
2611 type: "expect_outbound",
2612 frame: {
2613 id: 1,
2614 method: "thread/start",
2615 params: { config: { "tools.update_plan.enabled": true, ...recordedMcp } },
2616 },
2617 };
2618 entries.push({
2619 ...entries[0],
2620 frame: {
2621 id: 2,
2622 method: "thread/start",
2623 params: { config: { "tools.update_plan.enabled": true, ...recordedMcp } },
2624 },
2625 });
2626 const driver = yield* CodexReplay.makeReplayDriver(
2627 makeCodexReplayTranscript({
2628 scenario: "mcp-config-normalization",
2629 entries,
2630 }),
2631 );
2632 yield* Effect.gen(function* () {
2633 const client = yield* CodexClient.CodexAppServerClient;
2634 const response = yield* client.request("thread/start", { config: currentConfig });
2635 assert.equal(response.thread.id, "replayed-mcp-thread");
2636 assert.isNull((yield* Ref.get(driver.state)).failure);
2637 yield* client
2638 .request("thread/start", {
2639 config: { ...currentConfig, "tools.update_plan.enabled": false },
2640 })
2641 .pipe(Effect.flip);
2642 assert.instanceOf(
2643 (yield* Ref.get(driver.state)).failure,
2644 CodexReplay.CodexAppServerReplayFrameMismatchError,
2645 );
2646 }).pipe(Effect.provide(CodexReplay.layerReplayWithDriver(driver)));
2647 }
2648 }),
2649 );
2650
2651 it.effect("waits for native start before interrupting an acknowledged queued turn", () =>
2652 Effect.gen(function* () {
2653 const nativeThreadId = "early-stop-thread";
2654 const nativeTurnId = "early-stop-turn";
2655 const prompt = "Run a command.";
2656 const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt });
2657 const transcript = makeCodexReplayTranscript({
2658 scenario: "early-stop-await-native-start",
2659 entries: [
2660 ...preamble.slice(0, -2),
2661 {
2662 type: "emit_inbound",
2663 label: "turn/start/queued",
2664 frame: {
2665 id: 3,
2666 result: {
2667 turn: {
2668 ...makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }),
2669 startedAt: null,
2670 },
2671 },
2672 },
2673 },
2674 {
2675 type: "emit_inbound",
2676 label: "turn/started",
2677 afterMs: 1000,
2678 frame: {
2679 method: "turn/started",
2680 params: {
2681 threadId: nativeThreadId,
2682 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }),
2683 },
2684 },
2685 },
2686 {
2687 type: "expect_outbound",
2688 label: "turn/interrupt",
2689 frame: {
2690 id: 4,
2691 method: "turn/interrupt",
2692 params: { threadId: nativeThreadId, turnId: nativeTurnId },
2693 },
2694 },
2695 { type: "emit_inbound", label: "turn/interrupt", frame: { id: 4, result: {} } },
2696 {
2697 type: "emit_inbound",
2698 label: "turn/completed",
2699 frame: {
2700 method: "turn/completed",
2701 params: {
2702 threadId: nativeThreadId,
2703 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "interrupted" }),
2704 },
2705 },
2706 },
2707 ],
2708 });
2709 let interruptSent = false;
2710 const harness = yield* makeCodexReplayHarness(
2711 transcript,
2712 () => Effect.void,
2713 (method) =>
2714 Effect.sync(() => {
2715 if (method === "turn/interrupt") interruptSent = true;
2716 }),
2717 );
2718 yield* harness.runtime.startTurn(
2719 makeCodexTestTurnInput({
2720 threadId: harness.threadId,
2721 providerThread: harness.providerThread,
2722 now: yield* DateTime.now,
2723 attemptId: RunAttemptId.make("early-stop-attempt"),
2724 text: prompt,
2725 }),
2726 );
2727 const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
2728 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
2729 nativeTurnId,
2730 });
2731 const interrupt = yield* harness.runtime
2732 .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
2733 .pipe(Effect.forkScoped);
2734 yield* TestClock.adjust("500 millis");
2735 assert.isFalse(interruptSent, "Stop must not reach Codex before native turn/started");
2736 yield* TestClock.adjust("500 millis");
2737 yield* Fiber.join(interrupt);
2738 yield* harness.firstTerminal;
2739 assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
2740 assert.lengthOf(harness.terminalEvents(), 1);
2741 assert.isFalse(yield* harness.hasPendingBackgroundWork);
2742 }).pipe(
2743 Effect.scoped,
2744 Effect.provide(
2745 Layer.mergeAll(
2746 IdAllocator.layer,
2747 McpProviderSessions.layer,
2748 NodeServices.layer,
2749 NodeCrypto.layer,
2750 ),
2751 ),
2752 ),
2753 );
2754
2755 it.effect.each(["subagent", "remote", "toggled-off"] as const)(
2756 "never samples a suggestion for a %s thread",
2757 (delegation) =>
2758 Effect.gen(function* () {
2759 const nativeThreadId = `suggest-${delegation}-thread`;
2760 const prompt = "Continue the task.";
2761 const first = codexReplayPreamble({
2762 nativeThreadId,
2763 nativeTurnId: `${delegation}-turn-1`,
2764 prompt,
2765 });
2766 const second = codexReplayPreamble({
2767 nativeThreadId,
2768 nativeTurnId: `${delegation}-turn-2`,
2769 prompt,
2770 });
2771 const completed = (nativeTurnId: string): CodexReplay.CodexAppServerReplayEntry => ({
2772 type: "emit_inbound",
2773 label: `${nativeTurnId} completed`,
2774 frame: {
2775 method: "turn/completed",
2776 params: {
2777 threadId: nativeThreadId,
2778 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2779 },
2780 },
2781 });
2782 // The second turn is a barrier: a stray sample from the first turn is sent before it ends.
2783 const requests: Array<string> = [];
2784 const enabled = yield* Ref.make(true);
2785 const harness = yield* makeCodexReplayHarness(
2786 makeCodexReplayTranscript({
2787 scenario: `prompt-suggestion-${delegation}`,
2788 entries: [
2789 ...first,
2790 completed(`${delegation}-turn-1`),
2791 ...second.slice(5, 7).map((entry) => withReplayRequestId(entry, 4)),
2792 completed(`${delegation}-turn-2`),
2793 ],
2794 }),
2795 undefined,
2796 (method) => Effect.sync(() => requests.push(method)),
2797 undefined,
2798 undefined,
2799 undefined,
2800 Ref.get(enabled),
2801 );
2802 // The flag is read per turn: turning it off after the session opened stops sampling.
2803 if (delegation === "toggled-off") yield* Ref.set(enabled, false);
2804 const base = makeCodexTestTurnInput({
2805 threadId: harness.threadId,
2806 providerThread: harness.providerThread,
2807 now: yield* DateTime.now,
2808 attemptId: RunAttemptId.make(`${delegation}-attempt-1`),
2809 text: prompt,
2810 });
2811 const parentThreadId = ThreadId.make("thread-codex-suggestion-parent");
2812 const turn = {
2813 ...base,
2814 appThread:
2815 delegation === "toggled-off"
2816 ? base.appThread
2817 : delegation === "subagent"
2818 ? {
2819 ...base.appThread,
2820 lineage: {
2821 parentThreadId,
2822 relationshipToParent: "subagent" as const,
2823 rootThreadId: parentThreadId,
2824 },
2825 }
2826 : {
2827 ...base.appThread,
2828 delegatedFrom: {
2829 environmentId: EnvironmentId.make("environment-codex-suggestion-parent"),
2830 threadId: parentThreadId,
2831 title: "Parent",
2832 },
2833 },
2834 };
2835 yield* harness.runtime.startTurn(turn);
2836 yield* harness.awaitTerminal(1);
2837 yield* harness.runtime.startTurn({
2838 ...turn,
2839 runId: RunId.make(`${delegation}-run-2`),
2840 attemptId: RunAttemptId.make(`${delegation}-attempt-2`),
2841 rootNodeId: NodeId.make(`${delegation}-root-2`),
2842 runOrdinal: 2,
2843 providerTurnOrdinal: 2,
2844 });
2845 yield* harness.awaitTerminal(2);
2846 assert.deepEqual(
2847 harness.terminalEvents().map((event) => event.status),
2848 ["completed", "completed"],
2849 );
2850 assert.notInclude(requests, "thread/sample");
2851 }).pipe(
2852 Effect.scoped,
2853 Effect.provide(
2854 Layer.mergeAll(
2855 IdAllocator.layer,
2856 McpProviderSessions.layer,
2857 NodeServices.layer,
2858 NodeCrypto.layer,
2859 ),
2860 ),
2861 ),
2862 );
2863
2864 it.effect("does not suggest a sample that imitates a delegated task wake", () =>
2865 Effect.gen(function* () {
2866 const nativeThreadId = "suggest-wake-thread";
2867 const prompt = "Delegate the README check.";
2868 const first = codexReplayPreamble({ nativeThreadId, nativeTurnId: "wake-turn-1", prompt });
2869 const second = codexReplayPreamble({ nativeThreadId, nativeTurnId: "wake-turn-2", prompt });
2870 const completedAndSampled = (
2871 nativeTurnId: string,
2872 id: number,
2873 text: string,
2874 ): Array<CodexReplay.CodexAppServerReplayEntry> => [
2875 {
2876 type: "emit_inbound",
2877 label: `${nativeTurnId} completed`,
2878 frame: {
2879 method: "turn/completed",
2880 params: {
2881 threadId: nativeThreadId,
2882 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2883 },
2884 },
2885 },
2886 {
2887 type: "expect_outbound",
2888 label: `${nativeTurnId} thread/sample`,
2889 frame: {
2890 id,
2891 method: "thread/sample",
2892 params: {
2893 threadId: nativeThreadId,
2894 expectedTurnId: nativeTurnId,
2895 prompt: CodexAdapterV2.CODEX_PROMPT_SUGGESTION_PROMPT,
2896 effort: "low",
2897 },
2898 },
2899 },
2900 {
2901 type: "emit_inbound",
2902 label: `${nativeTurnId} thread/sample`,
2903 frame: { id, result: { sourceTurnId: nativeTurnId, text } },
2904 },
2905 ];
2906 // The second turn's ordinary suggestion is the barrier for the first turn's sample.
2907 const firstSampleAnswered = yield* Deferred.make<void>();
2908 const harness = yield* makeCodexReplayHarness(
2909 makeCodexReplayTranscript({
2910 scenario: "prompt-suggestion-delegated-wake",
2911 entries: [
2912 ...first,
2913 ...completedAndSampled(
2914 "wake-turn-1",
2915 4,
2916 "Delegated task (Read README) [completed]: Here is the first line of the README.",
2917 ),
2918 ...second.slice(5, 7).map((entry) => withReplayRequestId(entry, 5)),
2919 ...completedAndSampled("wake-turn-2", 6, "add tests for subtract"),
2920 ],
2921 }),
2922 undefined,
2923 undefined,
2924 undefined,
2925 (entry) =>
2926 entry.label === "wake-turn-1 thread/sample"
2927 ? Deferred.succeed(firstSampleAnswered, undefined).pipe(Effect.asVoid)
2928 : Effect.void,
2929 undefined,
2930 Effect.succeed(true),
2931 );
2932 const turn = makeCodexTestTurnInput({
2933 threadId: harness.threadId,
2934 providerThread: harness.providerThread,
2935 now: yield* DateTime.now,
2936 attemptId: RunAttemptId.make("wake-attempt-1"),
2937 text: prompt,
2938 });
2939 yield* harness.runtime.startTurn(turn);
2940 yield* harness.awaitTerminal(1);
2941 yield* Deferred.await(firstSampleAnswered);
2942 yield* harness.runtime.startTurn({
2943 ...turn,
2944 runId: RunId.make("wake-run-2"),
2945 attemptId: RunAttemptId.make("wake-attempt-2"),
2946 rootNodeId: NodeId.make("wake-root-2"),
2947 runOrdinal: 2,
2948 providerTurnOrdinal: 2,
2949 });
2950 yield* harness.until(() =>
2951 harness.events.some(
2952 (event) =>
2953 event.type === "prompt_suggestion.updated" && event.text === "add tests for subtract",
2954 ),
2955 );
2956 assert.deepEqual(
2957 harness.events.flatMap((event) =>
2958 event.type === "prompt_suggestion.updated" ? [event.text] : [],
2959 ),
2960 ["add tests for subtract"],
2961 );
2962 }).pipe(
2963 Effect.scoped,
2964 Effect.provide(
2965 Layer.mergeAll(
2966 IdAllocator.layer,
2967 McpProviderSessions.layer,
2968 NodeServices.layer,
2969 NodeCrypto.layer,
2970 ),
2971 ),
2972 ),
2973 );
2974
2975 it.effect("samples a next-prompt suggestion after a completed root turn", () =>
2976 Effect.gen(function* () {
2977 const nativeThreadId = "suggest-thread";
2978 const nativeTurnId = "suggest-turn";
2979 const prompt = "Add a subtract function.";
2980 const transcript = makeCodexReplayTranscript({
2981 scenario: "prompt-suggestion",
2982 entries: [
2983 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }),
2984 {
2985 type: "emit_inbound",
2986 label: "turn/completed",
2987 frame: {
2988 method: "turn/completed",
2989 params: {
2990 threadId: nativeThreadId,
2991 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2992 },
2993 },
2994 },
2995 {
2996 type: "expect_outbound",
2997 label: "thread/sample",
2998 frame: {
2999 id: 4,
3000 method: "thread/sample",
3001 params: {
3002 threadId: nativeThreadId,
3003 expectedTurnId: nativeTurnId,
3004 prompt: CodexAdapterV2.CODEX_PROMPT_SUGGESTION_PROMPT,
3005 effort: "low",
3006 },
3007 },
3008 },
3009 {
3010 type: "emit_inbound",
3011 label: "thread/sample",
3012 frame: {
3013 id: 4,
3014 result: {
3015 sourceTurnId: nativeTurnId,
3016 responseId: "resp-suggest",
3017 text: " add tests for subtract\n",
3018 inputTokens: 11448,
3019 cachedInputTokens: 11264,
3020 outputTokens: 16,
3021 },
3022 },
3023 },
3024 ],
3025 });
3026 const harness = yield* makeCodexReplayHarness(
3027 transcript,
3028 undefined,
3029 undefined,
3030 undefined,
3031 undefined,
3032 undefined,
3033 Effect.succeed(true),
3034 );
3035 const turnInput = makeCodexTestTurnInput({
3036 threadId: harness.threadId,
3037 providerThread: harness.providerThread,
3038 now: yield* DateTime.now,
3039 attemptId: RunAttemptId.make("suggest-attempt"),
3040 text: prompt,
3041 });
3042 yield* harness.runtime.startTurn(turnInput);
3043 yield* harness.until(() =>
3044 harness.events.some((event) => event.type === "prompt_suggestion.updated"),
3045 );
3046 assert.deepEqual(
3047 harness.events.filter((event) => event.type === "prompt_suggestion.updated"),
3048 [
3049 {
3050 type: "prompt_suggestion.updated",
3051 driver: CodexAdapterV2.CODEX_DRIVER_KIND,
3052 threadId: harness.threadId,
3053 runId: turnInput.runId,
3054 text: "add tests for subtract",
3055 },
3056 ],
3057 );
3058 }).pipe(
3059 Effect.scoped,
3060 Effect.provide(
3061 Layer.mergeAll(
3062 IdAllocator.layer,
3063 McpProviderSessions.layer,
3064 NodeServices.layer,
3065 NodeCrypto.layer,
3066 ),
3067 ),
3068 ),
3069 );
3070
3071 const assistantMessages = (events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) =>
3072 events.filter(
3073 (
3074 event,
3075 ): event is Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "message.updated" }> =>
3076 event.type === "message.updated" && event.message.role === "assistant",
3077 );
3078
3079 it.effect("keeps an asynchronous Codex question actionable after the turn completes", () =>
3080 Effect.gen(function* () {
3081 const nativeThreadId = "async-question-thread";
3082 const nativeTurnId = "async-question-turn";
3083 const usage = {
3084 totalTokens: 15,
3085 inputTokens: 10,
3086 cachedInputTokens: 2,
3087 outputTokens: 5,
3088 reasoningOutputTokens: 1,
3089 };
3090 const transcript = makeCodexReplayTranscript({
3091 scenario: "async-question-and-billed-usage",
3092 entries: [
3093 ...codexReplayPreamble({
3094 nativeThreadId,
3095 nativeTurnId,
3096 prompt: "Continue while I decide.",
3097 }),
3098 {
3099 type: "emit_inbound",
3100 label: "question",
3101 frame: {
3102 method: "item/completed",
3103 params: {
3104 threadId: nativeThreadId,
3105 turnId: nativeTurnId,
3106 item: {
3107 type: "agentMessage",
3108 id: "async-question-item",
3109 text: "Which branch?",
3110 delivery: "async",
3111 questions: [{ title: "Which branch?", options: ["main", "dev"] }],
3112 },
3113 },
3114 },
3115 },
3116 {
3117 type: "emit_inbound",
3118 label: "usage",
3119 frame: {
3120 method: "thread/tokenUsage/updated",
3121 params: {
3122 threadId: nativeThreadId,
3123 turnId: nativeTurnId,
3124 tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 },
3125 },
3126 },
3127 },
3128 {
3129 type: "emit_inbound",
3130 label: "complete",
3131 frame: {
3132 method: "turn/completed",
3133 params: {
3134 threadId: nativeThreadId,
3135 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
3136 },
3137 },
3138 },
3139 ],
3140 });
3141 const harness = yield* makeCodexReplayHarness(transcript);
3142 yield* harness.runtime.startTurn(
3143 makeCodexTestTurnInput({
3144 threadId: harness.threadId,
3145 providerThread: harness.providerThread,
3146 now: yield* DateTime.now,
3147 attemptId: RunAttemptId.make("async-question-attempt"),
3148 text: "Continue while I decide.",
3149 }),
3150 );
3151 yield* harness.firstTerminal;
3152 const requests = harness.events.flatMap((event) =>
3153 event.type === "runtime_request.updated" ? [event.runtimeRequest] : [],
3154 );
3155 assert.lengthOf(requests, 1);
3156 assert.equal(requests[0]?.status, "pending");
3157 assert.deepEqual(requests[0]?.responseCapability, { type: "message" });
3158 const questionItem = harness.events.find(
3159 (event) =>
3160 event.type === "turn_item.updated" && event.turnItem.type === "user_input_request",
3161 );
3162 assert.equal(questionItem?.type, "turn_item.updated");
3163 if (
3164 questionItem?.type === "turn_item.updated" &&
3165 questionItem.turnItem.type === "user_input_request"
3166 ) {
3167 assert.deepEqual(
3168 questionItem.turnItem.questions[0]?.options.map((option) => option.label),
3169 ["main", "dev"],
3170 );
3171 assert.equal(questionItem.turnItem.responseMode, "message");
3172 }
3173 const questionNode = harness.events.find(
3174 (event) => event.type === "node.updated" && event.node.id === requests[0]?.nodeId,
3175 );
3176 assert.equal(questionNode?.type === "node.updated" && questionNode.node.countsForRun, false);
3177 const contextReport = harness.events.find(
3178 (event) =>
3179 event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined,
3180 );
3181 assert.equal(contextReport?.type, "provider_turn.updated");
3182 if (contextReport?.type === "provider_turn.updated") {
3183 assert.equal(
3184 contextReport.providerTurn.runAttemptId,
3185 RunAttemptId.make("async-question-attempt"),
3186 );
3187 assert.equal(contextReport.providerTurn.providerThreadId, harness.providerThread.id);
3188 assert.equal(contextReport.providerTurn.tokenUsage?.usedTokens, 15);
3189 assert.equal(contextReport.providerTurn.tokenUsage?.maxTokens, 200_000);
3190 }
3191 const completed = harness.events.find(
3192 (event) =>
3193 event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
3194 );
3195 assert.equal(completed?.type, "provider_turn.updated");
3196 if (completed?.type === "provider_turn.updated") {
3197 assert.deepEqual(completed.providerTurn.turnTokenUsage, {
3198 usageStatus: "complete",
3199 usageScope: "main_agent",
3200 hasSubagents: false,
3201 inputTokens: 10,
3202 cachedInputTokens: 2,
3203 outputTokens: 5,
3204 reasoningTokens: 1,
3205 });
3206 }
3207 assert.isEmpty(assistantMessages(harness.events));
3208 }).pipe(
3209 Effect.provide(
3210 Layer.mergeAll(
3211 IdAllocator.layer,
3212 McpProviderSessions.layer,
3213 NodeServices.layer,
3214 NodeCrypto.layer,
3215 ),
3216 ),
3217 ),
3218 );
3219
3220 it.effect("returns a Codex question's answer under its native question id", () =>
3221 Effect.gen(function* () {
3222 const nativeThreadId = "question-id-thread";
3223 const nativeTurnId = "question-id-turn";
3224 const transcript = makeCodexReplayTranscript({
3225 scenario: "codex-question-native-id",
3226 entries: [
3227 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Pick one." }),
3228 {
3229 type: "emit_inbound",
3230 label: "question",
3231 frame: {
3232 id: 100,
3233 method: "item/tool/requestUserInput",
3234 params: {
3235 threadId: nativeThreadId,
3236 turnId: nativeTurnId,
3237 itemId: "question-id-item",
3238 isBlocking: true,
3239 questions: [
3240 {
3241 id: " choice ",
3242 header: "Choice",
3243 question: "Which option?",
3244 options: [{ label: "A", description: "Option A" }],
3245 },
3246 ],
3247 },
3248 },
3249 },
3250 {
3251 type: "expect_outbound",
3252 label: "answer",
3253 frame: { id: 100, result: { answers: { " choice ": { answers: ["A"] } } } },
3254 },
3255 {
3256 type: "emit_inbound",
3257 label: "complete",
3258 frame: {
3259 method: "turn/completed",
3260 params: {
3261 threadId: nativeThreadId,
3262 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
3263 },
3264 },
3265 },
3266 ],
3267 });
3268 const harness = yield* makeCodexReplayHarness(transcript);
3269 yield* harness.runtime.startTurn(
3270 makeCodexTestTurnInput({
3271 threadId: harness.threadId,
3272 providerThread: harness.providerThread,
3273 now: yield* DateTime.now,
3274 attemptId: RunAttemptId.make("question-id-attempt"),
3275 text: "Pick one.",
3276 }),
3277 );
3278 const questionItem = () =>
3279 harness.events.flatMap((event) =>
3280 event.type === "turn_item.updated" && event.turnItem.type === "user_input_request"
3281 ? [event.turnItem]
3282 : [],
3283 )[0];
3284 const request = () =>
3285 harness.events.flatMap((event) =>
3286 event.type === "runtime_request.updated" ? [event.runtimeRequest] : [],
3287 )[0];
3288 yield* harness.until(() => questionItem() !== undefined && request() !== undefined);
3289 const publishedId = questionItem()!.questions[0]!.id;
3290 yield* harness.runtime.respondToRuntimeRequest({
3291 requestId: request()!.id,
3292 answers: { [publishedId]: ["A"] },
3293 });
3294 yield* harness.firstTerminal;
3295 }).pipe(
3296 Effect.provide(
3297 Layer.mergeAll(
3298 IdAllocator.layer,
3299 McpProviderSessions.layer,
3300 NodeServices.layer,
3301 NodeCrypto.layer,
3302 ),
3303 ),
3304 ),
3305 );
3306
3307 it.effect("records the model Codex reports on the root provider turn", () =>
3308 Effect.gen(function* () {
3309 const nativeThreadId = "reported-model-thread";
3310 const nativeTurnId = "reported-model-turn";
3311 const transcript = makeCodexReplayTranscript({
3312 scenario: "codex-reported-model",
3313 entries: [
3314 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }),
3315 {
3316 type: "emit_inbound",
3317 label: "rerouted",
3318 frame: {
3319 method: "model/rerouted",
3320 params: {
3321 threadId: nativeThreadId,
3322 turnId: nativeTurnId,
3323 fromModel: "gpt-6-astra",
3324 toModel: "gpt-5.6-sol",
3325 reason: "highRiskCyberActivity",
3326 },
3327 },
3328 },
3329 {
3330 type: "emit_inbound",
3331 label: "complete",
3332 frame: {
3333 method: "turn/completed",
3334 params: {
3335 threadId: nativeThreadId,
3336 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
3337 },
3338 },
3339 },
3340 ],
3341 });
3342 const harness = yield* makeCodexReplayHarness(transcript);
3343 yield* harness.runtime.startTurn(
3344 makeCodexTestTurnInput({
3345 threadId: harness.threadId,
3346 providerThread: harness.providerThread,
3347 now: yield* DateTime.now,
3348 attemptId: RunAttemptId.make("reported-model-attempt"),
3349 text: "say hi",
3350 }),
3351 );
3352 yield* harness.firstTerminal;
3353 const completed = harness.events.find(
3354 (event) =>
3355 event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
3356 );
3357 assert.equal(completed?.type, "provider_turn.updated");
3358 if (completed?.type !== "provider_turn.updated") return;
3359 assert.deepEqual(completed.providerTurn.turnTokenUsage?.models, ["gpt-5.6-sol"]);
3360 assert.equal(completed.providerTurn.model, "gpt-5.6-sol");
3361 }).pipe(
3362 Effect.provide(
3363 Layer.mergeAll(
3364 IdAllocator.layer,
3365 McpProviderSessions.layer,
3366 NodeServices.layer,
3367 NodeCrypto.layer,
3368 ),
3369 ),
3370 ),
3371 );
3372
3373 it.effect("names the native thread after the T3 title and retries a failed rename", () =>
3374 Effect.gen(function* () {
3375 const nativeThreadId = "thread-name-thread";
3376 const nameSet = (
3377 id: number,
3378 name: string,
3379 response: "result" | "error",
3380 ): Array<CodexReplay.CodexAppServerReplayEntry> => [
3381 {
3382 type: "expect_outbound",
3383 label: "thread/name/set",
3384 frame: { id, method: "thread/name/set", params: { threadId: nativeThreadId, name } },
3385 },
3386 {
3387 type: "emit_inbound",
3388 label: "thread/name/set",
3389 frame:
3390 response === "result"
3391 ? { id, result: {} }
3392 : { id, error: { code: -32601, message: "Method not found" } },
3393 },
3394 ];
3395 const turn = (
3396 id: number,
3397 nativeTurnId: string,
3398 ): Array<CodexReplay.CodexAppServerReplayEntry> => {
3399 const entries = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" });
3400 return [
3401 withReplayRequestId(entries[5]!, id),
3402 withReplayRequestId(entries[6]!, id),
3403 {
3404 type: "emit_inbound",
3405 label: "turn/completed",
3406 frame: {
3407 method: "turn/completed",
3408 params: {
3409 threadId: nativeThreadId,
3410 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
3411 },
3412 },
3413 },
3414 ];
3415 };
3416 const names: Array<unknown> = [];
3417 const harness = yield* makeCodexReplayHarness(
3418 makeCodexReplayTranscript({
3419 scenario: "codex-thread-name",
3420 entries: [
3421 ...codexReplayPreamble({
3422 nativeThreadId,
3423 nativeTurnId: "unused",
3424 prompt: "work",
3425 }).slice(0, 5),
3426 ...nameSet(3, CODEX_TEST_THREAD_TITLE, "error"),
3427 ...turn(4, "thread-name-turn-1"),
3428 ...nameSet(5, CODEX_TEST_THREAD_TITLE, "result"),
3429 ...turn(6, "thread-name-turn-2"),
3430 ...turn(7, "thread-name-turn-3"),
3431 ...nameSet(8, "Renamed", "result"),
3432 ],
3433 }),
3434 () => Effect.void,
3435 (method, params) =>
3436 Effect.sync(() => {
3437 if (method === "thread/name/set") names.push(params);
3438 }),
3439 );
3440 const now = yield* DateTime.now;
3441 for (const ordinal of [1, 2, 3]) {
3442 yield* harness.runtime.startTurn({
3443 ...makeCodexTestTurnInput({
3444 threadId: harness.threadId,
3445 providerThread: harness.providerThread,
3446 now,
3447 attemptId: RunAttemptId.make(`thread-name-${ordinal}`),
3448 text: "work",
3449 }),
3450 runOrdinal: ordinal,
3451 providerTurnOrdinal: ordinal,
3452 });
3453 yield* harness.awaitTerminal(ordinal);
3454 }
3455 const applyThreadTitle = harness.runtime.applyThreadTitle;
3456 assert.isDefined(applyThreadTitle);
3457 for (const title of ["Renamed", "Renamed"]) {
3458 yield* applyThreadTitle({ providerThread: harness.providerThread, title });
3459 }
3460
3461 assert.deepEqual(names, [
3462 { threadId: nativeThreadId, name: CODEX_TEST_THREAD_TITLE },
3463 { threadId: nativeThreadId, name: CODEX_TEST_THREAD_TITLE },
3464 { threadId: nativeThreadId, name: "Renamed" },
3465 ]);
3466 assert.deepEqual(
3467 harness.terminalEvents().map((event) => event.status),
3468 ["completed", "completed", "completed"],
3469 );
3470 }).pipe(
3471 Effect.provide(
3472 Layer.mergeAll(
3473 IdAllocator.layer,
3474 McpProviderSessions.layer,
3475 NodeServices.layer,
3476 NodeCrypto.layer,
3477 ),
3478 ),
3479 ),
3480 );
3481
3482 it.effect("signs a Codex MCP server in only while it isn't connected in the thread", () =>
3483 Effect.gen(function* () {
3484 const nativeThreadId = "mcp-sign-in-thread";
3485 const status = (
3486 id: number,
3487 runtimeStatus: string,
3488 ): Array<CodexReplay.CodexAppServerReplayEntry> => [
3489 {
3490 type: "expect_outbound",
3491 label: "mcpServerStatus/list",
3492 frame: {
3493 id,
3494 method: "mcpServerStatus/list",
3495 params: { serverName: "linear", threadId: nativeThreadId, detail: "toolsAndAuthOnly" },
3496 },
3497 },
3498 {
3499 type: "emit_inbound",
3500 label: "mcpServerStatus/list",
3501 frame: {
3502 id,
3503 result: {
3504 data: [
3505 {
3506 name: "linear",
3507 runtimeStatus,
3508 authStatus: "oAuth",
3509 tools: {},
3510 resources: [],
3511 resourceTemplates: [],
3512 },
3513 ],
3514 },
3515 },
3516 },
3517 ];
3518 const authorizationUrl =
3519 "https://linear.example/authorize?redirect_uri=http%3A%2F%2F127.0.0.1%3A50123%2Fcallback%2Fabc&state=s1";
3520 const harness = yield* makeCodexReplayHarness(
3521 makeCodexReplayTranscript({
3522 scenario: "codex-mcp-sign-in",
3523 entries: [
3524 ...codexReplayPreamble({
3525 nativeThreadId,
3526 nativeTurnId: "unused",
3527 prompt: "work",
3528 }).slice(0, 5),
3529 ...status(3, "connected"),
3530 ...status(4, "authenticationRequired"),
3531 {
3532 type: "expect_outbound",
3533 label: "mcpServer/oauth/login",
3534 frame: {
3535 id: 5,
3536 method: "mcpServer/oauth/login",
3537 params: { name: "linear", threadId: nativeThreadId },
3538 },
3539 },
3540 {
3541 type: "emit_inbound",
3542 label: "mcpServer/oauth/login",
3543 frame: { id: 5, result: { authorizationUrl } },
3544 },
3545 // A browser on Codex's machine reached its callback page before anything was pasted.
3546 {
3547 type: "emit_inbound",
3548 label: "mcpServer/oauthLogin/completed",
3549 frame: {
3550 method: "mcpServer/oauthLogin/completed",
3551 params: { name: "linear", threadId: nativeThreadId, success: true },
3552 },
3553 },
3554 ],
3555 }),
3556 );
3557 const mcpSignIn = harness.runtime.mcpSignIn;
3558 assert.isDefined(mcpSignIn);
3559 const input = { providerThread: harness.providerThread, server: "linear" };
3560 assert.deepEqual(yield* mcpSignIn.start(input), { authorizationUrl: null });
3561 assert.deepEqual(yield* mcpSignIn.start(input), { authorizationUrl });
3562 yield* mcpSignIn.complete({
3563 ...input,
3564 callbackUrl: "127.0.0.1:50123/callback/abc?code=c1&state=s1",
3565 });
3566 }).pipe(
3567 Effect.provide(
3568 Layer.mergeAll(
3569 IdAllocator.layer,
3570 McpProviderSessions.layer,
3571 NodeServices.layer,
3572 NodeCrypto.layer,
3573 ),
3574 ),
3575 ),
3576 );
3577
3578 it.effect.each(["before", "during"] as const)(
3579 "surfaces a user MCP server that fails to start %s the turn, with a sign-in when it needs one",
3580 (timing) =>
3581 Effect.gen(function* () {
3582 const nativeThreadId = "mcp-startup-failed-thread";
3583 const nativeTurnId = "mcp-startup-failed-turn";
3584 const startupError =
3585 "MCP client for `example_mcp` failed to start: MCP startup failed: handshaking with MCP server failed";
3586 const startup: Array<CodexReplay.CodexAppServerReplayEntry> = [
3587 {
3588 type: "emit_inbound",
3589 label: "mcp-starting",
3590 frame: {
3591 method: "mcpServer/startupStatus/updated",
3592 params: {
3593 threadId: nativeThreadId,
3594 name: "example_mcp",
3595 status: "starting",
3596 error: null,
3597 failureReason: null,
3598 },
3599 },
3600 },
3601 {
3602 type: "emit_inbound",
3603 label: "mcp-failed",
3604 frame: {
3605 method: "mcpServer/startupStatus/updated",
3606 params: {
3607 threadId: nativeThreadId,
3608 name: "example_mcp",
3609 status: "failed",
3610 error: startupError,
3611 failureReason: null,
3612 },
3613 },
3614 },
3615 {
3616 type: "emit_inbound",
3617 label: "mcp-not-logged-in",
3618 frame: {
3619 method: "mcpServer/startupStatus/updated",
3620 params: {
3621 threadId: nativeThreadId,
3622 name: "login_mcp",
3623 status: "failed",
3624 // Verbatim from codex-cli 0.171.0, which sets no failureReason for it.
3625 error:
3626 "The login_mcp MCP server is not logged in. Run `codex mcp login login_mcp`.",
3627 failureReason: null,
3628 },
3629 },
3630 },
3631 ];
3632 const preamble = codexReplayPreamble({
3633 nativeThreadId,
3634 nativeTurnId,
3635 prompt: "use example_mcp",
3636 });
3637 const turnStart = preamble.findIndex(
3638 (entry) => entry.type === "expect_outbound" && entry.label === "turn/start",
3639 );
3640 const transcript = makeCodexReplayTranscript({
3641 scenario: "codex-mcp-startup-failed",
3642 entries: [
3643 ...(timing === "before"
3644 ? [...preamble.slice(0, turnStart), ...startup, ...preamble.slice(turnStart)]
3645 : [...preamble, ...startup]),
3646 {
3647 type: "emit_inbound",
3648 label: "complete",
3649 frame: {
3650 method: "turn/completed",
3651 params: {
3652 threadId: nativeThreadId,
3653 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
3654 },
3655 },
3656 },
3657 ],
3658 });
3659 const harness = yield* makeCodexReplayHarness(transcript);
3660 yield* harness.runtime.startTurn(
3661 makeCodexTestTurnInput({
3662 threadId: harness.threadId,
3663 providerThread: harness.providerThread,
3664 now: yield* DateTime.now,
3665 attemptId: RunAttemptId.make("mcp-startup-failed-attempt"),
3666 text: "use example_mcp",
3667 }),
3668 );
3669 yield* harness.firstTerminal;
3670 const notices = harness.events.flatMap((event) =>
3671 event.type === "turn_item.updated" && event.turnItem.type === "system_notice"
3672 ? [[event.turnItem.title, event.turnItem.mcpSignIn?.server ?? null]]
3673 : [],
3674 );
3675 assert.deepEqual(notices, [
3676 ["MCP server example_mcp failed to start", null],
3677 ["MCP server login_mcp failed to start", "login_mcp"],
3678 ]);
3679 }).pipe(
3680 Effect.provide(
3681 Layer.mergeAll(
3682 IdAllocator.layer,
3683 McpProviderSessions.layer,
3684 NodeServices.layer,
3685 NodeCrypto.layer,
3686 ),
3687 ),
3688 ),
3689 );
3690
3691 it.effect("stops asking for commands the user allowed for the session", () =>
3692 Effect.gen(function* () {
3693 const nativeThreadId = "session-approval-thread";
3694 const turnIds = [
3695 "session-approval-turn-1",
3696 "session-approval-turn-2",
3697 "session-approval-turn-3",
3698 ];
3699 const turnPolicies = {
3700 "approval-required": {
3701 approvalPolicy: "untrusted",
3702 approvalsReviewer: "user",
3703 sandboxPolicy: { type: "readOnly" },
3704 },
3705 "full-access": {
3706 approvalPolicy: "never",
3707 approvalsReviewer: "user",
3708 sandboxPolicy: { type: "dangerFullAccess" },
3709 },
3710 } as const;
3711 const turnModes = ["approval-required", "full-access", "approval-required"] as const;
3712 const turnText = (index: number) => `Review round ${index + 1}.`;
3713 const startTurn = (index: number): ReadonlyArray<CodexReplay.CodexAppServerReplayEntry> => [
3714 {
3715 type: "expect_outbound",
3716 label: `turn ${index + 1} turn/start`,
3717 frame: {
3718 id: 3 + index,
3719 method: "turn/start",
3720 params: {
3721 threadId: nativeThreadId,
3722 input: [{ type: "text", text: turnText(index) }],
3723 cwd: "/workspace",
3724 model: "gpt-5.4",
3725 ...turnPolicies[turnModes[index]!],
3726 summary: "auto",
3727 collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } },
3728 },
3729 },
3730 },
3731 {
3732 type: "emit_inbound",
3733 label: `turn ${index + 1} turn/start`,
3734 frame: {
3735 id: 3 + index,
3736 result: { turn: makeCodexReplayTurn({ id: turnIds[index]!, status: "inProgress" }) },
3737 },
3738 },
3739 turnEvent("turn/started", turnIds[index]!),
3740 ];
3741 const approval = (input: {
3742 readonly id: number;
3743 readonly turnId: string;
3744 readonly kind: "commandExecution" | "fileChange";
3745 readonly itemId: string;
3746 readonly decision: string;
3747 }): ReadonlyArray<CodexReplay.CodexAppServerReplayEntry> => [
3748 {
3749 type: "emit_inbound",
3750 label: `${input.itemId} approval`,
3751 frame: {
3752 id: input.id,
3753 method: `item/${input.kind}/requestApproval`,
3754 params: {
3755 threadId: nativeThreadId,
3756 turnId: input.turnId,
3757 itemId: input.itemId,
3758 startedAtMs: 1782622441000,
3759 ...(input.kind === "commandExecution" ? { command: `cat ${input.itemId}` } : {}),
3760 },
3761 },
3762 },
3763 {
3764 type: "expect_outbound",
3765 label: `${input.itemId} decision`,
3766 frame: { id: input.id, result: { decision: input.decision } },
3767 },
3768 ];
3769 const turnEvent = (
3770 method: "turn/started" | "turn/completed",
3771 turnId: string,
3772 ): CodexReplay.CodexAppServerReplayEntry => ({
3773 type: "emit_inbound",
3774 label: `${turnId} ${method}`,
3775 frame: {
3776 method,
3777 params: {
3778 threadId: nativeThreadId,
3779 turn: makeCodexReplayTurn({
3780 id: turnId,
3781 status: method === "turn/started" ? "inProgress" : "completed",
3782 }),
3783 },
3784 },
3785 });
3786 const [patchRequest, patchDecision] = approval({
3787 id: 102,
3788 turnId: turnIds[0]!,
3789 kind: "fileChange",
3790 itemId: "first-patch",
3791 decision: "acceptForSession",
3792 });
3793 const transcript = makeCodexReplayTranscript({
3794 scenario: "codex-session-approvals",
3795 entries: [
3796 ...codexReplayPreamble({
3797 nativeThreadId,
3798 nativeTurnId: turnIds[0]!,
3799 prompt: turnText(0),
3800 }).slice(0, -3),
3801 ...startTurn(0),
3802 ...approval({
3803 id: 100,
3804 turnId: turnIds[0]!,
3805 kind: "commandExecution",
3806 itemId: "first-command",
3807 decision: "acceptForSession",
3808 }),
3809 patchRequest!,
3810 ...approval({
3811 id: 101,
3812 turnId: turnIds[0]!,
3813 kind: "commandExecution",
3814 itemId: "second-command",
3815 decision: "acceptForSession",
3816 }),
3817 turnEvent("turn/completed", turnIds[0]!),
3818 ...startTurn(1),
3819 patchDecision!,
3820 turnEvent("turn/completed", turnIds[1]!),
3821 ...startTurn(2),
3822 ...approval({
3823 id: 103,
3824 turnId: turnIds[2]!,
3825 kind: "commandExecution",
3826 itemId: "third-command",
3827 decision: "accept",
3828 }),
3829 ...approval({
3830 id: 104,
3831 turnId: turnIds[2]!,
3832 kind: "fileChange",
3833 itemId: "second-patch",
3834 decision: "accept",
3835 }),
3836 turnEvent("turn/completed", turnIds[2]!),
3837 ],
3838 });
3839 const harness = yield* makeCodexReplayHarness(transcript);
3840 const requests = () => [
3841 ...new Map(
3842 harness.events.flatMap((event) =>
3843 event.type === "runtime_request.updated"
3844 ? [[event.runtimeRequest.id, event.runtimeRequest] as const]
3845 : [],
3846 ),
3847 ).values(),
3848 ];
3849 const answer = (
3850 count: number,
3851 kind: "command" | "file-change",
3852 decision: ProviderApprovalDecision,
3853 ) =>
3854 Effect.gen(function* () {
3855 yield* harness.until(() => requests().length === count);
3856 const request = requests()[count - 1]!;
3857 assert.equal(request.kind, kind);
3858 yield* harness.runtime.respondToRuntimeRequest({ requestId: request.id, decision });
3859 });
3860
3861 const runTurn = (index: number) =>
3862 Effect.gen(function* () {
3863 yield* harness.runtime.startTurn({
3864 ...makeCodexTestTurnInput({
3865 threadId: harness.threadId,
3866 providerThread: harness.providerThread,
3867 now: yield* DateTime.now,
3868 attemptId: RunAttemptId.make(`session-approvals-${index + 1}`),
3869 text: turnText(index),
3870 }),
3871 runOrdinal: index + 1,
3872 providerTurnOrdinal: index + 1,
3873 runtimePolicy: { ...CODEX_TEST_RUNTIME_POLICY, runtimeMode: turnModes[index]! },
3874 });
3875 });
3876
3877 yield* runTurn(0);
3878 yield* answer(1, "command", "acceptForSession");
3879 yield* harness.until(() => requests().length === 2);
3880 yield* harness.awaitTerminal(1);
3881 yield* runTurn(1);
3882 yield* answer(2, "file-change", "acceptForSession");
3883 yield* harness.awaitTerminal(2);
3884 yield* runTurn(2);
3885 yield* answer(3, "command", "accept");
3886 yield* answer(4, "file-change", "accept");
3887 yield* harness.awaitTerminal(3);
3888 assert.lengthOf(requests(), 4);
3889 }).pipe(
3890 Effect.provide(
3891 Layer.mergeAll(
3892 IdAllocator.layer,
3893 McpProviderSessions.layer,
3894 NodeServices.layer,
3895 NodeCrypto.layer,
3896 ),
3897 ),
3898 ),
3899 );
3900
3901 it.effect("preserves T3 context on the wire and restores it after compaction", () =>
3902 Effect.gen(function* () {
3903 const nativeThreadId = "context-thread";
3904 const nativeTurnId = "context-turn";
3905 // An explicit Standard must reach Codex, or Codex falls back to Daybreak.
3906 const modelSelection = {
3907 ...CODEX_TEST_MODEL_SELECTION,
3908 options: [{ id: "cyberAccessProgram", value: "standard" }],
3909 };
3910 const params = yield* CodexAdapterV2.buildCodexTurnStartParams({
3911 nativeThreadId,
3912 codexInput: [{ type: "text", text: "work" }],
3913 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3914 modelSelection,
3915 hasT3Mcp: true,
3916 cyberAccess: { defaultProgram: "daybreakBlue" },
3917 });
3918 assert.include(
3919 params.additionalContext?.t3_code_orchestration_01?.value ?? "",
3920 "delegate_task",
3921 );
3922 const entries = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" });
3923 const transcript = makeCodexReplayTranscript({
3924 scenario: "restore-context",
3925 entries: [
3926 ...entries.slice(0, 5),
3927 {
3928 type: "expect_outbound",
3929 label: "context turn",
3930 frame: { id: 3, method: "turn/start", params },
3931 },
3932 ...entries.slice(6),
3933 {
3934 type: "emit_inbound",
3935 label: "compacted",
3936 frame: {
3937 method: "item/completed",
3938 params: {
3939 threadId: nativeThreadId,
3940 turnId: nativeTurnId,
3941 item: { type: "contextCompaction", id: "compact-context" },
3942 },
3943 },
3944 },
3945 {
3946 type: "emit_inbound",
3947 label: "done",
3948 frame: {
3949 method: "turn/completed",
3950 params: {
3951 threadId: nativeThreadId,
3952 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
3953 },
3954 },
3955 },
3956 {
3957 type: "expect_outbound",
3958 label: "restore context",
3959 frame: {
3960 id: 4,
3961 method: "thread/inject_items",
3962 params: {
3963 threadId: nativeThreadId,
3964 items: Object.entries(params.additionalContext ?? {}).map(([key, entry]) => ({
3965 type: "message",
3966 role: "developer",
3967 content: [{ type: "input_text", text: `<${key}>${entry.value}</${key}>` }],
3968 })),
3969 },
3970 },
3971 },
3972 { type: "emit_inbound", label: "restored", frame: { id: 4, result: {} } },
3973 ],
3974 });
3975 // Codex queues items injected mid-turn as pending input and samples again.
3976 const wireOrder: Array<string> = [];
3977 const restoreRequested = yield* Deferred.make<void>();
3978 const harness = yield* makeCodexReplayHarness(
3979 transcript,
3980 undefined,
3981 (method) =>
3982 method === "thread/inject_items"
3983 ? Effect.sync(() => wireOrder.push(method)).pipe(
3984 Effect.andThen(Deferred.succeed(restoreRequested, undefined)),
3985 )
3986 : Effect.void,
3987 undefined,
3988 undefined,
3989 undefined,
3990 undefined,
3991 (method) =>
3992 Effect.sync(() => {
3993 if (method === "item/completed" || method === "turn/completed") wireOrder.push(method);
3994 }),
3995 Effect.succeed<ReadonlyArray<ServerProviderModel>>([
3996 {
3997 slug: modelSelection.model,
3998 name: modelSelection.model,
3999 isCustom: false,
4000 capabilities: {
4001 optionDescriptors: [
4002 {
4003 id: "cyberAccessProgram",
4004 label: "Cyber Access",
4005 type: "select",
4006 options: [
4007 { id: "standard", label: "Standard" },
4008 { id: "daybreakBlue", label: "Daybreak Blue", isDefault: true },
4009 ],
4010 currentValue: "daybreakBlue",
4011 },
4012 ],
4013 },
4014 },
4015 ]),
4016 );
4017 yield* (yield* McpProviderSessions.McpProviderSessions).set({
4018 environmentId: EnvironmentId.make("test"),
4019 threadId: harness.threadId,
4020 providerSessionId: "context-session",
4021 providerInstanceId: ProviderInstanceId.make("codex"),
4022 endpoint: "http://127.0.0.1:43123/mcp",
4023 authorizationHeader: "Bearer test",
4024 browserToolsAvailable: true,
4025 });
4026 yield* harness.runtime.startTurn({
4027 ...makeCodexTestTurnInput({
4028 threadId: harness.threadId,
4029 providerThread: harness.providerThread,
4030 now: yield* DateTime.now,
4031 attemptId: RunAttemptId.make("context-attempt"),
4032 text: "work",
4033 }),
4034 modelSelection,
4035 });
4036 yield* harness.firstTerminal;
4037 yield* Deferred.await(restoreRequested);
4038 assert.equal(harness.terminalEvents()[0]?.status, "completed");
4039 assert.deepEqual(
4040 wireOrder,
4041 ["item/completed", "turn/completed", "thread/inject_items"],
4042 "restored T3 context while the compacting native turn was still running",
4043 );
4044 }).pipe(
4045 Effect.provide(
4046 Layer.mergeAll(
4047 IdAllocator.layer,
4048 McpProviderSessions.layer,
4049 NodeServices.layer,
4050 NodeCrypto.layer,
4051 ),
4052 ),
4053 ),
4054 );
4055
4056 it.effect("compacts Codex with the native RPC and completes the compaction turn", () =>
4057 Effect.gen(function* () {
4058 const nativeThreadId = "compact-thread";
4059 const nativeTurnId = "compact-turn";
4060 const item = { type: "contextCompaction", id: "compact-item" };
4061 const transcript = makeCodexReplayTranscript({
4062 scenario: "native-compaction",
4063 entries: [
4064 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "unused" }).slice(0, 5),
4065 {
4066 type: "expect_outbound",
4067 label: "compact",
4068 frame: {
4069 id: 3,
4070 method: "thread/compact/start",
4071 params: { threadId: nativeThreadId },
4072 },
4073 },
4074 { type: "emit_inbound", label: "compact", frame: { id: 3, result: {} } },
4075 {
4076 type: "emit_inbound",
4077 label: "start",
4078 frame: {
4079 method: "turn/started",
4080 params: {
4081 threadId: nativeThreadId,
4082 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }),
4083 },
4084 },
4085 },
4086 ...(["item/started", "item/completed"] as const).map((method) => ({
4087 type: "emit_inbound" as const,
4088 label: method,
4089 frame: { method, params: { threadId: nativeThreadId, turnId: nativeTurnId, item } },
4090 })),
4091 {
4092 type: "emit_inbound",
4093 label: "complete",
4094 frame: {
4095 method: "turn/completed",
4096 params: {
4097 threadId: nativeThreadId,
4098 turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
4099 },
4100 },
4101 },
4102 ],
4103 });
4104 const harness = yield* makeCodexReplayHarness(transcript);
4105 assert.isDefined(harness.runtime.compactThread);
4106 yield* harness.runtime.compactThread!(
4107 makeCodexTestTurnInput({
4108 threadId: harness.threadId,
4109 providerThread: harness.providerThread,
4110 now: yield* DateTime.now,
4111 attemptId: RunAttemptId.make("compact-attempt"),
4112 text: "/compact",
4113 }),
4114 );
4115 yield* harness.firstTerminal;
4116 const items = harness.events.flatMap((event) =>
4117 event.type === "turn_item.updated" && event.turnItem.type === "compaction"
4118 ? [event.turnItem]
4119 : [],
4120 );
4121 assert.deepEqual(
4122 items.map((entry) => entry.status),
4123 ["running", "completed"],
4124 );
4125 assert.equal(items[0]?.id, items[1]?.id);
4126 assert.equal(harness.terminalEvents()[0]?.status, "completed");
4127 }).pipe(
4128 Effect.provide(
4129 Layer.mergeAll(
4130 IdAllocator.layer,
4131 McpProviderSessions.layer,
4132 NodeServices.layer,
4133 NodeCrypto.layer,
4134 ),
4135 ),
4136 ),
4137 );
4138
4139 it.effect.each([
4140 { itemType: "contextCompaction", outcome: "failed" },
4141 { itemType: "contextCompaction", outcome: "interrupted" },
4142 { itemType: "contextCompaction", outcome: "Stop" },
4143 { itemType: "webSearch", outcome: "completed" },
4144 { itemType: "webSearch", outcome: "failed" },
4145 { itemType: "webSearch", outcome: "interrupted" },
4146 { itemType: "webSearch", outcome: "Stop" },
4147 ] as const)(
4148 "settles unfinished $itemType on $outcome without changing completed items",
4149 ({ itemType, outcome }) =>
4150 Effect.gen(function* () {
4151 const nativeThreadId = "unfinished-item-thread";
4152 const nativeTurnId = "unfinished-item-turn";
4153 const error = {
4154 message: "Remote item stream disconnected",
4155 codexErrorInfo: "other",
4156 additionalDetails: null,
4157 };
4158 const transcript = makeCodexReplayTranscript({
4159 scenario: `unfinished-${itemType}-${outcome}`,
4160 entries: [
4161 ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
4162 ...(
4163 [
4164 { method: "item/started", id: "completed-item", startedAtMs: 1782622441000 },
4165 { method: "item/completed", id: "completed-item", completedAtMs: 1782622442000 },
4166 { method: "item/started", id: "unfinished-item", startedAtMs: 1782622443000 },
4167 ] as const
4168 ).map(({ method, id, ...timestamps }) => ({
4169 type: "emit_inbound" as const,
4170 label: `${method}/${id}`,
4171 frame: {
4172 method,
4173 params: {
4174 threadId: nativeThreadId,
4175 turnId: nativeTurnId,
4176 item: {
4177 type: itemType,
4178 id,
4179 ...(itemType === "webSearch" ? { query: "T3 Code", action: null } : {}),
4180 },
4181 ...timestamps,
4182 },
4183 },
4184 })),
4185 ...(outcome === "Stop"
4186 ? [
4187 {
4188 type: "expect_outbound" as const,
4189 label: "turn/interrupt",
4190 frame: {
4191 id: 4,
4192 method: "turn/interrupt",
4193 params: { threadId: nativeThreadId, turnId: nativeTurnId },
4194 },
4195 },
4196 {
4197 type: "emit_inbound" as const,
4198 label: "turn/interrupt/failed",
4199 frame: { id: 4, error: { code: -32_000, message: "Interrupt failed" } },
4200 },
4201 ]
4202 : [
4203 {
4204 type: "emit_inbound" as const,
4205 label: "turn/completed",
4206 frame: {
4207 method: "turn/completed",
4208 params: {
4209 threadId: nativeThreadId,
4210 turn: {
4211 ...makeCodexReplayTurn({ id: nativeTurnId, status: outcome }),
4212 error: outcome === "failed" ? error : null,
4213 },
4214 },
4215 },
4216 },
4217 ]),
4218 ],
4219 });
4220 const itemStarted = yield* Deferred.make<ProviderTurnId>();
4221 const harness = yield* makeCodexReplayHarness(transcript, (event) =>
4222 event.type === "turn_item.updated" &&
4223 event.turnItem.nativeItemRef?.nativeId === "unfinished-item" &&
4224 event.turnItem.status === "running" &&
4225 event.turnItem.providerTurnId !== null
4226 ? Deferred.succeed(itemStarted, event.turnItem.providerTurnId)
4227 : Effect.void,
4228 );
4229 yield* TestClock.setTime(1782622445000);
4230 yield* harness.runtime.startTurn(
4231 makeCodexTestTurnInput({
4232 threadId: harness.threadId,
4233 providerThread: harness.providerThread,
4234 now: yield* DateTime.now,
4235 attemptId: RunAttemptId.make(`unfinished-${itemType}-${outcome}-attempt`),
4236 text: "Continue.",
4237 }),
4238 );
4239 if (outcome === "Stop") {
4240 const providerTurnId = yield* Deferred.await(itemStarted);
4241 const interrupt = yield* harness.runtime
4242 .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
4243 .pipe(Effect.exit);
4244 assert.equal(interrupt._tag, "Failure");
4245 }
4246 yield* harness.firstTerminal;
4247 const items = harness.events.flatMap((event) =>
4248 event.type === "turn_item.updated" &&
4249 event.turnItem.type === (itemType === "webSearch" ? "web_search" : "compaction")
4250 ? [event.turnItem]
4251 : [],
4252 );
4253 const completed = items.filter((item) => item.nativeItemRef?.nativeId === "completed-item");
4254 const unfinished = items.filter(
4255 (item) => item.nativeItemRef?.nativeId === "unfinished-item",
4256 );
4257 const status =
4258 outcome === "completed" ? "cancelled" : outcome === "failed" ? "failed" : "interrupted";
4259 assert.deepEqual(
4260 unfinished.map((item) => item.status),
4261 ["running", status],
4262 );
4263 assert.equal(unfinished[0]?.id, unfinished[1]?.id);
4264 assert.deepEqual(unfinished[1]?.startedAt, DateTime.makeUnsafe(1782622443000));
4265 if (unfinished[1]?.type === "web_search") {
4266 assert.deepEqual(unfinished[1].patterns, ["T3 Code"]);
4267 assert.deepEqual(
4268 harness.events.flatMap((event) =>
4269 event.type === "node.updated" &&
4270 event.node.nativeItemRef?.nativeId === "unfinished-item"
4271 ? [event.node.status]
4272 : [],
4273 ),
4274 ["running", status],
4275 );
4276 }
4277 assert.deepEqual(
4278 unfinished[1]?.completedAt,
4279 DateTime.makeUnsafe(outcome === "Stop" ? 1782622445000 : 1782622450000),
4280 );
4281 assert.deepEqual(
4282 completed.map((item) => item.status),
4283 ["running", "completed"],
4284 );
4285 assert.deepEqual(completed[1]?.startedAt, DateTime.makeUnsafe(1782622441000));
4286 assert.deepEqual(
4287 completed[1]?.completedAt,
4288 DateTime.makeUnsafe(itemType === "webSearch" ? 1782622445000 : 1782622442000),
4289 );
4290 assert.equal(
4291 harness.terminalEvents()[0]?.status,
4292 outcome === "Stop" ? "interrupted" : outcome,
4293 );
4294 if (outcome === "failed") {
4295 assert.equal(harness.terminalEvents()[0]?.failure?.message, error.message);
4296 }
4297 }).pipe(
4298 Effect.provide(
4299 Layer.mergeAll(
4300 IdAllocator.layer,
4301 McpProviderSessions.layer,
4302 NodeServices.layer,
4303 NodeCrypto.layer,
4304 ),
4305 ),
4306 ),
4307 );
4308
4309 it.effect.each([
4310 { hook: "stopped", status: "interrupted", expected: true },
4311 { hook: "completed", status: "interrupted", expected: false },
4312 { hook: "warning", status: "interrupted", expected: false },
4313 { hook: "empty", status: "interrupted", expected: false },
4314 { hook: "wrong-turn", status: "interrupted", expected: false },
4315 { hook: "wrong-thread", status: "interrupted", expected: false },
4316 { hook: "unscoped", status: "interrupted", expected: false },
4317 { hook: "stopped", status: "completed", expected: true },
4318 { hook: "stopped", status: "failed", expected: false },
4319 ] as const)(
4320 "correlates $hook hook output with a $status turn only",
4321 ({ hook, status, expected }) =>
4322 Effect.gen(function* () {
4323 const nativeThreadId = "hook-thread";
4324 const stopReason = "Save a current task checkpoint before compaction.";
4325 const hookCompleted = (turnId: string | null) => ({
4326 type: "emit_inbound" as const,
4327 label: "hook/completed",
4328 frame: {
4329 method: "hook/completed",
4330 params: {
4331 threadId: hook === "wrong-thread" ? "other-thread" : nativeThreadId,
4332 turnId: hook === "unscoped" ? null : hook === "wrong-turn" ? "other-turn" : turnId,
4333 run: {
4334 id: "checkpoint-hook",
4335 eventName: "preCompact",
4336 source: "project",
4337 sourcePath: "/workspace/.codex/hooks.json",
4338 scope: "turn",
4339 executionMode: "sync",
4340 handlerType: "command",
4341 displayOrder: 1,
4342 startedAt: 1782622440,
4343 status: hook === "completed" ? "completed" : "stopped",
4344 entries: [
4345 { kind: "warning", text: "Unrelated hook diagnostic" },
4346 {
4347 kind: hook === "warning" ? "warning" : "stop",
4348 text: hook === "empty" ? " " : stopReason,
4349 },
4350 ],
4351 },
4352 },
4353 },
4354 });
4355 const transcript = makeCodexReplayTranscript({
4356 scenario: `hook-stop-${hook}-${status}`,
4357 entries: [
4358 ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "hook-turn", prompt: "work" }),
4359 hookCompleted("hook-turn"),
4360 {
4361 type: "emit_inbound",
4362 label: "turn/completed",
4363 frame: {
4364 method: "turn/completed",
4365 params: {
4366 threadId: nativeThreadId,
4367 turn: makeCodexReplayTurn({ id: "hook-turn", status }),
4368 },
4369 },
4370 },
4371 ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "next-turn", prompt: "work" })
4372 .slice(-3)
4373 .map((entry, index) => (index < 2 ? withReplayRequestId(entry, 4) : entry)),
4374 hookCompleted("hook-turn"),
4375 {
4376 type: "emit_inbound",
4377 label: "turn/completed/next",
4378 frame: {
4379 method: "turn/completed",
4380 params: {
4381 threadId: nativeThreadId,
4382 turn: makeCodexReplayTurn({ id: "next-turn", status: "interrupted" }),
4383 },
4384 },
4385 },
4386 ],
4387 });
4388 const harness = yield* makeCodexReplayHarness(transcript);
4389 for (const turn of ["hook-turn", "next-turn"]) {
4390 yield* harness.runtime.startTurn(
4391 makeCodexTestTurnInput({
4392 threadId: harness.threadId,
4393 providerThread: harness.providerThread,
4394 now: yield* DateTime.now,
4395 attemptId: RunAttemptId.make(turn),
4396 text: "work",
4397 }),
4398 );
4399 yield* harness.awaitTerminal(turn === "hook-turn" ? 1 : 2);
4400 }
4401 assert.deepEqual(
4402 harness.terminalEvents().map((event) => ({
4403 status: event.status,
4404 reason: event.status === "failed" ? undefined : event.reason,
4405 })),
4406 [
4407 { status, reason: expected ? `preCompact hook (project): ${stopReason}` : undefined },
4408 { status: "interrupted", reason: undefined },
4409 ],
4410 );
4411 }).pipe(
4412 Effect.scoped,
4413 Effect.provide(
4414 Layer.mergeAll(
4415 IdAllocator.layer,
4416 McpProviderSessions.layer,
4417 NodeServices.layer,
4418 NodeCrypto.layer,
4419 ),
4420 ),
4421 ),
4422 );
4423
4424 it.effect("resumes a provider thread without requesting or decoding its history", () =>
4425 Effect.gen(function* () {
4426 const scenario = "codex-resume-metadata";
4427 const nativeThreadId = `native-${scenario}-thread`;
4428 const preamble = codexReplayPreamble({
4429 nativeThreadId,
4430 nativeTurnId: "unused-turn",
4431 prompt: "unused-prompt",
4432 }).slice(0, 5);
4433 const transcript = makeCodexReplayTranscript({
4434 scenario,
4435 entries: [
4436 ...preamble,
4437 {
4438 type: "expect_outbound",
4439 label: "thread/resume",
4440 frame: {
4441 id: 3,
4442 method: "thread/resume",
4443 params: {
4444 threadId: nativeThreadId,
4445 excludeTurns: true,
4446 config: CodexAdapterV2.CODEX_THREAD_CONFIG,
4447 },
4448 },
4449 },
4450 {
4451 type: "emit_inbound",
4452 label: "thread/resume",
4453 frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
4454 },
4455 {
4456 type: "expect_outbound",
4457 label: "thread/resume without an app thread",
4458 frame: {
4459 id: 4,
4460 method: "thread/resume",
4461 params: {
4462 threadId: nativeThreadId,
4463 excludeTurns: true,
4464 config: CodexAdapterV2.CODEX_THREAD_CONFIG,
4465 },
4466 },
4467 },
4468 {
4469 type: "emit_inbound",
4470 label: "thread/resume without an app thread",
4471 frame: { id: 4, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
4472 },
4473 {
4474 type: "expect_outbound",
4475 label: "thread/resume with an explicit app thread",
4476 frame: {
4477 id: 5,
4478 method: "thread/resume",
4479 params: {
4480 threadId: nativeThreadId,
4481 excludeTurns: true,
4482 config: CodexAdapterV2.CODEX_THREAD_CONFIG,
4483 },
4484 },
4485 },
4486 {
4487 type: "emit_inbound",
4488 label: "thread/resume with an explicit app thread",
4489 frame: { id: 5, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
4490 },
4491 ],
4492 });
4493 const resumeThreadEnvs: Array<unknown> = [];
4494 const harness = yield* makeCodexReplayHarness(
4495 transcript,
4496 () => Effect.void,
4497 (method, params) =>
4498 Effect.sync(() => {
4499 if (method === "thread/resume") resumeThreadEnvs.push(threadEnvOf(params));
4500 }),
4501 );
4502 const resumed = yield* harness.runtime.resumeThread({
4503 providerThread: harness.providerThread,
4504 modelSelection: CODEX_TEST_MODEL_SELECTION,
4505 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
4506 });
4507 yield* harness.runtime.resumeThread({
4508 providerThread: { ...harness.providerThread, appThreadId: null },
4509 modelSelection: CODEX_TEST_MODEL_SELECTION,
4510 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
4511 });
4512 const explicitThreadId = ThreadId.make(`thread-${scenario}-explicit`);
4513 yield* harness.runtime.resumeThread({
4514 threadId: explicitThreadId,
4515 providerThread: harness.providerThread,
4516 modelSelection: CODEX_TEST_MODEL_SELECTION,
4517 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
4518 });
4519
4520 assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
4521 assert.equal(resumed.status, "idle");
4522 assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
4523 assert.deepEqual(resumeThreadEnvs, [harness.threadId, undefined, explicitThreadId]);
4524 }).pipe(
4525 Effect.provide(
4526 Layer.mergeAll(
4527 IdAllocator.layer,
4528 McpProviderSessions.layer,
4529 NodeServices.layer,
4530 NodeCrypto.layer,
4531 ),
4532 ),
4533 ),
4534 );
4535
4536 // regression: #15389 archived native Codex sessions resume via thread/unarchive
4537 it.effect.each(
4538 (
4539 [
4540 ["recovers archived-session errors", "session saved-thread is archived", 0, ""],
4541 ["preserves missing-thread errors", "thread not found", 3, "thread not found"],
4542 [
4543 "propagates unarchive missing-thread errors",
4544 "session saved-thread is archived",
4545 4,
4546 "thread not found",
4547 ],
4548 [
4549 "does not retry archived errors twice",
4550 "session saved-thread is archived",
4551 5,
4552 "session saved-thread is archived",
4553 ],
4554 ] as const
4555 ).map(([name, resumeError, failAt, finalError]) => ({ name, resumeError, failAt, finalError })),
4556 )("$name", ({ name, resumeError, failAt, finalError }) =>
4557 Effect.gen(function* () {
4558 const nativeThreadId = "saved-thread";
4559 const params = {
4560 threadId: nativeThreadId,
4561 excludeTurns: true,
4562 cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
4563 model: CODEX_TEST_MODEL_SELECTION.model,
4564 config: CodexAdapterV2.CODEX_THREAD_CONFIG,
4565 };
4566 const entries: Array<CodexReplay.CodexAppServerReplayEntry> = [
4567 ...codexReplayPreamble({
4568 nativeThreadId,
4569 nativeTurnId: "unused-turn",
4570 prompt: "unused-prompt",
4571 }).slice(0, 5),
4572 {
4573 type: "expect_outbound",
4574 label: "resume archived thread",
4575 frame: { id: 3, method: "thread/resume", params },
4576 },
4577 {
4578 type: "emit_inbound",
4579 label: "resume error",
4580 frame: { id: 3, error: { code: -32600, message: resumeError } },
4581 },
4582 ];
4583 if (failAt !== 3) {
4584 entries.push(
4585 {
4586 type: "expect_outbound",
4587 label: "unarchive same thread",
4588 frame: { id: 4, method: "thread/unarchive", params: { threadId: nativeThreadId } },
4589 },
4590 {
4591 type: "emit_inbound",
4592 label: "unarchive result",
4593 frame:
4594 failAt === 4
4595 ? { id: 4, error: { code: -32600, message: finalError } }
4596 : { id: 4, result: { thread: { turns: [{ type: "unknown-history-item" }] } } },
4597 },
4598 );
4599 }
4600 if (failAt === 0 || failAt === 5) {
4601 entries.push(
4602 {
4603 type: "expect_outbound",
4604 label: "retry identical resume",
4605 frame: { id: 5, method: "thread/resume", params },
4606 },
4607 {
4608 type: "emit_inbound",
4609 label: "retry result",
4610 frame:
4611 failAt === 5
4612 ? { id: 5, error: { code: -32600, message: finalError } }
4613 : {
4614 id: 5,
4615 result: {
4616 thread: {
4617 id: nativeThreadId,
4618 updatedAt: 1782622450,
4619 turns: [{ type: "unknown-history-item" }],
4620 },
4621 },
4622 },
4623 },
4624 );
4625 }
4626 const harness = yield* makeCodexReplayHarness(
4627 makeCodexReplayTranscript({ scenario: name, entries }),
4628 );
4629 const resume = harness.runtime.resumeThread({
4630 providerThread: harness.providerThread,
4631 modelSelection: CODEX_TEST_MODEL_SELECTION,
4632 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
4633 });
4634 if (failAt !== 0) {
4635 const error = yield* Effect.flip(resume);
4636 assert.equal(error._tag, "ProviderAdapterResumeThreadError");
4637 assert.nestedPropertyVal(error, "cause.errorMessage", finalError);
4638 assert.nestedPropertyVal(
4639 error,
4640 "cause.method",
4641 failAt === 4 ? "thread/unarchive" : "thread/resume",
4642 );
4643 // The thread start and the resume each read config first.
4644 assert.nestedPropertyVal(error, "cause.requestId", String(failAt + 2));
4645 return;
4646 }
4647 const resumed = yield* resume;
4648 assert.equal(resumed.id, harness.providerThread.id);
4649 assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
4650 assert.deepEqual(
4651 resumed.nativeConversationHeadRef,
4652 harness.providerThread.nativeConversationHeadRef,
4653 );
4654 assert.equal(resumed.status, "idle");
4655 assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
4656 }).pipe(
4657 Effect.provide(
4658 Layer.mergeAll(
4659 IdAllocator.layer,
4660 McpProviderSessions.layer,
4661 NodeServices.layer,
4662 NodeCrypto.layer,
4663 ),
4664 ),
4665 ),
4666 );
4667
4668 // regression: #33747 Codex refuses thread/resume until an unsubscribed thread finishes closing
4669 it.effect.each([
4670 { name: "waits for thread/closed after a closing error", closedFirst: false },
4671 { name: "retries at once when the thread already closed", closedFirst: true },
4672 ])("$name", ({ name, closedFirst }) =>
4673 Effect.gen(function* () {
4674 const nativeThreadId = "closing-thread";
4675 const params = {
4676 threadId: nativeThreadId,
4677 excludeTurns: true,
4678 cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
4679 model: CODEX_TEST_MODEL_SELECTION.model,
4680 config: CodexAdapterV2.CODEX_THREAD_CONFIG,
4681 };
4682 const closed: CodexReplay.CodexAppServerReplayEntry = {
4683 type: "emit_inbound",
4684 label: "thread closed",
4685 frame: { method: "thread/closed", params: { threadId: nativeThreadId } },
4686 };
4687 const closingError: CodexReplay.CodexAppServerReplayEntry = {
4688 type: "emit_inbound",
4689 label: "resume closing error",
4690 frame: {
4691 id: 4,
4692 error: {
4693 code: -32600,
4694 message: `thread ${nativeThreadId} is closing; retry thread/resume after the thread is closed`,
4695 },
4696 },
4697 };
4698 const harness = yield* makeCodexReplayHarness(
4699 makeCodexReplayTranscript({
4700 scenario: name,
4701 entries: [
4702 ...codexReplayPreamble({
4703 nativeThreadId,
4704 nativeTurnId: "unused-turn",
4705 prompt: "unused-prompt",
4706 }).slice(0, 5),
4707 {
4708 type: "expect_outbound",
4709 label: "unsubscribe",
4710 frame: {
4711 id: 3,
4712 method: "thread/unsubscribe",
4713 params: { threadId: nativeThreadId },
4714 },
4715 },
4716 {
4717 type: "emit_inbound",
4718 label: "unsubscribe result",
4719 frame: { id: 3, result: { status: "unsubscribed" } },
4720 },
4721 {
4722 type: "expect_outbound",
4723 label: "resume closing thread",
4724 frame: { id: 4, method: "thread/resume", params },
4725 },
4726 ...(closedFirst ? [closed, closingError] : [closingError, closed]),
4727 {
4728 type: "expect_outbound",
4729 label: "retry identical resume",
4730 frame: { id: 5, method: "thread/resume", params },
4731 },
4732 {
4733 type: "emit_inbound",
4734 label: "retry result",
4735 frame: {
4736 id: 5,
4737 result: {
4738 thread: {
4739 id: nativeThreadId,
4740 updatedAt: 1782622450,
4741 turns: [{ type: "unknown-history-item" }],
4742 },
4743 },
4744 },
4745 },
4746 ],
4747 }),
4748 );
4749 yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
4750 const resumed = yield* harness.runtime.resumeThread({
4751 providerThread: harness.providerThread,
4752 modelSelection: CODEX_TEST_MODEL_SELECTION,
4753 runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
4754 });
4755 assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
4756 assert.equal(resumed.status, "idle");
4757 }).pipe(
4758 Effect.provide(
4759 Layer.mergeAll(
4760 IdAllocator.layer,
4761 McpProviderSessions.layer,
4762 NodeServices.layer,
4763 NodeCrypto.layer,
4764 ),
4765 ),
4766 ),
4767 );
4768
4769 it.effect.each([
4770 "recover",
4771 "completion-only",
4772 "exhaust",
4773 "stop",
4774 "stop-continued",
4775 "stop-starting",
4776 "started-first",
4777 "completed-first",
4778 "new-run",
4779 "steer",
4780 "start-fails",
4781 "keep-changed-tier",
4782 ] as const)("handles terminal Codex capacity failures when retries %s", (outcome) =>
4783 Effect.gen(function* () {
4784 const scenario = `capacity-${outcome}`;
4785 const nativeThreadId = `native-${scenario}`;
4786 const nativeTurnId = (attempt: number) => `${nativeThreadId}-${attempt}`;
4787 const prompt = "Continue the task.";
4788 const capacityError = {
4789 message: "Selected model is at capacity. Please try a different model.",
4790 codexErrorInfo: "serverOverloaded",
4791 };
4792 const failureEntries = (attempt: number): Array<CodexReplay.CodexAppServerReplayEntry> => [
4793 {
4794 type: "emit_inbound",
4795 frame: {
4796 method: "error",
4797 params: {
4798 threadId: nativeThreadId,
4799 turnId: nativeTurnId(attempt),
4800 willRetry: false,
4801 error: capacityError,
4802 },
4803 },
4804 },
4805 {
4806 type: "emit_inbound",
4807 frame: {
4808 method: "turn/completed",
4809 params: {
4810 threadId: nativeThreadId,
4811 turn: {
4812 ...makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "failed" }),
4813 error: capacityError,
4814 },
4815 },
4816 },
4817 },
4818 ];
4819 const entries = codexReplayPreamble({
4820 nativeThreadId,
4821 nativeTurnId: nativeTurnId(0),
4822 prompt,
4823 });
4824 // A speed picked while the first attempt runs; the retry must not send the old one.
4825 const changedTier = outcome === "keep-changed-tier" ? "fast" : undefined;
4826 if (changedTier !== undefined) {
4827 entries.push(
4828 {
4829 type: "expect_outbound",
4830 label: "thread/settings/update",
4831 frame: {
4832 id: 4,
4833 method: "thread/settings/update",
4834 params: { threadId: nativeThreadId, serviceTier: changedTier },
4835 },
4836 },
4837 { type: "emit_inbound", frame: { id: 4, result: {} } },
4838 );
4839 }
4840 entries.push(
4841 ...(outcome === "completion-only" ? failureEntries(0).slice(1) : failureEntries(0)),
4842 );
4843 if (outcome === "completion-only") entries.push(...failureEntries(0).slice(1));
4844 // A live rename between attempts must not be undone by the retry.
4845 const renamedBeforeRetry = outcome === "started-first";
4846 if (renamedBeforeRetry) {
4847 entries.push(
4848 {
4849 type: "expect_outbound",
4850 frame: {
4851 id: 4,
4852 method: "thread/name/set",
4853 params: { threadId: nativeThreadId, name: "Renamed" },
4854 },
4855 },
4856 { type: "emit_inbound", frame: { id: 4, result: {} } },
4857 );
4858 }
4859 const retries = outcome === "exhaust" ? 5 : outcome === "stop" ? 0 : 1;
4860 const steeredText = "Use the smaller change.";
4861 for (let attempt = 1; attempt <= retries; attempt++) {
4862 const startId = 3 + attempt + (renamedBeforeRetry || changedTier !== undefined ? 1 : 0);
4863 const start = codexReplayPreamble({
4864 nativeThreadId,
4865 nativeTurnId: nativeTurnId(attempt),
4866 prompt,
4867 }).slice(-3);
4868 if (
4869 outcome === "started-first" ||
4870 outcome === "stop-starting" ||
4871 outcome === "completed-first" ||
4872 outcome === "new-run"
4873 ) {
4874 start.splice(1, 0, ...start.splice(2, 1));
4875 }
4876 for (const entry of start) {
4877 if (entry.type === "expect_outbound") {
4878 entries.push({
4879 ...entry,
4880 frame: {
4881 id: startId,
4882 method: "turn/start",
4883 params: {
4884 threadId: nativeThreadId,
4885 input: [],
4886 cwd: "/workspace",
4887 model: "gpt-5.4",
4888 approvalPolicy: "never",
4889 approvalsReviewer: "user",
4890 sandboxPolicy: { type: "dangerFullAccess" },
4891 summary: "auto",
4892 collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } },
4893 ...(changedTier === undefined ? {} : { serviceTier: changedTier }),
4894 },
4895 },
4896 });
4897 } else if (entry.type === "emit_inbound" && entry.label === "turn/start") {
4898 if (outcome === "completed-first" || outcome === "new-run")
4899 entries.push({
4900 type: "emit_inbound",
4901 frame: {
4902 method: "turn/completed",
4903 params: {
4904 threadId: nativeThreadId,
4905 turn: makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "completed" }),
4906 },
4907 },
4908 });
4909 if (outcome === "new-run") {
4910 entries.push(
4911 ...codexReplayPreamble({
4912 nativeThreadId,
4913 nativeTurnId: nativeTurnId(2),
4914 prompt: "Next task.",
4915 })
4916 .slice(-3)
4917 .map((next, index) => (index < 2 ? withReplayRequestId(next, 5) : next)),
4918 ...failureEntries(2),
4919 );
4920 }
4921 entries.push(
4922 outcome === "start-fails"
4923 ? {
4924 type: "emit_inbound",
4925 frame: {
4926 id: startId,
4927 error: { code: -32603, message: "Start failed" },
4928 },
4929 }
4930 : withReplayRequestId(entry, startId),
4931 );
4932 } else if (outcome !== "start-fails") {
4933 entries.push(
4934 outcome === "stop-starting" && entry.type === "emit_inbound"
4935 ? { ...entry, afterMs: 1_000 }
4936 : entry,
4937 );
4938 if (outcome === "stop-starting") {
4939 entries.push(
4940 {
4941 type: "expect_outbound",
4942 frame: {
4943 id: 5,
4944 method: "turn/interrupt",
4945 params: { threadId: nativeThreadId, turnId: nativeTurnId(attempt) },
4946 },
4947 },
4948 { type: "emit_inbound", frame: { id: 5, result: {} } },
4949 );
4950 }
4951 }
4952 }
4953 if (outcome === "exhaust") entries.push(...failureEntries(attempt));
4954 if (
4955 outcome === "recover" ||
4956 outcome === "keep-changed-tier" ||
4957 outcome === "completion-only" ||
4958 outcome === "started-first" ||
4959 outcome === "stop-starting"
4960 ) {
4961 entries.push({
4962 type: "emit_inbound",
4963 frame: {
4964 method: "turn/completed",
4965 params: {
4966 threadId: nativeThreadId,
4967 turn: makeCodexReplayTurn({
4968 id: nativeTurnId(attempt),
4969 status: outcome === "stop-starting" ? "interrupted" : "completed",
4970 }),
4971 },
4972 },
4973 });
4974 }
4975 if (outcome === "stop-continued" || outcome === "steer") {
4976 const steering = outcome === "steer";
4977 entries.push(
4978 {
4979 type: "expect_outbound",
4980 frame: {
4981 id: 5,
4982 method: steering ? "turn/steer" : "turn/interrupt",
4983 params: steering
4984 ? {
4985 threadId: nativeThreadId,
4986 expectedTurnId: nativeTurnId(attempt),
4987 input: [{ type: "text", text: steeredText }],
4988 }
4989 : { threadId: nativeThreadId, turnId: nativeTurnId(attempt) },
4990 },
4991 },
4992 {
4993 type: "emit_inbound",
4994 frame: { id: 5, result: steering ? { turnId: nativeTurnId(attempt) } : {} },
4995 },
4996 {
4997 type: "emit_inbound",
4998 frame: {
4999 method: "turn/completed",
5000 params: {
Showing first 5,000 of 12,742 lines. View raw