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

CodexCollabRuntime.integration.test.ts

762 lines28.1 KB

1/**
2 * Runtime-level collab regression: boots the REAL CodexSessionRuntime against
3 * a scripted mock app-server peer that replays the captured multi-agent wire
4 * sequence (codexMultiAgentWire.json) plus the shapes the capture alone can't
5 * script (receiver-turn bookkeeping via collabAgentToolCall, child terminal
6 * lifecycle, approval pass-through). This is the layer the pure routing-table
7 * test can't reach: ordering between the legacy receiver-turn suppressor and
8 * v2 interception, registration state, and synthetic event emission.
9 */
10// @effect-diagnostics nodeBuiltinImport:off
11import * as NodeFS from "node:fs";
12import * as NodePath from "node:path";
13​
14import * as NodeServices from "@effect/platform-node/NodeServices";
15import { it } from "@effect/vitest";
16import { type ProviderApprovalDecision, type ProviderEvent, ThreadId } from "@t3tools/contracts";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as Fiber from "effect/Fiber";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22import { assert, describe } from "vite-plus/test";
23​
24import wireFixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };
25import { makeCodexSessionRuntime } from "./CodexSessionRuntime.ts";
26​
27const ROOT = wireFixture.rootThreadId;
28const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];
29const MEMORY = "memory-consolidation-thread";
30const decodeMcpElicitationResponse = Schema.decodeUnknownEffect(
31 Schema.fromJsonString(
32 Schema.Struct({
33 id: Schema.Number,
34 result: Schema.Unknown,
35 }),
36 ),
37);
38​
39/**
40 * The captured sequence, extended with the shapes the live capture didn't
41 * include: a collabAgentToolCall with receiverThreadIds (feeds the legacy
42 * receiver-turn map, so ordering vs. v2 interception is exercised), child
43 * terminal lifecycle, and a serverRequest/resolved addressed to a child
44 * (must pass through to the parent path, not vanish).
45 */
46function buildScript() {
47 const captured = wireFixture.notifications;
48 const extras = [
49 {
50 method: "item/completed",
51 params: {
52 threadId: ROOT,
53 item: {
54 type: "collabAgentToolCall",
55 id: "call_fixture_wait",
56 tool: "wait",
57 status: "completed",
58 senderThreadId: ROOT,
59 receiverThreadIds: [CHILD_A, CHILD_B],
60 },
61 },
62 },
63 // Child terminal lifecycle AFTER the receiver map knows the children —
64 // pre-fix, the legacy suppressor dropped these before interception saw
65 // them, so no synthetic agent events were emitted.
66 {
67 method: "turn/completed",
68 params: {
69 threadId: CHILD_A,
70 turn: { id: `${CHILD_A}-turn-1`, status: "completed", items: [] },
71 },
72 },
73 { method: "thread/closed", params: { threadId: CHILD_B } },
74 // Parent-owned traffic addressed to a child conversation: must reach the
75 // parent path (approval correlation cleanup), not be swallowed.
76 { method: "serverRequest/resolved", params: { threadId: CHILD_A, requestId: "req-1" } },
77 ];
78 return {
79 rootThreadId: ROOT,
80 notifications: [...captured.filter((entry) => entry.method !== "turn/completed"), ...extras],
81 };
83​
84function capturedStartedActivity(childId = CHILD_A) {
85 const captured = wireFixture.notifications.find((entry) => {
86 const item = (entry.params as { item?: { type?: string; kind?: string } }).item;
87 return item?.type === "subAgentActivity" && item.kind === "started";
88 });
89 assert.isDefined(captured);
90 return {
91 ...captured,
92 params: {
93 ...captured.params,
94 item: {
95 ...captured.params.item,
96 agentThreadId: childId,
97 agentPath: "/root/model-check",
98 },
99 },
100 };
102​
103function capturedSpawnedThread(childId = CHILD_A) {
104 const captured = wireFixture.notifications.find((entry) => entry.method === "thread/started");
105 assert.isDefined(captured);
106 return {
107 ...captured,
108 params: {
109 thread: {
110 ...captured.params.thread,
111 id: childId,
112 sessionId: childId,
113 parentThreadId: ROOT,
114 agentNickname: "model-check",
115 agentRole: "verifier",
116 source: {
117 subAgent: {
118 thread_spawn: {
119 agent_nickname: "model-check",
120 agent_path: "/root/model-check",
121 agent_role: "verifier",
122 depth: 1,
123 parent_thread_id: ROOT,
124 },
125 },
126 },
127 },
128 },
129 };
131​
132function childSettings(threadId: string, model: string, effort: string) {
133 return {
134 method: "thread/settings/updated",
135 params: {
136 threadId,
137 threadSettings: {
138 approvalPolicy: "on-request",
139 approvalsReviewer: "auto_review",
140 collaborationMode: { mode: "default", settings: { model } },
141 cwd: "/workspace/repo",
142 effort,
143 model,
144 modelProvider: "openai",
145 sandboxPolicy: { type: "dangerFullAccess" },
146 },
147 },
148 };
150​
151function readRecordedRequests() {
152 return NodeFS.readFileSync(`${scriptPath}.requests`, "utf8")
153 .trim()
154 .split("\n")
155 .filter((line) => line.length > 0)
156 .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> });
158​
159const scriptPath = NodePath.join(import.meta.dirname, "../testFixtures/.collab-script.json");
160const peerPath = NodePath.join(import.meta.dirname, "../testFixtures/codexCollabMockPeer.sh");
161​
162describe("CodexSessionRuntime collab integration", () => {
163 it.effect("looks up child model metadata once after activity registration", () =>
164 Effect.gen(function* () {
165 const script = {
166 rootThreadId: ROOT,
167 recordRequests: true,
168 notifications: [
169 capturedStartedActivity(),
170 capturedStartedActivity(),
171 {
172 ...capturedStartedActivity(CHILD_B),
173 params: {
174 ...capturedStartedActivity(CHILD_B).params,
175 item: { ...capturedStartedActivity(CHILD_B).params.item, kind: "interacted" },
176 },
177 },
178 { method: "thread/closed", params: { threadId: CHILD_B } },
179 capturedSpawnedThread(ROOT),
180 ],
181 childResumeSnapshots: {
182 [CHILD_A]: { model: "gpt-5.6-luna", reasoningEffort: "low" },
183 },
184 };
185 // @effect-diagnostics-next-line preferSchemaOverJson:off
186 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
187 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
188 yield* Effect.addFinalizer(() =>
189 Effect.sync(() => {
190 NodeFS.rmSync(scriptPath, { force: true });
191 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
192 }),
193 );
194​
195 const runtime = yield* makeCodexSessionRuntime({
196 threadId: ThreadId.make("thread-collab-model-activity"),
197 binaryPath: peerPath,
198 cwd: "/tmp",
199 runtimeMode: "full-access",
200 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
201 });
202 const metadataFiber = yield* runtime.events.pipe(
203 Stream.filter(
204 (event) =>
205 event.method === "collabAgent/metadataUpdated" &&
206 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
207 ),
208 Stream.take(1),
209 Stream.runCollect,
210 Effect.forkScoped,
211 );
212​
213 const session = yield* runtime.start();
214 assert.equal(session.model, "gpt-5.6-sol");
215 yield* runtime.sendTurn({ input: "start one child" });
216 const metadataEvents = Array.from(yield* Fiber.join(metadataFiber));
217 assert.deepInclude(metadataEvents[0]?.payload, {
218 agentThreadId: CHILD_A,
219 model: "gpt-5.6-luna",
220 effort: "low",
221 });
222 assert.deepEqual(readRecordedRequests(), [
223 {
224 method: "thread/resume",
225 params: { threadId: CHILD_A, excludeTurns: true },
226 },
227 ]);
228​
229 yield* runtime.close;
230 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
231 );
232​
233 it.effect("keeps child settings and reroutes newer than the resume snapshot", () =>
234 Effect.gen(function* () {
235 const statusChanged = wireFixture.notifications.find(
236 (entry) =>
237 entry.method === "thread/status/changed" &&
238 (entry.params as { threadId?: string }).threadId === CHILD_A,
239 );
240 assert.isDefined(statusChanged);
241 const script = {
242 rootThreadId: ROOT,
243 recordRequests: true,
244 notifications: [
245 childSettings(CHILD_A, "child-before", "medium"),
246 capturedSpawnedThread(),
247 childSettings(CHILD_A, "child-after", "high"),
248 {
249 method: "model/rerouted",
250 params: {
251 threadId: CHILD_A,
252 turnId: `${CHILD_A}-turn`,
253 fromModel: "child-after",
254 toModel: "child-rerouted",
255 reason: "highRiskCyberActivity",
256 },
257 },
258 {
259 method: "model/rerouted",
260 params: {
261 threadId: ROOT,
262 turnId: `${ROOT}-turn`,
263 fromModel: "gpt-5.6-sol",
264 toModel: "root-rerouted",
265 reason: "highRiskCyberActivity",
266 },
267 },
268 ],
269 childResumeSnapshots: {
270 [CHILD_A]: {
271 model: "stale-snapshot",
272 reasoningEffort: "low",
273 notifications: [statusChanged],
274 },
275 },
276 };
277 // @effect-diagnostics-next-line preferSchemaOverJson:off
278 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
279 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
280 yield* Effect.addFinalizer(() =>
281 Effect.sync(() => {
282 NodeFS.rmSync(scriptPath, { force: true });
283 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
284 }),
285 );
286​
287 const runtime = yield* makeCodexSessionRuntime({
288 threadId: ThreadId.make("thread-collab-model-spawn"),
289 binaryPath: peerPath,
290 cwd: "/tmp",
291 runtimeMode: "full-access",
292 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
293 });
294 const eventsFiber = yield* runtime.events.pipe(
295 Stream.takeUntil(
296 (event) =>
297 event.method === "collabAgent/statusChanged" &&
298 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
299 ),
300 Stream.runCollect,
301 Effect.forkScoped,
302 );
303​
304 yield* runtime.start();
305 yield* runtime.sendTurn({ input: "start one spawned child" });
306 const events = Array.from(yield* Fiber.join(eventsFiber));
307 const started = events.find((event) => event.method === "collabAgent/started");
308 assert.deepInclude(started?.payload, {
309 agentThreadId: CHILD_A,
310 model: "child-before",
311 effort: "medium",
312 });
313 const childStatus = events.find((event) => event.method === "collabAgent/statusChanged");
314 assert.deepInclude(childStatus?.payload, {
315 agentThreadId: CHILD_A,
316 model: "child-rerouted",
317 effort: "high",
318 });
319 assert.isTrue(
320 events.some(
321 (event) =>
322 event.method === "model/rerouted" &&
323 (event.payload as { threadId?: string }).threadId === ROOT,
324 ),
325 "the root reroute must stay on the parent path",
326 );
327 assert.isFalse(
328 events.some(
329 (event) =>
330 (event.method === "thread/settings/updated" || event.method === "model/rerouted") &&
331 (event.payload as { threadId?: string }).threadId === CHILD_A,
332 ),
333 "child metadata notifications must not leak to the parent path",
334 );
335 assert.equal(readRecordedRequests().length, 1);
336​
337 yield* runtime.close;
338 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
339 );
340​
341 it.effect("does not delay the parent turn when the child lookup fails", () =>
342 Effect.gen(function* () {
343 yield* Effect.addFinalizer(() =>
344 Effect.sync(() => {
345 NodeFS.rmSync(scriptPath, { force: true });
346 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
347 }),
348 );
349 for (const [name, childSnapshot] of [
350 ["hang", { hang: true }],
351 ["error", { error: "child unavailable" }],
352 ] as const) {
353 yield* Effect.gen(function* () {
354 const marker = `lookup-${name}`;
355 const script = {
356 rootThreadId: ROOT,
357 recordRequests: true,
358 resumeRequestMarker: marker,
359 notifications: [capturedStartedActivity()],
360 childResumeSnapshots: { [CHILD_A]: childSnapshot },
361 };
362 // @effect-diagnostics-next-line preferSchemaOverJson:off
363 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
364 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
365​
366 const runtime = yield* makeCodexSessionRuntime({
367 threadId: ThreadId.make(`thread-collab-model-${name}`),
368 binaryPath: peerPath,
369 cwd: "/tmp",
370 runtimeMode: "full-access",
371 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
372 });
373 const eventsFiber = yield* runtime.events.pipe(
374 Stream.takeUntil(
375 (event) =>
376 event.method === "serverRequest/resolved" &&
377 (event.payload as { requestId?: string }).requestId === marker,
378 ),
379 Stream.runCollect,
380 Effect.forkScoped,
381 );
382​
383 yield* runtime.start();
384 yield* runtime.sendTurn({ input: "finish without child metadata" });
385 const events = Array.from(yield* Fiber.join(eventsFiber));
386 assert.isTrue(events.some((event) => event.method === "turn/completed"));
387 assert.equal(readRecordedRequests().length, 1);
388​
389 yield* runtime.close;
390 NodeFS.rmSync(scriptPath, { force: true });
391 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
392 }).pipe(Effect.scoped);
393 }
394 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
395 );
396​
397 it.effect("replays the captured fan-out into synthetic agent events without child leaks", () =>
398 Effect.gen(function* () {
399 // @effect-diagnostics-next-line preferSchemaOverJson:off
400 NodeFS.writeFileSync(scriptPath, JSON.stringify(buildScript()), "utf8");
401 yield* Effect.addFinalizer(() =>
402 Effect.sync(() => NodeFS.rmSync(scriptPath, { force: true })),
403 );
404​
405 const runtime = yield* makeCodexSessionRuntime({
406 threadId: ThreadId.make("thread-collab-integration"),
407 binaryPath: peerPath,
408 cwd: "/tmp",
409 runtimeMode: "full-access",
410 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
411 });
412​
413 const eventsFiber = yield* runtime.events.pipe(
414 Stream.takeUntil((event) => event.method === "turn/completed"),
415 Stream.runCollect,
416 Effect.forkScoped,
417 );
418​
419 yield* runtime.start();
420 yield* runtime.sendTurn({ input: "fan out" });
421​
422 const events = Array.from(yield* Fiber.join(eventsFiber));
423 const methods = events.map((event) => event.method);
424​
425 // Children registered from subAgentActivity become synthetic agent
426 // lifecycle — including terminal rows that arrive AFTER the receiver
427 // map knows them (the ordering this test exists to pin).
428 assert.include(methods, "collabAgent/activity");
429 assert.include(methods, "collabAgent/turnCompleted");
430 assert.include(methods, "collabAgent/closed");
431​
432 const childTurnCompleted = events.find(
433 (event) =>
434 event.method === "collabAgent/turnCompleted" &&
435 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
436 );
437 assert.isDefined(childTurnCompleted, "child A's turn completion becomes an agent event");
438​
439 const childClosed = events.find(
440 (event) =>
441 event.method === "collabAgent/closed" &&
442 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
443 );
444 assert.isDefined(childClosed, "child B's close becomes an agent event");
445​
446 // Parent-owned resolution passes through — not swallowed, not
447 // re-labelled as an agent event.
448 assert.include(methods, "serverRequest/resolved");
449​
450 // The root's own subAgentActivity about "/root" must NOT register the
451 // root as a child: the parent turn completion still flows.
452 assert.include(methods, "turn/completed");
453​
454 // No raw child conversation methods leak onto the parent stream.
455 const leaked = events.filter((event) => {
456 const payload = event.payload as { threadId?: string } | undefined;
457 const addressedToChild = payload?.threadId === CHILD_A || payload?.threadId === CHILD_B;
458 return addressedToChild && (event.method?.startsWith("thread/") ?? false);
459 });
460 assert.deepEqual(
461 leaked.map((event) => event.method),
462 [],
463 "child thread/* lifecycle must not appear as parent events",
464 );
465​
466 yield* runtime.close;
467 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
468 );
469​
470 // it.live: the runtime talks to a real child process; under it.effect's
471 // TestClock the internal timers freeze and the join never completes.
472 it.live("Stop interrupts every live child regardless of registration timing", () =>
473 Effect.gen(function* () {
474 // Ordering + liveness torture for stop-everything: child A's
475 // turn/started arrives BEFORE anything registers it (foreign
476 // suppression path must record the live turn); child B's arrives after
477 // registration; child A's interrupt HANGS (RPC never settles — worse
478 // than rejecting) and the bounded deadline must still deliver B's and
479 // the parent's interrupts. The turn stays open so children are live
480 // when Stop fires.
481 // Build from REAL captured rows (hand-written shapes fail notification
482 // schema validation and are silently dropped): reorder so child A's
483 // turn/started precedes its registration, and drop terminal rows so
484 // children stay live when Stop fires.
485 const byIndex = wireFixture.notifications;
486 const isTurnStarted = (entry: (typeof byIndex)[number], child: string) =>
487 entry.method === "turn/started" &&
488 (entry.params as { threadId?: string }).threadId === child;
489 const isRegistration = (entry: (typeof byIndex)[number], child: string) => {
490 const item = (entry.params as { item?: { type?: string; agentThreadId?: string } }).item;
491 return item?.type === "subAgentActivity" && item.agentThreadId === child;
492 };
493 const turnStartedA = byIndex.find((entry) => isTurnStarted(entry, CHILD_A));
494 const turnStartedB = byIndex.find((entry) => isTurnStarted(entry, CHILD_B));
495 const registrationA = byIndex.find((entry) => isRegistration(entry, CHILD_A));
496 const registrationB = byIndex.find((entry) => isRegistration(entry, CHILD_B));
497 const rootThreadStarted = byIndex.find((entry) => entry.method === "thread/started");
498 assert.isDefined(turnStartedA);
499 assert.isDefined(turnStartedB);
500 assert.isDefined(registrationA);
501 assert.isDefined(registrationB);
502 assert.isDefined(rootThreadStarted);
503 const memoryThreadStarted = {
504 ...rootThreadStarted,
505 params: {
506 thread: {
507 ...rootThreadStarted.params.thread,
508 id: MEMORY,
509 sessionId: MEMORY,
510 source: "unknown",
511 threadSource: "memory_consolidation",
512 },
513 },
514 };
515 const memoryTurnStarted = {
516 ...turnStartedA,
517 params: {
518 ...turnStartedA.params,
519 threadId: MEMORY,
520 turn: { ...turnStartedA.params.turn, id: "memory-consolidation-turn" },
521 },
522 };
523 const script = {
524 rootThreadId: ROOT,
525 holdTurnOpen: true,
526 hangInterruptFor: CHILD_A,
527 notifications: [
528 turnStartedA,
529 registrationA,
530 memoryThreadStarted,
531 memoryTurnStarted,
532 registrationB,
533 turnStartedB,
534 ],
535 };
536 // @effect-diagnostics-next-line preferSchemaOverJson:off
537 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
538 const interruptsPath = `${scriptPath}.interrupts`;
539 NodeFS.rmSync(interruptsPath, { force: true });
540 yield* Effect.addFinalizer(() =>
541 Effect.sync(() => {
542 NodeFS.rmSync(scriptPath, { force: true });
543 NodeFS.rmSync(interruptsPath, { force: true });
544 }),
545 );
546​
547 const runtime = yield* makeCodexSessionRuntime({
548 threadId: ThreadId.make("thread-collab-stop"),
549 binaryPath: peerPath,
550 cwd: "/tmp",
551 runtimeMode: "full-access",
552 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
553 });
554​
555 // Wait for both children's turnStarted signals to be processed before
556 // stopping (B via the registered-child path; A only produces live-turn
557 // bookkeeping, so key on B's synthetic event).
558 const childBStartedFiber = yield* runtime.events.pipe(
559 Stream.filter(
560 (event) =>
561 event.method === "collabAgent/turnStarted" &&
562 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
563 ),
564 Stream.take(1),
565 Stream.runCollect,
566 Effect.forkScoped,
567 );
568​
569 yield* runtime.start();
570 yield* runtime.sendTurn({ input: "fan out and hang" });
571 const childBStarted = yield* Fiber.join(childBStartedFiber).pipe(
572 Effect.timeoutOption("15 seconds"),
573 );
574 assert.isTrue(childBStarted._tag === "Some", "child B turnStarted never arrived");
575​
576 // Stop everything. A's interrupt hangs forever — the bounded child
577 // deadline must expire and the parent interrupt must still be sent.
578 yield* runtime.interruptTurn();
579​
580 const parseInterruptLine = (line: string) => JSON.parse(line) as { threadId?: string };
581 const interrupted = NodeFS.readFileSync(interruptsPath, "utf8")
582 .trim()
583 .split("\n")
584 .filter((line) => line.length > 0)
585 .map(parseInterruptLine);
586 const interruptedThreads = new Set(interrupted.map((entry) => entry.threadId));
587 assert.isTrue(
588 interruptedThreads.has(CHILD_A),
589 "pre-registration child A must still receive the interrupt RPC",
590 );
591 assert.isTrue(interruptedThreads.has(CHILD_B), "registered child B must be interrupted");
592 assert.isTrue(
593 interruptedThreads.has(MEMORY),
594 "memory consolidation must be interrupted without appearing in chat",
595 );
596 assert.isTrue(interruptedThreads.has(ROOT), "parent turn must be interrupted last");
597​
598 yield* runtime.close;
599 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
600 );
601​
602 it.live("Stop targets the active turn when Codex has accepted a queued follow-up", () =>
603 Effect.gen(function* () {
604 const activeTurnId = "019fe3e8-f908-7f31-8d51-283f4a47897a";
605 const queuedTurnId = "019fe3eb-8faf-7de3-a85b-ac64c7f9c8c3";
606 const script = {
607 rootThreadId: ROOT,
608 holdTurnOpen: true,
609 onlyFirstTurnStarts: true,
610 turnIds: [activeTurnId, queuedTurnId],
611 expectedActiveTurnId: activeTurnId,
612 notifications: [],
613 };
614 // @effect-diagnostics-next-line preferSchemaOverJson:off
615 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
616 const interruptsPath = `${scriptPath}.interrupts`;
617 NodeFS.rmSync(interruptsPath, { force: true });
618 yield* Effect.addFinalizer(() =>
619 Effect.sync(() => {
620 NodeFS.rmSync(scriptPath, { force: true });
621 NodeFS.rmSync(interruptsPath, { force: true });
622 }),
623 );
624​
625 const runtime = yield* makeCodexSessionRuntime({
626 threadId: ThreadId.make("thread-codex-queued-stop"),
627 binaryPath: peerPath,
628 cwd: "/tmp",
629 runtimeMode: "full-access",
630 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
631 });
632​
633 yield* runtime.start();
634 yield* runtime.sendTurn({ input: "keep working" });
635 yield* runtime.sendTurn({ input: "queued follow-up" });
636 yield* runtime.interruptTurn();
637​
638 const interrupts = NodeFS.readFileSync(interruptsPath, "utf8")
639 .trim()
640 .split("\n")
641 .map((line) => JSON.parse(line) as { threadId?: string; turnId?: string });
642 assert.deepEqual(interrupts.at(-1), {
643 threadId: ROOT,
644 turnId: activeTurnId,
645 });
646​
647 yield* runtime.close;
648 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
649 );
650​
651 const elicitationCases = [
652 {
653 decision: "accept",
654 response: { action: "accept", content: { approval: "once" } },
655 },
656 {
657 decision: "acceptForSession",
658 response: {
659 action: "accept",
660 _meta: { persist: "session" },
661 content: { approval: "session" },
662 },
663 },
664 {
665 decision: "acceptAlways",
666 response: {
667 action: "accept",
668 _meta: { persist: "always" },
669 content: { approval: "always" },
670 },
671 },
672 { decision: "decline", response: { action: "decline" } },
673 { decision: "cancel", response: { action: "cancel" } },
674 ] satisfies ReadonlyArray<{
675 readonly decision: ProviderApprovalDecision;
676 readonly response: Record<string, unknown>;
677 }>;
678​
679 for (const { decision, response } of elicitationCases) {
680 it.live(`returns the MCP elicitation ${decision} response to Codex`, () =>
681 Effect.gen(function* () {
682 const scriptedRequest = {
683 id: 7001,
684 method: "mcpServer/elicitation/request",
685 params: {
686 mode: "form",
687 message: "Allow ChatGPT to use Safari?",
688 serverName: "computer-use",
689 threadId: ROOT,
690 turnId: wireFixture.responses.turnStart.turn.id,
691 _meta: { app_name: "Safari", persist: ["session", "always"] },
692 requestedSchema: {
693 type: "object",
694 properties: {
695 approval: {
696 type: "string",
697 enum: ["once", "session", "always"],
698 },
699 },
700 required: ["approval"],
701 },
702 },
703 };
704 const script = {
705 rootThreadId: ROOT,
706 holdTurnOpen: true,
707 completeTurnOnServerResponse: true,
708 notifications: [],
709 serverRequests: [scriptedRequest],
710 };
711 const responsesPath = `${scriptPath}.responses`;
712 // @effect-diagnostics-next-line preferSchemaOverJson:off
713 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
714 NodeFS.rmSync(responsesPath, { force: true });
715 yield* Effect.addFinalizer(() =>
716 Effect.sync(() => {
717 NodeFS.rmSync(scriptPath, { force: true });
718 NodeFS.rmSync(responsesPath, { force: true });
719 }),
720 );
721​
722 const runtime = yield* makeCodexSessionRuntime({
723 threadId: ThreadId.make("thread-codex-mcp-elicitation"),
724 binaryPath: peerPath,
725 cwd: "/tmp",
726 runtimeMode: "auto",
727 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
728 });
729 const approvalRequested = yield* Deferred.make<ProviderEvent>();
730 const turnCompleted = yield* Deferred.make<void>();
731 yield* runtime.events.pipe(
732 Stream.runForEach((event) =>
733 event.method === "mcpServer/elicitation/request"
734 ? Deferred.succeed(approvalRequested, event).pipe(Effect.asVoid)
735 : event.method === "turn/completed"
736 ? Deferred.succeed(turnCompleted, undefined).pipe(Effect.asVoid)
737 : Effect.void,
738 ),
739 Effect.forkScoped,
740 );
741​
742 yield* runtime.start();
743 yield* runtime.sendTurn({ input: "Open Safari" });
744 const approval = yield* Deferred.await(approvalRequested);
745 assert.equal(approval.requestKind, "mcp-elicitation");
746 assert.isDefined(approval.requestId);
747 if (approval.requestId === undefined) return;
748​
749 yield* runtime.respondToRequest(approval.requestId, decision);
750 yield* Deferred.await(turnCompleted);
751​
752 const recordedResponse = yield* decodeMcpElicitationResponse(
753 NodeFS.readFileSync(responsesPath, "utf8"),
754 );
755 assert.equal(recordedResponse.id, scriptedRequest.id);
756 assert.deepEqual(recordedResponse.result, response);
757​
758 yield* runtime.close;
759 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
760 );
761 }
762});