Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 type ModelSelection,
5 NodeId,
6 type OrchestrationV2AppThread,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ExecutionNode,
9 type OrchestrationV2PlanArtifact,
10 type OrchestrationV2RuntimeRequest,
11 type OrchestrationV2ProviderThread,
12 type OrchestrationV2Run,
13 type OrchestrationV2TurnItem,
14 ProviderDriverKind,
15 ProviderInstanceId,
16 PlanId,
17 RunAttemptId,
18 RunId,
19 RuntimeRequestId,
20 TurnItemId,
21} from "@t3tools/contracts";
22import * as DateTime from "effect/DateTime";
23import * as Deferred from "effect/Deferred";
24import * as Fiber from "effect/Fiber";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Stream from "effect/Stream";
28import * as TestClock from "effect/testing/TestClock";
29
30import { toolOutputImages } from "@t3tools/shared/toolOutput";
31import * as SqlitePersistence from "../persistence/Sqlite.ts";
32import * as EventSink from "./EventSink.ts";
33import * as EventStore from "./EventStore.ts";
34import * as IdAllocator from "./IdAllocator.ts";
35import * as ProjectionStore from "./ProjectionStore.ts";
36import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
37import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
38import { makeProviderFailure } from "./ProviderFailure.ts";
39import {
40 makeProviderEventRoutingState,
41 type ProviderEventRouteIdentity,
42 routeProviderEvent,
43 selectInheritedBackgroundTurnItems,
44} from "./RunExecutionService.ts";
45
46const layerTestDatabase = SqlitePersistence.layerMemory;
47const layerTestStores = Layer.merge(EventStore.layer, ProjectionStore.layer).pipe(
48 Layer.provide(layerTestDatabase),
49);
50
51const layerTestEventSink = EventSink.layer.pipe(
52 Layer.provide(Layer.mergeAll(layerTestStores, layerTestDatabase)),
53);
54
55const layerTest = Layer.mergeAll(
56 layerTestStores,
57 layerTestEventSink,
58 IdAllocator.layer,
59 ThreadCommandExecutor.layer,
60 ProviderEventIngestor.layer.pipe(
61 Layer.provide(
62 Layer.mergeAll(
63 layerTestStores,
64 layerTestEventSink,
65 IdAllocator.layer,
66 ThreadCommandExecutor.layer,
67 ),
68 ),
69 ),
70);
71const modelSelection = {
72 instanceId: ProviderInstanceId.make("codex"),
73 model: "gpt-5.4",
74} satisfies ModelSelection;
75const CODEX_DRIVER = ProviderDriverKind.make("codex");
76
77function threadCreatedEvent(
78 now: DateTime.Utc,
79): Effect.Effect<
80 OrchestrationV2DomainEvent,
81 IdAllocator.IdAllocatorV2Error,
82 IdAllocator.IdAllocatorV2
83> {
84 return Effect.gen(function* () {
85 const idAllocator = yield* IdAllocator.IdAllocatorV2;
86 const projectId = yield* idAllocator.allocate.project({
87 fixtureName: "provider-event-ingestor",
88 });
89 const threadId = yield* idAllocator.allocate.thread({
90 fixtureName: "provider-event-ingestor",
91 projectId,
92 });
93 const providerThreadId = idAllocator.derive.providerThread({
94 driver: CODEX_DRIVER,
95 nativeThreadId: "native-thread",
96 });
97 const thread: OrchestrationV2AppThread = {
98 createdBy: "user",
99 creationSource: "web",
100 id: threadId,
101 projectId,
102 title: "Provider event ingestor",
103 providerInstanceId: modelSelection.instanceId,
104 modelSelection: modelSelection,
105 runtimeMode: "full-access",
106 interactionMode: "default",
107 branch: null,
108 worktreePath: null,
109 branchPullRequest: null,
110 activeOrderKey: null,
111 activeProviderThreadId: providerThreadId,
112 lineage: {
113 parentThreadId: null,
114 relationshipToParent: null,
115 rootThreadId: threadId,
116 },
117 forkedFrom: null,
118 createdAt: now,
119 updatedAt: now,
120 archivedAt: null,
121 settledOverride: null,
122 settledAt: null,
123 lastVisitedAt: null,
124 deletedAt: null,
125 };
126
127 return {
128 id: yield* idAllocator.allocate.event({ threadId }),
129 type: "thread.created",
130 threadId,
131 occurredAt: now,
132 payload: thread,
133 };
134 });
135}
136
137const layer = it.layer(layerTest);
138
139it.effect("records accepted billed turn usage once without billing the context window", () => {
140 const recorded: Array<Readonly<Record<string, unknown>>> = [];
141 const layerAnalytics = Layer.succeed(ProviderEventIngestor.ProviderTurnAnalytics, {
142 record: (properties: Readonly<Record<string, unknown>>) =>
143 Effect.sync(() => {
144 recorded.push(properties);
145 }),
146 });
147 return Effect.gen(function* () {
148 const now = yield* DateTime.now;
149 const eventSink = yield* EventSink.EventSinkV2;
150 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
151 const idAllocator = yield* IdAllocator.IdAllocatorV2;
152 const threadEvent = yield* threadCreatedEvent(now);
153 yield* eventSink.write({ events: [threadEvent] });
154 const providerSessionId = yield* idAllocator.allocate.providerSession({
155 providerInstanceId: modelSelection.instanceId,
156 threadId: threadEvent.threadId,
157 });
158 const providerThreadId = idAllocator.derive.providerThread({
159 driver: CODEX_DRIVER,
160 nativeThreadId: "billing-thread",
161 });
162 const providerTurn = {
163 id: idAllocator.derive.providerTurn({ driver: CODEX_DRIVER, nativeTurnId: "billing-turn" }),
164 providerThreadId,
165 nodeId: NodeId.make("node:billing-turn"),
166 runAttemptId: null,
167 nativeTurnRef: null,
168 ordinal: 1,
169 status: "completed" as const,
170 startedAt: now,
171 completedAt: DateTime.makeUnsafe(DateTime.toEpochMillis(now) + 120),
172 tokenUsage: {
173 inputTokens: 4000,
174 cachedInputTokens: 3000,
175 outputTokens: 100,
176 usedTokens: 4100,
177 updatedAt: DateTime.formatIso(now),
178 },
179 turnTokenUsage: {
180 usageStatus: "complete" as const,
181 usageScope: "main_agent" as const,
182 hasSubagents: false,
183 inputTokens: 40,
184 cachedInputTokens: 30,
185 outputTokens: 10,
186 },
187 };
188 const input = {
189 providerSessionId,
190 providerInstanceId: modelSelection.instanceId,
191 threadId: threadEvent.threadId,
192 analyticsContext: {
193 modelSelection,
194 runtimeMode: "full-access" as const,
195 interactionMode: "default" as const,
196 },
197 event: { type: "provider_turn.updated" as const, driver: CODEX_DRIVER, providerTurn },
198 };
199 yield* ingestor.ingestNormalized(input);
200 yield* ingestor.ingestNormalized(input);
201 const ignored = yield* ingestor.ingestNormalized({
202 ...input,
203 event: {
204 ...input.event,
205 providerTurn: {
206 ...providerTurn,
207 id: idAllocator.derive.providerTurn({
208 driver: CODEX_DRIVER,
209 nativeTurnId: "stale-billing-turn",
210 }),
211 },
212 },
213 writeIfRunCurrent: {
214 runId: RunId.make("missing-run"),
215 activeAttemptId: RunAttemptId.make("stale-attempt"),
216 expectedStatus: "running",
217 },
218 });
219 assert.isEmpty(ignored);
220 assert.lengthOf(recorded, 1);
221 assert.deepEqual(recorded[0], {
222 provider: CODEX_DRIVER,
223 terminalStatus: "completed",
224 usageStatus: "complete",
225 usageScope: "main_agent",
226 hasSubagents: false,
227 inputTokens: 40,
228 cachedInputTokens: 30,
229 outputTokens: 10,
230 model: modelSelection.model,
231 mixedModels: false,
232 runtimeMode: "full-access",
233 interactionMode: "default",
234 durationMs: 120,
235 });
236 }).pipe(Effect.provide(layerTest.pipe(Layer.provide(layerAnalytics))));
237});
238
239layer("ProviderEventIngestorV2", (it) => {
240 it.effect("normalizes provider events through the real event log and projection store", () =>
241 Effect.gen(function* () {
242 const now = yield* DateTime.now;
243 const eventSink = yield* EventSink.EventSinkV2;
244 const eventStore = yield* EventStore.EventStoreV2;
245 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
246 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
247 const idAllocator = yield* IdAllocator.IdAllocatorV2;
248 const threadEvent = yield* threadCreatedEvent(now);
249 const providerSessionId = yield* idAllocator.allocate.providerSession({
250 providerInstanceId: modelSelection.instanceId,
251 threadId: threadEvent.threadId,
252 });
253 const providerThread: OrchestrationV2ProviderThread = {
254 id: idAllocator.derive.providerThread({
255 driver: CODEX_DRIVER,
256 nativeThreadId: "native-thread",
257 }),
258 driver: CODEX_DRIVER,
259 providerInstanceId: modelSelection.instanceId,
260 providerSessionId,
261 appThreadId: threadEvent.threadId,
262 ownerNodeId: null,
263 nativeThreadRef: {
264 driver: CODEX_DRIVER,
265 nativeId: "native-thread",
266 strength: "strong",
267 },
268 nativeConversationHeadRef: null,
269 status: "idle",
270 firstRunOrdinal: null,
271 lastRunOrdinal: null,
272 handoffIds: [],
273 forkedFrom: null,
274 createdAt: now,
275 updatedAt: now,
276 };
277
278 yield* eventSink.write({ events: [threadEvent] });
279 const storedEvents = yield* ingestor.ingestNormalized({
280 providerSessionId,
281 providerInstanceId: modelSelection.instanceId,
282 threadId: threadEvent.threadId,
283 event: {
284 type: "provider_thread.updated",
285 driver: CODEX_DRIVER,
286 providerThread,
287 },
288 });
289
290 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
291 const storedDomainEvents = yield* eventStore.read({}).pipe(Stream.runCollect);
292 const afterFirstEvent = yield* eventStore
293 .read({ afterSequence: 1, threadId: threadEvent.threadId })
294 .pipe(Stream.runCollect);
295 const latestThreadSequence = yield* eventStore.latestSequence({
296 threadId: threadEvent.threadId,
297 });
298
299 assert.equal(storedEvents.length, 1);
300 assert.equal(storedEvents[0]?.event.type, "provider-thread.updated");
301 assert.deepEqual(
302 projection.providerThreads.map((thread) => thread.id),
303 [providerThread.id],
304 );
305 assert.deepEqual(
306 Array.from(storedDomainEvents).map((stored) => stored.event.type),
307 ["thread.created", "provider-thread.updated"],
308 );
309 assert.deepEqual(
310 Array.from(storedDomainEvents).map((stored) => stored.sequence),
311 [1, 2],
312 );
313 assert.deepEqual(
314 Array.from(afterFirstEvent).map((stored) => stored.event.type),
315 ["provider-thread.updated"],
316 );
317 assert.equal(latestThreadSequence, 2);
318 }),
319 );
320
321 it.effect("carries plan-step durations through consecutive and restarted ingestion", () =>
322 Effect.gen(function* () {
323 yield* TestClock.setTime(Date.parse("2026-09-07T00:00:00.000Z"));
324 const now = yield* DateTime.now;
325 const eventSink = yield* EventSink.EventSinkV2;
326 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
327 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
328 const idAllocator = yield* IdAllocator.IdAllocatorV2;
329 const threadEvent = yield* threadCreatedEvent(now);
330 const providerSessionId = yield* idAllocator.allocate.providerSession({
331 providerInstanceId: modelSelection.instanceId,
332 threadId: threadEvent.threadId,
333 });
334 const planId = PlanId.make("plan:provider-event-duration");
335 const nodeId = NodeId.make("node:provider-event-duration");
336 type TodoListPlan = Extract<OrchestrationV2PlanArtifact, { readonly kind: "todo_list" }>;
337 const plan = (steps: TodoListPlan["steps"]): TodoListPlan => ({
338 id: planId,
339 threadId: threadEvent.threadId,
340 runId: null,
341 nodeId,
342 kind: "todo_list",
343 status: "active",
344 steps,
345 });
346 const ingest = (
347 service: ProviderEventIngestor.ProviderEventIngestorV2["Service"],
348 steps: TodoListPlan["steps"],
349 ) =>
350 service.ingestNormalized({
351 providerSessionId,
352 providerInstanceId: modelSelection.instanceId,
353 threadId: threadEvent.threadId,
354 event: { type: "plan.updated", driver: CODEX_DRIVER, plan: plan(steps) },
355 });
356
357 yield* eventSink.write({ events: [threadEvent] });
358 yield* ingest(ingestor, [
359 { id: "duplicate-a", text: "Verify", status: "running" },
360 { id: "duplicate-b", text: "Verify", status: "pending" },
361 { id: "fallback", text: "Report", status: "pending" },
362 ]);
363 yield* TestClock.adjust("3 seconds");
364 yield* ingest(ingestor, [
365 { id: "duplicate-a", text: "Verify", status: "completed" },
366 { id: "duplicate-b", text: "Verify", status: "pending" },
367 { id: "fallback", text: "Report", status: "pending" },
368 ]);
369
370 const restartedIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
371 Effect.provide(
372 Layer.fresh(ProviderEventIngestor.layer).pipe(
373 Layer.provide(
374 Layer.succeed(ProjectionStore.ProjectionStoreV2, {
375 ...projectionStore,
376 getThreadProjection: () => Effect.die("Plan timing must not load thread history"),
377 }),
378 ),
379 ),
380 ),
381 );
382 yield* TestClock.adjust("4 seconds");
383 yield* ingest(restartedIngestor, [
384 { id: "duplicate-a", text: "Verify", status: "completed" },
385 { id: "duplicate-b", text: "Verify", status: "completed" },
386 { id: "fallback", text: "Report", status: "pending" },
387 ]);
388 yield* TestClock.adjust("5 seconds");
389 yield* ingest(restartedIngestor, [
390 { id: "duplicate-a", text: "Verify", status: "completed" },
391 { id: "duplicate-b", text: "Verify", status: "completed" },
392 { id: "fallback", text: "Report", status: "completed" },
393 ]);
394
395 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
396 const persisted = projection.plans.find(
397 (candidate): candidate is TodoListPlan =>
398 candidate.kind === "todo_list" && candidate.id === planId,
399 );
400 assert.deepEqual(
401 persisted?.steps.map(({ id, text, status, durationMs }) => ({
402 id,
403 text,
404 status,
405 durationMs,
406 })),
407 [
408 { id: "duplicate-a", text: "Verify", status: "completed", durationMs: 3_000 },
409 { id: "duplicate-b", text: "Verify", status: "completed", durationMs: 4_000 },
410 { id: "fallback", text: "Report", status: "completed", durationMs: 5_000 },
411 ],
412 );
413
414 yield* ingest(restartedIngestor, [
415 { id: "duplicate-a", text: "Inserted task", status: "running" },
416 { id: "duplicate-b", text: "Verify", status: "completed" },
417 { id: "fallback", text: "Different completed task", status: "completed" },
418 ]);
419 yield* TestClock.adjust("2 seconds");
420 yield* ingest(restartedIngestor, [
421 { id: "duplicate-a", text: "Inserted task", status: "completed" },
422 { id: "duplicate-b", text: "Verify", status: "completed" },
423 { id: "fallback", text: "Different completed task", status: "completed" },
424 ]);
425 const updated = yield* projectionStore.getThreadProjection(threadEvent.threadId);
426 const changedPlan = updated.plans.find(
427 (candidate): candidate is TodoListPlan =>
428 candidate.kind === "todo_list" && candidate.id === planId,
429 );
430 assert.deepEqual(
431 changedPlan?.steps.map((step) => step.durationMs),
432 [2_000, 4_000, undefined],
433 );
434 }),
435 );
436
437 it.effect(
438 "treats successful provider terminal markers as non-persisted orchestration control signals",
439 () =>
440 Effect.gen(function* () {
441 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
442 const idAllocator = yield* IdAllocator.IdAllocatorV2;
443 const projectId = yield* idAllocator.allocate.project({
444 fixtureName: "provider-event-terminal",
445 });
446 const threadId = yield* idAllocator.allocate.thread({
447 fixtureName: "provider-event-terminal",
448 projectId,
449 });
450 const providerSessionId = yield* idAllocator.allocate.providerSession({
451 providerInstanceId: modelSelection.instanceId,
452 threadId,
453 });
454 const normalized = yield* ingestor.normalize({
455 providerSessionId,
456 providerInstanceId: modelSelection.instanceId,
457 threadId,
458 event: {
459 type: "turn.terminal",
460 driver: CODEX_DRIVER,
461 providerThreadId: idAllocator.derive.providerThread({
462 driver: CODEX_DRIVER,
463 nativeThreadId: "native-thread",
464 }),
465 providerTurnId: idAllocator.derive.providerTurn({
466 driver: CODEX_DRIVER,
467 nativeTurnId: "native-turn",
468 }),
469 runOrdinal: 1,
470 status: "completed",
471 failure: null,
472 threadDisposition: "reusable",
473 },
474 });
475
476 assert.deepEqual(normalized, []);
477 }),
478 );
479
480 it.effect("persists an interrupted run's inherited terminal through the live run router", () =>
481 Effect.gen(function* () {
482 const now = yield* DateTime.now;
483 const eventSink = yield* EventSink.EventSinkV2;
484 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
485 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
486 const idAllocator = yield* IdAllocator.IdAllocatorV2;
487 const threadEvent = yield* threadCreatedEvent(now);
488 const priorRunId = RunId.make("run:provider-event-inherited:prior");
489 const currentRunId = RunId.make("run:provider-event-inherited:current");
490 const itemId = TurnItemId.make("turn-item:provider-event-inherited");
491 const providerSessionId = yield* idAllocator.allocate.providerSession({
492 providerInstanceId: modelSelection.instanceId,
493 threadId: threadEvent.threadId,
494 });
495 const providerThreadId = idAllocator.derive.providerThread({
496 driver: CODEX_DRIVER,
497 nativeThreadId: "native-thread-inherited",
498 });
499 const providerTurnId = idAllocator.derive.providerTurn({
500 driver: CODEX_DRIVER,
501 nativeTurnId: "native-turn-inherited",
502 });
503 const runningItem = {
504 id: itemId,
505 threadId: threadEvent.threadId,
506 runId: priorRunId,
507 nodeId: NodeId.make("node:provider-event-inherited"),
508 providerThreadId,
509 providerTurnId,
510 nativeItemRef: null,
511 parentItemId: null,
512 ordinal: 101,
513 status: "running",
514 title: "Inherited background command",
515 startedAt: now,
516 completedAt: null,
517 updatedAt: now,
518 type: "command_execution",
519 input: "sleep 60",
520 } satisfies OrchestrationV2TurnItem;
521 const terminalItem = {
522 ...runningItem,
523 status: "completed" as const,
524 completedAt: now,
525 updatedAt: now,
526 };
527
528 yield* eventSink.write({ events: [threadEvent] });
529 yield* ingestor.ingestNormalized({
530 providerSessionId,
531 providerInstanceId: modelSelection.instanceId,
532 threadId: threadEvent.threadId,
533 runId: priorRunId,
534 event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem: runningItem },
535 });
536
537 const identity: ProviderEventRouteIdentity = {
538 threadId: threadEvent.threadId,
539 runId: currentRunId,
540 attemptId: RunAttemptId.make("attempt:provider-event-inherited:current"),
541 providerThreadId,
542 };
543 const inheritedBackgroundTurnItems = selectInheritedBackgroundTurnItems({
544 threadId: threadEvent.threadId,
545 currentProviderThreadId: providerThreadId,
546 currentRunOrdinal: 2,
547 runs: [
548 {
549 id: priorRunId,
550 threadId: threadEvent.threadId,
551 ordinal: 1,
552 status: "interrupted",
553 } as OrchestrationV2Run,
554 {
555 id: currentRunId,
556 threadId: threadEvent.threadId,
557 ordinal: 2,
558 status: "running",
559 } as OrchestrationV2Run,
560 ],
561 turnItems: [runningItem],
562 });
563 const routeState = makeProviderEventRoutingState({
564 identity,
565 inheritedBackgroundTurnItems,
566 providerTurnId: null,
567 });
568 const terminalEvent = {
569 type: "turn_item.updated",
570 driver: CODEX_DRIVER,
571 turnItem: terminalItem,
572 } as const;
573 const [accepted] = routeProviderEvent(terminalEvent, identity, routeState);
574 assert.isTrue(accepted);
575
576 const stored = yield* ingestor.ingestNormalized({
577 providerSessionId,
578 providerInstanceId: modelSelection.instanceId,
579 threadId: threadEvent.threadId,
580 runId: currentRunId,
581 event: terminalEvent,
582 });
583 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
584 const persisted = projection.turnItems.find((item) => item.id === itemId);
585
586 assert.equal(stored.length, 1);
587 assert.equal(stored[0]?.event.type, "turn-item.updated");
588 assert.equal(persisted?.runId, priorRunId);
589 assert.equal(persisted?.threadId, threadEvent.threadId);
590 assert.equal(persisted?.status, "completed");
591 }),
592 );
593
594 it.effect("persists a completed run's late background terminal exactly once", () =>
595 Effect.gen(function* () {
596 const now = yield* DateTime.now;
597 const eventSink = yield* EventSink.EventSinkV2;
598 const eventStore = yield* EventStore.EventStoreV2;
599 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
600 const idAllocator = yield* IdAllocator.IdAllocatorV2;
601 const threadEvent = yield* threadCreatedEvent(now);
602 const priorRunId = RunId.make("run:provider-event-completed:prior");
603 const currentRunId = RunId.make("run:provider-event-completed:current");
604 const itemId = TurnItemId.make("turn-item:provider-event-completed");
605 const providerSessionId = yield* idAllocator.allocate.providerSession({
606 providerInstanceId: modelSelection.instanceId,
607 threadId: threadEvent.threadId,
608 });
609 const providerThreadId = idAllocator.derive.providerThread({
610 driver: CODEX_DRIVER,
611 nativeThreadId: "native-thread-completed",
612 });
613 const providerTurnId = idAllocator.derive.providerTurn({
614 driver: CODEX_DRIVER,
615 nativeTurnId: "native-turn-completed",
616 });
617 const runningItem = {
618 id: itemId,
619 threadId: threadEvent.threadId,
620 runId: priorRunId,
621 nodeId: NodeId.make("node:provider-event-completed"),
622 providerThreadId,
623 providerTurnId,
624 nativeItemRef: null,
625 parentItemId: null,
626 ordinal: 101,
627 status: "running",
628 title: "Completed run background command",
629 startedAt: now,
630 completedAt: null,
631 updatedAt: now,
632 type: "command_execution",
633 input: "sleep 60",
634 } satisfies OrchestrationV2TurnItem;
635 const terminalEvent = {
636 type: "turn_item.updated",
637 driver: CODEX_DRIVER,
638 turnItem: {
639 ...runningItem,
640 status: "completed" as const,
641 completedAt: now,
642 updatedAt: now,
643 },
644 } as const;
645
646 yield* eventSink.write({ events: [threadEvent] });
647 yield* ingestor.ingestNormalized({
648 providerSessionId,
649 providerInstanceId: modelSelection.instanceId,
650 threadId: threadEvent.threadId,
651 runId: priorRunId,
652 event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem: runningItem },
653 });
654
655 const priorIdentity: ProviderEventRouteIdentity = {
656 threadId: threadEvent.threadId,
657 runId: priorRunId,
658 attemptId: RunAttemptId.make("attempt:provider-event-completed:prior"),
659 providerThreadId,
660 };
661 const currentIdentity: ProviderEventRouteIdentity = {
662 threadId: threadEvent.threadId,
663 runId: currentRunId,
664 attemptId: RunAttemptId.make("attempt:provider-event-completed:current"),
665 providerThreadId,
666 };
667 const inheritedBackgroundTurnItems = selectInheritedBackgroundTurnItems({
668 threadId: threadEvent.threadId,
669 currentProviderThreadId: providerThreadId,
670 currentRunOrdinal: 2,
671 runs: [
672 {
673 id: priorRunId,
674 threadId: threadEvent.threadId,
675 ordinal: 1,
676 status: "completed",
677 } as OrchestrationV2Run,
678 {
679 id: currentRunId,
680 threadId: threadEvent.threadId,
681 ordinal: 2,
682 status: "running",
683 } as OrchestrationV2Run,
684 ],
685 turnItems: [runningItem],
686 });
687 const routers = [
688 {
689 identity: priorIdentity,
690 state: makeProviderEventRoutingState({
691 identity: priorIdentity,
692 providerTurnId: providerTurnId,
693 }),
694 },
695 {
696 identity: currentIdentity,
697 state: makeProviderEventRoutingState({
698 identity: currentIdentity,
699 inheritedBackgroundTurnItems,
700 providerTurnId: null,
701 }),
702 },
703 ];
704 const acceptedRouters = routers.filter(
705 ({ identity, state }) => routeProviderEvent(terminalEvent, identity, state)[0],
706 );
707
708 yield* Effect.forEach(
709 acceptedRouters,
710 ({ identity }) =>
711 ingestor.ingestNormalized({
712 providerSessionId,
713 providerInstanceId: modelSelection.instanceId,
714 threadId: threadEvent.threadId,
715 runId: identity.runId,
716 event: terminalEvent,
717 }),
718 { concurrency: 1 },
719 );
720
721 const storedEvents = yield* eventStore
722 .read({ threadId: threadEvent.threadId })
723 .pipe(Stream.runCollect);
724 const storedTerminals = Array.from(storedEvents).filter(
725 (stored) =>
726 stored.event.type === "turn-item.updated" &&
727 stored.event.payload.id === itemId &&
728 stored.event.payload.status === "completed",
729 );
730
731 assert.equal(storedTerminals.length, 1);
732 assert.equal(acceptedRouters.length, 1);
733 assert.equal(acceptedRouters[0]?.identity.runId, priorRunId);
734 }),
735 );
736
737 it.effect.each(["completed", "interrupted", "failed", "cancelled", "control"] as const)(
738 "dismisses only native questions when a provider turn ends with %s",
739 (terminal) =>
740 Effect.gen(function* () {
741 const now = yield* DateTime.now;
742 const eventSink = yield* EventSink.EventSinkV2;
743 const eventStore = yield* EventStore.EventStoreV2;
744 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
745 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
746 const idAllocator = yield* IdAllocator.IdAllocatorV2;
747 const threadEvent = yield* threadCreatedEvent(now);
748 const threadId = threadEvent.threadId;
749 const providerSessionId = yield* idAllocator.allocate.providerSession({
750 providerInstanceId: modelSelection.instanceId,
751 threadId,
752 });
753 const providerThreadId = idAllocator.derive.providerThread({
754 driver: CODEX_DRIVER,
755 nativeThreadId: `${threadId}:questions`,
756 });
757 const providerTurnId = idAllocator.derive.providerTurn({
758 driver: CODEX_DRIVER,
759 nativeTurnId: `${threadId}:questions`,
760 });
761 const otherTurnId = idAllocator.derive.providerTurn({
762 driver: CODEX_DRIVER,
763 nativeTurnId: `${threadId}:other-turn`,
764 });
765 const specs = [
766 { key: "native", responseCapability: { type: "live", providerSessionId } },
767 {
768 key: "unavailable",
769 responseCapability: { type: "not_resumable", reason: "Turn ended" },
770 },
771 { key: "message", responseCapability: { type: "message" } },
772 { key: "answered", responseCapability: { type: "live", providerSessionId } },
773 { key: "other-turn", responseCapability: { type: "live", providerSessionId } },
774 { key: "approval", responseCapability: { type: "live", providerSessionId } },
775 ] as const;
776 const fixtures = specs.map((spec, ordinal) => {
777 const nodeId = NodeId.make(`${threadId}:${spec.key}`);
778 const resolved = spec.key === "answered";
779 const request: OrchestrationV2RuntimeRequest = {
780 id: RuntimeRequestId.make(`${threadId}:${spec.key}`),
781 nodeId,
782 providerTurnId: spec.key === "other-turn" ? otherTurnId : providerTurnId,
783 nativeRequestRef: null,
784 kind: spec.key === "approval" ? "command" : "user_input",
785 status: resolved ? "resolved" : "pending",
786 responseCapability: spec.responseCapability,
787 createdAt: now,
788 resolvedAt: resolved ? now : null,
789 };
790 const node: OrchestrationV2ExecutionNode = {
791 id: nodeId,
792 threadId,
793 runId: null,
794 parentNodeId: null,
795 rootNodeId: nodeId,
796 kind: spec.key === "approval" ? "approval_request" : "user_input_request",
797 status: resolved ? "completed" : "waiting",
798 countsForRun: false,
799 providerThreadId,
800 providerTurnId: request.providerTurnId,
801 nativeItemRef: null,
802 runtimeRequestId: request.id,
803 checkpointScopeId: null,
804 startedAt: now,
805 completedAt: resolved ? now : null,
806 };
807 const item: OrchestrationV2TurnItem = {
808 id: TurnItemId.make(`${threadId}:${spec.key}`),
809 threadId,
810 runId: null,
811 nodeId,
812 providerThreadId,
813 providerTurnId: request.providerTurnId,
814 nativeItemRef: null,
815 parentItemId: null,
816 ordinal,
817 status: resolved ? "completed" : "waiting",
818 title: "Which option?",
819 startedAt: now,
820 completedAt: resolved ? now : null,
821 updatedAt: now,
822 ...(spec.key === "approval"
823 ? { type: "approval_request", requestId: request.id, requestKind: "command" }
824 : {
825 type: "user_input_request",
826 requestId: request.id,
827 questions: [],
828 ...(spec.key === "message" ? { responseMode: "message" as const } : {}),
829 }),
830 };
831 return { key: spec.key, request, node, item };
832 });
833 const seedEvents: Array<OrchestrationV2DomainEvent> = [threadEvent];
834 for (const fixture of fixtures) {
835 for (const payload of [
836 { type: "runtime-request.updated" as const, payload: fixture.request },
837 { type: "node.updated" as const, payload: fixture.node },
838 { type: "turn-item.updated" as const, payload: fixture.item },
839 ]) {
840 seedEvents.push({
841 id: yield* idAllocator.allocate.event({ threadId }),
842 threadId,
843 occurredAt: now,
844 ...payload,
845 });
846 }
847 }
848 yield* eventSink.write({ events: seedEvents });
849 const input = {
850 providerSessionId,
851 providerInstanceId: modelSelection.instanceId,
852 threadId,
853 event:
854 terminal === "control"
855 ? {
856 type: "turn.terminal" as const,
857 driver: CODEX_DRIVER,
858 providerThreadId,
859 providerTurnId,
860 runOrdinal: 1,
861 status: "completed" as const,
862 failure: null,
863 threadDisposition: "reusable" as const,
864 }
865 : {
866 type: "provider_turn.updated" as const,
867 driver: CODEX_DRIVER,
868 providerTurn: {
869 id: providerTurnId,
870 providerThreadId,
871 nodeId: NodeId.make(`${threadId}:root`),
872 runAttemptId: null,
873 nativeTurnRef: null,
874 ordinal: 1,
875 status: terminal,
876 startedAt: now,
877 completedAt: now,
878 },
879 },
880 };
881 const stored = yield* ingestor.ingestNormalized(input);
882 const projection = yield* projectionStore.getThreadProjection(threadId);
883 for (const fixture of fixtures) {
884 const closed = fixture.key === "native" || fixture.key === "unavailable";
885 const request = projection.runtimeRequests.find(
886 (item) => item.id === fixture.request.id,
887 )!;
888 const node = projection.nodes.find((item) => item.id === fixture.node.id)!;
889 const item = projection.turnItems.find((item) => item.id === fixture.item.id)!;
890 if (closed) {
891 assert.equal(request.status, "cancelled");
892 assert.isNotNull(request.resolvedAt);
893 assert.equal(node.status, "cancelled");
894 assert.isNotNull(node.completedAt);
895 assert.equal(item.status, "cancelled");
896 assert.isNotNull(item.completedAt);
897 } else {
898 assert.equal(request.status, fixture.request.status);
899 assert.equal(node.status, fixture.node.status);
900 assert.equal(item.status, fixture.item.status);
901 }
902 }
903 assert.equal(
904 stored.filter((entry) => entry.event.type === "runtime-request.updated").length,
905 2,
906 );
907 assert.isEmpty(
908 (yield* projectionStore.getPendingNativeUserInputs(threadId, providerTurnId))
909 .runtimeRequests,
910 );
911 const replayed = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
912 assert.equal(
913 replayed.filter(
914 (entry) =>
915 entry.event.type === "runtime-request.updated" &&
916 entry.event.payload.status === "cancelled",
917 ).length,
918 2,
919 );
920 const repeated = yield* ingestor.ingestNormalized(input);
921 assert.isFalse(repeated.some((entry) => entry.event.type === "runtime-request.updated"));
922 }),
923 );
924
925 it.effect(
926 "preserves an answer committed after terminal normalization reads a pending question",
927 () =>
928 Effect.scoped(
929 Effect.gen(function* () {
930 const eventSink = yield* EventSink.EventSinkV2;
931 const eventStore = yield* EventStore.EventStoreV2;
932 const projections = yield* ProjectionStore.ProjectionStoreV2;
933 const idAllocator = yield* IdAllocator.IdAllocatorV2;
934 const now = yield* DateTime.now;
935 const threadEvent = yield* threadCreatedEvent(now);
936 const threadId = threadEvent.threadId;
937 const providerSessionId = yield* idAllocator.allocate.providerSession({
938 providerInstanceId: modelSelection.instanceId,
939 threadId,
940 });
941 const providerThreadId = idAllocator.derive.providerThread({
942 driver: CODEX_DRIVER,
943 nativeThreadId: `${threadId}:race`,
944 });
945 const providerTurnId = idAllocator.derive.providerTurn({
946 driver: CODEX_DRIVER,
947 nativeTurnId: `${threadId}:race`,
948 });
949 const nodeId = NodeId.make(`${threadId}:question`);
950 const request: OrchestrationV2RuntimeRequest = {
951 id: RuntimeRequestId.make(`${threadId}:question`),
952 nodeId,
953 providerTurnId,
954 nativeRequestRef: null,
955 kind: "user_input",
956 status: "pending",
957 responseCapability: { type: "live", providerSessionId },
958 createdAt: now,
959 resolvedAt: null,
960 };
961 const node: OrchestrationV2ExecutionNode = {
962 id: nodeId,
963 threadId,
964 runId: null,
965 parentNodeId: null,
966 rootNodeId: nodeId,
967 kind: "user_input_request",
968 status: "waiting",
969 countsForRun: false,
970 providerThreadId,
971 providerTurnId,
972 nativeItemRef: null,
973 runtimeRequestId: request.id,
974 checkpointScopeId: null,
975 startedAt: now,
976 completedAt: null,
977 };
978 const item: OrchestrationV2TurnItem = {
979 id: TurnItemId.make(`${threadId}:question`),
980 threadId,
981 runId: null,
982 nodeId,
983 providerThreadId,
984 providerTurnId,
985 nativeItemRef: null,
986 parentItemId: null,
987 ordinal: 1,
988 status: "waiting",
989 title: "Which option?",
990 startedAt: now,
991 completedAt: null,
992 updatedAt: now,
993 type: "user_input_request",
994 requestId: request.id,
995 questions: [],
996 };
997 const seedEvents: Array<OrchestrationV2DomainEvent> = [threadEvent];
998 for (const payload of [
999 { type: "runtime-request.updated" as const, payload: request },
1000 { type: "node.updated" as const, payload: node },
1001 { type: "turn-item.updated" as const, payload: item },
1002 ])
1003 seedEvents.push({
1004 id: yield* idAllocator.allocate.event({ threadId }),
1005 threadId,
1006 occurredAt: now,
1007 ...payload,
1008 });
1009 yield* eventSink.write({ events: seedEvents });
1010 const normalized = yield* Deferred.make<void>();
1011 const releaseTerminalWrite = yield* Deferred.make<void>();
1012 const gatedSink = EventSink.EventSinkV2.of({
1013 ...eventSink,
1014 write: (input) =>
1015 Deferred.succeed(normalized, undefined).pipe(
1016 Effect.andThen(Deferred.await(releaseTerminalWrite)),
1017 Effect.andThen(eventSink.write(input)),
1018 ),
1019 });
1020 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
1021 Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),
1022 Effect.provideService(EventSink.EventSinkV2, gatedSink),
1023 );
1024 const terminal = yield* ingestor
1025 .ingestNormalized({
1026 providerSessionId,
1027 providerInstanceId: modelSelection.instanceId,
1028 threadId,
1029 event: {
1030 type: "provider_turn.updated",
1031 driver: CODEX_DRIVER,
1032 providerTurn: {
1033 id: providerTurnId,
1034 providerThreadId,
1035 nodeId,
1036 runAttemptId: null,
1037 nativeTurnRef: null,
1038 ordinal: 1,
1039 status: "completed",
1040 startedAt: now,
1041 completedAt: now,
1042 },
1043 },
1044 })
1045 .pipe(Effect.forkScoped);
1046 yield* Deferred.await(normalized);
1047 const answers = { decision: "Use the existing workspace" };
1048 const responseEvents: Array<OrchestrationV2DomainEvent> = [];
1049 for (const payload of [
1050 {
1051 type: "runtime-request.updated" as const,
1052 payload: { ...request, status: "resolved" as const, answers, resolvedAt: now },
1053 },
1054 {
1055 type: "node.updated" as const,
1056 payload: { ...node, status: "completed" as const, completedAt: now },
1057 },
1058 {
1059 type: "turn-item.updated" as const,
1060 payload: { ...item, status: "completed" as const, completedAt: now },
1061 },
1062 ])
1063 responseEvents.push({
1064 id: yield* idAllocator.allocate.event({ threadId }),
1065 threadId,
1066 occurredAt: now,
1067 ...payload,
1068 });
1069 yield* eventSink.write({ events: responseEvents });
1070 yield* Deferred.succeed(releaseTerminalWrite, undefined);
1071 const committedTerminal = yield* Fiber.join(terminal);
1072 assert.deepEqual(
1073 committedTerminal.map((stored) => stored.event.type),
1074 ["provider-turn.updated"],
1075 );
1076 const projection = yield* projections.getThreadProjection(threadId);
1077 const answered = projection.runtimeRequests.find((entry) => entry.id === request.id)!;
1078 assert.equal(answered.status, "resolved");
1079 assert.deepEqual(answered.answers, answers);
1080 assert.equal(projection.nodes.find((entry) => entry.id === nodeId)!.status, "completed");
1081 assert.equal(
1082 projection.turnItems.find((entry) => entry.id === item.id)!.status,
1083 "completed",
1084 );
1085 const history = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
1086 assert.isFalse(
1087 history.some(
1088 (stored) =>
1089 stored.event.type === "runtime-request.updated" &&
1090 stored.event.payload.status === "cancelled",
1091 ),
1092 );
1093 }),
1094 ),
1095 );
1096
1097 it.effect("persists a failed provider terminal as one expected error item", () =>
1098 Effect.gen(function* () {
1099 const now = yield* DateTime.now;
1100 const retryStartedAt = DateTime.makeUnsafe(DateTime.toEpochMillis(now) - 5_000);
1101 const eventSink = yield* EventSink.EventSinkV2;
1102 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1103 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1104 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1105 const threadEvent = yield* threadCreatedEvent(now);
1106 const providerSessionId = yield* idAllocator.allocate.providerSession({
1107 providerInstanceId: modelSelection.instanceId,
1108 threadId: threadEvent.threadId,
1109 });
1110 const providerThreadId = idAllocator.derive.providerThread({
1111 driver: CODEX_DRIVER,
1112 nativeThreadId: "native-thread-failed",
1113 });
1114 const providerTurnId = idAllocator.derive.providerTurn({
1115 driver: CODEX_DRIVER,
1116 nativeTurnId: "native-turn-failed",
1117 });
1118
1119 yield* eventSink.write({ events: [threadEvent] });
1120 const stored = yield* ingestor.ingestNormalized({
1121 providerSessionId,
1122 providerInstanceId: modelSelection.instanceId,
1123 threadId: threadEvent.threadId,
1124 event: {
1125 type: "turn.terminal",
1126 driver: CODEX_DRIVER,
1127 providerThreadId,
1128 providerTurnId,
1129 runOrdinal: 1,
1130 failureItemOrdinal: 102,
1131 status: "failed",
1132 failure: makeProviderFailure({
1133 message: "Invalid reasoning effort.",
1134 code: "invalid_request",
1135 class: "validation_error",
1136 }),
1137 retry: {
1138 attempt: 3,
1139 maxAttempts: 3,
1140 retryDelayMs: 2_000,
1141 },
1142 retryStartedAt,
1143 threadDisposition: "reusable",
1144 },
1145 });
1146
1147 const projection = yield* projectionStore.getThreadProjection(threadEvent.threadId);
1148 const errorItems = projection.visibleTurnItems.filter(
1149 (candidate) => candidate.item.type === "error",
1150 );
1151
1152 assert.equal(stored.length, 1);
1153 assert.equal(stored[0]?.event.type, "turn-item.updated");
1154 assert.equal(errorItems.length, 1);
1155 const errorItem = errorItems[0]?.item;
1156 assert.equal(errorItem?.type, "error");
1157 if (errorItem?.type !== "error") return;
1158 assert.equal(errorItem.failure.message, "Invalid reasoning effort.");
1159 assert.equal(errorItem.failure.code, "invalid_request");
1160 assert.deepEqual(errorItem.retry, {
1161 attempt: 3,
1162 maxAttempts: 3,
1163 retryDelayMs: 2_000,
1164 });
1165 const errorStartedAt = errorItem.startedAt;
1166 assert.ok(errorStartedAt);
1167 assert.equal(DateTime.toEpochMillis(errorStartedAt), DateTime.toEpochMillis(retryStartedAt));
1168 assert.equal(errorItem.providerThreadId, providerThreadId);
1169 assert.equal(errorItem.providerTurnId, providerTurnId);
1170 }),
1171 );
1172
1173 it.effect("stores tool image bytes only where a tool-output-image asset serves them", () =>
1174 Effect.gen(function* () {
1175 const now = yield* DateTime.now;
1176 const eventSink = yield* EventSink.EventSinkV2;
1177 const eventStore = yield* EventStore.EventStoreV2;
1178 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1179 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1180 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1181 const threadEvent = yield* threadCreatedEvent(now);
1182 const providerSessionId = yield* idAllocator.allocate.providerSession({
1183 providerInstanceId: modelSelection.instanceId,
1184 threadId: threadEvent.threadId,
1185 });
1186 const readBase64 = Buffer.alloc(30_000, 7).toString("base64");
1187 const screenshotBase64 = Buffer.alloc(20_000, 9).toString("base64");
1188 const toolItem = (
1189 id: string,
1190 ordinal: number,
1191 toolName: string,
1192 output: unknown,
1193 ): OrchestrationV2TurnItem => ({
1194 id: TurnItemId.make(id),
1195 threadId: threadEvent.threadId,
1196 runId: null,
1197 nodeId: null,
1198 providerThreadId: null,
1199 providerTurnId: null,
1200 nativeItemRef: null,
1201 parentItemId: null,
1202 ordinal,
1203 status: "completed",
1204 title: toolName,
1205 startedAt: now,
1206 completedAt: now,
1207 updatedAt: now,
1208 type: "dynamic_tool",
1209 toolName,
1210 input: {},
1211 output,
1212 });
1213 const read = toolItem("turn-item:read-image", 1, "Read", {
1214 type: "image",
1215 file: { base64: readBase64, type: "image/png", originalSize: 30_000 },
1216 });
1217 const screenshot = toolItem("turn-item:screenshot", 2, "mcp__t3-code__device_screenshot", {
1218 content: [
1219 {
1220 type: "image",
1221 source: { type: "base64", media_type: "image/png", data: screenshotBase64 },
1222 },
1223 ],
1224 });
1225
1226 yield* eventSink.write({ events: [threadEvent] });
1227 for (const turnItem of [read, screenshot]) {
1228 yield* ingestor.ingestNormalized({
1229 providerSessionId,
1230 providerInstanceId: modelSelection.instanceId,
1231 threadId: threadEvent.threadId,
1232 event: { type: "turn_item.updated", driver: CODEX_DRIVER, turnItem },
1233 });
1234 }
1235
1236 const storedEvents = yield* eventStore
1237 .read({ threadId: threadEvent.threadId, eventType: "turn-item.updated" })
1238 .pipe(Stream.runCollect);
1239 const storedJson = JSON.stringify(Array.from(storedEvents, (stored) => stored.event));
1240 const projectedRead = yield* projectionStore.getTurnItem({
1241 threadId: threadEvent.threadId,
1242 itemId: read.id,
1243 });
1244 const projectedScreenshot = yield* projectionStore.getTurnItem({
1245 threadId: threadEvent.threadId,
1246 itemId: screenshot.id,
1247 });
1248
1249 assert.equal(storedJson.includes(readBase64), false);
1250 assert.equal(storedJson.includes(screenshotBase64), true);
1251 assert.deepEqual(projectedRead?.type === "dynamic_tool" ? projectedRead.output : null, {
1252 type: "image",
1253 file: { type: "image/png", originalSize: 30_000, sizeBytes: 30_000 },
1254 });
1255 assert.deepEqual(
1256 toolOutputImages(
1257 projectedScreenshot?.type === "dynamic_tool" ? projectedScreenshot.output : null,
1258 ),
1259 [{ mimeType: "image/png", data: screenshotBase64 }],
1260 );
1261 }),
1262 );
1263
1264 it.effect("routes provider-owned child artifacts to their child app thread", () =>
1265 Effect.gen(function* () {
1266 const now = yield* DateTime.now;
1267 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1268 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1269 const rootEvent = yield* threadCreatedEvent(now);
1270 if (rootEvent.type !== "thread.created") {
1271 throw new Error("Expected a thread.created fixture event");
1272 }
1273 const childThreadId = idAllocator.derive.threadFromProviderThread({
1274 driver: CODEX_DRIVER,
1275 nativeThreadId: "native-subagent-thread",
1276 });
1277 const childRootNodeId = NodeId.make("node:subagent-root");
1278 const childThread: OrchestrationV2AppThread = {
1279 ...rootEvent.payload,
1280 id: childThreadId,
1281 title: "inspect package",
1282 activeProviderThreadId: null,
1283 lineage: {
1284 parentThreadId: rootEvent.threadId,
1285 relationshipToParent: "subagent",
1286 rootThreadId: rootEvent.threadId,
1287 },
1288 forkedFrom: {
1289 type: "node",
1290 nodeId: NodeId.make("node:parent-subagent"),
1291 },
1292 };
1293 const providerSessionId = yield* idAllocator.allocate.providerSession({
1294 providerInstanceId: modelSelection.instanceId,
1295 threadId: rootEvent.threadId,
1296 });
1297
1298 const threadEvents = yield* ingestor.normalize({
1299 providerSessionId,
1300 providerInstanceId: modelSelection.instanceId,
1301 threadId: rootEvent.threadId,
1302 event: {
1303 type: "app_thread.created",
1304 driver: CODEX_DRIVER,
1305 appThread: childThread,
1306 },
1307 });
1308 const messageEvents = yield* ingestor.normalize({
1309 providerSessionId,
1310 providerInstanceId: modelSelection.instanceId,
1311 threadId: rootEvent.threadId,
1312 event: {
1313 type: "message.updated",
1314 driver: CODEX_DRIVER,
1315 message: {
1316 createdBy: "agent",
1317 creationSource: "provider",
1318 id: MessageId.make("message:subagent-response"),
1319 threadId: childThreadId,
1320 runId: null,
1321 nodeId: childRootNodeId,
1322 role: "assistant",
1323 text: "Subagent result",
1324 attachments: [],
1325 streaming: false,
1326 createdAt: now,
1327 updatedAt: now,
1328 },
1329 },
1330 });
1331
1332 assert.equal(threadEvents[0]?.type, "thread.created");
1333 assert.equal(threadEvents[0]?.threadId, childThreadId);
1334 assert.equal(messageEvents[0]?.type, "message.updated");
1335 assert.equal(messageEvents[0]?.threadId, childThreadId);
1336 }),
1337 );
1338
1339 it.effect("moves a native subagent's thread to the model its provider reports later", () =>
1340 Effect.gen(function* () {
1341 const now = yield* DateTime.now;
1342 const eventSink = yield* EventSink.EventSinkV2;
1343 const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
1344 const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
1345 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1346 const rootEvent = yield* threadCreatedEvent(now);
1347 if (rootEvent.type !== "thread.created") {
1348 throw new Error("Expected a thread.created fixture event");
1349 }
1350 const childThreadId = idAllocator.derive.threadFromProviderThread({
1351 driver: CODEX_DRIVER,
1352 nativeThreadId: "native-late-model-subagent",
1353 });
1354 const providerSessionId = yield* idAllocator.allocate.providerSession({
1355 providerInstanceId: modelSelection.instanceId,
1356 threadId: rootEvent.threadId,
1357 });
1358 const ingest = (event: ProviderEventIngestor.ProviderEventIngestInput["event"]) =>
1359 ingestor.ingestNormalized({
1360 providerSessionId,
1361 providerInstanceId: modelSelection.instanceId,
1362 threadId: rootEvent.threadId,
1363 event,
1364 });
1365 yield* eventSink.write({ events: [rootEvent] });
1366 // The subagent's thread starts on the parent's model and options.
1367 yield* ingest({
1368 type: "app_thread.created",
1369 driver: CODEX_DRIVER,
1370 appThread: {
1371 ...rootEvent.payload,
1372 id: childThreadId,
1373 title: "review design",
1374 modelSelection: {
1375 ...modelSelection,
1376 options: [{ id: "reasoningEffort", value: "xhigh" }],
1377 },
1378 activeProviderThreadId: null,
1379 lineage: {
1380 parentThreadId: rootEvent.threadId,
1381 relationshipToParent: "subagent",
1382 rootThreadId: rootEvent.threadId,
1383 },
1384 },
1385 });
1386 const subagentUpdated = {
1387 type: "subagent.updated",
1388 driver: CODEX_DRIVER,
1389 subagent: {
1390 id: NodeId.make("node:late-model-subagent"),
1391 threadId: rootEvent.threadId,
1392 runId: null,
1393 parentNodeId: NodeId.make("node:root"),
1394 origin: "provider_native",
1395 createdBy: "agent",
1396 driver: CODEX_DRIVER,
1397 providerInstanceId: modelSelection.instanceId,
1398 providerThreadId: null,
1399 childThreadId,
1400 nativeTaskRef: null,
1401 prompt: "Review the design",
1402 title: "review design",
1403 model: "gpt-6.1-sol",
1404 status: "running",
1405 result: null,
1406 startedAt: now,
1407 completedAt: null,
1408 updatedAt: now,
1409 },
1410 } satisfies ProviderEventIngestor.ProviderEventIngestInput["event"];
1411
1412 const first = yield* ingest(subagentUpdated);
1413 const repeated = yield* ingest(subagentUpdated);
1414 const childThread = yield* projectionStore.getThread(childThreadId);
1415
1416 assert.deepEqual(
1417 first.map((stored) => [stored.event.type, stored.event.threadId]),
1418 [
1419 ["subagent.updated", rootEvent.threadId],
1420 ["thread.model-selection-updated", childThreadId],
1421 ],
1422 );
1423 assert.deepEqual(
1424 repeated.map((stored) => stored.event.type),
1425 ["subagent.updated"],
1426 );
1427 assert.deepEqual(childThread.modelSelection, {
1428 instanceId: modelSelection.instanceId,
1429 model: "gpt-6.1-sol",
1430 });
1431 }),
1432 );
1433});