Open History to see the last commit
1import { makeAssistantStreamingFilter } from "./assistantStreaming.ts";
2import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3import {
4 isOrchestrationV2WorkActive,
5 CommandId,
6 type EventId,
7 type ModelSelection,
8 type NodeId,
9 type OrchestrationV2AppThread,
10 type OrchestrationV2CheckpointScope,
11 type OrchestrationV2DomainEvent,
12 type OrchestrationV2ExecutionNode,
13 type OrchestrationV2ProviderFailure,
14 type OrchestrationV2ProviderThread,
15 type OrchestrationV2ProviderTurn,
16 type OrchestrationV2Run,
17 type OrchestrationV2RunAttempt,
18 type OrchestrationV2Subagent,
19 type OrchestrationV2TurnItem,
20 type ProviderSessionId,
21 type ProviderThreadId,
22 type ProviderTurnId,
23 type RunAttemptId,
24 type ThreadId,
25 type TurnItemId,
26} from "@t3tools/contracts";
27import * as Context from "effect/Context";
28import * as Cause from "effect/Cause";
29import * as DateTime from "effect/DateTime";
30import * as Effect from "effect/Effect";
31import * as Fiber from "effect/Fiber";
32import * as Layer from "effect/Layer";
33import * as Ref from "effect/Ref";
34import * as Schema from "effect/Schema";
35import * as Stream from "effect/Stream";
36
37import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
38import { ServerSettingsService } from "../serverSettings.ts";
39import { CheckpointServiceV2 } from "./CheckpointService.ts";
40import { EventSinkV2 } from "./EventSink.ts";
41import {
42 IdAllocatorV2,
43 type IdAllocatorV2AllocationError,
44 type IdAllocatorV2Shape,
45} from "./IdAllocator.ts";
46import type {
47 ProviderAdapterV2Event,
48 ProviderAdapterV2RuntimePolicy,
49 ProviderAdapterV2SessionRuntime,
50 ProviderAdapterV2TurnMessage,
51} from "./ProviderAdapter.ts";
52import { ProviderAdapterTurnStartError } from "./ProviderAdapter.ts";
53import { ProviderEventIngestorV2 } from "./ProviderEventIngestor.ts";
54import { makeProviderFailure, makeProviderFailureTurnItem } from "./ProviderFailure.ts";
55import { RunFinalizationObserver } from "./RunFinalizationService.ts";
56
57export interface ProviderEventRoutingState {
58 readonly ownedThreadIds: ReadonlySet<ThreadId>;
59 readonly ownedProviderThreadIds: ReadonlySet<ProviderThreadId>;
60 readonly ownedProviderTurnIds: ReadonlySet<ProviderTurnId>;
61 readonly inheritedBackgroundTurnItems: ReadonlyMap<TurnItemId, OrchestrationV2Run["id"]>;
62 readonly rootProviderTurnId: ProviderTurnId | null;
63}
64
65export interface ProviderEventRouteIdentity {
66 readonly threadId: ThreadId;
67 readonly runId: OrchestrationV2Run["id"];
68 readonly attemptId: RunAttemptId;
69 readonly providerThreadId: ProviderThreadId;
70}
71
72export interface InheritedBackgroundTurnItemRoute {
73 readonly id: TurnItemId;
74 readonly runId: OrchestrationV2Run["id"];
75}
76
77type ProviderTerminalEvent = Extract<ProviderAdapterV2Event, { readonly type: "turn.terminal" }>;
78
79function isTerminalProviderTurnStatus(status: OrchestrationV2ProviderTurn["status"]): boolean {
80 return (
81 status === "completed" ||
82 status === "interrupted" ||
83 status === "failed" ||
84 status === "cancelled"
85 );
86}
87
88function isSettledSubagentStatus(status: OrchestrationV2Subagent["status"]): boolean {
89 return !isOrchestrationV2WorkActive(status);
90}
91
92// Turn item types whose lifecycle can outlive the root turn (background
93// commands, monitors/dynamic tools, subagent rows). Ingestion must not stop
94// while one of these is still non-terminal, or the late completion event is
95// dropped and the item spins forever in the projection.
96const backgroundCapableTurnItemTypes: ReadonlySet<OrchestrationV2TurnItem["type"]> = new Set([
97 "command_execution",
98 "dynamic_tool",
99 "subagent",
100]);
101
102function isSettledTurnItemStatus(status: OrchestrationV2TurnItem["status"]): boolean {
103 return !isOrchestrationV2WorkActive(status);
104}
105
106function isSettledRunEligibleForInheritedBackground(status: OrchestrationV2Run["status"]): boolean {
107 return status === "interrupted" || status === "failed" || status === "cancelled";
108}
109
110/**
111 * Transfer delivery permission for exact live background items whose original
112 * run no longer has a subscriber. Provider sessions are runtime containers and
113 * can host multiple provider threads, so the durable provider-thread lineage is
114 * the discriminator. Completed, rolled-back, and already-terminal items remain
115 * excluded.
116 */
117export function selectInheritedBackgroundTurnItems(input: {
118 readonly threadId: ThreadId;
119 readonly currentProviderThreadId: ProviderThreadId;
120 readonly currentRunOrdinal: number;
121 readonly runs: ReadonlyArray<OrchestrationV2Run>;
122 readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
123}): ReadonlyArray<InheritedBackgroundTurnItemRoute> {
124 const settledPriorRunIds = new Set(
125 input.runs
126 .filter(
127 (run) =>
128 run.threadId === input.threadId &&
129 run.ordinal < input.currentRunOrdinal &&
130 isSettledRunEligibleForInheritedBackground(run.status),
131 )
132 .map((run) => run.id),
133 );
134 return input.turnItems.flatMap((turnItem) =>
135 turnItem.threadId === input.threadId &&
136 turnItem.providerThreadId === input.currentProviderThreadId &&
137 turnItem.runId !== null &&
138 settledPriorRunIds.has(turnItem.runId) &&
139 backgroundCapableTurnItemTypes.has(turnItem.type) &&
140 !isSettledTurnItemStatus(turnItem.status)
141 ? [{ id: turnItem.id, runId: turnItem.runId }]
142 : [],
143 );
144}
145
146type SubagentTurnItem = Extract<OrchestrationV2TurnItem, { readonly type: "subagent" }>;
147
148type OpenRunOwnedSubagentProjection = {
149 readonly subagents: ReadonlyMap<NodeId, OrchestrationV2Subagent>;
150 readonly turnItems: ReadonlyMap<NodeId, SubagentTurnItem>;
151 readonly childTurnItems: ReadonlyMap<TurnItemId, OrchestrationV2TurnItem>;
152 readonly nodes: ReadonlyMap<NodeId, OrchestrationV2ExecutionNode>;
153 /** Child threads once linked by a root-run subagent row; kept for cascade. */
154 readonly linkedChildThreadIds: ReadonlySet<ThreadId>;
155};
156
157type RunOwnedSubagentTerminalStatus = Extract<
158 OrchestrationV2Subagent["status"],
159 "interrupted" | "failed" | "cancelled"
160>;
161
162function isOpenExecutionNodeStatus(status: OrchestrationV2ExecutionNode["status"]): boolean {
163 return status === "pending" || status === "running" || status === "waiting";
164}
165
166function isRunOwnedSubagentTerminalStatus(
167 status: ProviderTerminalEvent["status"],
168): status is RunOwnedSubagentTerminalStatus {
169 return status === "interrupted" || status === "failed" || status === "cancelled";
170}
171
172export function canRouteRelatedSubagent(status: OrchestrationV2Subagent["status"]): boolean {
173 return status !== "interrupted" && status !== "failed" && status !== "cancelled";
174}
175
176function emptyOpenRunOwnedSubagentProjection(): OpenRunOwnedSubagentProjection {
177 return {
178 subagents: new Map(),
179 turnItems: new Map(),
180 childTurnItems: new Map(),
181 nodes: new Map(),
182 linkedChildThreadIds: new Set(),
183 };
184}
185
186function withLinkedChildThreadId(
187 current: OpenRunOwnedSubagentProjection,
188 childThreadId: ThreadId | null,
189): OpenRunOwnedSubagentProjection {
190 if (childThreadId === null || current.linkedChildThreadIds.has(childThreadId)) {
191 return current;
192 }
193 const linkedChildThreadIds = new Set(current.linkedChildThreadIds);
194 linkedChildThreadIds.add(childThreadId);
195 return { ...current, linkedChildThreadIds };
196}
197
198export function cascadeTerminalizeRunOwnedSubagents(input: {
199 readonly run: OrchestrationV2Run;
200 readonly open: OpenRunOwnedSubagentProjection;
201 readonly status: RunOwnedSubagentTerminalStatus;
202 readonly completedAt: DateTime.Utc;
203 readonly allocateEventId: () => Effect.Effect<EventId, IdAllocatorV2AllocationError>;
204}): Effect.Effect<ReadonlyArray<OrchestrationV2DomainEvent>, IdAllocatorV2AllocationError> {
205 return Effect.gen(function* () {
206 const events: Array<OrchestrationV2DomainEvent> = [];
207 // Prefer lifetime linkage over currently-open rows: subagent/turn-item
208 // snapshots may terminalize before the linked child-thread node settles.
209 const childThreadIds = new Set(input.open.linkedChildThreadIds);
210 for (const item of [...input.open.subagents.values(), ...input.open.turnItems.values()]) {
211 if (item.childThreadId !== null) {
212 childThreadIds.add(item.childThreadId);
213 }
214 }
215 const keys = new Set<NodeId>([
216 ...input.open.subagents.keys(),
217 ...input.open.turnItems.keys(),
218 ...input.open.nodes.keys(),
219 ]);
220 for (const key of keys) {
221 const subagent = input.open.subagents.get(key);
222 if (subagent !== undefined && !isSettledSubagentStatus(subagent.status)) {
223 events.push({
224 id: yield* input.allocateEventId(),
225 type: "subagent.updated",
226 threadId: subagent.threadId,
227 runId: input.run.id,
228 nodeId: subagent.id,
229 driver: subagent.driver,
230 providerInstanceId: subagent.providerInstanceId,
231 occurredAt: input.completedAt,
232 payload: {
233 ...subagent,
234 status: input.status,
235 completedAt: input.completedAt,
236 updatedAt: input.completedAt,
237 },
238 });
239 }
240 const node = input.open.nodes.get(key);
241 if (
242 node !== undefined &&
243 ((node.threadId === input.run.threadId && node.runId === input.run.id) ||
244 childThreadIds.has(node.threadId)) &&
245 isOpenExecutionNodeStatus(node.status)
246 ) {
247 events.push({
248 id: yield* input.allocateEventId(),
249 type: "node.updated",
250 threadId: node.threadId,
251 runId: node.runId ?? input.run.id,
252 nodeId: node.id,
253 providerInstanceId: input.run.providerInstanceId,
254 occurredAt: input.completedAt,
255 payload: {
256 ...node,
257 status: input.status,
258 completedAt: input.completedAt,
259 },
260 });
261 }
262 const turnItem = input.open.turnItems.get(key);
263 if (
264 turnItem !== undefined &&
265 turnItem.runId === input.run.id &&
266 !isSettledTurnItemStatus(turnItem.status)
267 ) {
268 events.push({
269 id: yield* input.allocateEventId(),
270 type: "turn-item.updated",
271 threadId: turnItem.threadId,
272 runId: input.run.id,
273 ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
274 providerInstanceId: input.run.providerInstanceId,
275 occurredAt: input.completedAt,
276 payload: {
277 ...turnItem,
278 status: input.status,
279 completedAt: input.completedAt,
280 updatedAt: input.completedAt,
281 },
282 });
283 }
284 }
285 for (const turnItem of input.open.childTurnItems.values()) {
286 if (!childThreadIds.has(turnItem.threadId) || isSettledTurnItemStatus(turnItem.status)) {
287 continue;
288 }
289 events.push({
290 id: yield* input.allocateEventId(),
291 type: "turn-item.updated",
292 threadId: turnItem.threadId,
293 runId: turnItem.runId ?? input.run.id,
294 ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
295 providerInstanceId: input.run.providerInstanceId,
296 occurredAt: input.completedAt,
297 payload: {
298 ...turnItem,
299 ...("streaming" in turnItem ? { streaming: false } : {}),
300 status: input.status,
301 completedAt: input.completedAt,
302 updatedAt: input.completedAt,
303 },
304 });
305 }
306 return events;
307 });
308}
309
310export function finalProviderThreadStatus(
311 disposition: ProviderTerminalEvent["threadDisposition"],
312): OrchestrationV2ProviderThread["status"] {
313 return disposition === "broken" ? "error" : "idle";
314}
315
316export function makeProviderEventRoutingState(input: {
317 readonly identity: ProviderEventRouteIdentity;
318 readonly inheritedBackgroundTurnItems?: ReadonlyArray<InheritedBackgroundTurnItemRoute>;
319 readonly providerTurnId: ProviderTurnId | null;
320 readonly relatedThreadIds?: ReadonlyArray<ThreadId>;
321 readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
322}): ProviderEventRoutingState {
323 return {
324 ownedThreadIds: new Set([input.identity.threadId, ...(input.relatedThreadIds ?? [])]),
325 ownedProviderThreadIds: new Set([
326 input.identity.providerThreadId,
327 ...(input.relatedProviderThreadIds ?? []),
328 ]),
329 ownedProviderTurnIds:
330 input.providerTurnId === null ? new Set() : new Set([input.providerTurnId]),
331 inheritedBackgroundTurnItems: new Map(
332 (input.inheritedBackgroundTurnItems ?? []).map((item) => [item.id, item.runId]),
333 ),
334 rootProviderTurnId: input.providerTurnId,
335 };
336}
337
338export function routeProviderEvent(
339 event: ProviderAdapterV2Event,
340 input: ProviderEventRouteIdentity,
341 state: ProviderEventRoutingState,
342): readonly [boolean, ProviderEventRoutingState] {
343 const ownsThread = (threadId: ThreadId): boolean => state.ownedThreadIds.has(threadId);
344 const ownsChildThread = (threadId: ThreadId): boolean =>
345 threadId !== input.threadId && ownsThread(threadId);
346 const ownsRun = (runId: string | null): boolean => runId === input.runId;
347 const addProviderThread = (providerThreadId: ProviderThreadId): ProviderEventRoutingState => ({
348 ...state,
349 ownedProviderThreadIds: new Set([...state.ownedProviderThreadIds, providerThreadId]),
350 });
351 const addProviderTurn = (
352 providerTurnId: ProviderTurnId,
353 root: boolean,
354 ): ProviderEventRoutingState => ({
355 ...state,
356 ownedProviderTurnIds: new Set([...state.ownedProviderTurnIds, providerTurnId]),
357 rootProviderTurnId: root ? providerTurnId : state.rootProviderTurnId,
358 });
359
360 switch (event.type) {
361 case "provider_session.updated":
362 // The session manager persists process-wide status once for every
363 // attached app thread before broadcasting the adapter event.
364 return [false, state];
365 case "app_thread.created": {
366 if (event.appThread.id === input.threadId) {
367 return [true, state];
368 }
369 const isOwnedSubagent =
370 event.appThread.lineage.relationshipToParent === "subagent" &&
371 event.appThread.lineage.parentThreadId !== null &&
372 ownsThread(event.appThread.lineage.parentThreadId);
373 if (!isOwnedSubagent) {
374 return [false, state];
375 }
376 return [
377 true,
378 {
379 ...state,
380 ownedThreadIds: new Set([...state.ownedThreadIds, event.appThread.id]),
381 },
382 ];
383 }
384 case "provider_thread.updated": {
385 const belongs =
386 state.ownedProviderThreadIds.has(event.providerThread.id) ||
387 (event.providerThread.appThreadId !== null && ownsThread(event.providerThread.appThreadId));
388 return belongs ? [true, addProviderThread(event.providerThread.id)] : [false, state];
389 }
390 case "provider_turn.updated": {
391 const isRoot = event.providerTurn.runAttemptId === input.attemptId;
392 const belongs =
393 isRoot ||
394 (event.providerTurn.providerThreadId !== input.providerThreadId &&
395 state.ownedProviderThreadIds.has(event.providerTurn.providerThreadId)) ||
396 state.ownedProviderTurnIds.has(event.providerTurn.id) ||
397 (event.threadId !== undefined && ownsChildThread(event.threadId));
398 return belongs ? [true, addProviderTurn(event.providerTurn.id, isRoot)] : [false, state];
399 }
400 case "node.updated": {
401 const belongs = ownsRun(event.node.runId) || ownsChildThread(event.node.threadId);
402 if (!belongs || event.node.providerThreadId === null) {
403 return [belongs, state];
404 }
405 return [true, addProviderThread(event.node.providerThreadId)];
406 }
407 case "subagent.updated":
408 return [ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId), state];
409 case "message.updated":
410 return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state];
411 case "turn_item.updated": {
412 if (ownsRun(event.turnItem.runId) || ownsChildThread(event.turnItem.threadId)) {
413 return [true, state];
414 }
415 const inheritedRunId = state.inheritedBackgroundTurnItems.get(event.turnItem.id);
416 // Preserve the item's original ownership while allowing the one live run
417 // to deliver an exact carryover identity selected from the projection.
418 const isInheritedBackgroundItem =
419 event.turnItem.threadId === input.threadId &&
420 event.turnItem.runId !== null &&
421 event.turnItem.runId === inheritedRunId &&
422 backgroundCapableTurnItemTypes.has(event.turnItem.type);
423 if (!isInheritedBackgroundItem) {
424 return [false, state];
425 }
426 if (!isSettledTurnItemStatus(event.turnItem.status)) {
427 return [true, state];
428 }
429 const inheritedBackgroundTurnItems = new Map(state.inheritedBackgroundTurnItems);
430 inheritedBackgroundTurnItems.delete(event.turnItem.id);
431 return [true, { ...state, inheritedBackgroundTurnItems }];
432 }
433 case "plan.updated":
434 return [ownsRun(event.plan.runId) || ownsChildThread(event.plan.threadId), state];
435 case "runtime_request.updated":
436 return [
437 (event.threadId !== undefined && ownsChildThread(event.threadId)) ||
438 (event.runtimeRequest.providerTurnId !== null &&
439 state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),
440 state,
441 ];
442 case "turn.terminal":
443 return [event.providerTurnId === state.rootProviderTurnId, state];
444 }
445}
446
447/**
448 * ERRORS
449 */
450export class RunExecutionStartError extends Schema.TaggedError<RunExecutionStartError>()(
451 "RunExecutionStartError",
452 {
453 commandId: CommandId,
454 runId: Schema.String,
455 cause: Schema.optional(Schema.Defect()),
456 },
457) {
458 override get message(): string {
459 return `Failed to start orchestration V2 run execution ${this.runId}.`;
460 }
461}
462
463export class RunExecutionIngestError extends Schema.TaggedError<RunExecutionIngestError>()(
464 "RunExecutionIngestError",
465 {
466 runId: Schema.String,
467 cause: Schema.optional(Schema.Defect()),
468 },
469) {
470 override get message(): string {
471 return `Failed while ingesting orchestration V2 run execution ${this.runId}.`;
472 }
473}
474
475export const RunExecutionServiceV2Error = Schema.Union([
476 RunExecutionStartError,
477 RunExecutionIngestError,
478]);
479export type RunExecutionServiceV2Error = typeof RunExecutionServiceV2Error.Type;
480
481/**
482 * SERVICE DEFINITION
483 */
484export interface RunExecutionServiceV2StartRootRunInput {
485 readonly commandId: CommandId;
486 readonly appThread: OrchestrationV2AppThread;
487 readonly providerSessionId: ProviderSessionId;
488 readonly session: ProviderAdapterV2SessionRuntime;
489 readonly run: OrchestrationV2Run;
490 readonly rootNode: OrchestrationV2ExecutionNode;
491 readonly checkpointScope: OrchestrationV2CheckpointScope;
492 readonly providerThread: OrchestrationV2ProviderThread;
493 readonly attempt: OrchestrationV2RunAttempt;
494 readonly attemptId: RunAttemptId;
495 readonly providerTurnOrdinal: number;
496 readonly loadInheritedBackgroundTurnItems?: () => Effect.Effect<
497 ReadonlyArray<InheritedBackgroundTurnItemRoute>,
498 unknown
499 >;
500 readonly relatedThreadIds?: ReadonlyArray<ThreadId>;
501 readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
502 readonly shouldStartProviderTurn?: () => Effect.Effect<boolean, never>;
503 readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
504 readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
505 readonly message: ProviderAdapterV2TurnMessage;
506 readonly modelSelection: ModelSelection;
507 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
508}
509
510export interface RunExecutionServiceV2Shape {
511 readonly startRootRun: (
512 input: RunExecutionServiceV2StartRootRunInput,
513 ) => Effect.Effect<void, RunExecutionServiceV2Error>;
514}
515
516export class RunExecutionServiceV2 extends Context.Service<
517 RunExecutionServiceV2,
518 RunExecutionServiceV2Shape
519>()("t3/orchestration-v2/RunExecutionService/RunExecutionServiceV2") {}
520
521/**
522 * IMPLEMENTATIONS
523 */
524export const layer: Layer.Layer<
525 RunExecutionServiceV2,
526 never,
527 | CheckpointServiceV2
528 | EventSinkV2
529 | IdAllocatorV2
530 | ProviderEventIngestorV2
531 | ServerSettingsService
532> = Layer.effect(
533 RunExecutionServiceV2,
534 Effect.gen(function* () {
535 const checkpointService = yield* CheckpointServiceV2;
536 const eventSink = yield* EventSinkV2;
537 const idAllocator = yield* IdAllocatorV2;
538 const providerEventIngestor = yield* ProviderEventIngestorV2;
539 const serverSettings = yield* ServerSettingsService;
540 const finalizationObserver = yield* RunFinalizationObserver;
541
542 const writeFinalRunEvents = (input: {
543 readonly run: OrchestrationV2Run;
544 readonly rootNode: OrchestrationV2ExecutionNode;
545 readonly checkpointScope: OrchestrationV2CheckpointScope;
546 readonly providerThread: OrchestrationV2ProviderThread;
547 readonly attempt: OrchestrationV2RunAttempt;
548 readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
549 readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
550 readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
551 readonly terminal: ProviderTerminalEvent;
552 readonly failureItemPersisted: boolean;
553 readonly refreshAfterTurn: Effect.Effect<void>;
554 readonly writeIfRunCurrent?: {
555 readonly activeAttemptId: RunAttemptId;
556 readonly expectedStatus: OrchestrationV2Run["status"];
557 };
558 }) =>
559 Effect.gen(function* () {
560 const completedAt = yield* DateTime.now;
561 const finalizedAttempt: OrchestrationV2RunAttempt | null = {
562 ...input.attempt,
563 status: input.terminal.status,
564 completedAt,
565 };
566 const shouldFinalizeRun =
567 input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun();
568 if (!shouldFinalizeRun) {
569 // Superseded attempt (steer / selection restart). Emit
570 // run_interrupt_result only when hard Stop left an unpaired request
571 // for this run; plain steers and already-paired stops emit nothing.
572 if (input.terminal.status === "interrupted") {
573 const hasUnpairedRequest =
574 input.hasUnpairedRunInterruptRequest === undefined
575 ? false
576 : yield* input.hasUnpairedRunInterruptRequest();
577 if (hasUnpairedRequest) {
578 yield* eventSink.writeWithEffects({
579 effects: [],
580 events: [
581 {
582 id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
583 type: "turn-item.updated" as const,
584 threadId: input.run.threadId,
585 runId: input.run.id,
586 nodeId: input.rootNode.id,
587 providerInstanceId: input.run.providerInstanceId,
588 occurredAt: completedAt,
589 payload: makeInterruptResultTurnItem({
590 idAllocator,
591 run: input.run,
592 rootNode: input.rootNode,
593 providerThread: input.providerThread,
594 completedAt,
595 }),
596 },
597 ],
598 });
599 yield* input.refreshAfterTurn;
600 }
601 }
602 return;
603 }
604 const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId });
605 const open = input.openRunOwnedSubagents ?? emptyOpenRunOwnedSubagentProjection();
606 const hasOpenSubagentProjection =
607 open.subagents.size > 0 ||
608 open.turnItems.size > 0 ||
609 open.childTurnItems.size > 0 ||
610 open.nodes.size > 0;
611 const cascadedSubagentEvents =
612 isRunOwnedSubagentTerminalStatus(input.terminal.status) && hasOpenSubagentProjection
613 ? yield* cascadeTerminalizeRunOwnedSubagents({
614 run: input.run,
615 open,
616 status: input.terminal.status,
617 completedAt,
618 allocateEventId,
619 })
620 : [];
621 const persistedStatus =
622 input.terminal.status === "completed" ? "waiting" : input.terminal.status;
623 // Completion cohorts are advanced by Orchestrator while a provider
624 // turn is in flight. Do not replay the run snapshot captured at start
625 // over a newer acknowledgement, successor, or Stop barrier.
626 const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } =
627 input.run;
628 const finalizedRun: OrchestrationV2Run = {
629 ...runWithoutDelegatedCompletion,
630 status: persistedStatus,
631 completedAt: input.terminal.status === "completed" ? null : completedAt,
632 };
633 const finalizedRootNode: OrchestrationV2ExecutionNode = {
634 ...input.rootNode,
635 status: persistedStatus,
636 completedAt: input.terminal.status === "completed" ? null : completedAt,
637 checkpointScopeId: input.checkpointScope.id,
638 };
639 const finalizedProviderThread: OrchestrationV2ProviderThread = {
640 ...input.providerThread,
641 status: finalProviderThreadStatus(input.terminal.threadDisposition),
642 updatedAt: completedAt,
643 };
644 const runEventId = yield* allocateEventId();
645 const nodeEventId = yield* allocateEventId();
646 const providerThreadEventId = yield* allocateEventId();
647 const checkpointCaptureCommandId = CommandId.make(
648 `command:effect:checkpoint.capture:${input.run.id}`,
649 );
650 const finalization = {
651 effects:
652 input.terminal.status === "completed"
653 ? [
654 {
655 id: `effect:checkpoint.capture:${input.run.id}`,
656 commandId: checkpointCaptureCommandId,
657 threadId: input.run.threadId,
658 request: {
659 type: "checkpoint.capture" as const,
660 runId: input.run.id,
661 scopeId: input.checkpointScope.id,
662 },
663 },
664 ]
665 : [],
666 events: [
667 // Terminalize open run-owned subagent rows before the root run
668 // settles so projections never keep a forever-running subagent card.
669 ...cascadedSubagentEvents,
670 ...(finalizedAttempt === null
671 ? []
672 : [
673 {
674 id: yield* allocateEventId(),
675 type: "run-attempt.updated" as const,
676 threadId: input.run.threadId,
677 runId: input.run.id,
678 nodeId: input.rootNode.id,
679 providerInstanceId: input.run.providerInstanceId,
680 occurredAt: completedAt,
681 payload: finalizedAttempt,
682 },
683 ]),
684 ...(input.terminal.status === "interrupted"
685 ? [
686 {
687 id: yield* allocateEventId(),
688 type: "turn-item.updated" as const,
689 threadId: input.run.threadId,
690 runId: input.run.id,
691 nodeId: input.rootNode.id,
692 providerInstanceId: input.run.providerInstanceId,
693 occurredAt: completedAt,
694 payload: makeInterruptResultTurnItem({
695 idAllocator,
696 run: input.run,
697 rootNode: input.rootNode,
698 providerThread: input.providerThread,
699 completedAt,
700 }),
701 },
702 ]
703 : []),
704 ...(input.terminal.status === "failed" && !input.failureItemPersisted
705 ? [
706 {
707 id: yield* allocateEventId(),
708 type: "turn-item.updated" as const,
709 threadId: input.run.threadId,
710 runId: input.run.id,
711 nodeId: input.rootNode.id,
712 providerInstanceId: input.run.providerInstanceId,
713 occurredAt: completedAt,
714 payload: makeProviderFailureTurnItem({
715 idAllocator,
716 driver: input.terminal.driver,
717 threadId: input.run.threadId,
718 runId: input.run.id,
719 nodeId: input.rootNode.id,
720 providerThreadId: input.terminal.providerThreadId,
721 providerTurnId: input.terminal.providerTurnId,
722 itemOrdinal: input.terminal.failureItemOrdinal,
723 failure: input.terminal.failure,
724 occurredAt: completedAt,
725 }),
726 },
727 ]
728 : []),
729 {
730 id: runEventId,
731 type: "run.updated",
732 threadId: input.run.threadId,
733 runId: input.run.id,
734 nodeId: input.rootNode.id,
735 providerInstanceId: input.run.providerInstanceId,
736 occurredAt: completedAt,
737 payload: finalizedRun,
738 },
739 {
740 id: nodeEventId,
741 type: "node.updated",
742 threadId: input.run.threadId,
743 runId: input.run.id,
744 nodeId: input.rootNode.id,
745 providerInstanceId: input.run.providerInstanceId,
746 occurredAt: completedAt,
747 payload: finalizedRootNode,
748 },
749 {
750 id: providerThreadEventId,
751 type: "provider-thread.updated",
752 threadId: input.run.threadId,
753 providerInstanceId: input.run.providerInstanceId,
754 occurredAt: completedAt,
755 payload: finalizedProviderThread,
756 },
757 ],
758 } satisfies Parameters<typeof eventSink.writeWithEffects>[0];
759 if (input.writeIfRunCurrent !== undefined) {
760 const result = yield* eventSink.writeIfRunCurrent({
761 threadId: input.run.threadId,
762 runId: input.run.id,
763 activeAttemptId: input.writeIfRunCurrent.activeAttemptId,
764 expectedStatus: input.writeIfRunCurrent.expectedStatus,
765 events: finalization.events,
766 });
767 if (!result.committed) {
768 return;
769 }
770 } else {
771 yield* eventSink.writeWithEffects(finalization);
772 }
773 yield* input.refreshAfterTurn;
774 });
775
776 return RunExecutionServiceV2.of({
777 startRootRun: (input) =>
778 Effect.gen(function* () {
779 // Startup failure and stream shutdown can report the same attempt.
780 const refreshAfterTurn = yield* Effect.cached(
781 finalizationObserver.refreshAfterTurn(input.appThread.projectId).pipe(
782 Effect.catchCause((cause) =>
783 Effect.logWarning("failed to refresh pull requests after run termination", {
784 threadId: input.run.threadId,
785 runId: input.run.id,
786 cause,
787 }),
788 ),
789 ),
790 );
791 const makeFailedTerminalEvent = (
792 failure: OrchestrationV2ProviderFailure,
793 failureItemOrdinal: number,
794 ): ProviderTerminalEvent => ({
795 type: "turn.terminal",
796 driver: input.providerThread.driver,
797 providerThreadId: input.providerThread.id,
798 providerTurnId:
799 input.attempt.providerTurnId ??
800 idAllocator.derive.providerTurn({
801 driver: input.providerThread.driver,
802 nativeTurnId: `failed:${input.attempt.id}`,
803 }),
804 runOrdinal: input.run.ordinal,
805 failureItemOrdinal,
806 status: "failed",
807 failure,
808 threadDisposition: "reusable",
809 });
810 const responseStreamingMode = yield* Effect.gen(function* () {
811 const responseStreamingMode = yield* serverSettings.getSettings.pipe(
812 Effect.map(
813 (settings) =>
814 resolveProjectSettings(settings, input.appThread.projectId).settings
815 .responseStreamingMode,
816 ),
817 );
818 yield* checkpointService
819 .captureBaseline({
820 scope: input.checkpointScope,
821 ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
822 })
823 .pipe(
824 Effect.catchCause((cause) =>
825 Cause.hasInterruptsOnly(cause)
826 ? Effect.failCause(cause)
827 : Effect.logWarning(
828 "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline",
829 { runId: input.run.id },
830 ),
831 ),
832 );
833 if (
834 input.shouldStartProviderTurn !== undefined &&
835 !(yield* input.shouldStartProviderTurn())
836 ) {
837 return null;
838 }
839 return responseStreamingMode;
840 }).pipe(
841 Effect.catchCause((cause) =>
842 Effect.gen(function* () {
843 if (Cause.hasInterruptsOnly(cause)) {
844 return yield* Effect.failCause(cause);
845 }
846 yield* Effect.logError("orchestration V2 run preparation failed", {
847 runId: input.run.id,
848 cause,
849 });
850 yield* writeFinalRunEvents({
851 run: input.run,
852 rootNode: input.rootNode,
853 checkpointScope: input.checkpointScope,
854 providerThread: input.providerThread,
855 attempt: input.attempt,
856 terminal: makeFailedTerminalEvent(
857 makeProviderFailure({
858 cause: Cause.squash(cause),
859 // Keep exact underlying text in the logged cause only;
860 // the persisted turn item gets a bounded curated message.
861 message: "Run preparation failed.",
862 class: "unknown",
863 }),
864 input.providerTurnOrdinal * 100 + 1,
865 ),
866 failureItemPersisted: false,
867 refreshAfterTurn,
868 writeIfRunCurrent: {
869 activeAttemptId: input.attemptId,
870 expectedStatus: "running",
871 },
872 });
873 return null;
874 }),
875 ),
876 Effect.mapError(
877 (cause) =>
878 new RunExecutionStartError({
879 commandId: input.commandId,
880 runId: input.run.id,
881 cause,
882 }),
883 ),
884 );
885 if (responseStreamingMode === null) {
886 return;
887 }
888 const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);
889 const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);
890 const latestProviderThread = yield* Ref.make(input.providerThread);
891 const routeIdentity: ProviderEventRouteIdentity = {
892 threadId: input.run.threadId,
893 runId: input.run.id,
894 attemptId: input.attempt.id,
895 providerThreadId: input.providerThread.id,
896 };
897 const eventSubscription =
898 input.session.subscribeEvents === undefined
899 ? { events: input.session.events, close: Effect.void }
900 : yield* input.session.subscribeEvents;
901 const inheritedBackgroundTurnItems = yield* (
902 input.loadInheritedBackgroundTurnItems?.() ?? Effect.succeed([])
903 ).pipe(
904 Effect.onError(() => eventSubscription.close),
905 Effect.mapError(
906 (cause) =>
907 new RunExecutionStartError({
908 commandId: input.commandId,
909 runId: input.run.id,
910 cause,
911 }),
912 ),
913 );
914 const inheritedBackgroundTurnItemsById = new Map(
915 inheritedBackgroundTurnItems.map((item) => [item.id, item.runId]),
916 );
917 const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
918 makeProviderEventRoutingState({
919 identity: routeIdentity,
920 inheritedBackgroundTurnItems,
921 providerTurnId: input.attempt.providerTurnId,
922 ...(input.relatedThreadIds === undefined
923 ? {}
924 : { relatedThreadIds: input.relatedThreadIds }),
925 ...(input.relatedProviderThreadIds === undefined
926 ? {}
927 : { relatedProviderThreadIds: input.relatedProviderThreadIds }),
928 }),
929 );
930 const rootTerminalSeen = yield* Ref.make(false);
931 const rootRunFinalized = yield* Ref.make(false);
932 const providerThreadOwnerLost = yield* Ref.make(false);
933 const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
934 const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
935 const activeBackgroundTurnItems = yield* Ref.make<
936 ReadonlySet<OrchestrationV2TurnItem["id"]>
937 >(new Set(inheritedBackgroundTurnItemsById.keys()));
938 const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
939 const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
940 Effect.gen(function* () {
941 if (yield* Ref.get(rootRunFinalized)) {
942 return;
943 }
944 const providerThread = yield* Ref.get(latestProviderThread);
945 const openSubagents = yield* Ref.get(openRunOwnedSubagents);
946 yield* writeFinalRunEvents({
947 run: input.run,
948 rootNode: input.rootNode,
949 checkpointScope: input.checkpointScope,
950 providerThread,
951 attempt: input.attempt,
952 ...(input.shouldFinalizeRun === undefined
953 ? {}
954 : { shouldFinalizeRun: input.shouldFinalizeRun }),
955 ...(input.hasUnpairedRunInterruptRequest === undefined
956 ? {}
957 : {
958 hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
959 }),
960 openRunOwnedSubagents: openSubagents,
961 terminal,
962 failureItemPersisted: terminal.status === "failed",
963 refreshAfterTurn,
964 }).pipe(
965 Effect.mapError(
966 (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
967 ),
968 );
969 if (isRunOwnedSubagentTerminalStatus(terminal.status)) {
970 yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
971 }
972 yield* Ref.set(rootRunFinalized, true);
973 });
974 const trackChildLifecycle = (event: ProviderAdapterV2Event, deliverable: boolean) =>
975 Effect.gen(function* () {
976 const routing = yield* Ref.get(eventRouting);
977 if (event.type === "provider_turn.updated") {
978 const isRoot =
979 event.providerTurn.runAttemptId === input.attempt.id ||
980 event.providerTurn.id === routing.rootProviderTurnId;
981 if (!isRoot) {
982 yield* Ref.update(activeChildProviderTurns, (current) => {
983 const next = new Set(current);
984 if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
985 next.delete(event.providerTurn.id);
986 } else {
987 next.add(event.providerTurn.id);
988 }
989 return next;
990 });
991 }
992 }
993 if (event.type === "subagent.updated") {
994 const belongsToRootRun = event.subagent.runId === input.run.id;
995 const belongsToOwnedChildThread =
996 event.subagent.threadId !== input.run.threadId &&
997 routing.ownedThreadIds.has(event.subagent.threadId);
998 if (belongsToRootRun || belongsToOwnedChildThread) {
999 yield* Ref.update(activeChildSubagents, (current) => {
1000 const next = new Set(current);
1001 if (isSettledSubagentStatus(event.subagent.status)) {
1002 next.delete(event.subagent.id);
1003 } else {
1004 next.add(event.subagent.id);
1005 }
1006 return next;
1007 });
1008 }
1009 // Snapshot run-owned subagents for interrupt cascade.
1010 // Preserve childThreadId linkage for the root-run lifetime even
1011 // after the subagent row terminalizes, so open child-thread
1012 // nodes can still be proven linked on a later root interrupt.
1013 if (belongsToRootRun) {
1014 yield* Ref.update(openRunOwnedSubagents, (current) => {
1015 const withLink = withLinkedChildThreadId(current, event.subagent.childThreadId);
1016 const subagents = new Map(withLink.subagents);
1017 if (isSettledSubagentStatus(event.subagent.status)) {
1018 subagents.delete(event.subagent.id);
1019 } else {
1020 subagents.set(event.subagent.id, event.subagent);
1021 }
1022 return { ...withLink, subagents };
1023 });
1024 }
1025 }
1026 if (event.type === "node.updated") {
1027 const belongsToRootSubagent =
1028 event.node.kind === "subagent" && event.node.runId === input.run.id;
1029 const belongsToOwnedChildThread =
1030 event.node.threadId !== input.run.threadId &&
1031 routing.ownedThreadIds.has(event.node.threadId);
1032 if (!belongsToRootSubagent && !belongsToOwnedChildThread) {
1033 return;
1034 }
1035 yield* Ref.update(openRunOwnedSubagents, (current) => {
1036 const nodes = new Map(current.nodes);
1037 if (isOpenExecutionNodeStatus(event.node.status)) {
1038 nodes.set(event.node.id, event.node);
1039 } else {
1040 nodes.delete(event.node.id);
1041 }
1042 return { ...current, nodes };
1043 });
1044 }
1045 if (event.type === "turn_item.updated") {
1046 const belongsToRootRun = event.turnItem.runId === input.run.id;
1047 const belongsToOwnedChildThread =
1048 event.turnItem.threadId !== input.run.threadId &&
1049 routing.ownedThreadIds.has(event.turnItem.threadId);
1050 const belongsToInheritedBackgroundItem =
1051 event.turnItem.threadId === input.run.threadId &&
1052 event.turnItem.runId !== null &&
1053 inheritedBackgroundTurnItemsById.get(event.turnItem.id) === event.turnItem.runId;
1054 if (
1055 backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
1056 (belongsToRootRun ||
1057 belongsToOwnedChildThread ||
1058 belongsToInheritedBackgroundItem)
1059 ) {
1060 yield* Ref.update(activeBackgroundTurnItems, (current) => {
1061 const next = new Set(current);
1062 if (isSettledTurnItemStatus(event.turnItem.status)) {
1063 next.delete(event.turnItem.id);
1064 } else {
1065 next.add(event.turnItem.id);
1066 }
1067 return next;
1068 });
1069 }
1070 if (belongsToOwnedChildThread && deliverable) {
1071 yield* Ref.update(openRunOwnedSubagents, (current) => {
1072 const childTurnItems = new Map(current.childTurnItems);
1073 if (isSettledTurnItemStatus(event.turnItem.status)) {
1074 childTurnItems.delete(event.turnItem.id);
1075 } else {
1076 childTurnItems.set(event.turnItem.id, event.turnItem);
1077 }
1078 return { ...current, childTurnItems };
1079 });
1080 }
1081 if (belongsToRootRun && event.turnItem.type === "subagent") {
1082 const subagentItem = event.turnItem;
1083 yield* Ref.update(openRunOwnedSubagents, (current) => {
1084 const withLink = withLinkedChildThreadId(current, subagentItem.childThreadId);
1085 const turnItems = new Map(withLink.turnItems);
1086 if (isSettledTurnItemStatus(subagentItem.status)) {
1087 turnItems.delete(subagentItem.subagentId);
1088 } else {
1089 turnItems.set(subagentItem.subagentId, subagentItem);
1090 }
1091 return { ...withLink, turnItems };
1092 });
1093 }
1094 }
1095 });
1096 const shouldStopProviderEventIngestion = Effect.gen(function* () {
1097 if (!(yield* Ref.get(rootTerminalSeen))) {
1098 return false;
1099 }
1100 const terminal = yield* Ref.get(terminalEvent);
1101 // Non-completed terminals drop background tracking immediately.
1102 if (terminal !== null && terminal.status !== "completed") {
1103 return true;
1104 }
1105 const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
1106 if (childProviderTurns.size > 0) {
1107 return false;
1108 }
1109 const childSubagents = yield* Ref.get(activeChildSubagents);
1110 if (childSubagents.size > 0) {
1111 return false;
1112 }
1113 // Keep ingesting past root settlement while background-capable
1114 // items owned by this run (or an owned child thread) are still
1115 // non-terminal, so their late completion events reach the
1116 // projection (stuck-spinner fix). Only for completed runs:
1117 // interrupted/failed turns intentionally drop background tracking
1118 // rather than pinning the stream open. Newly owned items depend on
1119 // adapters emitting a non-terminal event before the root terminal.
1120 // Exact inherited items are seeded from their selected durable rows.
1121 //
1122 // Owner loss (a newer run claimed lastRunOrdinal) must not close
1123 // this stream while these sets are non-empty: turn_item.updated
1124 // writes are not ownership-gated, so late completions still land.
1125 const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
1126 if (backgroundItems.size > 0) {
1127 return false;
1128 }
1129 // Owner loss means do not hold the stream open solely for the
1130 // roster probe; once background sets are empty, release.
1131 if (yield* Ref.get(providerThreadOwnerLost)) {
1132 return true;
1133 }
1134 // Claude background Bash has no turn-item projection. Keep the
1135 // stream open while this root's provider thread still reports
1136 // pending roster work so late empty updates can clear Waiting.
1137 // Use only the thread-scoped probe: session-wide pending work
1138 // (siblings, wake buffers, session subagents) must not pin this
1139 // root subscription. Session idle release still uses
1140 // hasPendingBackgroundWork via ProviderSessionManager.
1141 const latestProviderThreadSnapshot = yield* Ref.get(latestProviderThread);
1142 if (input.session.hasPendingBackgroundWorkForThread !== undefined) {
1143 const hasPendingWork = yield* input.session
1144 .hasPendingBackgroundWorkForThread(latestProviderThreadSnapshot)
1145 .pipe(Effect.catchCause(() => Effect.succeed(false)));
1146 if (hasPendingWork) {
1147 return false;
1148 }
1149 }
1150 return true;
1151 });
1152 const filterAssistantEvent = makeAssistantStreamingFilter(responseStreamingMode);
1153 const providerEventFiber = yield* eventSubscription.events.pipe(
1154 Stream.filterEffect((event) =>
1155 Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
1156 ),
1157 Stream.tap((event) =>
1158 Effect.gen(function* () {
1159 let storedEventCount = 0;
1160 const deliveredEvent = filterAssistantEvent(
1161 event,
1162 DateTime.toEpochMillis(yield* DateTime.now),
1163 );
1164 if (deliveredEvent) {
1165 // Root provider_thread.updated always uses an ownership gate:
1166 // pre-terminal writeIfRunCurrent (attempt still running), or
1167 // post-terminal writeIfProviderThreadOwner so late roster
1168 // clears still land while this attempt owns the run and this
1169 // run owns lastRunOrdinal.
1170 const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen);
1171 const isRootProviderThreadUpdate =
1172 event.type === "provider_thread.updated" &&
1173 event.providerThread.id === input.providerThread.id;
1174 const storedEvents = yield* providerEventIngestor.ingestNormalized({
1175 analyticsContext: {
1176 modelSelection: input.modelSelection,
1177 runtimeMode: input.runtimePolicy.runtimeMode,
1178 interactionMode: input.runtimePolicy.interactionMode,
1179 },
1180 providerSessionId: input.providerSessionId,
1181 providerInstanceId: input.run.providerInstanceId,
1182 threadId: input.run.threadId,
1183 runId: input.run.id,
1184 nodeId: input.rootNode.id,
1185 event: deliveredEvent,
1186 ...(isRootProviderThreadUpdate
1187 ? rootTerminalAlreadySeen
1188 ? {
1189 writeIfProviderThreadOwner: {
1190 providerThreadId: input.providerThread.id,
1191 runId: input.run.id,
1192 activeAttemptId: input.attempt.id,
1193 expectedLastRunOrdinal: input.run.ordinal,
1194 },
1195 }
1196 : {
1197 writeIfRunCurrent: {
1198 runId: input.run.id,
1199 activeAttemptId: input.attempt.id,
1200 expectedStatus: "running" as const,
1201 },
1202 }
1203 : {}),
1204 });
1205 storedEventCount = storedEvents.length;
1206 if (
1207 isRootProviderThreadUpdate &&
1208 rootTerminalAlreadySeen &&
1209 storedEventCount === 0
1210 ) {
1211 // Ownership lost (or thread row missing). Stop pinning the
1212 // stream on this run's background probe.
1213 yield* Ref.set(providerThreadOwnerLost, true);
1214 }
1215 }
1216 if (event.type === "provider_thread.updated") {
1217 if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
1218 yield* Ref.set(latestProviderThread, event.providerThread);
1219 }
1220 }
1221 if (
1222 event.type === "turn_item.updated" &&
1223 event.turnItem.providerTurnId ===
1224 (yield* Ref.get(eventRouting)).rootProviderTurnId
1225 ) {
1226 yield* Ref.update(latestTurnItemOrdinal, (current) =>
1227 Math.max(current, event.turnItem.ordinal),
1228 );
1229 }
1230 if (event.type === "turn.terminal") {
1231 yield* Ref.set(terminalEvent, event);
1232 yield* Ref.set(rootTerminalSeen, true);
1233 yield* finalizeRootRun(event);
1234 }
1235 yield* trackChildLifecycle(event, deliveredEvent !== null);
1236 }),
1237 ),
1238 Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
1239 Stream.runDrain,
1240 Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
1241 Effect.flatMap(() =>
1242 Effect.gen(function* () {
1243 const terminal = yield* Ref.get(terminalEvent);
1244 if (terminal === null) {
1245 return;
1246 }
1247 yield* finalizeRootRun(terminal);
1248 }),
1249 ),
1250 Effect.catchCause((cause) =>
1251 Ref.get(rootRunFinalized).pipe(
1252 Effect.flatMap((finalized) =>
1253 Effect.logWarning("orchestration V2 provider event ingestion failed", {
1254 runId: input.run.id,
1255 cause,
1256 }).pipe(
1257 Effect.andThen(
1258 finalized
1259 ? Effect.void
1260 : Ref.get(latestProviderThread).pipe(
1261 Effect.flatMap((providerThread) =>
1262 Ref.get(latestTurnItemOrdinal).pipe(
1263 Effect.flatMap((latestItemOrdinal) =>
1264 Ref.get(openRunOwnedSubagents).pipe(
1265 Effect.flatMap((openSubagents) =>
1266 writeFinalRunEvents({
1267 run: input.run,
1268 rootNode: input.rootNode,
1269 checkpointScope: input.checkpointScope,
1270 providerThread,
1271 attempt: input.attempt,
1272 ...(input.shouldFinalizeRun === undefined
1273 ? {}
1274 : { shouldFinalizeRun: input.shouldFinalizeRun }),
1275 ...(input.hasUnpairedRunInterruptRequest === undefined
1276 ? {}
1277 : {
1278 hasUnpairedRunInterruptRequest:
1279 input.hasUnpairedRunInterruptRequest,
1280 }),
1281 openRunOwnedSubagents: openSubagents,
1282 terminal: makeFailedTerminalEvent(
1283 makeProviderFailure({
1284 cause: Cause.squash(cause),
1285 class: "unknown",
1286 }),
1287 latestItemOrdinal + 1,
1288 ),
1289 failureItemPersisted: false,
1290 refreshAfterTurn,
1291 }),
1292 ),
1293 ),
1294 ),
1295 ),
1296 ),
1297 ),
1298 ),
1299 Effect.mapError(
1300 (writeCause) =>
1301 new RunExecutionIngestError({
1302 runId: input.run.id,
1303 cause: { ingest: cause, write: writeCause },
1304 }),
1305 ),
1306 ),
1307 ),
1308 ),
1309 ),
1310 Effect.ensuring(eventSubscription.close),
1311 Effect.forkDetach,
1312 );
1313
1314 if (
1315 input.shouldStartProviderTurn !== undefined &&
1316 !(yield* input.shouldStartProviderTurn())
1317 ) {
1318 yield* Fiber.interrupt(providerEventFiber);
1319 return;
1320 }
1321
1322 // A provider turn is a sign that the session is still alive. Keep
1323 // its already-issued MCP credential valid even when the agent goes
1324 // a long time between browser-tool calls.
1325 yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
1326 const turnInput = {
1327 appThread: input.appThread,
1328 threadId: input.run.threadId,
1329 runId: input.run.id,
1330 runOrdinal: input.run.ordinal,
1331 providerTurnOrdinal: input.providerTurnOrdinal,
1332 ...(input.run.restartContinuationOfRunId === undefined
1333 ? {}
1334 : {
1335 restartContinuationOfRunId: input.run.restartContinuationOfRunId,
1336 }),
1337 attemptId: input.attemptId,
1338 rootNodeId: input.rootNode.id,
1339 providerThread: input.providerThread,
1340 message: input.message,
1341 modelSelection: input.modelSelection,
1342 runtimePolicy: input.runtimePolicy,
1343 };
1344 const compact =
1345 input.message.attachments.length === 0 &&
1346 input.message.text.trim().toLowerCase() === "/compact";
1347 const startTurn = compact
1348 ? (input.session.compactThread?.(turnInput) ??
1349 Effect.fail(
1350 new ProviderAdapterTurnStartError({
1351 driver: input.session.driver,
1352 threadId: input.run.threadId,
1353 providerThreadId: input.providerThread.id,
1354 runId: input.run.id,
1355 cause: "This provider does not support context compaction.",
1356 }),
1357 ))
1358 : input.session.startTurn(turnInput);
1359 yield* startTurn.pipe(
1360 Effect.catchCause((cause) =>
1361 Effect.logError("orchestration V2 provider turn start failed", {
1362 runId: input.run.id,
1363 cause,
1364 }).pipe(
1365 Effect.andThen(Fiber.interrupt(providerEventFiber)),
1366 Effect.andThen(Ref.get(latestProviderThread)),
1367 Effect.flatMap((providerThread) =>
1368 Ref.get(latestTurnItemOrdinal).pipe(
1369 Effect.flatMap((latestItemOrdinal) =>
1370 Ref.get(openRunOwnedSubagents).pipe(
1371 Effect.flatMap((openSubagents) =>
1372 writeFinalRunEvents({
1373 run: input.run,
1374 rootNode: input.rootNode,
1375 checkpointScope: input.checkpointScope,
1376 providerThread,
1377 attempt: input.attempt,
1378 ...(input.shouldFinalizeRun === undefined
1379 ? {}
1380 : { shouldFinalizeRun: input.shouldFinalizeRun }),
1381 ...(input.hasUnpairedRunInterruptRequest === undefined
1382 ? {}
1383 : {
1384 hasUnpairedRunInterruptRequest:
1385 input.hasUnpairedRunInterruptRequest,
1386 }),
1387 openRunOwnedSubagents: openSubagents,
1388 terminal: makeFailedTerminalEvent(
1389 makeProviderFailure({
1390 cause: Cause.squash(cause),
1391 class: "provider_error",
1392 }),
1393 latestItemOrdinal + 1,
1394 ),
1395 failureItemPersisted: false,
1396 refreshAfterTurn,
1397 }),
1398 ),
1399 ),
1400 ),
1401 ),
1402 ),
1403 Effect.mapError(
1404 (writeCause) =>
1405 new RunExecutionStartError({
1406 commandId: input.commandId,
1407 runId: input.run.id,
1408 cause: { start: cause, write: writeCause },
1409 }),
1410 ),
1411 ),
1412 ),
1413 );
1414 }),
1415 } satisfies RunExecutionServiceV2Shape);
1416 }),
1417);
1418
1419function makeInterruptResultTurnItem(input: {
1420 readonly idAllocator: IdAllocatorV2Shape;
1421 readonly run: OrchestrationV2Run;
1422 readonly rootNode: OrchestrationV2ExecutionNode;
1423 readonly providerThread: OrchestrationV2ProviderThread;
1424 readonly completedAt: DateTime.Utc;
1425}): OrchestrationV2TurnItem {
1426 return {
1427 id: input.idAllocator.derive.runSignalTurnItem({
1428 runId: input.run.id,
1429 signal: "interrupt-result",
1430 }),
1431 threadId: input.run.threadId,
1432 runId: input.run.id,
1433 nodeId: input.rootNode.id,
1434 providerThreadId: input.providerThread.id,
1435 providerTurnId: input.rootNode.providerTurnId,
1436 nativeItemRef: null,
1437 parentItemId: input.idAllocator.derive.runSignalTurnItem({
1438 runId: input.run.id,
1439 signal: "interrupt-request",
1440 }),
1441 ordinal: input.run.ordinal * 100 + 98,
1442 status: "interrupted",
1443 title: "Interrupted",
1444 startedAt: input.completedAt,
1445 completedAt: input.completedAt,
1446 updatedAt: input.completedAt,
1447 type: "run_interrupt_result",
1448 message: "Run interrupted by user",
1449 };
1450}