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

RunExecutionService.ts

1,480 lines62.4 KB

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