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

RunExecutionService.ts

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