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