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

ProviderRuntimeRecoveryService.ts

1,269 lines49.5 KB

1import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
2import {
3 CommandId,
4 isProviderNativeSubagentThread,
5 type OrchestrationV2DomainEvent,
6 type ProviderThreadId,
7 type RunAttemptId,
8 type OrchestrationV2RestartCancelledBackgroundWork,
9 type OrchestrationV2Subagent,
10 type OrchestrationV2ThreadProjection,
11 isOrchestrationV2WorkActive,
12 ThreadId,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Context from "effect/Context";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as Schema from "effect/Schema";
21​
22import * as EffectOutbox from "./EffectOutbox.ts";
23import * as EventSink from "./EventSink.ts";
24import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
25import * as ProjectionStore from "./ProjectionStore.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import {
28 restartContinuationBlocked,
29 restartContinuationRun,
30 restartStopRequested,
31} from "./RestartContinuation.ts";
32import { isBufferedProviderNotification } from "./NotificationMailbox.ts";
33import { queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts";
34import {
35 endOrphanedNativeSubagent,
36 endRunlessRootTurns,
37} from "@t3tools/provider-core/server/subagentProjection";
38import {
39 awaitingProviderThreadId,
40 cancelledRosterTaskWork,
41 cancelledTurnItemWork,
42 mergeRestartCancelledBackgroundWork,
43 latestStartedRun,
44 neverStarted,
45} from "./RestartBackgroundNote.ts";
46​
47export class ProviderRuntimeRecoveryError extends Schema.TaggedError<ProviderRuntimeRecoveryError>()(
48 "ProviderRuntimeRecoveryError",
49 {
50 operation: Schema.Literals(["read-projections", "reconcile", "drain-outbox"]),
51 threadId: Schema.optional(ThreadId),
52 cause: Schema.Defect(),
53 },
54) {
55 override get message(): string {
56 return `Provider runtime recovery failed during ${this.operation}.`;
57 }
59​
60const isProviderRuntimeRecoveryError = Schema.is(ProviderRuntimeRecoveryError);
61​
62const MAX_RESENDS = 3;
63​
64export interface ProviderRuntimeRecoverySummary {
65 readonly terminalizedRuns: number;
66 readonly stoppedSessions: number;
67 readonly closedRequests: number;
68 readonly retiredEffects: number;
69 readonly requeuedEffects: number;
71​
72export interface ProviderRuntimeReconciliationSummary {
73 readonly terminalizedRuns: number;
74 readonly stoppedSessions: number;
75 readonly closedRequests: number;
76 readonly retiredEffects: number;
77 readonly requeuedEffects: number;
79​
80export class ProviderRuntimeRecoveryService extends Context.Service<
81 ProviderRuntimeRecoveryService,
82 {
83 readonly reconcile: (
84 trigger: "startup" | "shutdown",
85 ) => Effect.Effect<ProviderRuntimeReconciliationSummary, ProviderRuntimeRecoveryError>;
86 readonly prepareForShutdown: Effect.Effect<void, ProviderRuntimeRecoveryError>;
87 readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
88 }
89>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
90​
91function nonterminalRuns(projection: ProjectionStore.ProjectionRuntimeRecoveryState) {
92 return projection.runs.filter((run) => {
93 const status: string = run.status;
94 return (
95 status === "preparing" ||
96 run.status === "starting" ||
97 run.status === "running" ||
98 run.status === "waiting"
99 );
100 });
102​
103function isBackgroundCapableTurnItemType(type: string): boolean {
104 return type === "command_execution" || type === "dynamic_tool" || type === "subagent";
106​
107function isNonterminalTurnItemStatus(status: string): boolean {
108 return status === "pending" || status === "running" || status === "waiting";
110​
111/**
112 * A delegate_task child. Its own thread is reconciled and continued on its own
113 * (here, or in the linked environment it runs in) and reports back through
114 * the app, so it is not provider background work.
115 */
116function isAppOwnedDelegation(task: {
117 readonly origin: OrchestrationV2Subagent["origin"];
118 readonly childThreadId: ThreadId | null;
119 readonly remoteChild?: OrchestrationV2Subagent["remoteChild"];
120}): boolean {
121 return (
122 task.origin === "app_owned" && (task.childThreadId !== null || task.remoteChild !== undefined)
123 );
125​
126function isAppOwnedDelegationItem(
127 item: OrchestrationV2ThreadProjection["turnItems"][number],
128): boolean {
129 return item.type === "subagent" && isAppOwnedDelegation(item);
131​
132function providerThreadHasPendingBackgroundTasks(
133 providerThread: OrchestrationV2ThreadProjection["providerThreads"][number],
134): boolean {
135 return (providerThread.pendingBackgroundTasks?.length ?? 0) > 0;
137​
138function resolveStaleBackgroundItemProviderInstanceId(
139 item: OrchestrationV2ThreadProjection["turnItems"][number],
140 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
141): OrchestrationV2ThreadProjection["thread"]["providerInstanceId"] {
142 if (item.runId !== null) {
143 const run = projection.runs.find((candidate) => candidate.id === item.runId);
144 if (run !== undefined) {
145 return run.providerInstanceId;
146 }
147 }
148 if (item.type === "subagent") {
149 return item.providerInstanceId;
150 }
151 if (item.providerThreadId !== null && item.providerThreadId !== undefined) {
152 const providerThread = projection.providerThreads.find(
153 (candidate) => candidate.id === item.providerThreadId,
154 );
155 if (providerThread !== undefined) {
156 return providerThread.providerInstanceId;
157 }
158 }
159 return projection.providerThreads[0]?.providerInstanceId ?? projection.thread.providerInstanceId;
161​
162const cancelledItem = (
163 item: OrchestrationV2ThreadProjection["turnItems"][number],
164 now: DateTime.Utc,
165): OrchestrationV2ThreadProjection["turnItems"][number] =>
166 item.type === "secret_request" && item.secretStatus === "pending"
167 ? { ...item, status: "cancelled", secretStatus: "cancelled", completedAt: now, updatedAt: now }
168 : {
169 ...item,
170 ...("streaming" in item ? { streaming: false } : {}),
171 status: "cancelled",
172 completedAt: now,
173 updatedAt: now,
174 };
175​
176export const make = Effect.gen(function* () {
177 const settings = yield* ServerSettings.ServerSettingsService;
178 const projections = yield* ProjectionStore.ProjectionStoreV2;
179 const eventSink = yield* EventSink.EventSinkV2;
180 const ids = yield* IdAllocator.IdAllocatorV2;
181 const outbox = yield* EffectOutbox.EffectOutboxV2;
182 type RecoverySession = ProjectionStore.ProjectionRuntimeRecoveryState["providerSessions"][number];
183 /** Shared sessions stop on their first recovered thread; later threads still decide wakes from pre-recovery liveness. */
184 const sessionsLiveAtStart = (
185 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
186 stoppedThisPass: ReadonlyMap<string, RecoverySession>,
187 ) => {
188 const sessions = new Map(projection.providerSessions.map((session) => [session.id, session]));
189 for (const providerThread of projection.providerThreads) {
190 const stopped =
191 providerThread.providerSessionId === null
192 ? undefined
193 : stoppedThisPass.get(providerThread.providerSessionId);
194 if (stopped !== undefined) sessions.set(stopped.id, stopped);
195 }
196 return [...sessions.values()];
197 };
198​
199 /**
200 * A run is marked running before its provider accepts the prompt, so only a provider turn of
201 * one of its attempts proves the prompt arrived. Recovery treats the others as never started.
202 */
203 const rewindUnacceptedRuns = Effect.fn("ProviderRuntimeRecoveryService.rewindUnacceptedRuns")(
204 function* (projection: ProjectionStore.ProjectionRuntimeRecoveryState) {
205 const runIdByAttempt = new Map(
206 projection.runs.flatMap((run) =>
207 (run.status === "running" || (run.status === "starting" && run.startedAt !== null)) &&
208 run.activeAttemptId !== null
209 ? [[run.activeAttemptId, run.id] as const]
210 : [],
211 ),
212 );
213 if (runIdByAttempt.size === 0) return projection;
214 const unaccepted = new Set(runIdByAttempt.values());
215 const accept = (turns: ReadonlyArray<{ readonly runAttemptId: RunAttemptId | null }>) => {
216 for (const turn of turns) {
217 const runId =
218 turn.runAttemptId === null ? undefined : runIdByAttempt.get(turn.runAttemptId);
219 if (runId !== undefined) unaccepted.delete(runId);
220 }
221 };
222 accept(projection.providerTurns);
223 if (unaccepted.size === 0) return projection;
224 for (const attempt of projection.attempts) {
225 if (unaccepted.has(attempt.runId)) runIdByAttempt.set(attempt.id, attempt.runId);
226 }
227 // The recovery projection omits ended provider turns, such as one a steer replaced.
228 accept(
229 (yield* projections
230 .getThreadRecords(projection.thread.id, ["providerTurns"], {
231 providerTurnAttemptIds: [...runIdByAttempt].flatMap(([attemptId, runId]) =>
232 unaccepted.has(runId) ? [attemptId] : [],
233 ),
234 })
235 .pipe(
236 Effect.mapError(
237 (cause) =>
238 new ProviderRuntimeRecoveryError({
239 operation: "read-projections",
240 threadId: projection.thread.id,
241 cause,
242 }),
243 ),
244 )).providerTurns,
245 );
246 return {
247 ...projection,
248 runs: projection.runs.map((run) =>
249 unaccepted.has(run.id) ? { ...run, status: "starting" as const, startedAt: null } : run,
250 ),
251 };
252 },
253 );
254​
255 const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
256 function* (
257 stored: ProjectionStore.ProjectionRuntimeRecoveryState,
258 trigger: "startup" | "shutdown",
259 continueAfterRestart: boolean,
260 stoppedThisPass: ReadonlyMap<string, RecoverySession> = new Map(),
261 ) {
262 const now = yield* DateTime.now;
263 const projection = yield* rewindUnacceptedRuns(stored);
264 let runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
265 for (const run of nonterminalRuns(projection)) {
266 if (run.status === "waiting") {
267 const checkpointEffects = yield* outbox
268 .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`))
269 .pipe(
270 Effect.mapError(
271 (cause) =>
272 new ProviderRuntimeRecoveryError({
273 operation: "reconcile",
274 threadId: projection.thread.id,
275 cause,
276 }),
277 ),
278 );
279 const hasReplayableCheckpoint = checkpointEffects.some(
280 (effect) =>
281 effect.request.type === "checkpoint.capture" &&
282 effect.request.runId === run.id &&
283 (effect.status === "pending" || effect.status === "running"),
284 );
285 if (hasReplayableCheckpoint) continue;
286 }
287 runs.push(run);
288 }
289 const pendingRequests = projection.runtimeRequests.filter(
290 (request) => request.status === "pending",
291 );
292 const questionItems = new Map(
293 (projection.turnItems ?? []).flatMap((item) =>
294 item.type === "user_input_request" ? [[item.requestId, item] as const] : [],
295 ),
296 );
297 // The lost provider callback cannot resume; persisted questions can be
298 // answered by a new user message in threads that accept messages.
299 const questions = pendingRequests.filter((request) => {
300 const item = questionItems.get(request.id);
301 return (
302 request.kind === "user_input" &&
303 request.responseCapability.type === "live" &&
304 item?.nodeId === request.nodeId &&
305 item.questions.length > 0 &&
306 item.questions.every((question) => question.question.trim().length > 0) &&
307 !isProviderNativeSubagentThread(projection.thread)
308 );
309 });
310 const recoveredRequestIds = new Set(questions.map((request) => request.id));
311 // An orphaned message-mode question has no card to answer or dismiss.
312 const messageRequests = pendingRequests.filter(
313 (request) =>
314 recoveredRequestIds.has(request.id) ||
315 (request.responseCapability.type === "message" &&
316 (request.kind !== "user_input" ||
317 questionItems.get(request.id)?.nodeId === request.nodeId)),
318 );
319 const messageRequestIds = new Set(messageRequests.map((request) => request.id));
320 const messageRequestNodeIds = new Set(messageRequests.map((request) => request.nodeId));
321 const requests = pendingRequests.filter((request) => !messageRequestIds.has(request.id));
322 // Delegated task rows, items and nodes stay open: the child settles them.
323 const delegatedTaskNodeIds = new Set<string>([
324 ...(projection.subagents ?? []).filter(isAppOwnedDelegation).map((subagent) => subagent.id),
325 ...(projection.turnItems ?? []).flatMap((item) =>
326 item.type === "subagent" && isAppOwnedDelegation(item) ? [item.subagentId] : [],
327 ),
328 ]);
329 const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
330 const commandId = CommandId.make(
331 `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
332 );
333 const allocateEventId = () =>
334 ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
335 Effect.mapError(
336 (cause) =>
337 new ProviderRuntimeRecoveryError({
338 operation: "reconcile",
339 threadId: projection.thread.id,
340 cause,
341 }),
342 ),
343 );
344 const events: Array<OrchestrationV2DomainEvent> = [];
345 const cancelledBackgroundWork = new Map<
346 ProviderThreadId,
347 Array<OrchestrationV2RestartCancelledBackgroundWork>
348 >();
349 const cancelledBackgroundNativeIds = new Set<string>();
350 const recordCancelledBackgroundWork = (
351 providerThreadId: ProviderThreadId | null | undefined,
352 work: OrchestrationV2RestartCancelledBackgroundWork,
353 ) => {
354 if (providerThreadId == null) return;
355 const existing = cancelledBackgroundWork.get(providerThreadId);
356 if (existing === undefined) cancelledBackgroundWork.set(providerThreadId, [work]);
357 else existing.push(work);
358 };
359 const recordCancelledBackgroundItem = (
360 item: OrchestrationV2ThreadProjection["turnItems"][number],
361 ) => {
362 if (!isBackgroundCapableTurnItemType(item.type)) return;
363 const awaitingId = awaitingProviderThreadId(item, projection.runs);
364 const ownProviderThread =
365 item.providerThreadId === awaitingId
366 ? undefined
367 : (projection.providerThreads ?? []).find(
368 (candidate) => candidate.id === item.providerThreadId,
369 );
370 const work = cancelledTurnItemWork(
371 item,
372 ownProviderThread?.nativeThreadRef?.nativeId ?? undefined,
373 );
374 if (work === undefined) return;
375 const nativeId = item.nativeItemRef?.nativeId;
376 // The roster lists this shell too, by its own id or the item's: record it once, keeping its wait.
377 const rosterTask =
378 item.type === "command_execution" && nativeId != null
379 ? projection.providerThreads
380 ?.find((candidate) => candidate.id === awaitingId)
381 ?.pendingBackgroundTasks?.find(
382 (task) => task.taskId === nativeId || task.nativeItemId === nativeId,
383 )
384 : undefined;
385 recordCancelledBackgroundWork(
386 awaitingId,
387 rosterTask?.awaited === true ? { ...work, awaited: true } : work,
388 );
389 if (nativeId != null) {
390 cancelledBackgroundNativeIds.add(nativeId);
391 }
392 if (rosterTask !== undefined) {
393 cancelledBackgroundNativeIds.add(rosterTask.taskId);
394 }
395 };
396 const unstartedRuns = runs.filter(
397 (run) =>
398 run.status === "starting" &&
399 neverStarted(run) &&
400 !projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) &&
401 !projection.runtimeRequests.some(
402 (request) =>
403 request.status === "pending" &&
404 projection.nodes.some((node) => node.id === request.nodeId && node.runId === run.id),
405 ),
406 );
407 const queuedRuns = projection.runs.filter((run) => run.status === "queued");
408 const pendingRuns = [...unstartedRuns, ...queuedRuns];
409 const queuedMessages =
410 pendingRuns.length === 0
411 ? []
412 : [
413 ...(yield* projections
414 .getMessagesById(
415 projection.thread.id,
416 pendingRuns.map((run) => run.userMessageId),
417 )
418 .pipe(
419 Effect.mapError(
420 (cause) =>
421 new ProviderRuntimeRecoveryError({
422 operation: "read-projections",
423 threadId: projection.thread.id,
424 cause,
425 }),
426 ),
427 )).values(),
428 ];
429 const bufferedMessageIds = new Set(
430 queuedMessages.filter(isBufferedProviderNotification).map((message) => message.id),
431 );
432 const retryableMessageIds = new Set(
433 queuedMessages
434 .filter(
435 (message) =>
436 message.createdBy === "user" &&
437 message.scheduledTaskId === undefined &&
438 message.notification === undefined &&
439 message.delegatedCompletion === undefined,
440 )
441 .map((message) => message.id),
442 );
443 // A saved user message the provider never accepted stays available through the held queue.
444 const retryableRuns = unstartedRuns.filter((run) =>
445 retryableMessageIds.has(run.userMessageId),
446 );
447 // Nobody reviews a delegated, agent-sent or scheduled prompt, so it is sent again instead.
448 const unattendedRuns = continueAfterRestart
449 ? unstartedRuns.filter((run) =>
450 queuedMessages.some(
451 (message) =>
452 message.id === run.userMessageId &&
453 !retryableMessageIds.has(message.id) &&
454 message.notification === undefined &&
455 message.delegatedCompletion === undefined &&
456 (message.scheduledTaskId !== undefined || message.creationSource === "mcp"),
457 ),
458 )
459 : [];
460 const resentRuns: Array<OrchestrationV2ThreadProjection["runs"][number]> = [];
461 const resends: Array<EffectOutbox.PendingOrchestrationEffectV2> = [];
462 for (const run of unattendedRuns) {
463 if (
464 restartContinuationBlocked(projection, run, now, false) ||
465 (yield* restartStopRequested(projections.getThreadRecords, projection.thread, run).pipe(
466 Effect.mapError(
467 (cause) =>
468 new ProviderRuntimeRecoveryError({
469 operation: "read-projections",
470 threadId: projection.thread.id,
471 cause,
472 }),
473 ),
474 ))
475 )
476 continue;
477 const resendCommandId = CommandId.make(`command:restart-resend:${run.id}`);
478 const earlierResends = yield* outbox.listByCommandId(resendCommandId).pipe(
479 Effect.mapError(
480 (cause) =>
481 new ProviderRuntimeRecoveryError({
482 operation: "reconcile",
483 threadId: projection.thread.id,
484 cause,
485 }),
486 ),
487 );
488 // A prompt whose start keeps crashing the server would otherwise be sent forever.
489 if (earlierResends.filter((effect) => effect.attemptCount > 0).length >= MAX_RESENDS) {
490 yield* Effect.logWarning("Not resending a prompt that restarts cut too many times", {
491 threadId: projection.thread.id,
492 runId: run.id,
493 });
494 continue;
495 }
496 resentRuns.push(run);
497 resends.push({
498 id: `effect:restart-resend:${run.id}:${commandId}`,
499 commandId: resendCommandId,
500 threadId: projection.thread.id,
501 request: { type: "provider-turn.start", runId: run.id },
502 });
503 }
504 for (const run of resentRuns) {
505 events.push({
506 id: yield* allocateEventId(),
507 type: "run.updated",
508 threadId: projection.thread.id,
509 runId: run.id,
510 providerInstanceId: run.providerInstanceId,
511 occurredAt: now,
512 payload: run,
513 });
514 }
515 const keptRuns = [...retryableRuns, ...resentRuns];
516 for (const run of keptRuns) {
517 for (const attempt of projection.attempts.filter(
518 (candidate) => candidate.id === run.activeAttemptId && candidate.status === "running",
519 )) {
520 events.push({
521 id: yield* allocateEventId(),
522 type: "run-attempt.updated",
523 threadId: projection.thread.id,
524 runId: run.id,
525 nodeId: attempt.rootNodeId,
526 providerInstanceId: run.providerInstanceId,
527 occurredAt: now,
528 payload: { ...attempt, status: "pending", startedAt: null },
529 });
530 }
531 for (const node of projection.nodes.filter(
532 (candidate) => candidate.id === run.rootNodeId && candidate.status === "running",
533 )) {
534 events.push({
535 id: yield* allocateEventId(),
536 type: "node.updated",
537 threadId: projection.thread.id,
538 runId: run.id,
539 nodeId: node.id,
540 providerInstanceId: run.providerInstanceId,
541 occurredAt: now,
542 payload: { ...node, status: "pending", startedAt: null },
543 });
544 }
545 }
546 const retryableItems =
547 retryableRuns.length === 0
548 ? []
549 : (yield* projections
550 .getThreadRecords(projection.thread.id, ["turnItems"], {
551 turnItemTypes: ["user_message"],
552 turnItemRunIds: retryableRuns.map((run) => run.id),
553 })
554 .pipe(
555 Effect.mapError(
556 (cause) =>
557 new ProviderRuntimeRecoveryError({
558 operation: "read-projections",
559 threadId: projection.thread.id,
560 cause,
561 }),
562 ),
563 )).turnItems;
564 for (const item of retryableItems) {
565 if (item.type !== "user_message" || !retryableMessageIds.has(item.messageId)) continue;
566 events.push({
567 id: yield* allocateEventId(),
568 type: "turn-item.updated",
569 threadId: projection.thread.id,
570 ...(item.runId === null ? {} : { runId: item.runId }),
571 occurredAt: now,
572 payload: {
573 ...item,
574 inputIntent: "queued_turn",
575 status: "pending",
576 startedAt: null,
577 completedAt: null,
578 updatedAt: now,
579 },
580 });
581 }
582 runs = runs.filter((run) => !keptRuns.some((kept) => kept.id === run.id));
583 const heldRuns = [
584 ...retryableRuns,
585 ...queuedRunsInDeliveryOrder({ runs: queuedRuns, messages: queuedMessages }),
586 ];
587 for (const [index, run] of heldRuns.entries()) {
588 if (bufferedMessageIds.has(run.userMessageId)) {
589 runs.push(run);
590 continue;
591 }
592 if (run.queueHeld === true && retryableRuns.length === 0) continue;
593 events.push({
594 id: yield* allocateEventId(),
595 type: "run.updated",
596 threadId: projection.thread.id,
597 runId: run.id,
598 providerInstanceId: run.providerInstanceId,
599 occurredAt: now,
600 payload: {
601 ...run,
602 status: "queued",
603 queueHeld: true,
604 ...(retryableRuns.length === 0 ? {} : { queuePosition: index + 1 }),
605 },
606 });
607 }
608 const unsentResumeRunIds = runs.flatMap((run) =>
609 run.startedAt === null && run.usageLimitContinuationOfRunId !== undefined ? [run.id] : [],
610 );
611 const limitRecovery = projection.thread.limitRecovery;
612 // The unsent resume spent the worker's request id, so a fresh one lets it send again. An
613 // untagged resume from an older server stays cancelled: its copy couldn't be hidden.
614 if (limitRecovery?.autoResume === true && unsentResumeRunIds.length > 0) {
615 events.push({
616 id: yield* allocateEventId(),
617 type: "thread.metadata-updated",
618 threadId: projection.thread.id,
619 occurredAt: now,
620 payload: {
621 ...projection.thread,
622 limitRecovery: { ...limitRecovery, requestId: commandId },
623 updatedAt: now,
624 },
625 });
626 }
627 // The worker sends the auto-resume again, so the unsent copy leaves the transcript the way
628 // cancelled queued input does.
629 const unsentResumePrompts =
630 unsentResumeRunIds.length === 0
631 ? []
632 : (yield* projections
633 .getThreadRecords(projection.thread.id, ["turnItems"], {
634 turnItemTypes: ["user_message"],
635 turnItemRunIds: unsentResumeRunIds,
636 })
637 .pipe(
638 Effect.mapError(
639 (cause) =>
640 new ProviderRuntimeRecoveryError({
641 operation: "read-projections",
642 threadId: projection.thread.id,
643 cause,
644 }),
645 ),
646 )).turnItems;
647 const unsentResumePromptIds = new Set(unsentResumePrompts.map((item) => item.id));
648 for (const item of unsentResumePrompts) {
649 if (item.type !== "user_message") continue;
650 const active =
651 item.status === "pending" || item.status === "running" || item.status === "waiting";
652 events.push({
653 id: yield* allocateEventId(),
654 type: "turn-item.updated",
655 threadId: projection.thread.id,
656 ...(item.runId === null ? {} : { runId: item.runId }),
657 occurredAt: now,
658 payload: {
659 ...item,
660 ...(active ? { status: "cancelled", completedAt: now } : {}),
661 inputIntent: "queued_turn",
662 updatedAt: now,
663 },
664 });
665 }
666 for (const question of questions) {
667 events.push({
668 id: yield* allocateEventId(),
669 type: "runtime-request.updated",
670 threadId: projection.thread.id,
671 nodeId: question.nodeId,
672 occurredAt: now,
673 payload: { ...question, responseCapability: { type: "message" } },
674 });
675 }
676 for (const request of requests) {
677 events.push({
678 id: yield* allocateEventId(),
679 type: "runtime-request.updated",
680 threadId: projection.thread.id,
681 nodeId: request.nodeId,
682 occurredAt: now,
683 payload: {
684 ...request,
685 status: trigger === "startup" ? "expired" : "cancelled",
686 responseCapability: {
687 type: "not_resumable",
688 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
689 },
690 resolvedAt: now,
691 },
692 });
693 }
694 for (const run of runs) {
695 events.push({
696 id: yield* allocateEventId(),
697 type: "run.updated",
698 threadId: projection.thread.id,
699 runId: run.id,
700 providerInstanceId: run.providerInstanceId,
701 occurredAt: now,
702 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
703 });
704 for (const attempt of projection.attempts.filter(
705 (candidate) =>
706 candidate.runId === run.id &&
707 (candidate.status === "pending" || candidate.status === "running"),
708 )) {
709 events.push({
710 id: yield* allocateEventId(),
711 type: "run-attempt.updated",
712 threadId: projection.thread.id,
713 runId: run.id,
714 nodeId: attempt.rootNodeId,
715 providerInstanceId: run.providerInstanceId,
716 occurredAt: now,
717 payload: { ...attempt, status: "cancelled", completedAt: now },
718 });
719 }
720 for (const node of projection.nodes.filter(
721 (candidate) =>
722 candidate.runId === run.id &&
723 !messageRequestNodeIds.has(candidate.id) &&
724 !delegatedTaskNodeIds.has(candidate.id) &&
725 (candidate.status === "pending" ||
726 candidate.status === "running" ||
727 candidate.status === "waiting"),
728 )) {
729 events.push({
730 id: yield* allocateEventId(),
731 type: "node.updated",
732 threadId: projection.thread.id,
733 runId: run.id,
734 nodeId: node.id,
735 providerInstanceId: run.providerInstanceId,
736 occurredAt: now,
737 payload: { ...node, status: "cancelled", completedAt: now },
738 });
739 }
740 for (const providerTurn of projection.providerTurns.filter(
741 (candidate) =>
742 candidate.runAttemptId !== null &&
743 projection.attempts.some(
744 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
745 ) &&
746 (candidate.status === "pending" || candidate.status === "running"),
747 )) {
748 events.push({
749 id: yield* allocateEventId(),
750 type: "provider-turn.updated",
751 threadId: projection.thread.id,
752 runId: run.id,
753 nodeId: providerTurn.nodeId,
754 providerInstanceId: run.providerInstanceId,
755 occurredAt: now,
756 payload: { ...providerTurn, status: "cancelled", completedAt: now },
757 });
758 }
759 for (const message of projection.messages.filter(
760 (candidate) => candidate.runId === run.id && candidate.streaming,
761 )) {
762 events.push({
763 id: yield* allocateEventId(),
764 type: "message.updated",
765 threadId: projection.thread.id,
766 runId: run.id,
767 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
768 providerInstanceId: run.providerInstanceId,
769 occurredAt: now,
770 payload: { ...message, streaming: false, updatedAt: now },
771 });
772 }
773 for (const item of projection.turnItems.filter(
774 (candidate) =>
775 candidate.runId === run.id &&
776 !unsentResumePromptIds.has(candidate.id) &&
777 (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
778 !isAppOwnedDelegationItem(candidate) &&
779 // A link card waits on the user, not the run, and answers by message.
780 candidate.type !== "link_request" &&
781 // So does a feedback card, answered from what it recorded.
782 candidate.type !== "feedback_request" &&
783 candidate.type !== "handoff_request" &&
784 // The orchestrator queues a steer the provider never reported reading.
785 !(
786 candidate.type === "user_message" &&
787 candidate.status === "pending" &&
788 (candidate.inputIntent === "steer" ||
789 candidate.inputIntent === "promoted_queued_to_steer")
790 ) &&
791 (candidate.status === "pending" ||
792 candidate.status === "running" ||
793 candidate.status === "waiting"),
794 )) {
795 // Cut native subagents do not resume; record them for the continuation to restart.
796 if (run.status === "waiting") recordCancelledBackgroundItem(item);
797 else if (item.type === "subagent" && item.origin === "provider_native")
798 recordCancelledBackgroundItem(item);
799 events.push({
800 id: yield* allocateEventId(),
801 type: "turn-item.updated",
802 threadId: projection.thread.id,
803 runId: run.id,
804 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
805 providerInstanceId: run.providerInstanceId,
806 occurredAt: now,
807 payload: cancelledItem(item, now),
808 });
809 }
810 // Queued runs and unsent resumes leave no visible turn behind, so there is nothing to explain.
811 if (run.status === "queued" || unsentResumeRunIds.includes(run.id)) continue;
812 events.push({
813 id: yield* allocateEventId(),
814 type: "turn-item.updated",
815 threadId: projection.thread.id,
816 runId: run.id,
817 ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
818 providerInstanceId: run.providerInstanceId,
819 occurredAt: now,
820 payload: {
821 id: ids.derive.runSignalTurnItem({ runId: run.id, signal: "server-recovery" }),
822 threadId: projection.thread.id,
823 runId: run.id,
824 nodeId: run.rootNodeId,
825 providerThreadId: run.providerThreadId,
826 providerTurnId: null,
827 nativeItemRef: null,
828 parentItemId: null,
829 // EventSink allocates the real position, after the run's existing items.
830 ordinal: 0,
831 status: "completed",
832 title: trigger === "startup" ? "Server restarted" : "Server shut down",
833 startedAt: now,
834 completedAt: now,
835 updatedAt: now,
836 type: "system_notice",
837 message: detail,
838 },
839 });
840 }
841 // Blocking waits die with their turn; let child results wake the parent continuation as async tasks.
842 const cutRunIds = new Set(runs.map((run) => run.id));
843 for (const task of projection.subagents ?? []) {
844 if (
845 task.origin !== "app_owned" ||
846 task.runId === null ||
847 !cutRunIds.has(task.runId) ||
848 task.completionWake !== "settled_only" ||
849 !isOrchestrationV2WorkActive(task.status)
850 )
851 continue;
852 events.push({
853 id: yield* allocateEventId(),
854 type: "subagent.updated",
855 threadId: projection.thread.id,
856 runId: task.runId,
857 nodeId: task.id,
858 driver: task.driver,
859 providerInstanceId: task.providerInstanceId,
860 occurredAt: now,
861 payload: { ...task, completionWake: "always", updatedAt: now },
862 });
863 }
864 const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
865 const cancelledStaleNodeIds = new Set<string>();
866 for (const item of projection.turnItems ?? []) {
867 if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
868 continue;
869 }
870 if (!isBackgroundCapableTurnItemType(item.type)) {
871 continue;
872 }
873 if (!isNonterminalTurnItemStatus(item.status) || isAppOwnedDelegationItem(item)) {
874 continue;
875 }
876 const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
877 recordCancelledBackgroundItem(item);
878 events.push({
879 id: yield* allocateEventId(),
880 type: "turn-item.updated",
881 threadId: projection.thread.id,
882 ...(item.runId === null ? {} : { runId: item.runId }),
883 ...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
884 providerInstanceId,
885 occurredAt: now,
886 payload: cancelledItem(item, now),
887 });
888 if (item.nodeId !== null && item.nodeId !== undefined) {
889 const staleItemNode = projection.nodes.find(
890 (candidate) =>
891 candidate.id === item.nodeId && isNonterminalTurnItemStatus(candidate.status),
892 );
893 if (staleItemNode !== undefined && !cancelledStaleNodeIds.has(staleItemNode.id)) {
894 cancelledStaleNodeIds.add(staleItemNode.id);
895 events.push({
896 id: yield* allocateEventId(),
897 type: "node.updated",
898 threadId: projection.thread.id,
899 ...(item.runId === null ? {} : { runId: item.runId }),
900 nodeId: staleItemNode.id,
901 providerInstanceId,
902 occurredAt: now,
903 payload: { ...staleItemNode, status: "cancelled", completedAt: now },
904 });
905 }
906 }
907 }
908 // No provider process survives the server; open native subagents can never report completion.
909 for (const subagent of projection.subagents ?? []) {
910 events.push(
911 ...(yield* endOrphanedNativeSubagent({
912 projection,
913 subagentId: subagent.id,
914 status: "cancelled",
915 now,
916 emitted: events,
917 allocateEventId,
918 })),
919 );
920 }
921 // Native subagent threads have no runs to settle their runless root turns.
922 events.push(
923 ...(yield* endRunlessRootTurns({
924 threadId: projection.thread.id,
925 providerInstanceId: projection.thread.providerInstanceId,
926 projection,
927 status: "cancelled",
928 now,
929 emitted: events,
930 allocateEventId,
931 })),
932 );
933 for (const providerThread of projection.providerThreads ?? []) {
934 const needsIdle = providerThread.status === "active";
935 const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
936 if (!needsIdle && !needsRosterClear) {
937 continue;
938 }
939 if (providerThread.ownerNodeId === null) {
940 for (const task of providerThread.pendingBackgroundTasks ?? []) {
941 // A subagent already recorded covers the shells it started.
942 if (
943 cancelledBackgroundNativeIds.has(task.taskId) ||
944 (task.parentTaskId !== undefined &&
945 cancelledBackgroundNativeIds.has(task.parentTaskId))
946 )
947 continue;
948 cancelledBackgroundNativeIds.add(task.taskId);
949 recordCancelledBackgroundWork(providerThread.id, cancelledRosterTaskWork(task));
950 }
951 }
952 events.push({
953 id: yield* allocateEventId(),
954 type: "provider-thread.updated",
955 threadId: projection.thread.id,
956 driver: providerThread.driver,
957 providerInstanceId: providerThread.providerInstanceId,
958 occurredAt: now,
959 payload: {
960 ...providerThread,
961 status: needsIdle ? "idle" : providerThread.status,
962 pendingBackgroundTasks: [],
963 updatedAt: now,
964 },
965 });
966 }
967 for (const session of projection.providerSessions.filter(
968 (candidate) =>
969 (candidate.status !== "stopped" && candidate.status !== "error") ||
970 (candidate.status === "error" && (candidate.extensionStatuses?.length ?? 0) > 0),
971 )) {
972 events.push({
973 id: yield* allocateEventId(),
974 type: "provider-session.updated",
975 threadId: projection.thread.id,
976 driver: session.driver,
977 providerInstanceId: session.providerInstanceId,
978 occurredAt: now,
979 payload: {
980 ...session,
981 status: session.status === "error" ? "error" : "stopped",
982 ...(session.extensionStatuses === undefined ? {} : { extensionStatuses: [] }),
983 updatedAt: now,
984 lastError: session.status === "error" ? session.lastError : null,
985 },
986 });
987 }
988 for (const [providerThreadId, work] of cancelledBackgroundWork) {
989 const noteRun = latestStartedRun(projection.runs, providerThreadId);
990 if (noteRun === undefined) continue;
991 // Use a separate event; stale run snapshots can overwrite intervening lifecycle changes.
992 events.push({
993 id: yield* allocateEventId(),
994 type: "run.background-work-cancelled",
995 threadId: projection.thread.id,
996 runId: noteRun.id,
997 providerInstanceId: noteRun.providerInstanceId,
998 occurredAt: now,
999 payload: {
1000 runId: noteRun.id,
1001 restartCancelledBackgroundWork: mergeRestartCancelledBackgroundWork(
1002 noteRun.restartCancelledBackgroundWork ?? [],
1003 work,
1004 ),
1005 },
1006 });
1008 const continuationRun =
1009 continueAfterRestart && trigger === "startup"
1010 ? restartContinuationRun(
1011 { ...projection, providerSessions: sessionsLiveAtStart(projection, stoppedThisPass) },
1012 now,
1014 : undefined;
1015 let processLossCount = 1;
1016 // Normal upgrades must not exhaust an unfinished turn's crash allowance.
1017 if (
1018 continuationRun?.restartContinuationOfRunId !== undefined &&
1019 continuationRun.status !== "completed" &&
1020 continuationRun.status !== "waiting"
1021 ) {
1022 const previous = yield* outbox
1023 .get(`effect:restart-continuation:${continuationRun.restartContinuationOfRunId}`)
1024 .pipe(
1025 Effect.mapError(
1026 (cause) =>
1027 new ProviderRuntimeRecoveryError({
1028 operation: "reconcile",
1029 threadId: projection.thread.id,
1030 cause,
1031 }),
1032 ),
1033 );
1034 if (Option.isSome(previous) && previous.value.request.type === "provider-runtime.continue")
1035 processLossCount += previous.value.request.processLossCount ?? 0;
1037 const effects: Array<EffectOutbox.PendingOrchestrationEffectV2> = continuationRun
1038 ? [
1040 id: `effect:restart-continuation:${continuationRun.id}`,
1041 commandId,
1042 threadId: projection.thread.id,
1043 request: {
1044 type: "provider-runtime.continue",
1045 sourceRunId: continuationRun.id,
1046 processLossCount,
1047 },
1048 },
1050 : [];
1051 const stoppedSessions = projection.providerSessions.filter(
1052 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
1053 ).length;
1054 let retiredEffects: number;
1055 let cancelledEffectIds: ReadonlyArray<string> = [];
1056 if (events.length === 0) {
1057 const retiredEffectIds = yield* outbox
1058 .cancelUnsettled({
1059 threadId: projection.thread.id,
1060 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
1061 reason: detail,
1062 })
1063 .pipe(
1064 Effect.mapError(
1065 (cause) =>
1066 new ProviderRuntimeRecoveryError({
1067 operation: "reconcile",
1068 threadId: projection.thread.id,
1069 cause: { detail, cause },
1070 }),
1071 ),
1072 );
1073 cancelledEffectIds = retiredEffectIds;
1074 retiredEffects = retiredEffectIds.length;
1075 } else {
1076 const result = yield* eventSink
1077 .commitCommand({
1078 commandId,
1079 threadId: projection.thread.id,
1080 commandType: "provider-runtime.reconcile",
1081 acceptedAt: now,
1082 events,
1083 effects,
1084 cancelUnsettledEffects: {
1085 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
1086 reason: detail,
1087 },
1088 })
1089 .pipe(
1090 Effect.mapError(
1091 (cause) =>
1092 new ProviderRuntimeRecoveryError({
1093 operation: "reconcile",
1094 threadId: projection.thread.id,
1095 cause,
1096 }),
1097 ),
1098 );
1099 retiredEffects = result.cancelledEffectCount;
1101 return {
1102 terminalizedRuns: runs.length,
1103 stoppedSessions,
1104 closedRequests: requests.length,
1105 retiredEffects,
1106 cancelledEffectIds,
1107 resends,
1108 };
1109 },
1110 );
1111​
1112 const reconcile = Effect.fn("ProviderRuntimeRecoveryService.reconcile")(function* (
1113 trigger: "startup" | "shutdown",
1114 ) {
1115 const continueAfterRestart = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
1116 const threadIds = yield* projections
1117 .getRecoveryThreadIds("runtime")
1118 .pipe(
1119 Effect.mapError(
1120 (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
1121 ),
1122 );
1123 let terminalizedRuns = 0;
1124 let stoppedSessions = 0;
1125 let closedRequests = 0;
1126 let retiredEffects = 0;
1127 const resends: Array<EffectOutbox.PendingOrchestrationEffectV2> = [];
1128 const stoppedThisPass = new Map<string, RecoverySession>();
1129 const grouped = trigger === "shutdown" && threadIds.length > 1;
1130 const groupSize = grouped ? 32 : 1;
1131 for (let offset = 0; offset < threadIds.length; offset += groupSize) {
1132 const cancelledEffectIds: string[] = [];
1133 // Read and decide on the writer so shared sessions see earlier updates in this group.
1134 const reconcileGroup = Effect.gen(function* () {
1135 for (const threadId of threadIds.slice(offset, offset + groupSize)) {
1136 const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
1137 Effect.mapError(
1138 (cause) =>
1139 new ProviderRuntimeRecoveryError({
1140 operation: "read-projections",
1141 threadId,
1142 cause,
1143 }),
1144 ),
1145 );
1146 const enabled =
1147 continueAfterRestart !== null &&
1148 resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
1149 .continueThreadsAfterServerUpdate;
1150 const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
1151 for (const session of projection.providerSessions) {
1152 if (session.status !== "stopped" && session.status !== "error") {
1153 stoppedThisPass.set(session.id, session);
1156 cancelledEffectIds.push(...result.cancelledEffectIds);
1157 resends.push(...result.resends);
1158 terminalizedRuns += result.terminalizedRuns;
1159 stoppedSessions += result.stoppedSessions;
1160 closedRequests += result.closedRequests;
1161 retiredEffects += result.retiredEffects;
1163 });
1164 yield* (grouped ? eventSink.withProviderBatch(reconcileGroup) : reconcileGroup).pipe(
1165 Effect.mapError((cause) =>
1166 isProviderRuntimeRecoveryError(cause)
1167 ? cause
1168 : new ProviderRuntimeRecoveryError({ operation: "reconcile", cause }),
1169 ),
1170 );
1171 // Eventless outbox cancellations also wait for the group's durable commit.
1172 if (cancelledEffectIds.length > 0) yield* outbox.signalCancellations(cancelledEffectIds);
1174 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
1175 Effect.mapError(
1176 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
1177 ),
1178 );
1179 // After the drain, which cancels every unsettled provider start. A crash before this write
1180 // leaves the run unstarted, so the next recovery sends it again.
1181 if (resends.length > 0) {
1182 yield* eventSink
1183 .writeWithEffects({ events: [], effects: resends })
1184 .pipe(
1185 Effect.mapError(
1186 (cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause }),
1187 ),
1188 );
1190 return {
1191 terminalizedRuns,
1192 stoppedSessions,
1193 closedRequests,
1194 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
1195 requeuedEffects: outboxReconciliation.requeued,
1196 } satisfies ProviderRuntimeReconciliationSummary;
1197 });
1198​
1199 const prepareForShutdown = Effect.gen(function* () {
1200 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
1201 if (!enabled) return;
1202 const enabledProjects = Object.entries(enabled.projectSettingsOverrides)
1203 .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === true)
1204 .map(([id]) => id);
1205 if (!enabled.continueThreadsAfterServerUpdate && enabledProjects.length === 0) return;
1206 const disabledProjects = Object.entries(enabled.projectSettingsOverrides)
1207 .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === false)
1208 .map(([id]) => id);
1209 const threadIds = yield* projections.getRecoveryThreadIds(
1210 "restart-continuations",
1211 enabled.continueThreadsAfterServerUpdate
1212 ? { exclude: disabledProjects }
1213 : { include: enabledProjects },
1214 );
1215 yield* Effect.forEach(
1216 threadIds,
1217 (threadId) =>
1218 Effect.gen(function* () {
1219 const projection = yield* projections.getRuntimeRecoveryProjection(threadId);
1220 if (
1221 !resolveProjectSettings(enabled, projection.thread.projectId).settings
1222 .continueThreadsAfterServerUpdate
1224 return;
1225 const run = restartContinuationRun(
1226 yield* rewindUnacceptedRuns(projection),
1227 yield* DateTime.now,
1228 );
1229 if (!run) return;
1230 const commandId = CommandId.make(`command:restart-prepare:${run.id}`);
1231 yield* eventSink.writeWithEffects({
1232 commandId,
1233 events: [],
1234 effects: [
1236 id: `effect:restart-continuation:${run.id}`,
1237 commandId,
1238 threadId,
1239 request: {
1240 type: "provider-runtime.continue",
1241 sourceRunId: run.id,
1242 processLossCount: 0,
1243 },
1244 },
1245 ],
1246 });
1247 }).pipe(
1248 Effect.catchCauseIf(
1249 (cause) => !Cause.hasInterruptsOnly(cause),
1250 (cause) =>
1251 Effect.logWarning("Failed to prepare a restart continuation", { threadId, cause }),
1252 ),
1253 ),
1254 // Leave room in the four-reader pool for other shutdown reads.
1255 { concurrency: 2, discard: true },
1256 );
1257 }).pipe(
1258 Effect.withSpan("ProviderRuntimeRecoveryService.prepareForShutdown"),
1259 Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })),
1260 );
1261​
1262 const recover = Effect.gen(function* () {
1263 return (yield* reconcile("startup")) satisfies ProviderRuntimeRecoverySummary;
1264 });
1265​
1266 return ProviderRuntimeRecoveryService.of({ reconcile, prepareForShutdown, recover });
1267});
1268​
1269export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);