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

RunExecutionService.ts

1,454 lines61.0 KB

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