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

RunExecutionService.ts

1,206 lines48.8 KB

1import {
2 CommandId,
3 type EventId,
4 type ModelSelection,
5 type NodeId,
6 type OrchestrationV2AppThread,
7 type OrchestrationV2CheckpointScope,
8 type OrchestrationV2DomainEvent,
9 type OrchestrationV2ExecutionNode,
10 type OrchestrationV2ProviderFailure,
11 type OrchestrationV2ProviderThread,
12 type OrchestrationV2ProviderTurn,
13 type OrchestrationV2Run,
14 type OrchestrationV2RunAttempt,
15 type OrchestrationV2Subagent,
16 type OrchestrationV2TurnItem,
17 type ProviderSessionId,
18 type ProviderThreadId,
19 type ProviderTurnId,
20 type RunAttemptId,
21 type ThreadId,
22 type TurnItemId,
23} from "@t3tools/contracts";
24import * as Context from "effect/Context";
25import * as Cause from "effect/Cause";
26import * as DateTime from "effect/DateTime";
27import * as Effect from "effect/Effect";
28import * as Fiber from "effect/Fiber";
29import * as Layer from "effect/Layer";
30import * as Ref from "effect/Ref";
31import * as Schema from "effect/Schema";
32import * as Stream from "effect/Stream";
33​
34import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
35import { ServerSettingsService } from "../serverSettings.ts";
36import { CheckpointServiceV2 } from "./CheckpointService.ts";
37import { EventSinkV2 } from "./EventSink.ts";
38import {
39 IdAllocatorV2,
40 type IdAllocatorV2AllocationError,
41 type IdAllocatorV2Shape,
42} from "./IdAllocator.ts";
43import type {
44 ProviderAdapterV2Event,
45 ProviderAdapterV2RuntimePolicy,
46 ProviderAdapterV2SessionRuntime,
47 ProviderAdapterV2TurnMessage,
48} from "./ProviderAdapter.ts";
49import { ProviderEventIngestorV2 } from "./ProviderEventIngestor.ts";
50import { makeProviderFailure, makeProviderFailureTurnItem } from "./ProviderFailure.ts";
51​
52export interface ProviderEventRoutingState {
53 readonly ownedThreadIds: ReadonlySet<ThreadId>;
54 readonly ownedProviderThreadIds: ReadonlySet<ProviderThreadId>;
55 readonly ownedProviderTurnIds: ReadonlySet<ProviderTurnId>;
56 readonly rootProviderTurnId: ProviderTurnId | null;
58​
59export interface ProviderEventRouteIdentity {
60 readonly threadId: ThreadId;
61 readonly runId: OrchestrationV2Run["id"];
62 readonly attemptId: RunAttemptId;
63 readonly providerThreadId: ProviderThreadId;
65​
66type ProviderTerminalEvent = Extract<ProviderAdapterV2Event, { readonly type: "turn.terminal" }>;
67​
68function isTerminalProviderTurnStatus(status: OrchestrationV2ProviderTurn["status"]): boolean {
69 return (
70 status === "completed" ||
71 status === "interrupted" ||
72 status === "failed" ||
73 status === "cancelled"
74 );
76​
77function isTerminalSubagentStatus(status: OrchestrationV2Subagent["status"]): boolean {
78 return (
79 status === "completed" ||
80 status === "interrupted" ||
81 status === "failed" ||
82 status === "cancelled"
83 );
85​
86// Turn item types whose lifecycle can outlive the root turn (background
87// commands, monitors/dynamic tools, subagent rows). Ingestion must not stop
88// while one of these is still non-terminal, or the late completion event is
89// dropped and the item spins forever in the projection.
90const backgroundCapableTurnItemTypes: ReadonlySet<OrchestrationV2TurnItem["type"]> = new Set([
91 "command_execution",
92 "dynamic_tool",
93 "subagent",
94]);
95​
96function isTerminalTurnItemStatus(status: OrchestrationV2TurnItem["status"]): boolean {
97 return (
98 status === "completed" ||
99 status === "interrupted" ||
100 status === "failed" ||
101 status === "cancelled"
102 );
104​
105type SubagentTurnItem = Extract<OrchestrationV2TurnItem, { readonly type: "subagent" }>;
106​
107type OpenRunOwnedSubagentProjection = {
108 readonly subagents: ReadonlyMap<NodeId, OrchestrationV2Subagent>;
109 readonly turnItems: ReadonlyMap<NodeId, SubagentTurnItem>;
110 readonly childTurnItems: ReadonlyMap<TurnItemId, OrchestrationV2TurnItem>;
111 readonly nodes: ReadonlyMap<NodeId, OrchestrationV2ExecutionNode>;
112 /** Child threads once linked by a root-run subagent row; kept for cascade. */
113 readonly linkedChildThreadIds: ReadonlySet<ThreadId>;
114};
115​
116type RunOwnedSubagentTerminalStatus = Extract<
117 OrchestrationV2Subagent["status"],
118 "interrupted" | "failed" | "cancelled"
119>;
120​
121function isOpenExecutionNodeStatus(status: OrchestrationV2ExecutionNode["status"]): boolean {
122 return status === "pending" || status === "running" || status === "waiting";
124​
125function isRunOwnedSubagentTerminalStatus(
126 status: ProviderTerminalEvent["status"],
127): status is RunOwnedSubagentTerminalStatus {
128 return status === "interrupted" || status === "failed" || status === "cancelled";
130​
131export function canRouteRelatedSubagent(status: OrchestrationV2Subagent["status"]): boolean {
132 return status !== "interrupted" && status !== "failed" && status !== "cancelled";
134​
135function emptyOpenRunOwnedSubagentProjection(): OpenRunOwnedSubagentProjection {
136 return {
137 subagents: new Map(),
138 turnItems: new Map(),
139 childTurnItems: new Map(),
140 nodes: new Map(),
141 linkedChildThreadIds: new Set(),
142 };
144​
145function withLinkedChildThreadId(
146 current: OpenRunOwnedSubagentProjection,
147 childThreadId: ThreadId | null,
148): OpenRunOwnedSubagentProjection {
149 if (childThreadId === null || current.linkedChildThreadIds.has(childThreadId)) {
150 return current;
151 }
152 const linkedChildThreadIds = new Set(current.linkedChildThreadIds);
153 linkedChildThreadIds.add(childThreadId);
154 return { ...current, linkedChildThreadIds };
156​
157export function cascadeTerminalizeRunOwnedSubagents(input: {
158 readonly run: OrchestrationV2Run;
159 readonly open: OpenRunOwnedSubagentProjection;
160 readonly status: RunOwnedSubagentTerminalStatus;
161 readonly completedAt: DateTime.Utc;
162 readonly allocateEventId: () => Effect.Effect<EventId, IdAllocatorV2AllocationError>;
163}): Effect.Effect<ReadonlyArray<OrchestrationV2DomainEvent>, IdAllocatorV2AllocationError> {
164 return Effect.gen(function* () {
165 const events: Array<OrchestrationV2DomainEvent> = [];
166 // Prefer lifetime linkage over currently-open rows: subagent/turn-item
167 // snapshots may terminalize before the linked child-thread node settles.
168 const childThreadIds = new Set(input.open.linkedChildThreadIds);
169 for (const item of [...input.open.subagents.values(), ...input.open.turnItems.values()]) {
170 if (item.childThreadId !== null) {
171 childThreadIds.add(item.childThreadId);
172 }
173 }
174 const keys = new Set<NodeId>([
175 ...input.open.subagents.keys(),
176 ...input.open.turnItems.keys(),
177 ...input.open.nodes.keys(),
178 ]);
179 for (const key of keys) {
180 const subagent = input.open.subagents.get(key);
181 if (subagent !== undefined && !isTerminalSubagentStatus(subagent.status)) {
182 events.push({
183 id: yield* input.allocateEventId(),
184 type: "subagent.updated",
185 threadId: subagent.threadId,
186 runId: input.run.id,
187 nodeId: subagent.id,
188 driver: subagent.driver,
189 providerInstanceId: subagent.providerInstanceId,
190 occurredAt: input.completedAt,
191 payload: {
192 ...subagent,
193 status: input.status,
194 completedAt: input.completedAt,
195 updatedAt: input.completedAt,
196 },
197 });
198 }
199 const node = input.open.nodes.get(key);
200 if (
201 node !== undefined &&
202 ((node.threadId === input.run.threadId && node.runId === input.run.id) ||
203 childThreadIds.has(node.threadId)) &&
204 isOpenExecutionNodeStatus(node.status)
205 ) {
206 events.push({
207 id: yield* input.allocateEventId(),
208 type: "node.updated",
209 threadId: node.threadId,
210 runId: node.runId ?? input.run.id,
211 nodeId: node.id,
212 providerInstanceId: input.run.providerInstanceId,
213 occurredAt: input.completedAt,
214 payload: {
215 ...node,
216 status: input.status,
217 completedAt: input.completedAt,
218 },
219 });
220 }
221 const turnItem = input.open.turnItems.get(key);
222 if (
223 turnItem !== undefined &&
224 turnItem.runId === input.run.id &&
225 !isTerminalTurnItemStatus(turnItem.status)
226 ) {
227 events.push({
228 id: yield* input.allocateEventId(),
229 type: "turn-item.updated",
230 threadId: turnItem.threadId,
231 runId: input.run.id,
232 ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
233 providerInstanceId: input.run.providerInstanceId,
234 occurredAt: input.completedAt,
235 payload: {
236 ...turnItem,
237 status: input.status,
238 completedAt: input.completedAt,
239 updatedAt: input.completedAt,
240 },
241 });
242 }
243 }
244 for (const turnItem of input.open.childTurnItems.values()) {
245 if (!childThreadIds.has(turnItem.threadId) || isTerminalTurnItemStatus(turnItem.status)) {
246 continue;
247 }
248 events.push({
249 id: yield* input.allocateEventId(),
250 type: "turn-item.updated",
251 threadId: turnItem.threadId,
252 runId: turnItem.runId ?? input.run.id,
253 ...(turnItem.nodeId === null ? {} : { nodeId: turnItem.nodeId }),
254 providerInstanceId: input.run.providerInstanceId,
255 occurredAt: input.completedAt,
256 payload: {
257 ...turnItem,
258 ...("streaming" in turnItem ? { streaming: false } : {}),
259 status: input.status,
260 completedAt: input.completedAt,
261 updatedAt: input.completedAt,
262 },
263 });
264 }
265 return events;
266 });
268​
269export function finalProviderThreadStatus(
270 disposition: ProviderTerminalEvent["threadDisposition"],
271): OrchestrationV2ProviderThread["status"] {
272 return disposition === "broken" ? "error" : "idle";
274​
275export function makeProviderEventRoutingState(input: {
276 readonly identity: ProviderEventRouteIdentity;
277 readonly providerTurnId: ProviderTurnId | null;
278 readonly relatedThreadIds?: ReadonlyArray<ThreadId>;
279 readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
280}): ProviderEventRoutingState {
281 return {
282 ownedThreadIds: new Set([input.identity.threadId, ...(input.relatedThreadIds ?? [])]),
283 ownedProviderThreadIds: new Set([
284 input.identity.providerThreadId,
285 ...(input.relatedProviderThreadIds ?? []),
286 ]),
287 ownedProviderTurnIds:
288 input.providerTurnId === null ? new Set() : new Set([input.providerTurnId]),
289 rootProviderTurnId: input.providerTurnId,
290 };
292​
293export function routeProviderEvent(
294 event: ProviderAdapterV2Event,
295 input: ProviderEventRouteIdentity,
296 state: ProviderEventRoutingState,
297): readonly [boolean, ProviderEventRoutingState] {
298 const ownsThread = (threadId: ThreadId): boolean => state.ownedThreadIds.has(threadId);
299 const ownsChildThread = (threadId: ThreadId): boolean =>
300 threadId !== input.threadId && ownsThread(threadId);
301 const ownsRun = (runId: string | null): boolean => runId === input.runId;
302 const addProviderThread = (providerThreadId: ProviderThreadId): ProviderEventRoutingState => ({
303 ...state,
304 ownedProviderThreadIds: new Set([...state.ownedProviderThreadIds, providerThreadId]),
305 });
306 const addProviderTurn = (
307 providerTurnId: ProviderTurnId,
308 root: boolean,
309 ): ProviderEventRoutingState => ({
310 ...state,
311 ownedProviderTurnIds: new Set([...state.ownedProviderTurnIds, providerTurnId]),
312 rootProviderTurnId: root ? providerTurnId : state.rootProviderTurnId,
313 });
314​
315 switch (event.type) {
316 case "provider_session.updated":
317 // The session manager persists process-wide status once for every
318 // attached app thread before broadcasting the adapter event.
319 return [false, state];
320 case "app_thread.created": {
321 if (event.appThread.id === input.threadId) {
322 return [true, state];
323 }
324 const isOwnedSubagent =
325 event.appThread.lineage.relationshipToParent === "subagent" &&
326 event.appThread.lineage.parentThreadId !== null &&
327 ownsThread(event.appThread.lineage.parentThreadId);
328 if (!isOwnedSubagent) {
329 return [false, state];
330 }
331 return [
332 true,
333 {
334 ...state,
335 ownedThreadIds: new Set([...state.ownedThreadIds, event.appThread.id]),
336 },
337 ];
338 }
339 case "provider_thread.updated": {
340 const belongs =
341 state.ownedProviderThreadIds.has(event.providerThread.id) ||
342 (event.providerThread.appThreadId !== null && ownsThread(event.providerThread.appThreadId));
343 return belongs ? [true, addProviderThread(event.providerThread.id)] : [false, state];
344 }
345 case "provider_turn.updated": {
346 const isRoot = event.providerTurn.runAttemptId === input.attemptId;
347 const belongs =
348 isRoot ||
349 (event.providerTurn.providerThreadId !== input.providerThreadId &&
350 state.ownedProviderThreadIds.has(event.providerTurn.providerThreadId)) ||
351 state.ownedProviderTurnIds.has(event.providerTurn.id) ||
352 (event.threadId !== undefined && ownsChildThread(event.threadId));
353 return belongs ? [true, addProviderTurn(event.providerTurn.id, isRoot)] : [false, state];
354 }
355 case "node.updated": {
356 const belongs = ownsRun(event.node.runId) || ownsChildThread(event.node.threadId);
357 if (!belongs || event.node.providerThreadId === null) {
358 return [belongs, state];
359 }
360 return [true, addProviderThread(event.node.providerThreadId)];
361 }
362 case "subagent.updated":
363 return [ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId), state];
364 case "message.updated":
365 return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state];
366 case "turn_item.updated":
367 return [ownsRun(event.turnItem.runId) || ownsChildThread(event.turnItem.threadId), state];
368 case "plan.updated":
369 return [ownsRun(event.plan.runId) || ownsChildThread(event.plan.threadId), state];
370 case "runtime_request.updated":
371 return [
372 (event.threadId !== undefined && ownsChildThread(event.threadId)) ||
373 (event.runtimeRequest.providerTurnId !== null &&
374 state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),
375 state,
376 ];
377 case "turn.terminal":
378 return [event.providerTurnId === state.rootProviderTurnId, state];
379 }
381​
382/**
383 * ERRORS
384 */
385export class RunExecutionStartError extends Schema.TaggedErrorClass<RunExecutionStartError>()(
386 "RunExecutionStartError",
387 {
388 commandId: CommandId,
389 runId: Schema.String,
390 cause: Schema.optional(Schema.Defect()),
391 },
392) {
393 override get message(): string {
394 return `Failed to start orchestration V2 run execution ${this.runId}.`;
395 }
397​
398export class RunExecutionIngestError extends Schema.TaggedErrorClass<RunExecutionIngestError>()(
399 "RunExecutionIngestError",
400 {
401 runId: Schema.String,
402 cause: Schema.optional(Schema.Defect()),
403 },
404) {
405 override get message(): string {
406 return `Failed while ingesting orchestration V2 run execution ${this.runId}.`;
407 }
409​
410export const RunExecutionServiceV2Error = Schema.Union([
411 RunExecutionStartError,
412 RunExecutionIngestError,
413]);
414export type RunExecutionServiceV2Error = typeof RunExecutionServiceV2Error.Type;
415​
416/**
417 * SERVICE DEFINITION
418 */
419export interface RunExecutionServiceV2StartRootRunInput {
420 readonly commandId: CommandId;
421 readonly appThread: OrchestrationV2AppThread;
422 readonly providerSessionId: ProviderSessionId;
423 readonly session: ProviderAdapterV2SessionRuntime;
424 readonly run: OrchestrationV2Run;
425 readonly rootNode: OrchestrationV2ExecutionNode;
426 readonly checkpointScope: OrchestrationV2CheckpointScope;
427 readonly providerThread: OrchestrationV2ProviderThread;
428 readonly attempt: OrchestrationV2RunAttempt;
429 readonly attemptId: RunAttemptId;
430 readonly providerTurnOrdinal: number;
431 readonly relatedThreadIds?: ReadonlyArray<ThreadId>;
432 readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
433 readonly shouldStartProviderTurn?: () => Effect.Effect<boolean, never>;
434 readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
435 readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
436 readonly message: ProviderAdapterV2TurnMessage;
437 readonly modelSelection: ModelSelection;
438 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
440​
441export interface RunExecutionServiceV2Shape {
442 readonly startRootRun: (
443 input: RunExecutionServiceV2StartRootRunInput,
444 ) => Effect.Effect<void, RunExecutionServiceV2Error>;
446​
447export class RunExecutionServiceV2 extends Context.Service<
448 RunExecutionServiceV2,
449 RunExecutionServiceV2Shape
450>()("t3/orchestration-v2/RunExecutionService/RunExecutionServiceV2") {}
451​
452export function shouldDeliverProviderEvent(
453 event: ProviderAdapterV2Event,
454 assistantStreamingEnabled: boolean,
455): boolean {
456 if (assistantStreamingEnabled) {
457 return true;
458 }
459​
460 switch (event.type) {
461 case "node.updated":
462 return event.node.kind !== "assistant_message" || event.node.status !== "running";
463 case "message.updated":
464 return event.message.role !== "assistant" || !event.message.streaming;
465 case "turn_item.updated":
466 return event.turnItem.type !== "assistant_message" || !event.turnItem.streaming;
467 default:
468 return true;
469 }
471​
472/**
473 * IMPLEMENTATIONS
474 */
475export const layer: Layer.Layer<
476 RunExecutionServiceV2,
477 never,
478 | CheckpointServiceV2
479 | EventSinkV2
480 | IdAllocatorV2
481 | ProviderEventIngestorV2
482 | ServerSettingsService
483> = Layer.effect(
484 RunExecutionServiceV2,
485 Effect.gen(function* () {
486 const checkpointService = yield* CheckpointServiceV2;
487 const eventSink = yield* EventSinkV2;
488 const idAllocator = yield* IdAllocatorV2;
489 const providerEventIngestor = yield* ProviderEventIngestorV2;
490 const serverSettings = yield* ServerSettingsService;
491​
492 const writeFinalRunEvents = (input: {
493 readonly run: OrchestrationV2Run;
494 readonly rootNode: OrchestrationV2ExecutionNode;
495 readonly checkpointScope: OrchestrationV2CheckpointScope;
496 readonly providerThread: OrchestrationV2ProviderThread;
497 readonly attempt: OrchestrationV2RunAttempt;
498 readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
499 readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
500 readonly openRunOwnedSubagents?: OpenRunOwnedSubagentProjection;
501 readonly terminal: ProviderTerminalEvent;
502 readonly failureItemPersisted: boolean;
503 }) =>
504 Effect.gen(function* () {
505 const completedAt = yield* DateTime.now;
506 const finalizedAttempt: OrchestrationV2RunAttempt | null = {
507 ...input.attempt,
508 status: input.terminal.status,
509 completedAt,
510 };
511 const shouldFinalizeRun =
512 input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun();
513 if (!shouldFinalizeRun) {
514 // Superseded attempt (steer / selection restart). Emit
515 // run_interrupt_result only when hard Stop left an unpaired request
516 // for this run; plain steers and already-paired stops emit nothing.
517 if (input.terminal.status === "interrupted") {
518 const hasUnpairedRequest =
519 input.hasUnpairedRunInterruptRequest === undefined
520 ? false
521 : yield* input.hasUnpairedRunInterruptRequest();
522 if (hasUnpairedRequest) {
523 yield* eventSink.writeWithEffects({
524 effects: [],
525 events: [
526 {
527 id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
528 type: "turn-item.updated" as const,
529 threadId: input.run.threadId,
530 runId: input.run.id,
531 nodeId: input.rootNode.id,
532 providerInstanceId: input.run.providerInstanceId,
533 occurredAt: completedAt,
534 payload: makeInterruptResultTurnItem({
535 idAllocator,
536 run: input.run,
537 rootNode: input.rootNode,
538 providerThread: input.providerThread,
539 completedAt,
540 }),
541 },
542 ],
543 });
544 }
545 }
546 return;
547 }
548 const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId });
549 const open = input.openRunOwnedSubagents ?? emptyOpenRunOwnedSubagentProjection();
550 const hasOpenSubagentProjection =
551 open.subagents.size > 0 ||
552 open.turnItems.size > 0 ||
553 open.childTurnItems.size > 0 ||
554 open.nodes.size > 0;
555 const cascadedSubagentEvents =
556 isRunOwnedSubagentTerminalStatus(input.terminal.status) && hasOpenSubagentProjection
557 ? yield* cascadeTerminalizeRunOwnedSubagents({
558 run: input.run,
559 open,
560 status: input.terminal.status,
561 completedAt,
562 allocateEventId,
563 })
564 : [];
565 const persistedStatus =
566 input.terminal.status === "completed" ? "waiting" : input.terminal.status;
567 const finalizedRun: OrchestrationV2Run = {
568 ...input.run,
569 status: persistedStatus,
570 completedAt: input.terminal.status === "completed" ? null : completedAt,
571 };
572 const finalizedRootNode: OrchestrationV2ExecutionNode = {
573 ...input.rootNode,
574 status: persistedStatus,
575 completedAt: input.terminal.status === "completed" ? null : completedAt,
576 checkpointScopeId: input.checkpointScope.id,
577 };
578 const finalizedProviderThread: OrchestrationV2ProviderThread = {
579 ...input.providerThread,
580 status: finalProviderThreadStatus(input.terminal.threadDisposition),
581 updatedAt: completedAt,
582 };
583 const runEventId = yield* allocateEventId();
584 const nodeEventId = yield* allocateEventId();
585 const providerThreadEventId = yield* allocateEventId();
586 const checkpointCaptureCommandId = CommandId.make(
587 `command:effect:checkpoint.capture:${input.run.id}`,
588 );
589 yield* eventSink.writeWithEffects({
590 effects:
591 input.terminal.status === "completed"
592 ? [
593 {
594 id: `effect:checkpoint.capture:${input.run.id}`,
595 commandId: checkpointCaptureCommandId,
596 threadId: input.run.threadId,
597 request: {
598 type: "checkpoint.capture" as const,
599 runId: input.run.id,
600 scopeId: input.checkpointScope.id,
601 },
602 },
603 ]
604 : [],
605 events: [
606 // Terminalize open run-owned subagent rows before the root run
607 // settles so projections never keep a forever-running subagent card.
608 ...cascadedSubagentEvents,
609 ...(finalizedAttempt === null
610 ? []
611 : [
612 {
613 id: yield* allocateEventId(),
614 type: "run-attempt.updated" as const,
615 threadId: input.run.threadId,
616 runId: input.run.id,
617 nodeId: input.rootNode.id,
618 providerInstanceId: input.run.providerInstanceId,
619 occurredAt: completedAt,
620 payload: finalizedAttempt,
621 },
622 ]),
623 ...(input.terminal.status === "interrupted"
624 ? [
625 {
626 id: yield* allocateEventId(),
627 type: "turn-item.updated" as const,
628 threadId: input.run.threadId,
629 runId: input.run.id,
630 nodeId: input.rootNode.id,
631 providerInstanceId: input.run.providerInstanceId,
632 occurredAt: completedAt,
633 payload: makeInterruptResultTurnItem({
634 idAllocator,
635 run: input.run,
636 rootNode: input.rootNode,
637 providerThread: input.providerThread,
638 completedAt,
639 }),
640 },
641 ]
642 : []),
643 ...(input.terminal.status === "failed" && !input.failureItemPersisted
644 ? [
645 {
646 id: yield* allocateEventId(),
647 type: "turn-item.updated" as const,
648 threadId: input.run.threadId,
649 runId: input.run.id,
650 nodeId: input.rootNode.id,
651 providerInstanceId: input.run.providerInstanceId,
652 occurredAt: completedAt,
653 payload: makeProviderFailureTurnItem({
654 idAllocator,
655 driver: input.terminal.driver,
656 threadId: input.run.threadId,
657 runId: input.run.id,
658 nodeId: input.rootNode.id,
659 providerThreadId: input.terminal.providerThreadId,
660 providerTurnId: input.terminal.providerTurnId,
661 itemOrdinal: input.terminal.failureItemOrdinal,
662 failure: input.terminal.failure,
663 occurredAt: completedAt,
664 }),
665 },
666 ]
667 : []),
668 {
669 id: runEventId,
670 type: "run.updated",
671 threadId: input.run.threadId,
672 runId: input.run.id,
673 nodeId: input.rootNode.id,
674 providerInstanceId: input.run.providerInstanceId,
675 occurredAt: completedAt,
676 payload: finalizedRun,
677 },
678 {
679 id: nodeEventId,
680 type: "node.updated",
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: finalizedRootNode,
687 },
688 {
689 id: providerThreadEventId,
690 type: "provider-thread.updated",
691 threadId: input.run.threadId,
692 providerInstanceId: input.run.providerInstanceId,
693 occurredAt: completedAt,
694 payload: finalizedProviderThread,
695 },
696 ],
697 });
698 });
699​
700 return RunExecutionServiceV2.of({
701 startRootRun: (input) =>
702 Effect.gen(function* () {
703 const assistantStreamingEnabled = yield* serverSettings.getSettings.pipe(
704 Effect.map((settings) => settings.enableAssistantStreaming),
705 Effect.mapError(
706 (cause) =>
707 new RunExecutionStartError({
708 commandId: input.commandId,
709 runId: input.run.id,
710 cause,
711 }),
712 ),
713 );
714 yield* checkpointService
715 .captureBaseline({
716 scope: input.checkpointScope,
717 ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
718 })
719 .pipe(
720 Effect.mapError(
721 (cause) =>
722 new RunExecutionStartError({
723 commandId: input.commandId,
724 runId: input.run.id,
725 cause,
726 }),
727 ),
728 );
729 if (
730 input.shouldStartProviderTurn !== undefined &&
731 !(yield* input.shouldStartProviderTurn())
732 ) {
733 return;
734 }
735 const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);
736 const makeFailedTerminalEvent = (
737 failure: OrchestrationV2ProviderFailure,
738 failureItemOrdinal: number,
739 ): ProviderTerminalEvent => ({
740 type: "turn.terminal",
741 driver: input.providerThread.driver,
742 providerThreadId: input.providerThread.id,
743 providerTurnId:
744 input.attempt.providerTurnId ??
745 idAllocator.derive.providerTurn({
746 driver: input.providerThread.driver,
747 nativeTurnId: `failed:${input.attempt.id}`,
748 }),
749 runOrdinal: input.run.ordinal,
750 failureItemOrdinal,
751 status: "failed",
752 failure,
753 threadDisposition: "reusable",
754 });
755 const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);
756 const latestProviderThread = yield* Ref.make(input.providerThread);
757 const routeIdentity: ProviderEventRouteIdentity = {
758 threadId: input.run.threadId,
759 runId: input.run.id,
760 attemptId: input.attempt.id,
761 providerThreadId: input.providerThread.id,
762 };
763 const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
764 makeProviderEventRoutingState({
765 identity: routeIdentity,
766 providerTurnId: input.attempt.providerTurnId,
767 ...(input.relatedThreadIds === undefined
768 ? {}
769 : { relatedThreadIds: input.relatedThreadIds }),
770 ...(input.relatedProviderThreadIds === undefined
771 ? {}
772 : { relatedProviderThreadIds: input.relatedProviderThreadIds }),
773 }),
774 );
775 const rootTerminalSeen = yield* Ref.make(false);
776 const rootRunFinalized = yield* Ref.make(false);
777 const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
778 const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
779 const activeBackgroundTurnItems = yield* Ref.make<
780 ReadonlySet<OrchestrationV2TurnItem["id"]>
781 >(new Set());
782 const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection());
783 const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
784 Effect.gen(function* () {
785 if (yield* Ref.get(rootRunFinalized)) {
786 return;
787 }
788 const providerThread = yield* Ref.get(latestProviderThread);
789 const openSubagents = yield* Ref.get(openRunOwnedSubagents);
790 yield* writeFinalRunEvents({
791 run: input.run,
792 rootNode: input.rootNode,
793 checkpointScope: input.checkpointScope,
794 providerThread,
795 attempt: input.attempt,
796 ...(input.shouldFinalizeRun === undefined
797 ? {}
798 : { shouldFinalizeRun: input.shouldFinalizeRun }),
799 ...(input.hasUnpairedRunInterruptRequest === undefined
800 ? {}
801 : {
802 hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest,
803 }),
804 openRunOwnedSubagents: openSubagents,
805 terminal,
806 failureItemPersisted: terminal.status === "failed",
807 }).pipe(
808 Effect.mapError(
809 (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
810 ),
811 );
812 if (isRunOwnedSubagentTerminalStatus(terminal.status)) {
813 yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());
814 }
815 yield* Ref.set(rootRunFinalized, true);
816 });
817 const trackChildLifecycle = (event: ProviderAdapterV2Event, deliverable: boolean) =>
818 Effect.gen(function* () {
819 const routing = yield* Ref.get(eventRouting);
820 if (event.type === "provider_turn.updated") {
821 const isRoot =
822 event.providerTurn.runAttemptId === input.attempt.id ||
823 event.providerTurn.id === routing.rootProviderTurnId;
824 if (!isRoot) {
825 yield* Ref.update(activeChildProviderTurns, (current) => {
826 const next = new Set(current);
827 if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
828 next.delete(event.providerTurn.id);
829 } else {
830 next.add(event.providerTurn.id);
831 }
832 return next;
833 });
834 }
835 }
836 if (event.type === "subagent.updated") {
837 const belongsToRootRun = event.subagent.runId === input.run.id;
838 const belongsToOwnedChildThread =
839 event.subagent.threadId !== input.run.threadId &&
840 routing.ownedThreadIds.has(event.subagent.threadId);
841 if (belongsToRootRun || belongsToOwnedChildThread) {
842 yield* Ref.update(activeChildSubagents, (current) => {
843 const next = new Set(current);
844 if (isTerminalSubagentStatus(event.subagent.status)) {
845 next.delete(event.subagent.id);
846 } else {
847 next.add(event.subagent.id);
848 }
849 return next;
850 });
851 }
852 // Snapshot run-owned subagents for interrupt cascade.
853 // Preserve childThreadId linkage for the root-run lifetime even
854 // after the subagent row terminalizes, so open child-thread
855 // nodes can still be proven linked on a later root interrupt.
856 if (belongsToRootRun) {
857 yield* Ref.update(openRunOwnedSubagents, (current) => {
858 const withLink = withLinkedChildThreadId(current, event.subagent.childThreadId);
859 const subagents = new Map(withLink.subagents);
860 if (isTerminalSubagentStatus(event.subagent.status)) {
861 subagents.delete(event.subagent.id);
862 } else {
863 subagents.set(event.subagent.id, event.subagent);
864 }
865 return { ...withLink, subagents };
866 });
867 }
868 }
869 if (event.type === "node.updated") {
870 const belongsToRootSubagent =
871 event.node.kind === "subagent" && event.node.runId === input.run.id;
872 const belongsToOwnedChildThread =
873 event.node.threadId !== input.run.threadId &&
874 routing.ownedThreadIds.has(event.node.threadId);
875 if (!belongsToRootSubagent && !belongsToOwnedChildThread) {
876 return;
877 }
878 yield* Ref.update(openRunOwnedSubagents, (current) => {
879 const nodes = new Map(current.nodes);
880 if (isOpenExecutionNodeStatus(event.node.status)) {
881 nodes.set(event.node.id, event.node);
882 } else {
883 nodes.delete(event.node.id);
884 }
885 return { ...current, nodes };
886 });
887 }
888 if (event.type === "turn_item.updated") {
889 const belongsToRootRun = event.turnItem.runId === input.run.id;
890 const belongsToOwnedChildThread =
891 event.turnItem.threadId !== input.run.threadId &&
892 routing.ownedThreadIds.has(event.turnItem.threadId);
893 if (
894 backgroundCapableTurnItemTypes.has(event.turnItem.type) &&
895 (belongsToRootRun || belongsToOwnedChildThread)
896 ) {
897 yield* Ref.update(activeBackgroundTurnItems, (current) => {
898 const next = new Set(current);
899 if (isTerminalTurnItemStatus(event.turnItem.status)) {
900 next.delete(event.turnItem.id);
901 } else {
902 next.add(event.turnItem.id);
903 }
904 return next;
905 });
906 }
907 if (belongsToOwnedChildThread && deliverable) {
908 yield* Ref.update(openRunOwnedSubagents, (current) => {
909 const childTurnItems = new Map(current.childTurnItems);
910 if (isTerminalTurnItemStatus(event.turnItem.status)) {
911 childTurnItems.delete(event.turnItem.id);
912 } else {
913 childTurnItems.set(event.turnItem.id, event.turnItem);
914 }
915 return { ...current, childTurnItems };
916 });
917 }
918 if (belongsToRootRun && event.turnItem.type === "subagent") {
919 const subagentItem = event.turnItem;
920 yield* Ref.update(openRunOwnedSubagents, (current) => {
921 const withLink = withLinkedChildThreadId(current, subagentItem.childThreadId);
922 const turnItems = new Map(withLink.turnItems);
923 if (isTerminalTurnItemStatus(subagentItem.status)) {
924 turnItems.delete(subagentItem.subagentId);
925 } else {
926 turnItems.set(subagentItem.subagentId, subagentItem);
927 }
928 return { ...withLink, turnItems };
929 });
930 }
931 }
932 });
933 const shouldStopProviderEventIngestion = Effect.gen(function* () {
934 if (!(yield* Ref.get(rootTerminalSeen))) {
935 return false;
936 }
937 const terminal = yield* Ref.get(terminalEvent);
938 if (terminal !== null && terminal.status !== "completed") {
939 return true;
940 }
941 const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
942 if (childProviderTurns.size > 0) {
943 return false;
944 }
945 const childSubagents = yield* Ref.get(activeChildSubagents);
946 if (childSubagents.size > 0) {
947 return false;
948 }
949 // Keep ingesting past root settlement while background-capable
950 // items owned by this run (or an owned child thread) are still
951 // non-terminal, so their late completion events reach the
952 // projection (stuck-spinner fix). Only for completed runs:
953 // interrupted/failed turns intentionally drop background tracking
954 // rather than pinning the stream open. Assumes adapters emit an
955 // item's non-terminal event before the root terminal; an item
956 // first seen after the terminal is not pinned.
957 const backgroundItems = yield* Ref.get(activeBackgroundTurnItems);
958 return backgroundItems.size === 0;
959 });
960 const eventSubscription =
961 input.session.subscribeEvents === undefined
962 ? { events: input.session.events, close: Effect.void }
963 : yield* input.session.subscribeEvents;
964 const providerEventFiber = yield* eventSubscription.events.pipe(
965 Stream.filterEffect((event) =>
966 Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
967 ),
968 Stream.tap((event) =>
969 Effect.gen(function* () {
970 let storedEventCount = 0;
971 const shouldDeliver = shouldDeliverProviderEvent(event, assistantStreamingEnabled);
972 if (shouldDeliver) {
973 const storedEvents = yield* providerEventIngestor.ingestNormalized({
974 providerSessionId: input.providerSessionId,
975 providerInstanceId: input.run.providerInstanceId,
976 threadId: input.run.threadId,
977 runId: input.run.id,
978 nodeId: input.rootNode.id,
979 event,
980 ...(event.type === "provider_thread.updated" &&
981 event.providerThread.id === input.providerThread.id
982 ? {
983 writeIfRunCurrent: {
984 runId: input.run.id,
985 activeAttemptId: input.attempt.id,
986 expectedStatus: "running" as const,
987 },
988 }
989 : {}),
990 });
991 storedEventCount = storedEvents.length;
992 }
993 if (event.type === "provider_thread.updated") {
994 if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
995 yield* Ref.set(latestProviderThread, event.providerThread);
996 }
997 }
998 if (
999 event.type === "turn_item.updated" &&
1000 event.turnItem.providerTurnId ===
1001 (yield* Ref.get(eventRouting)).rootProviderTurnId
1002 ) {
1003 yield* Ref.update(latestTurnItemOrdinal, (current) =>
1004 Math.max(current, event.turnItem.ordinal),
1005 );
1007 if (event.type === "turn.terminal") {
1008 yield* Ref.set(terminalEvent, event);
1009 yield* Ref.set(rootTerminalSeen, true);
1010 yield* finalizeRootRun(event);
1012 yield* trackChildLifecycle(event, shouldDeliver);
1013 }),
1014 ),
1015 Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
1016 Stream.runDrain,
1017 Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
1018 Effect.flatMap(() =>
1019 Effect.gen(function* () {
1020 const terminal = yield* Ref.get(terminalEvent);
1021 if (terminal === null) {
1022 return;
1024 yield* finalizeRootRun(terminal);
1025 }),
1026 ),
1027 Effect.catchCause((cause) =>
1028 Ref.get(rootRunFinalized).pipe(
1029 Effect.flatMap((finalized) =>
1030 Effect.logWarning("orchestration V2 provider event ingestion failed", {
1031 runId: input.run.id,
1032 cause,
1033 }).pipe(
1034 Effect.andThen(
1035 finalized
1036 ? Effect.void
1037 : Ref.get(latestProviderThread).pipe(
1038 Effect.flatMap((providerThread) =>
1039 Ref.get(latestTurnItemOrdinal).pipe(
1040 Effect.flatMap((latestItemOrdinal) =>
1041 Ref.get(openRunOwnedSubagents).pipe(
1042 Effect.flatMap((openSubagents) =>
1043 writeFinalRunEvents({
1044 run: input.run,
1045 rootNode: input.rootNode,
1046 checkpointScope: input.checkpointScope,
1047 providerThread,
1048 attempt: input.attempt,
1049 ...(input.shouldFinalizeRun === undefined
1050 ? {}
1051 : { shouldFinalizeRun: input.shouldFinalizeRun }),
1052 ...(input.hasUnpairedRunInterruptRequest === undefined
1053 ? {}
1054 : {
1055 hasUnpairedRunInterruptRequest:
1056 input.hasUnpairedRunInterruptRequest,
1057 }),
1058 openRunOwnedSubagents: openSubagents,
1059 terminal: makeFailedTerminalEvent(
1060 makeProviderFailure({
1061 cause: Cause.squash(cause),
1062 class: "unknown",
1063 }),
1064 latestItemOrdinal + 1,
1065 ),
1066 failureItemPersisted: false,
1067 }),
1068 ),
1069 ),
1070 ),
1071 ),
1072 ),
1073 ),
1074 ),
1075 Effect.mapError(
1076 (writeCause) =>
1077 new RunExecutionIngestError({
1078 runId: input.run.id,
1079 cause: { ingest: cause, write: writeCause },
1080 }),
1081 ),
1082 ),
1083 ),
1084 ),
1085 ),
1086 Effect.ensuring(eventSubscription.close),
1087 Effect.forkDetach,
1088 );
1089​
1090 if (
1091 input.shouldStartProviderTurn !== undefined &&
1092 !(yield* input.shouldStartProviderTurn())
1093 ) {
1094 yield* Fiber.interrupt(providerEventFiber);
1095 return;
1097​
1098 // A provider turn is a sign that the session is still alive. Keep
1099 // its already-issued MCP credential valid even when the agent goes
1100 // a long time between browser-tool calls.
1101 yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
1102 yield* input.session
1103 .startTurn({
1104 appThread: input.appThread,
1105 threadId: input.run.threadId,
1106 runId: input.run.id,
1107 runOrdinal: input.run.ordinal,
1108 providerTurnOrdinal: input.providerTurnOrdinal,
1109 attemptId: input.attemptId,
1110 rootNodeId: input.rootNode.id,
1111 providerThread: input.providerThread,
1112 message: input.message,
1113 modelSelection: input.modelSelection,
1114 runtimePolicy: input.runtimePolicy,
1115 })
1116 .pipe(
1117 Effect.catchCause((cause) =>
1118 Effect.logError("orchestration V2 provider turn start failed", {
1119 runId: input.run.id,
1120 cause,
1121 }).pipe(
1122 Effect.andThen(Fiber.interrupt(providerEventFiber)),
1123 Effect.andThen(Ref.get(latestProviderThread)),
1124 Effect.flatMap((providerThread) =>
1125 Ref.get(latestTurnItemOrdinal).pipe(
1126 Effect.flatMap((latestItemOrdinal) =>
1127 Ref.get(openRunOwnedSubagents).pipe(
1128 Effect.flatMap((openSubagents) =>
1129 writeFinalRunEvents({
1130 run: input.run,
1131 rootNode: input.rootNode,
1132 checkpointScope: input.checkpointScope,
1133 providerThread,
1134 attempt: input.attempt,
1135 ...(input.shouldFinalizeRun === undefined
1136 ? {}
1137 : { shouldFinalizeRun: input.shouldFinalizeRun }),
1138 ...(input.hasUnpairedRunInterruptRequest === undefined
1139 ? {}
1140 : {
1141 hasUnpairedRunInterruptRequest:
1142 input.hasUnpairedRunInterruptRequest,
1143 }),
1144 openRunOwnedSubagents: openSubagents,
1145 terminal: makeFailedTerminalEvent(
1146 makeProviderFailure({
1147 cause: Cause.squash(cause),
1148 class: "provider_error",
1149 }),
1150 latestItemOrdinal + 1,
1151 ),
1152 failureItemPersisted: false,
1153 }),
1154 ),
1155 ),
1156 ),
1157 ),
1158 ),
1159 Effect.mapError(
1160 (writeCause) =>
1161 new RunExecutionStartError({
1162 commandId: input.commandId,
1163 runId: input.run.id,
1164 cause: { start: cause, write: writeCause },
1165 }),
1166 ),
1167 ),
1168 ),
1169 );
1170 }),
1171 } satisfies RunExecutionServiceV2Shape);
1172 }),
1174​
1175function makeInterruptResultTurnItem(input: {
1176 readonly idAllocator: IdAllocatorV2Shape;
1177 readonly run: OrchestrationV2Run;
1178 readonly rootNode: OrchestrationV2ExecutionNode;
1179 readonly providerThread: OrchestrationV2ProviderThread;
1180 readonly completedAt: DateTime.Utc;
1181}): OrchestrationV2TurnItem {
1182 return {
1183 id: input.idAllocator.derive.runSignalTurnItem({
1184 runId: input.run.id,
1185 signal: "interrupt-result",
1186 }),
1187 threadId: input.run.threadId,
1188 runId: input.run.id,
1189 nodeId: input.rootNode.id,
1190 providerThreadId: input.providerThread.id,
1191 providerTurnId: input.rootNode.providerTurnId,
1192 nativeItemRef: null,
1193 parentItemId: input.idAllocator.derive.runSignalTurnItem({
1194 runId: input.run.id,
1195 signal: "interrupt-request",
1196 }),
1197 ordinal: input.run.ordinal * 100 + 98,
1198 status: "interrupted",
1199 title: "Interrupted",
1200 startedAt: input.completedAt,
1201 completedAt: input.completedAt,
1202 updatedAt: input.completedAt,
1203 type: "run_interrupt_result",
1204 message: "Run interrupted by user",
1205 };