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

RunExecutionService.ts

1,407 lines58.5 KB

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