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

RunExecutionService.ts

1,399 lines58.1 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.mapError(
792 (cause) =>
793 new RunExecutionStartError({
794 commandId: input.commandId,
795 runId: input.run.id,
796 cause,
797 }),
798 ),
799 );
800 if (
801 input.shouldStartProviderTurn !== undefined &&
802 !(yield* input.shouldStartProviderTurn())
803 ) {
804 return;
805 }
806 // Startup failure and stream shutdown can report the same attempt.
807 const refreshAfterTurn = yield* Effect.cached(
808 finalizationObserver.refreshAfterTurn.pipe(
809 Effect.catchCause((cause) =>
810 Effect.logWarning("failed to refresh pull requests after run termination", {
811 threadId: input.run.threadId,
812 runId: input.run.id,
813 cause,
814 }),
815 ),
816 ),
817 );
818 const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);
819 const makeFailedTerminalEvent = (
820 failure: OrchestrationV2ProviderFailure,
821 failureItemOrdinal: number,
822 ): ProviderTerminalEvent => ({
823 type: "turn.terminal",
824 driver: input.providerThread.driver,
825 providerThreadId: input.providerThread.id,
826 providerTurnId:
827 input.attempt.providerTurnId ??
828 idAllocator.derive.providerTurn({
829 driver: input.providerThread.driver,
830 nativeTurnId: `failed:${input.attempt.id}`,
831 }),
832 runOrdinal: input.run.ordinal,
833 failureItemOrdinal,
834 status: "failed",
835 failure,
836 threadDisposition: "reusable",
837 });
838 const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);
839 const latestProviderThread = yield* Ref.make(input.providerThread);
840 const routeIdentity: ProviderEventRouteIdentity = {
841 threadId: input.run.threadId,
842 runId: input.run.id,
843 attemptId: input.attempt.id,
844 providerThreadId: input.providerThread.id,
845 };
846 const eventSubscription =
847 input.session.subscribeEvents === undefined
848 ? { events: input.session.events, close: Effect.void }
849 : yield* input.session.subscribeEvents;
850 const inheritedBackgroundTurnItems = yield* (
851 input.loadInheritedBackgroundTurnItems?.() ?? Effect.succeed([])
852 ).pipe(
853 Effect.onError(() => eventSubscription.close),
854 Effect.mapError(
855 (cause) =>
856 new RunExecutionStartError({
857 commandId: input.commandId,
858 runId: input.run.id,
859 cause,
860 }),
861 ),
862 );
863 const inheritedBackgroundTurnItemsById = new Map(
864 inheritedBackgroundTurnItems.map((item) => [item.id, item.runId]),
865 );
866 const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
867 makeProviderEventRoutingState({
868 identity: routeIdentity,
869 inheritedBackgroundTurnItems,
870 providerTurnId: input.attempt.providerTurnId,
871 ...(input.relatedThreadIds === undefined
872 ? {}
873 : { relatedThreadIds: input.relatedThreadIds }),
874 ...(input.relatedProviderThreadIds === undefined
875 ? {}
876 : { relatedProviderThreadIds: input.relatedProviderThreadIds }),
877 }),
878 );
879 const rootTerminalSeen = yield* Ref.make(false);
880 const rootRunFinalized = yield* Ref.make(false);
881 const providerThreadOwnerLost = yield* Ref.make(false);
882 const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
883 const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
884 const activeBackgroundTurnItems = yield* Ref.make<
885 ReadonlySet<OrchestrationV2TurnItem["id"]>
886 >(new Set(inheritedBackgroundTurnItemsById.keys()));
887 const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
888 const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
889 Effect.gen(function* () {
890 if (yield* Ref.get(rootRunFinalized)) {
891 return;
892 }
893 const providerThread = yield* Ref.get(latestProviderThread);
894 const openSubagents = yield* Ref.get(openRunOwnedSubagents);
895 yield* writeFinalRunEvents({
896 run: input.run,
897 rootNode: input.rootNode,
898 checkpointScope: input.checkpointScope,
899 providerThread,
900 attempt: input.attempt,
901 ...(input.shouldFinalizeRun === undefined
902 ? {}
903 : { shouldFinalizeRun: input.shouldFinalizeRun }),
904 ...(input.hasUnpairedRunInterruptRequest === undefined
905 ? {}
906 : {
907 hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
908 }),
909 openRunOwnedSubagents: openSubagents,
910 terminal,
911 failureItemPersisted: terminal.status === "failed",
912 refreshAfterTurn,
913 }).pipe(
914 Effect.mapError(
915 (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
916 ),
917 );
918 if (isRunOwnedSubagentTerminalStatus(terminal.status)) {
919 yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
920 }
921 yield* Ref.set(rootRunFinalized, true);
922 });
923 const trackChildLifecycle = (event: ProviderAdapterV2Event, deliverable: boolean) =>
924 Effect.gen(function* () {
925 const routing = yield* Ref.get(eventRouting);
926 if (event.type === "provider_turn.updated") {
927 const isRoot =
928 event.providerTurn.runAttemptId === input.attempt.id ||
929 event.providerTurn.id === routing.rootProviderTurnId;
930 if (!isRoot) {
931 yield* Ref.update(activeChildProviderTurns, (current) => {
932 const next = new Set(current);
933 if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
934 next.delete(event.providerTurn.id);
935 } else {
936 next.add(event.providerTurn.id);
937 }
938 return next;
939 });
940 }
941 }
942 if (event.type === "subagent.updated") {
943 const belongsToRootRun = event.subagent.runId === input.run.id;
944 const belongsToOwnedChildThread =
945 event.subagent.threadId !== input.run.threadId &&
946 routing.ownedThreadIds.has(event.subagent.threadId);
947 if (belongsToRootRun || belongsToOwnedChildThread) {
948 yield* Ref.update(activeChildSubagents, (current) => {
949 const next = new Set(current);
950 if (isTerminalSubagentStatus(event.subagent.status)) {
951 next.delete(event.subagent.id);
952 } else {
953 next.add(event.subagent.id);
954 }
955 return next;
956 });
957 }
958 // Snapshot run-owned subagents for interrupt cascade.
959 // Preserve childThreadId linkage for the root-run lifetime even
960 // after the subagent row terminalizes, so open child-thread
961 // nodes can still be proven linked on a later root interrupt.
962 if (belongsToRootRun) {
963 yield* Ref.update(openRunOwnedSubagents, (current) => {
964 const withLink = withLinkedChildThreadId(current, event.subagent.childThreadId);
965 const subagents = new Map(withLink.subagents);
966 if (isTerminalSubagentStatus(event.subagent.status)) {
967 subagents.delete(event.subagent.id);
968 } else {
969 subagents.set(event.subagent.id, event.subagent);
970 }
971 return { ...withLink, subagents };
972 });
973 }
974 }
975 if (event.type === "node.updated") {
976 const belongsToRootSubagent =
977 event.node.kind === "subagent" && event.node.runId === input.run.id;
978 const belongsToOwnedChildThread =
979 event.node.threadId !== input.run.threadId &&
980 routing.ownedThreadIds.has(event.node.threadId);
981 if (!belongsToRootSubagent && !belongsToOwnedChildThread) {
982 return;
983 }
984 yield* Ref.update(openRunOwnedSubagents, (current) => {
985 const nodes = new Map(current.nodes);
986 if (isOpenExecutionNodeStatus(event.node.status)) {
987 nodes.set(event.node.id, event.node);
988 } else {
989 nodes.delete(event.node.id);
990 }
991 return { ...current, nodes };
992 });
993 }
994 if (event.type === "turn_item.updated") {
995 const belongsToRootRun = event.turnItem.runId === input.run.id;
996 const belongsToOwnedChildThread =
997 event.turnItem.threadId !== input.run.threadId &&
998 routing.ownedThreadIds.has(event.turnItem.threadId);
999 const belongsToInheritedBackgroundItem =
1000 event.turnItem.threadId === input.run.threadId &&
1001 event.turnItem.runId !== null &&
1002 inheritedBackgroundTurnItemsById.get(event.turnItem.id) === event.turnItem.runId;
1003 if (
1004 backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
1005 (belongsToRootRun ||
1006 belongsToOwnedChildThread ||
1007 belongsToInheritedBackgroundItem)
1008 ) {
1009 yield* Ref.update(activeBackgroundTurnItems, (current) => {
1010 const next = new Set(current);
1011 if (isTerminalTurnItemStatus(event.turnItem.status)) {
1012 next.delete(event.turnItem.id);
1013 } else {
1014 next.add(event.turnItem.id);
1016 return next;
1017 });
1019 if (belongsToOwnedChildThread && deliverable) {
1020 yield* Ref.update(openRunOwnedSubagents, (current) => {
1021 const childTurnItems = new Map(current.childTurnItems);
1022 if (isTerminalTurnItemStatus(event.turnItem.status)) {
1023 childTurnItems.delete(event.turnItem.id);
1024 } else {
1025 childTurnItems.set(event.turnItem.id, event.turnItem);
1027 return { ...current, childTurnItems };
1028 });
1030 if (belongsToRootRun && event.turnItem.type === "subagent") {
1031 const subagentItem = event.turnItem;
1032 yield* Ref.update(openRunOwnedSubagents, (current) => {
1033 const withLink = withLinkedChildThreadId(current, subagentItem.childThreadId);
1034 const turnItems = new Map(withLink.turnItems);
1035 if (isTerminalTurnItemStatus(subagentItem.status)) {
1036 turnItems.delete(subagentItem.subagentId);
1037 } else {
1038 turnItems.set(subagentItem.subagentId, subagentItem);
1040 return { ...withLink, turnItems };
1041 });
1044 });
1045 const shouldStopProviderEventIngestion = Effect.gen(function* () {
1046 if (!(yield* Ref.get(rootTerminalSeen))) {
1047 return false;
1049 const terminal = yield* Ref.get(terminalEvent);
1050 // Non-completed terminals drop background tracking immediately.
1051 if (terminal !== null && terminal.status !== "completed") {
1052 return true;
1054 const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
1055 if (childProviderTurns.size > 0) {
1056 return false;
1058 const childSubagents = yield* Ref.get(activeChildSubagents);
1059 if (childSubagents.size > 0) {
1060 return false;
1062 // Keep ingesting past root settlement while background-capable
1063 // items owned by this run (or an owned child thread) are still
1064 // non-terminal, so their late completion events reach the
1065 // projection (stuck-spinner fix). Only for completed runs:
1066 // interrupted/failed turns intentionally drop background tracking
1067 // rather than pinning the stream open. Newly owned items depend on
1068 // adapters emitting a non-terminal event before the root terminal.
1069 // Exact inherited items are seeded from their selected durable rows.
1070 //
1071 // Owner loss (a newer run claimed lastRunOrdinal) must not close
1072 // this stream while these sets are non-empty: turn_item.updated
1073 // writes are not ownership-gated, so late completions still land.
1074 const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
1075 if (backgroundItems.size > 0) {
1076 return false;
1078 // Owner loss means do not hold the stream open solely for the
1079 // roster probe; once background sets are empty, release.
1080 if (yield* Ref.get(providerThreadOwnerLost)) {
1081 return true;
1083 // Claude background Bash has no turn-item projection. Keep the
1084 // stream open while this root's provider thread still reports
1085 // pending roster work so late empty updates can clear Waiting.
1086 // Use only the thread-scoped probe: session-wide pending work
1087 // (siblings, wake buffers, session subagents) must not pin this
1088 // root subscription. Session idle release still uses
1089 // hasPendingBackgroundWork via ProviderSessionManager.
1090 const latestProviderThreadSnapshot = yield* Ref.get(latestProviderThread);
1091 if (input.session.hasPendingBackgroundWorkForThread !== undefined) {
1092 const hasPendingWork = yield* input.session
1093 .hasPendingBackgroundWorkForThread(latestProviderThreadSnapshot)
1094 .pipe(Effect.catchCause(() => Effect.succeed(false)));
1095 if (hasPendingWork) {
1096 return false;
1099 return true;
1100 });
1101 const filterAssistantEvent = makeAssistantStreamingFilter(responseStreamingMode);
1102 const providerEventFiber = yield* eventSubscription.events.pipe(
1103 Stream.filterEffect((event) =>
1104 Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
1105 ),
1106 Stream.tap((event) =>
1107 Effect.gen(function* () {
1108 let storedEventCount = 0;
1109 const deliveredEvent = filterAssistantEvent(
1110 event,
1111 DateTime.toEpochMillis(yield* DateTime.now),
1112 );
1113 if (deliveredEvent) {
1114 // Root provider_thread.updated always uses an ownership gate:
1115 // pre-terminal writeIfRunCurrent (attempt still running), or
1116 // post-terminal writeIfProviderThreadOwner so late roster
1117 // clears still land while this attempt owns the run and this
1118 // run owns lastRunOrdinal.
1119 const rootTerminalAlreadySeen = yield* Ref.get(rootTerminalSeen);
1120 const isRootProviderThreadUpdate =
1121 event.type === "provider_thread.updated" &&
1122 event.providerThread.id === input.providerThread.id;
1123 const storedEvents = yield* providerEventIngestor.ingestNormalized({
1124 analyticsContext: {
1125 modelSelection: input.modelSelection,
1126 runtimeMode: input.runtimePolicy.runtimeMode,
1127 interactionMode: input.runtimePolicy.interactionMode,
1128 },
1129 providerSessionId: input.providerSessionId,
1130 providerInstanceId: input.run.providerInstanceId,
1131 threadId: input.run.threadId,
1132 runId: input.run.id,
1133 nodeId: input.rootNode.id,
1134 event: deliveredEvent,
1135 ...(isRootProviderThreadUpdate
1136 ? rootTerminalAlreadySeen
1137 ? {
1138 writeIfProviderThreadOwner: {
1139 providerThreadId: input.providerThread.id,
1140 runId: input.run.id,
1141 activeAttemptId: input.attempt.id,
1142 expectedLastRunOrdinal: input.run.ordinal,
1143 },
1145 : {
1146 writeIfRunCurrent: {
1147 runId: input.run.id,
1148 activeAttemptId: input.attempt.id,
1149 expectedStatus: "running" as const,
1150 },
1152 : {}),
1153 });
1154 storedEventCount = storedEvents.length;
1155 if (
1156 isRootProviderThreadUpdate &&
1157 rootTerminalAlreadySeen &&
1158 storedEventCount === 0
1159 ) {
1160 // Ownership lost (or thread row missing). Stop pinning the
1161 // stream on this run's background probe.
1162 yield* Ref.set(providerThreadOwnerLost, true);
1165 if (event.type === "provider_thread.updated") {
1166 if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
1167 yield* Ref.set(latestProviderThread, event.providerThread);
1170 if (
1171 event.type === "turn_item.updated" &&
1172 event.turnItem.providerTurnId ===
1173 (yield* Ref.get(eventRouting)).rootProviderTurnId
1174 ) {
1175 yield* Ref.update(latestTurnItemOrdinal, (current) =>
1176 Math.max(current, event.turnItem.ordinal),
1177 );
1179 if (event.type === "turn.terminal") {
1180 yield* Ref.set(terminalEvent, event);
1181 yield* Ref.set(rootTerminalSeen, true);
1182 yield* finalizeRootRun(event);
1184 yield* trackChildLifecycle(event, deliveredEvent !== null);
1185 }),
1186 ),
1187 Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
1188 Stream.runDrain,
1189 Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
1190 Effect.flatMap(() =>
1191 Effect.gen(function* () {
1192 const terminal = yield* Ref.get(terminalEvent);
1193 if (terminal === null) {
1194 return;
1196 yield* finalizeRootRun(terminal);
1197 }),
1198 ),
1199 Effect.catchCause((cause) =>
1200 Ref.get(rootRunFinalized).pipe(
1201 Effect.flatMap((finalized) =>
1202 Effect.logWarning("orchestration V2 provider event ingestion failed", {
1203 runId: input.run.id,
1204 cause,
1205 }).pipe(
1206 Effect.andThen(
1207 finalized
1208 ? Effect.void
1209 : Ref.get(latestProviderThread).pipe(
1210 Effect.flatMap((providerThread) =>
1211 Ref.get(latestTurnItemOrdinal).pipe(
1212 Effect.flatMap((latestItemOrdinal) =>
1213 Ref.get(openRunOwnedSubagents).pipe(
1214 Effect.flatMap((openSubagents) =>
1215 writeFinalRunEvents({
1216 run: input.run,
1217 rootNode: input.rootNode,
1218 checkpointScope: input.checkpointScope,
1219 providerThread,
1220 attempt: input.attempt,
1221 ...(input.shouldFinalizeRun === undefined
1222 ? {}
1223 : { shouldFinalizeRun: input.shouldFinalizeRun }),
1224 ...(input.hasUnpairedRunInterruptRequest === undefined
1225 ? {}
1226 : {
1227 hasUnpairedRunInterruptRequest:
1228 input.hasUnpairedRunInterruptRequest,
1229 }),
1230 openRunOwnedSubagents: openSubagents,
1231 terminal: makeFailedTerminalEvent(
1232 makeProviderFailure({
1233 cause: Cause.squash(cause),
1234 class: "unknown",
1235 }),
1236 latestItemOrdinal + 1,
1237 ),
1238 failureItemPersisted: false,
1239 refreshAfterTurn,
1240 }),
1241 ),
1242 ),
1243 ),
1244 ),
1245 ),
1246 ),
1247 ),
1248 Effect.mapError(
1249 (writeCause) =>
1250 new RunExecutionIngestError({
1251 runId: input.run.id,
1252 cause: { ingest: cause, write: writeCause },
1253 }),
1254 ),
1255 ),
1256 ),
1257 ),
1258 ),
1259 Effect.ensuring(eventSubscription.close),
1260 Effect.forkDetach,
1261 );
1262​
1263 if (
1264 input.shouldStartProviderTurn !== undefined &&
1265 !(yield* input.shouldStartProviderTurn())
1266 ) {
1267 yield* Fiber.interrupt(providerEventFiber);
1268 return;
1270​
1271 // A provider turn is a sign that the session is still alive. Keep
1272 // its already-issued MCP credential valid even when the agent goes
1273 // a long time between browser-tool calls.
1274 yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
1275 const turnInput = {
1276 appThread: input.appThread,
1277 threadId: input.run.threadId,
1278 runId: input.run.id,
1279 runOrdinal: input.run.ordinal,
1280 providerTurnOrdinal: input.providerTurnOrdinal,
1281 ...(input.run.restartContinuationOfRunId === undefined
1282 ? {}
1283 : {
1284 restartContinuationOfRunId: input.run.restartContinuationOfRunId,
1285 }),
1286 attemptId: input.attemptId,
1287 rootNodeId: input.rootNode.id,
1288 providerThread: input.providerThread,
1289 message: input.message,
1290 modelSelection: input.modelSelection,
1291 runtimePolicy: input.runtimePolicy,
1292 };
1293 const compact =
1294 input.message.attachments.length === 0 &&
1295 input.message.text.trim().toLowerCase() === "/compact";
1296 const startTurn = compact
1297 ? (input.session.compactThread?.(turnInput) ??
1298 Effect.fail(
1299 new ProviderAdapterTurnStartError({
1300 driver: input.session.driver,
1301 threadId: input.run.threadId,
1302 providerThreadId: input.providerThread.id,
1303 runId: input.run.id,
1304 cause: "This provider does not support context compaction.",
1305 }),
1306 ))
1307 : input.session.startTurn(turnInput);
1308 yield* startTurn.pipe(
1309 Effect.catchCause((cause) =>
1310 Effect.logError("orchestration V2 provider turn start failed", {
1311 runId: input.run.id,
1312 cause,
1313 }).pipe(
1314 Effect.andThen(Fiber.interrupt(providerEventFiber)),
1315 Effect.andThen(Ref.get(latestProviderThread)),
1316 Effect.flatMap((providerThread) =>
1317 Ref.get(latestTurnItemOrdinal).pipe(
1318 Effect.flatMap((latestItemOrdinal) =>
1319 Ref.get(openRunOwnedSubagents).pipe(
1320 Effect.flatMap((openSubagents) =>
1321 writeFinalRunEvents({
1322 run: input.run,
1323 rootNode: input.rootNode,
1324 checkpointScope: input.checkpointScope,
1325 providerThread,
1326 attempt: input.attempt,
1327 ...(input.shouldFinalizeRun === undefined
1328 ? {}
1329 : { shouldFinalizeRun: input.shouldFinalizeRun }),
1330 ...(input.hasUnpairedRunInterruptRequest === undefined
1331 ? {}
1332 : {
1333 hasUnpairedRunInterruptRequest:
1334 input.hasUnpairedRunInterruptRequest,
1335 }),
1336 openRunOwnedSubagents: openSubagents,
1337 terminal: makeFailedTerminalEvent(
1338 makeProviderFailure({
1339 cause: Cause.squash(cause),
1340 class: "provider_error",
1341 }),
1342 latestItemOrdinal + 1,
1343 ),
1344 failureItemPersisted: false,
1345 refreshAfterTurn,
1346 }),
1347 ),
1348 ),
1349 ),
1350 ),
1351 ),
1352 Effect.mapError(
1353 (writeCause) =>
1354 new RunExecutionStartError({
1355 commandId: input.commandId,
1356 runId: input.run.id,
1357 cause: { start: cause, write: writeCause },
1358 }),
1359 ),
1360 ),
1361 ),
1362 );
1363 }),
1364 } satisfies RunExecutionServiceV2Shape);
1365 }),
1367​
1368function makeInterruptResultTurnItem(input: {
1369 readonly idAllocator: IdAllocatorV2Shape;
1370 readonly run: OrchestrationV2Run;
1371 readonly rootNode: OrchestrationV2ExecutionNode;
1372 readonly providerThread: OrchestrationV2ProviderThread;
1373 readonly completedAt: DateTime.Utc;
1374}): OrchestrationV2TurnItem {
1375 return {
1376 id: input.idAllocator.derive.runSignalTurnItem({
1377 runId: input.run.id,
1378 signal: "interrupt-result",
1379 }),
1380 threadId: input.run.threadId,
1381 runId: input.run.id,
1382 nodeId: input.rootNode.id,
1383 providerThreadId: input.providerThread.id,
1384 providerTurnId: input.rootNode.providerTurnId,
1385 nativeItemRef: null,
1386 parentItemId: input.idAllocator.derive.runSignalTurnItem({
1387 runId: input.run.id,
1388 signal: "interrupt-request",
1389 }),
1390 ordinal: input.run.ordinal * 100 + 98,
1391 status: "interrupted",
1392 title: "Interrupted",
1393 startedAt: input.completedAt,
1394 completedAt: input.completedAt,
1395 updatedAt: input.completedAt,
1396 type: "run_interrupt_result",
1397 message: "Run interrupted by user",
1398 };