Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RunExecutionService.ts

1,364 lines56.3 KB

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