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