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