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

RunExecutionService.ts

870 lines34.4 KB

1import {
2 CommandId,
3 type ModelSelection,
4 type NodeId,
5 type OrchestrationV2AppThread,
6 type OrchestrationV2CheckpointScope,
7 type OrchestrationV2ExecutionNode,
8 type OrchestrationV2ProviderFailure,
9 type OrchestrationV2ProviderThread,
10 type OrchestrationV2ProviderTurn,
11 type OrchestrationV2Run,
12 type OrchestrationV2RunAttempt,
13 type OrchestrationV2Subagent,
14 type OrchestrationV2TurnItem,
15 type ProviderSessionId,
16 type ProviderThreadId,
17 type ProviderTurnId,
18 type RunAttemptId,
19 type ThreadId,
20} from "@t3tools/contracts";
21import * as Context from "effect/Context";
22import * as Cause from "effect/Cause";
23import * as DateTime from "effect/DateTime";
24import * as Effect from "effect/Effect";
25import * as Fiber from "effect/Fiber";
26import * as Layer from "effect/Layer";
27import * as Ref from "effect/Ref";
28import * as Schema from "effect/Schema";
29import * as Stream from "effect/Stream";
30​
31import { ServerSettingsService } from "../serverSettings.ts";
32import { CheckpointServiceV2 } from "./CheckpointService.ts";
33import { EventSinkV2 } from "./EventSink.ts";
34import { IdAllocatorV2, type IdAllocatorV2Shape } from "./IdAllocator.ts";
35import type {
36 ProviderAdapterV2Event,
37 ProviderAdapterV2RuntimePolicy,
38 ProviderAdapterV2SessionRuntime,
39 ProviderAdapterV2TurnMessage,
40} from "./ProviderAdapter.ts";
41import { ProviderEventIngestorV2 } from "./ProviderEventIngestor.ts";
42import { makeProviderFailure, makeProviderFailureTurnItem } from "./ProviderFailure.ts";
43​
44export interface ProviderEventRoutingState {
45 readonly ownedThreadIds: ReadonlySet<ThreadId>;
46 readonly ownedProviderThreadIds: ReadonlySet<ProviderThreadId>;
47 readonly ownedProviderTurnIds: ReadonlySet<ProviderTurnId>;
48 readonly rootProviderTurnId: ProviderTurnId | null;
50​
51export interface ProviderEventRouteIdentity {
52 readonly threadId: ThreadId;
53 readonly runId: OrchestrationV2Run["id"];
54 readonly attemptId: RunAttemptId;
55 readonly providerThreadId: ProviderThreadId;
57​
58type ProviderTerminalEvent = Extract<ProviderAdapterV2Event, { readonly type: "turn.terminal" }>;
59​
60function isTerminalProviderTurnStatus(status: OrchestrationV2ProviderTurn["status"]): boolean {
61 return (
62 status === "completed" ||
63 status === "interrupted" ||
64 status === "failed" ||
65 status === "cancelled"
66 );
68​
69function isTerminalSubagentStatus(status: OrchestrationV2Subagent["status"]): boolean {
70 return (
71 status === "completed" ||
72 status === "interrupted" ||
73 status === "failed" ||
74 status === "cancelled"
75 );
77​
78export function finalProviderThreadStatus(
79 disposition: ProviderTerminalEvent["threadDisposition"],
80): OrchestrationV2ProviderThread["status"] {
81 return disposition === "broken" ? "error" : "idle";
83​
84export function makeProviderEventRoutingState(input: {
85 readonly identity: ProviderEventRouteIdentity;
86 readonly providerTurnId: ProviderTurnId | null;
87 readonly relatedThreadIds?: ReadonlyArray<ThreadId>;
88 readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
89}): ProviderEventRoutingState {
90 return {
91 ownedThreadIds: new Set([input.identity.threadId, ...(input.relatedThreadIds ?? [])]),
92 ownedProviderThreadIds: new Set([
93 input.identity.providerThreadId,
94 ...(input.relatedProviderThreadIds ?? []),
95 ]),
96 ownedProviderTurnIds:
97 input.providerTurnId === null ? new Set() : new Set([input.providerTurnId]),
98 rootProviderTurnId: input.providerTurnId,
99 };
101​
102export function routeProviderEvent(
103 event: ProviderAdapterV2Event,
104 input: ProviderEventRouteIdentity,
105 state: ProviderEventRoutingState,
106): readonly [boolean, ProviderEventRoutingState] {
107 const ownsThread = (threadId: ThreadId): boolean => state.ownedThreadIds.has(threadId);
108 const ownsChildThread = (threadId: ThreadId): boolean =>
109 threadId !== input.threadId && ownsThread(threadId);
110 const ownsRun = (runId: string | null): boolean => runId === input.runId;
111 const addProviderThread = (providerThreadId: ProviderThreadId): ProviderEventRoutingState => ({
112 ...state,
113 ownedProviderThreadIds: new Set([...state.ownedProviderThreadIds, providerThreadId]),
114 });
115 const addProviderTurn = (
116 providerTurnId: ProviderTurnId,
117 root: boolean,
118 ): ProviderEventRoutingState => ({
119 ...state,
120 ownedProviderTurnIds: new Set([...state.ownedProviderTurnIds, providerTurnId]),
121 rootProviderTurnId: root ? providerTurnId : state.rootProviderTurnId,
122 });
123​
124 switch (event.type) {
125 case "provider_session.updated":
126 // The session manager persists process-wide status once for every
127 // attached app thread before broadcasting the adapter event.
128 return [false, state];
129 case "app_thread.created": {
130 if (event.appThread.id === input.threadId) {
131 return [true, state];
132 }
133 const isOwnedSubagent =
134 event.appThread.lineage.relationshipToParent === "subagent" &&
135 event.appThread.lineage.parentThreadId !== null &&
136 ownsThread(event.appThread.lineage.parentThreadId);
137 if (!isOwnedSubagent) {
138 return [false, state];
139 }
140 return [
141 true,
142 {
143 ...state,
144 ownedThreadIds: new Set([...state.ownedThreadIds, event.appThread.id]),
145 },
146 ];
147 }
148 case "provider_thread.updated": {
149 const belongs =
150 state.ownedProviderThreadIds.has(event.providerThread.id) ||
151 (event.providerThread.appThreadId !== null && ownsThread(event.providerThread.appThreadId));
152 return belongs ? [true, addProviderThread(event.providerThread.id)] : [false, state];
153 }
154 case "provider_turn.updated": {
155 const isRoot = event.providerTurn.runAttemptId === input.attemptId;
156 const belongs =
157 isRoot ||
158 (event.providerTurn.providerThreadId !== input.providerThreadId &&
159 state.ownedProviderThreadIds.has(event.providerTurn.providerThreadId)) ||
160 state.ownedProviderTurnIds.has(event.providerTurn.id) ||
161 (event.threadId !== undefined && ownsChildThread(event.threadId));
162 return belongs ? [true, addProviderTurn(event.providerTurn.id, isRoot)] : [false, state];
163 }
164 case "node.updated": {
165 const belongs = ownsRun(event.node.runId) || ownsChildThread(event.node.threadId);
166 if (!belongs || event.node.providerThreadId === null) {
167 return [belongs, state];
168 }
169 return [true, addProviderThread(event.node.providerThreadId)];
170 }
171 case "subagent.updated":
172 return [ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId), state];
173 case "message.updated":
174 return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state];
175 case "turn_item.updated":
176 return [ownsRun(event.turnItem.runId) || ownsChildThread(event.turnItem.threadId), state];
177 case "plan.updated":
178 return [ownsRun(event.plan.runId) || ownsChildThread(event.plan.threadId), state];
179 case "runtime_request.updated":
180 return [
181 (event.threadId !== undefined && ownsChildThread(event.threadId)) ||
182 (event.runtimeRequest.providerTurnId !== null &&
183 state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),
184 state,
185 ];
186 case "turn.terminal":
187 return [event.providerTurnId === state.rootProviderTurnId, state];
188 }
190​
191/**
192 * ERRORS
193 */
194export class RunExecutionStartError extends Schema.TaggedErrorClass<RunExecutionStartError>()(
195 "RunExecutionStartError",
196 {
197 commandId: CommandId,
198 runId: Schema.String,
199 cause: Schema.optional(Schema.Defect()),
200 },
201) {
202 override get message(): string {
203 return `Failed to start orchestration V2 run execution ${this.runId}.`;
204 }
206​
207export class RunExecutionIngestError extends Schema.TaggedErrorClass<RunExecutionIngestError>()(
208 "RunExecutionIngestError",
209 {
210 runId: Schema.String,
211 cause: Schema.optional(Schema.Defect()),
212 },
213) {
214 override get message(): string {
215 return `Failed while ingesting orchestration V2 run execution ${this.runId}.`;
216 }
218​
219export const RunExecutionServiceV2Error = Schema.Union([
220 RunExecutionStartError,
221 RunExecutionIngestError,
222]);
223export type RunExecutionServiceV2Error = typeof RunExecutionServiceV2Error.Type;
224​
225/**
226 * SERVICE DEFINITION
227 */
228export interface RunExecutionServiceV2StartRootRunInput {
229 readonly commandId: CommandId;
230 readonly appThread: OrchestrationV2AppThread;
231 readonly providerSessionId: ProviderSessionId;
232 readonly session: ProviderAdapterV2SessionRuntime;
233 readonly run: OrchestrationV2Run;
234 readonly rootNode: OrchestrationV2ExecutionNode;
235 readonly checkpointScope: OrchestrationV2CheckpointScope;
236 readonly providerThread: OrchestrationV2ProviderThread;
237 readonly attempt: OrchestrationV2RunAttempt;
238 readonly attemptId: RunAttemptId;
239 readonly providerTurnOrdinal: number;
240 readonly relatedThreadIds?: ReadonlyArray<ThreadId>;
241 readonly relatedProviderThreadIds?: ReadonlyArray<ProviderThreadId>;
242 readonly shouldStartProviderTurn?: () => Effect.Effect<boolean, never>;
243 readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
244 readonly message: ProviderAdapterV2TurnMessage;
245 readonly modelSelection: ModelSelection;
246 readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
248​
249export interface RunExecutionServiceV2Shape {
250 readonly startRootRun: (
251 input: RunExecutionServiceV2StartRootRunInput,
252 ) => Effect.Effect<void, RunExecutionServiceV2Error>;
254​
255export class RunExecutionServiceV2 extends Context.Service<
256 RunExecutionServiceV2,
257 RunExecutionServiceV2Shape
258>()("t3/orchestration-v2/RunExecutionService/RunExecutionServiceV2") {}
259​
260export function shouldDeliverProviderEvent(
261 event: ProviderAdapterV2Event,
262 assistantStreamingEnabled: boolean,
263): boolean {
264 if (assistantStreamingEnabled) {
265 return true;
266 }
267​
268 switch (event.type) {
269 case "node.updated":
270 return event.node.kind !== "assistant_message" || event.node.status !== "running";
271 case "message.updated":
272 return event.message.role !== "assistant" || !event.message.streaming;
273 case "turn_item.updated":
274 return event.turnItem.type !== "assistant_message" || !event.turnItem.streaming;
275 default:
276 return true;
277 }
279​
280/**
281 * IMPLEMENTATIONS
282 */
283export const layer: Layer.Layer<
284 RunExecutionServiceV2,
285 never,
286 | CheckpointServiceV2
287 | EventSinkV2
288 | IdAllocatorV2
289 | ProviderEventIngestorV2
290 | ServerSettingsService
291> = Layer.effect(
292 RunExecutionServiceV2,
293 Effect.gen(function* () {
294 const checkpointService = yield* CheckpointServiceV2;
295 const eventSink = yield* EventSinkV2;
296 const idAllocator = yield* IdAllocatorV2;
297 const providerEventIngestor = yield* ProviderEventIngestorV2;
298 const serverSettings = yield* ServerSettingsService;
299​
300 const writeFinalRunEvents = (input: {
301 readonly run: OrchestrationV2Run;
302 readonly rootNode: OrchestrationV2ExecutionNode;
303 readonly checkpointScope: OrchestrationV2CheckpointScope;
304 readonly providerThread: OrchestrationV2ProviderThread;
305 readonly attempt: OrchestrationV2RunAttempt;
306 readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;
307 readonly terminal: ProviderTerminalEvent;
308 readonly failureItemPersisted: boolean;
309 }) =>
310 Effect.gen(function* () {
311 const completedAt = yield* DateTime.now;
312 const finalizedAttempt: OrchestrationV2RunAttempt | null = {
313 ...input.attempt,
314 status: input.terminal.status,
315 completedAt,
316 };
317 const shouldFinalizeRun =
318 input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun();
319 if (!shouldFinalizeRun) {
320 // A newer attempt already owns the run and the command that created
321 // it terminalized this attempt as superseded. Preserve that domain
322 // status while retaining the provider's interruption artifact.
323 if (input.terminal.status === "interrupted") {
324 yield* eventSink.write({
325 events: [
326 {
327 id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
328 type: "turn-item.updated" as const,
329 threadId: input.run.threadId,
330 runId: input.run.id,
331 nodeId: input.rootNode.id,
332 providerInstanceId: input.run.providerInstanceId,
333 occurredAt: completedAt,
334 payload: makeInterruptResultTurnItem({
335 idAllocator,
336 run: input.run,
337 rootNode: input.rootNode,
338 providerThread: input.providerThread,
339 completedAt,
340 }),
341 },
342 ],
343 });
344 }
345 return;
346 }
347 const persistedStatus =
348 input.terminal.status === "completed" ? "waiting" : input.terminal.status;
349 const finalizedRun: OrchestrationV2Run = {
350 ...input.run,
351 status: persistedStatus,
352 completedAt: input.terminal.status === "completed" ? null : completedAt,
353 };
354 const finalizedRootNode: OrchestrationV2ExecutionNode = {
355 ...input.rootNode,
356 status: persistedStatus,
357 completedAt: input.terminal.status === "completed" ? null : completedAt,
358 checkpointScopeId: input.checkpointScope.id,
359 };
360 const finalizedProviderThread: OrchestrationV2ProviderThread = {
361 ...input.providerThread,
362 status: finalProviderThreadStatus(input.terminal.threadDisposition),
363 updatedAt: completedAt,
364 };
365 const runEventId = yield* idAllocator.allocate.event({ threadId: input.run.threadId });
366 const nodeEventId = yield* idAllocator.allocate.event({ threadId: input.run.threadId });
367 const providerThreadEventId = yield* idAllocator.allocate.event({
368 threadId: input.run.threadId,
369 });
370 const checkpointCaptureCommandId = CommandId.make(
371 `command:effect:checkpoint.capture:${input.run.id}`,
372 );
373 yield* eventSink.writeWithEffects({
374 effects:
375 input.terminal.status === "completed"
376 ? [
377 {
378 id: `effect:checkpoint.capture:${input.run.id}`,
379 commandId: checkpointCaptureCommandId,
380 threadId: input.run.threadId,
381 request: {
382 type: "checkpoint.capture" as const,
383 runId: input.run.id,
384 scopeId: input.checkpointScope.id,
385 },
386 },
387 ]
388 : [],
389 events: [
390 ...(finalizedAttempt === null
391 ? []
392 : [
393 {
394 id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
395 type: "run-attempt.updated" as const,
396 threadId: input.run.threadId,
397 runId: input.run.id,
398 nodeId: input.rootNode.id,
399 providerInstanceId: input.run.providerInstanceId,
400 occurredAt: completedAt,
401 payload: finalizedAttempt,
402 },
403 ]),
404 ...(input.terminal.status === "interrupted"
405 ? [
406 {
407 id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
408 type: "turn-item.updated" as const,
409 threadId: input.run.threadId,
410 runId: input.run.id,
411 nodeId: input.rootNode.id,
412 providerInstanceId: input.run.providerInstanceId,
413 occurredAt: completedAt,
414 payload: makeInterruptResultTurnItem({
415 idAllocator,
416 run: input.run,
417 rootNode: input.rootNode,
418 providerThread: input.providerThread,
419 completedAt,
420 }),
421 },
422 ]
423 : []),
424 ...(input.terminal.status === "failed" && !input.failureItemPersisted
425 ? [
426 {
427 id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }),
428 type: "turn-item.updated" as const,
429 threadId: input.run.threadId,
430 runId: input.run.id,
431 nodeId: input.rootNode.id,
432 providerInstanceId: input.run.providerInstanceId,
433 occurredAt: completedAt,
434 payload: makeProviderFailureTurnItem({
435 idAllocator,
436 driver: input.terminal.driver,
437 threadId: input.run.threadId,
438 runId: input.run.id,
439 nodeId: input.rootNode.id,
440 providerThreadId: input.terminal.providerThreadId,
441 providerTurnId: input.terminal.providerTurnId,
442 itemOrdinal: input.terminal.failureItemOrdinal,
443 failure: input.terminal.failure,
444 occurredAt: completedAt,
445 }),
446 },
447 ]
448 : []),
449 {
450 id: runEventId,
451 type: "run.updated",
452 threadId: input.run.threadId,
453 runId: input.run.id,
454 nodeId: input.rootNode.id,
455 providerInstanceId: input.run.providerInstanceId,
456 occurredAt: completedAt,
457 payload: finalizedRun,
458 },
459 {
460 id: nodeEventId,
461 type: "node.updated",
462 threadId: input.run.threadId,
463 runId: input.run.id,
464 nodeId: input.rootNode.id,
465 providerInstanceId: input.run.providerInstanceId,
466 occurredAt: completedAt,
467 payload: finalizedRootNode,
468 },
469 {
470 id: providerThreadEventId,
471 type: "provider-thread.updated",
472 threadId: input.run.threadId,
473 providerInstanceId: input.run.providerInstanceId,
474 occurredAt: completedAt,
475 payload: finalizedProviderThread,
476 },
477 ],
478 });
479 });
480​
481 return RunExecutionServiceV2.of({
482 startRootRun: (input) =>
483 Effect.gen(function* () {
484 const assistantStreamingEnabled = yield* serverSettings.getSettings.pipe(
485 Effect.map((settings) => settings.enableAssistantStreaming),
486 Effect.mapError(
487 (cause) =>
488 new RunExecutionStartError({
489 commandId: input.commandId,
490 runId: input.run.id,
491 cause,
492 }),
493 ),
494 );
495 yield* checkpointService
496 .captureBaseline({
497 scope: input.checkpointScope,
498 ordinalWithinScope: Math.max(0, input.run.ordinal - 1),
499 })
500 .pipe(
501 Effect.mapError(
502 (cause) =>
503 new RunExecutionStartError({
504 commandId: input.commandId,
505 runId: input.run.id,
506 cause,
507 }),
508 ),
509 );
510 if (
511 input.shouldStartProviderTurn !== undefined &&
512 !(yield* input.shouldStartProviderTurn())
513 ) {
514 return;
515 }
516 const terminalEvent = yield* Ref.make<ProviderTerminalEvent | null>(null);
517 const makeFailedTerminalEvent = (
518 failure: OrchestrationV2ProviderFailure,
519 failureItemOrdinal: number,
520 ): ProviderTerminalEvent => ({
521 type: "turn.terminal",
522 driver: input.providerThread.driver,
523 providerThreadId: input.providerThread.id,
524 providerTurnId:
525 input.attempt.providerTurnId ??
526 idAllocator.derive.providerTurn({
527 driver: input.providerThread.driver,
528 nativeTurnId: `failed:${input.attempt.id}`,
529 }),
530 runOrdinal: input.run.ordinal,
531 failureItemOrdinal,
532 status: "failed",
533 failure,
534 threadDisposition: "reusable",
535 });
536 const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);
537 const latestProviderThread = yield* Ref.make(input.providerThread);
538 const routeIdentity: ProviderEventRouteIdentity = {
539 threadId: input.run.threadId,
540 runId: input.run.id,
541 attemptId: input.attempt.id,
542 providerThreadId: input.providerThread.id,
543 };
544 const eventRouting = yield* Ref.make<ProviderEventRoutingState>(
545 makeProviderEventRoutingState({
546 identity: routeIdentity,
547 providerTurnId: input.attempt.providerTurnId,
548 ...(input.relatedThreadIds === undefined
549 ? {}
550 : { relatedThreadIds: input.relatedThreadIds }),
551 ...(input.relatedProviderThreadIds === undefined
552 ? {}
553 : { relatedProviderThreadIds: input.relatedProviderThreadIds }),
554 }),
555 );
556 const rootTerminalSeen = yield* Ref.make(false);
557 const rootRunFinalized = yield* Ref.make(false);
558 const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
559 const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
560 const finalizeRootRun = (terminal: ProviderTerminalEvent) =>
561 Effect.gen(function* () {
562 if (yield* Ref.get(rootRunFinalized)) {
563 return;
564 }
565 const providerThread = yield* Ref.get(latestProviderThread);
566 yield* writeFinalRunEvents({
567 run: input.run,
568 rootNode: input.rootNode,
569 checkpointScope: input.checkpointScope,
570 providerThread,
571 attempt: input.attempt,
572 ...(input.shouldFinalizeRun === undefined
573 ? {}
574 : { shouldFinalizeRun: input.shouldFinalizeRun }),
575 terminal,
576 failureItemPersisted: terminal.status === "failed",
577 }).pipe(
578 Effect.mapError(
579 (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),
580 ),
581 );
582 yield* Ref.set(rootRunFinalized, true);
583 });
584 const trackChildLifecycle = (event: ProviderAdapterV2Event) =>
585 Effect.gen(function* () {
586 const routing = yield* Ref.get(eventRouting);
587 if (event.type === "provider_turn.updated") {
588 const isRoot =
589 event.providerTurn.runAttemptId === input.attempt.id ||
590 event.providerTurn.id === routing.rootProviderTurnId;
591 if (!isRoot) {
592 yield* Ref.update(activeChildProviderTurns, (current) => {
593 const next = new Set(current);
594 if (isTerminalProviderTurnStatus(event.providerTurn.status)) {
595 next.delete(event.providerTurn.id);
596 } else {
597 next.add(event.providerTurn.id);
598 }
599 return next;
600 });
601 }
602 }
603 if (event.type === "subagent.updated") {
604 const belongsToRootRun = event.subagent.runId === input.run.id;
605 const belongsToOwnedChildThread =
606 event.subagent.threadId !== input.run.threadId &&
607 routing.ownedThreadIds.has(event.subagent.threadId);
608 if (belongsToRootRun || belongsToOwnedChildThread) {
609 yield* Ref.update(activeChildSubagents, (current) => {
610 const next = new Set(current);
611 if (isTerminalSubagentStatus(event.subagent.status)) {
612 next.delete(event.subagent.id);
613 } else {
614 next.add(event.subagent.id);
615 }
616 return next;
617 });
618 }
619 }
620 });
621 const shouldStopProviderEventIngestion = Effect.gen(function* () {
622 if (!(yield* Ref.get(rootTerminalSeen))) {
623 return false;
624 }
625 const childProviderTurns = yield* Ref.get(activeChildProviderTurns);
626 if (childProviderTurns.size > 0) {
627 return false;
628 }
629 const childSubagents = yield* Ref.get(activeChildSubagents);
630 return childSubagents.size === 0;
631 });
632 const eventSubscription =
633 input.session.subscribeEvents === undefined
634 ? { events: input.session.events, close: Effect.void }
635 : yield* input.session.subscribeEvents;
636 const providerEventFiber = yield* eventSubscription.events.pipe(
637 Stream.filterEffect((event) =>
638 Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
639 ),
640 Stream.tap((event) =>
641 Effect.gen(function* () {
642 let storedEventCount = 0;
643 if (shouldDeliverProviderEvent(event, assistantStreamingEnabled)) {
644 const storedEvents = yield* providerEventIngestor.ingestNormalized({
645 providerSessionId: input.providerSessionId,
646 providerInstanceId: input.run.providerInstanceId,
647 threadId: input.run.threadId,
648 runId: input.run.id,
649 nodeId: input.rootNode.id,
650 event,
651 ...(event.type === "provider_thread.updated" &&
652 event.providerThread.id === input.providerThread.id
653 ? {
654 writeIfRunCurrent: {
655 runId: input.run.id,
656 activeAttemptId: input.attempt.id,
657 expectedStatus: "running" as const,
658 },
659 }
660 : {}),
661 });
662 storedEventCount = storedEvents.length;
663 }
664 if (event.type === "provider_thread.updated") {
665 if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
666 yield* Ref.set(latestProviderThread, event.providerThread);
667 }
668 }
669 if (
670 event.type === "turn_item.updated" &&
671 event.turnItem.providerTurnId ===
672 (yield* Ref.get(eventRouting)).rootProviderTurnId
673 ) {
674 yield* Ref.update(latestTurnItemOrdinal, (current) =>
675 Math.max(current, event.turnItem.ordinal),
676 );
677 }
678 if (event.type === "turn.terminal") {
679 yield* Ref.set(terminalEvent, event);
680 yield* Ref.set(rootTerminalSeen, true);
681 yield* finalizeRootRun(event);
682 }
683 yield* trackChildLifecycle(event);
684 }).pipe(
685 // A single unmappable event (e.g. a late subagent notification
686 // that references an already-finalized run) must not tear down
687 // ingestion for the whole session: dropping it keeps the
688 // pipeline alive for every later event. Root turn.terminal
689 // failures still escalate so the fallback finalization in the
690 // outer catch keeps running.
691 Effect.catchCause((eventCause) =>
692 event.type === "turn.terminal"
693 ? Effect.failCause(eventCause)
694 : Effect.logWarning(
695 "orchestration V2 provider event dropped after ingestion failure",
696 {
697 runId: input.run.id,
698 eventType: event.type,
699 cause: Cause.pretty(eventCause),
700 },
701 ),
702 ),
703 ),
704 ),
705 Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
706 Stream.runDrain,
707 Effect.mapError((cause) => new RunExecutionIngestError({ runId: input.run.id, cause })),
708 Effect.flatMap(() =>
709 Effect.gen(function* () {
710 const terminal = yield* Ref.get(terminalEvent);
711 if (terminal === null) {
712 return;
713 }
714 yield* finalizeRootRun(terminal);
715 }),
716 ),
717 Effect.catchCause((cause) =>
718 Ref.get(rootRunFinalized).pipe(
719 Effect.flatMap((finalized) =>
720 Effect.logWarning("orchestration V2 provider event ingestion failed", {
721 runId: input.run.id,
722 cause: Cause.pretty(cause),
723 }).pipe(
724 Effect.andThen(
725 finalized
726 ? Effect.void
727 : Ref.get(latestProviderThread).pipe(
728 Effect.flatMap((providerThread) =>
729 Ref.get(latestTurnItemOrdinal).pipe(
730 Effect.flatMap((latestItemOrdinal) =>
731 writeFinalRunEvents({
732 run: input.run,
733 rootNode: input.rootNode,
734 checkpointScope: input.checkpointScope,
735 providerThread,
736 attempt: input.attempt,
737 ...(input.shouldFinalizeRun === undefined
738 ? {}
739 : { shouldFinalizeRun: input.shouldFinalizeRun }),
740 terminal: makeFailedTerminalEvent(
741 makeProviderFailure({
742 cause: Cause.squash(cause),
743 class: "unknown",
744 }),
745 latestItemOrdinal + 1,
746 ),
747 failureItemPersisted: false,
748 }),
749 ),
750 ),
751 ),
752 ),
753 ),
754 Effect.mapError(
755 (writeCause) =>
756 new RunExecutionIngestError({
757 runId: input.run.id,
758 cause: { ingest: cause, write: writeCause },
759 }),
760 ),
761 ),
762 ),
763 ),
764 ),
765 Effect.ensuring(eventSubscription.close),
766 Effect.forkDetach,
767 );
768​
769 if (
770 input.shouldStartProviderTurn !== undefined &&
771 !(yield* input.shouldStartProviderTurn())
772 ) {
773 yield* Fiber.interrupt(providerEventFiber);
774 return;
775 }
776​
777 yield* input.session
778 .startTurn({
779 appThread: input.appThread,
780 threadId: input.run.threadId,
781 runId: input.run.id,
782 runOrdinal: input.run.ordinal,
783 providerTurnOrdinal: input.providerTurnOrdinal,
784 attemptId: input.attemptId,
785 rootNodeId: input.rootNode.id,
786 providerThread: input.providerThread,
787 message: input.message,
788 modelSelection: input.modelSelection,
789 runtimePolicy: input.runtimePolicy,
790 })
791 .pipe(
792 Effect.catchCause((cause) =>
793 Effect.logError("orchestration V2 provider turn start failed", {
794 runId: input.run.id,
795 cause: Cause.pretty(cause),
796 }).pipe(
797 Effect.andThen(Fiber.interrupt(providerEventFiber)),
798 Effect.andThen(Ref.get(latestProviderThread)),
799 Effect.flatMap((providerThread) =>
800 Ref.get(latestTurnItemOrdinal).pipe(
801 Effect.flatMap((latestItemOrdinal) =>
802 writeFinalRunEvents({
803 run: input.run,
804 rootNode: input.rootNode,
805 checkpointScope: input.checkpointScope,
806 providerThread,
807 attempt: input.attempt,
808 ...(input.shouldFinalizeRun === undefined
809 ? {}
810 : { shouldFinalizeRun: input.shouldFinalizeRun }),
811 terminal: makeFailedTerminalEvent(
812 makeProviderFailure({
813 cause: Cause.squash(cause),
814 class: "provider_error",
815 }),
816 latestItemOrdinal + 1,
817 ),
818 failureItemPersisted: false,
819 }),
820 ),
821 ),
822 ),
823 Effect.mapError(
824 (writeCause) =>
825 new RunExecutionStartError({
826 commandId: input.commandId,
827 runId: input.run.id,
828 cause: { start: cause, write: writeCause },
829 }),
830 ),
831 ),
832 ),
833 );
834 }),
835 } satisfies RunExecutionServiceV2Shape);
836 }),
837);
838​
839function makeInterruptResultTurnItem(input: {
840 readonly idAllocator: IdAllocatorV2Shape;
841 readonly run: OrchestrationV2Run;
842 readonly rootNode: OrchestrationV2ExecutionNode;
843 readonly providerThread: OrchestrationV2ProviderThread;
844 readonly completedAt: DateTime.Utc;
845}): OrchestrationV2TurnItem {
846 return {
847 id: input.idAllocator.derive.runSignalTurnItem({
848 runId: input.run.id,
849 signal: "interrupt-result",
850 }),
851 threadId: input.run.threadId,
852 runId: input.run.id,
853 nodeId: input.rootNode.id,
854 providerThreadId: input.providerThread.id,
855 providerTurnId: input.rootNode.providerTurnId,
856 nativeItemRef: null,
857 parentItemId: input.idAllocator.derive.runSignalTurnItem({
858 runId: input.run.id,
859 signal: "interrupt-request",
860 }),
861 ordinal: input.run.ordinal * 100 + 98,
862 status: "interrupted",
863 title: "Interrupted",
864 startedAt: input.completedAt,
865 completedAt: input.completedAt,
866 updatedAt: input.completedAt,
867 type: "run_interrupt_result",
868 message: "Run interrupted by user",
869 };