Open History to see the last commit
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 }
58}
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;
70}
71
72export interface ProviderRuntimeReconciliationSummary {
73 readonly terminalizedRuns: number;
74 readonly stoppedSessions: number;
75 readonly closedRequests: number;
76 readonly retiredEffects: number;
77 readonly requeuedEffects: number;
78}
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 });
101}
102
103function isBackgroundCapableTurnItemType(type: string): boolean {
104 return type === "command_execution" || type === "dynamic_tool" || type === "subagent";
105}
106
107function isNonterminalTurnItemStatus(status: string): boolean {
108 return status === "pending" || status === "running" || status === "waiting";
109}
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 );
124}
125
126function isAppOwnedDelegationItem(
127 item: OrchestrationV2ThreadProjection["turnItems"][number],
128): boolean {
129 return item.type === "subagent" && isAppOwnedDelegation(item);
130}
131
132function providerThreadHasPendingBackgroundTasks(
133 providerThread: OrchestrationV2ThreadProjection["providerThreads"][number],
134): boolean {
135 return (providerThread.pendingBackgroundTasks?.length ?? 0) > 0;
136}
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;
160}
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 // The lost provider callback cannot resume; persisted questions can be
293 // answered by a new user message in threads that accept messages.
294 const questions = pendingRequests.filter(
295 (request) =>
296 request.kind === "user_input" &&
297 request.responseCapability.type === "live" &&
298 projection.turnItems.some(
299 (item) =>
300 item.type === "user_input_request" &&
301 item.requestId === request.id &&
302 item.nodeId === request.nodeId &&
303 item.questions.length > 0 &&
304 item.questions.every((question) => question.question.trim().length > 0),
305 ) &&
306 !isProviderNativeSubagentThread(projection.thread),
307 );
308 const recoveredRequestIds = new Set(questions.map((request) => request.id));
309 const messageRequestNodeIds = new Set(
310 pendingRequests
311 .filter(
312 (request) =>
313 request.responseCapability.type === "message" || recoveredRequestIds.has(request.id),
314 )
315 .map((request) => request.nodeId),
316 );
317 const requests = pendingRequests.filter(
318 (request) =>
319 request.responseCapability.type !== "message" && !recoveredRequestIds.has(request.id),
320 );
321 // Delegated task rows, items and nodes stay open: the child settles them.
322 const delegatedTaskNodeIds = new Set<string>([
323 ...(projection.subagents ?? []).filter(isAppOwnedDelegation).map((subagent) => subagent.id),
324 ...(projection.turnItems ?? []).flatMap((item) =>
325 item.type === "subagent" && isAppOwnedDelegation(item) ? [item.subagentId] : [],
326 ),
327 ]);
328 const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
329 const commandId = CommandId.make(
330 `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
331 );
332 const allocateEventId = () =>
333 ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
334 Effect.mapError(
335 (cause) =>
336 new ProviderRuntimeRecoveryError({
337 operation: "reconcile",
338 threadId: projection.thread.id,
339 cause,
340 }),
341 ),
342 );
343 const events: Array<OrchestrationV2DomainEvent> = [];
344 const cancelledBackgroundWork = new Map<
345 ProviderThreadId,
346 Array<OrchestrationV2RestartCancelledBackgroundWork>
347 >();
348 const cancelledBackgroundNativeIds = new Set<string>();
349 const recordCancelledBackgroundWork = (
350 providerThreadId: ProviderThreadId | null | undefined,
351 work: OrchestrationV2RestartCancelledBackgroundWork,
352 ) => {
353 if (providerThreadId == null) return;
354 const existing = cancelledBackgroundWork.get(providerThreadId);
355 if (existing === undefined) cancelledBackgroundWork.set(providerThreadId, [work]);
356 else existing.push(work);
357 };
358 const recordCancelledBackgroundItem = (
359 item: OrchestrationV2ThreadProjection["turnItems"][number],
360 ) => {
361 if (!isBackgroundCapableTurnItemType(item.type)) return;
362 const awaitingId = awaitingProviderThreadId(item, projection.runs);
363 const ownProviderThread =
364 item.providerThreadId === awaitingId
365 ? undefined
366 : (projection.providerThreads ?? []).find(
367 (candidate) => candidate.id === item.providerThreadId,
368 );
369 const work = cancelledTurnItemWork(
370 item,
371 ownProviderThread?.nativeThreadRef?.nativeId ?? undefined,
372 );
373 if (work === undefined) return;
374 recordCancelledBackgroundWork(awaitingId, work);
375 if (item.nativeItemRef?.nativeId != null) {
376 cancelledBackgroundNativeIds.add(item.nativeItemRef.nativeId);
377 }
378 };
379 const unstartedRuns = runs.filter(
380 (run) =>
381 run.status === "starting" &&
382 neverStarted(run) &&
383 !projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) &&
384 !projection.runtimeRequests.some(
385 (request) =>
386 request.status === "pending" &&
387 projection.nodes.some((node) => node.id === request.nodeId && node.runId === run.id),
388 ),
389 );
390 const queuedRuns = projection.runs.filter((run) => run.status === "queued");
391 const pendingRuns = [...unstartedRuns, ...queuedRuns];
392 const queuedMessages =
393 pendingRuns.length === 0
394 ? []
395 : [
396 ...(yield* projections
397 .getMessagesById(
398 projection.thread.id,
399 pendingRuns.map((run) => run.userMessageId),
400 )
401 .pipe(
402 Effect.mapError(
403 (cause) =>
404 new ProviderRuntimeRecoveryError({
405 operation: "read-projections",
406 threadId: projection.thread.id,
407 cause,
408 }),
409 ),
410 )).values(),
411 ];
412 const bufferedMessageIds = new Set(
413 queuedMessages.filter(isBufferedProviderNotification).map((message) => message.id),
414 );
415 const retryableMessageIds = new Set(
416 queuedMessages
417 .filter(
418 (message) =>
419 message.createdBy === "user" &&
420 message.scheduledTaskId === undefined &&
421 message.notification === undefined &&
422 message.delegatedCompletion === undefined,
423 )
424 .map((message) => message.id),
425 );
426 // A saved user message the provider never accepted stays available through the held queue.
427 const retryableRuns = unstartedRuns.filter((run) =>
428 retryableMessageIds.has(run.userMessageId),
429 );
430 // Nobody reviews a delegated, agent-sent or scheduled prompt, so it is sent again instead.
431 const unattendedRuns = continueAfterRestart
432 ? unstartedRuns.filter((run) =>
433 queuedMessages.some(
434 (message) =>
435 message.id === run.userMessageId &&
436 !retryableMessageIds.has(message.id) &&
437 message.notification === undefined &&
438 message.delegatedCompletion === undefined &&
439 (message.scheduledTaskId !== undefined || message.creationSource === "mcp"),
440 ),
441 )
442 : [];
443 const resentRuns: Array<OrchestrationV2ThreadProjection["runs"][number]> = [];
444 const resends: Array<EffectOutbox.PendingOrchestrationEffectV2> = [];
445 for (const run of unattendedRuns) {
446 if (
447 restartContinuationBlocked(projection, run, now, false) ||
448 (yield* restartStopRequested(projections.getThreadRecords, projection.thread, run).pipe(
449 Effect.mapError(
450 (cause) =>
451 new ProviderRuntimeRecoveryError({
452 operation: "read-projections",
453 threadId: projection.thread.id,
454 cause,
455 }),
456 ),
457 ))
458 )
459 continue;
460 const resendCommandId = CommandId.make(`command:restart-resend:${run.id}`);
461 const earlierResends = yield* outbox.listByCommandId(resendCommandId).pipe(
462 Effect.mapError(
463 (cause) =>
464 new ProviderRuntimeRecoveryError({
465 operation: "reconcile",
466 threadId: projection.thread.id,
467 cause,
468 }),
469 ),
470 );
471 // A prompt whose start keeps crashing the server would otherwise be sent forever.
472 if (earlierResends.filter((effect) => effect.attemptCount > 0).length >= MAX_RESENDS) {
473 yield* Effect.logWarning("Not resending a prompt that restarts cut too many times", {
474 threadId: projection.thread.id,
475 runId: run.id,
476 });
477 continue;
478 }
479 resentRuns.push(run);
480 resends.push({
481 id: `effect:restart-resend:${run.id}:${commandId}`,
482 commandId: resendCommandId,
483 threadId: projection.thread.id,
484 request: { type: "provider-turn.start", runId: run.id },
485 });
486 }
487 for (const run of resentRuns) {
488 events.push({
489 id: yield* allocateEventId(),
490 type: "run.updated",
491 threadId: projection.thread.id,
492 runId: run.id,
493 providerInstanceId: run.providerInstanceId,
494 occurredAt: now,
495 payload: run,
496 });
497 }
498 const keptRuns = [...retryableRuns, ...resentRuns];
499 for (const run of keptRuns) {
500 for (const attempt of projection.attempts.filter(
501 (candidate) => candidate.id === run.activeAttemptId && candidate.status === "running",
502 )) {
503 events.push({
504 id: yield* allocateEventId(),
505 type: "run-attempt.updated",
506 threadId: projection.thread.id,
507 runId: run.id,
508 nodeId: attempt.rootNodeId,
509 providerInstanceId: run.providerInstanceId,
510 occurredAt: now,
511 payload: { ...attempt, status: "pending", startedAt: null },
512 });
513 }
514 for (const node of projection.nodes.filter(
515 (candidate) => candidate.id === run.rootNodeId && candidate.status === "running",
516 )) {
517 events.push({
518 id: yield* allocateEventId(),
519 type: "node.updated",
520 threadId: projection.thread.id,
521 runId: run.id,
522 nodeId: node.id,
523 providerInstanceId: run.providerInstanceId,
524 occurredAt: now,
525 payload: { ...node, status: "pending", startedAt: null },
526 });
527 }
528 }
529 const retryableItems =
530 retryableRuns.length === 0
531 ? []
532 : (yield* projections
533 .getThreadRecords(projection.thread.id, ["turnItems"], {
534 turnItemTypes: ["user_message"],
535 turnItemRunIds: retryableRuns.map((run) => run.id),
536 })
537 .pipe(
538 Effect.mapError(
539 (cause) =>
540 new ProviderRuntimeRecoveryError({
541 operation: "read-projections",
542 threadId: projection.thread.id,
543 cause,
544 }),
545 ),
546 )).turnItems;
547 for (const item of retryableItems) {
548 if (item.type !== "user_message" || !retryableMessageIds.has(item.messageId)) continue;
549 events.push({
550 id: yield* allocateEventId(),
551 type: "turn-item.updated",
552 threadId: projection.thread.id,
553 ...(item.runId === null ? {} : { runId: item.runId }),
554 occurredAt: now,
555 payload: {
556 ...item,
557 inputIntent: "queued_turn",
558 status: "pending",
559 startedAt: null,
560 completedAt: null,
561 updatedAt: now,
562 },
563 });
564 }
565 runs = runs.filter((run) => !keptRuns.some((kept) => kept.id === run.id));
566 const heldRuns = [
567 ...retryableRuns,
568 ...queuedRunsInDeliveryOrder({ runs: queuedRuns, messages: queuedMessages }),
569 ];
570 for (const [index, run] of heldRuns.entries()) {
571 if (bufferedMessageIds.has(run.userMessageId)) {
572 runs.push(run);
573 continue;
574 }
575 if (run.queueHeld === true && retryableRuns.length === 0) continue;
576 events.push({
577 id: yield* allocateEventId(),
578 type: "run.updated",
579 threadId: projection.thread.id,
580 runId: run.id,
581 providerInstanceId: run.providerInstanceId,
582 occurredAt: now,
583 payload: {
584 ...run,
585 status: "queued",
586 queueHeld: true,
587 ...(retryableRuns.length === 0 ? {} : { queuePosition: index + 1 }),
588 },
589 });
590 }
591 const unsentResumeRunIds = runs.flatMap((run) =>
592 run.startedAt === null && run.usageLimitContinuationOfRunId !== undefined ? [run.id] : [],
593 );
594 const limitRecovery = projection.thread.limitRecovery;
595 // The unsent resume spent the worker's request id, so a fresh one lets it send again. An
596 // untagged resume from an older server stays cancelled: its copy couldn't be hidden.
597 if (limitRecovery?.autoResume === true && unsentResumeRunIds.length > 0) {
598 events.push({
599 id: yield* allocateEventId(),
600 type: "thread.metadata-updated",
601 threadId: projection.thread.id,
602 occurredAt: now,
603 payload: {
604 ...projection.thread,
605 limitRecovery: { ...limitRecovery, requestId: commandId },
606 updatedAt: now,
607 },
608 });
609 }
610 // The worker sends the auto-resume again, so the unsent copy leaves the transcript the way
611 // cancelled queued input does.
612 const unsentResumePrompts =
613 unsentResumeRunIds.length === 0
614 ? []
615 : (yield* projections
616 .getThreadRecords(projection.thread.id, ["turnItems"], {
617 turnItemTypes: ["user_message"],
618 turnItemRunIds: unsentResumeRunIds,
619 })
620 .pipe(
621 Effect.mapError(
622 (cause) =>
623 new ProviderRuntimeRecoveryError({
624 operation: "read-projections",
625 threadId: projection.thread.id,
626 cause,
627 }),
628 ),
629 )).turnItems;
630 const unsentResumePromptIds = new Set(unsentResumePrompts.map((item) => item.id));
631 for (const item of unsentResumePrompts) {
632 if (item.type !== "user_message") continue;
633 const active =
634 item.status === "pending" || item.status === "running" || item.status === "waiting";
635 events.push({
636 id: yield* allocateEventId(),
637 type: "turn-item.updated",
638 threadId: projection.thread.id,
639 ...(item.runId === null ? {} : { runId: item.runId }),
640 occurredAt: now,
641 payload: {
642 ...item,
643 ...(active ? { status: "cancelled", completedAt: now } : {}),
644 inputIntent: "queued_turn",
645 updatedAt: now,
646 },
647 });
648 }
649 for (const question of questions) {
650 events.push({
651 id: yield* allocateEventId(),
652 type: "runtime-request.updated",
653 threadId: projection.thread.id,
654 nodeId: question.nodeId,
655 occurredAt: now,
656 payload: { ...question, responseCapability: { type: "message" } },
657 });
658 }
659 for (const request of requests) {
660 events.push({
661 id: yield* allocateEventId(),
662 type: "runtime-request.updated",
663 threadId: projection.thread.id,
664 nodeId: request.nodeId,
665 occurredAt: now,
666 payload: {
667 ...request,
668 status: trigger === "startup" ? "expired" : "cancelled",
669 responseCapability: {
670 type: "not_resumable",
671 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
672 },
673 resolvedAt: now,
674 },
675 });
676 }
677 for (const run of runs) {
678 events.push({
679 id: yield* allocateEventId(),
680 type: "run.updated",
681 threadId: projection.thread.id,
682 runId: run.id,
683 providerInstanceId: run.providerInstanceId,
684 occurredAt: now,
685 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
686 });
687 for (const attempt of projection.attempts.filter(
688 (candidate) =>
689 candidate.runId === run.id &&
690 (candidate.status === "pending" || candidate.status === "running"),
691 )) {
692 events.push({
693 id: yield* allocateEventId(),
694 type: "run-attempt.updated",
695 threadId: projection.thread.id,
696 runId: run.id,
697 nodeId: attempt.rootNodeId,
698 providerInstanceId: run.providerInstanceId,
699 occurredAt: now,
700 payload: { ...attempt, status: "cancelled", completedAt: now },
701 });
702 }
703 for (const node of projection.nodes.filter(
704 (candidate) =>
705 candidate.runId === run.id &&
706 !messageRequestNodeIds.has(candidate.id) &&
707 !delegatedTaskNodeIds.has(candidate.id) &&
708 (candidate.status === "pending" ||
709 candidate.status === "running" ||
710 candidate.status === "waiting"),
711 )) {
712 events.push({
713 id: yield* allocateEventId(),
714 type: "node.updated",
715 threadId: projection.thread.id,
716 runId: run.id,
717 nodeId: node.id,
718 providerInstanceId: run.providerInstanceId,
719 occurredAt: now,
720 payload: { ...node, status: "cancelled", completedAt: now },
721 });
722 }
723 for (const providerTurn of projection.providerTurns.filter(
724 (candidate) =>
725 candidate.runAttemptId !== null &&
726 projection.attempts.some(
727 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
728 ) &&
729 (candidate.status === "pending" || candidate.status === "running"),
730 )) {
731 events.push({
732 id: yield* allocateEventId(),
733 type: "provider-turn.updated",
734 threadId: projection.thread.id,
735 runId: run.id,
736 nodeId: providerTurn.nodeId,
737 providerInstanceId: run.providerInstanceId,
738 occurredAt: now,
739 payload: { ...providerTurn, status: "cancelled", completedAt: now },
740 });
741 }
742 for (const message of projection.messages.filter(
743 (candidate) => candidate.runId === run.id && candidate.streaming,
744 )) {
745 events.push({
746 id: yield* allocateEventId(),
747 type: "message.updated",
748 threadId: projection.thread.id,
749 runId: run.id,
750 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
751 providerInstanceId: run.providerInstanceId,
752 occurredAt: now,
753 payload: { ...message, streaming: false, updatedAt: now },
754 });
755 }
756 for (const item of projection.turnItems.filter(
757 (candidate) =>
758 candidate.runId === run.id &&
759 !unsentResumePromptIds.has(candidate.id) &&
760 (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
761 !isAppOwnedDelegationItem(candidate) &&
762 // A link card waits on the user, not the run, and answers by message.
763 candidate.type !== "link_request" &&
764 // So does a feedback card, answered from what it recorded.
765 candidate.type !== "feedback_request" &&
766 // The orchestrator queues a steer the provider never reported reading.
767 !(
768 candidate.type === "user_message" &&
769 candidate.status === "pending" &&
770 (candidate.inputIntent === "steer" ||
771 candidate.inputIntent === "promoted_queued_to_steer")
772 ) &&
773 (candidate.status === "pending" ||
774 candidate.status === "running" ||
775 candidate.status === "waiting"),
776 )) {
777 // Cut native subagents do not resume; record them for the continuation to restart.
778 if (run.status === "waiting") recordCancelledBackgroundItem(item);
779 else if (item.type === "subagent" && item.origin === "provider_native")
780 recordCancelledBackgroundItem(item);
781 events.push({
782 id: yield* allocateEventId(),
783 type: "turn-item.updated",
784 threadId: projection.thread.id,
785 runId: run.id,
786 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
787 providerInstanceId: run.providerInstanceId,
788 occurredAt: now,
789 payload: cancelledItem(item, now),
790 });
791 }
792 // Queued runs and unsent resumes leave no visible turn behind, so there is nothing to explain.
793 if (run.status === "queued" || unsentResumeRunIds.includes(run.id)) continue;
794 events.push({
795 id: yield* allocateEventId(),
796 type: "turn-item.updated",
797 threadId: projection.thread.id,
798 runId: run.id,
799 ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }),
800 providerInstanceId: run.providerInstanceId,
801 occurredAt: now,
802 payload: {
803 id: ids.derive.runSignalTurnItem({ runId: run.id, signal: "server-recovery" }),
804 threadId: projection.thread.id,
805 runId: run.id,
806 nodeId: run.rootNodeId,
807 providerThreadId: run.providerThreadId,
808 providerTurnId: null,
809 nativeItemRef: null,
810 parentItemId: null,
811 // EventSink allocates the real position, after the run's existing items.
812 ordinal: 0,
813 status: "completed",
814 title: trigger === "startup" ? "Server restarted" : "Server shut down",
815 startedAt: now,
816 completedAt: now,
817 updatedAt: now,
818 type: "system_notice",
819 message: detail,
820 },
821 });
822 }
823 // Blocking waits die with their turn; let child results wake the parent continuation as async tasks.
824 const cutRunIds = new Set(runs.map((run) => run.id));
825 for (const task of projection.subagents ?? []) {
826 if (
827 task.origin !== "app_owned" ||
828 task.runId === null ||
829 !cutRunIds.has(task.runId) ||
830 task.completionWake !== "settled_only" ||
831 !isOrchestrationV2WorkActive(task.status)
832 )
833 continue;
834 events.push({
835 id: yield* allocateEventId(),
836 type: "subagent.updated",
837 threadId: projection.thread.id,
838 runId: task.runId,
839 nodeId: task.id,
840 driver: task.driver,
841 providerInstanceId: task.providerInstanceId,
842 occurredAt: now,
843 payload: { ...task, completionWake: "always", updatedAt: now },
844 });
845 }
846 const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
847 const cancelledStaleNodeIds = new Set<string>();
848 for (const item of projection.turnItems ?? []) {
849 if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
850 continue;
851 }
852 if (!isBackgroundCapableTurnItemType(item.type)) {
853 continue;
854 }
855 if (!isNonterminalTurnItemStatus(item.status) || isAppOwnedDelegationItem(item)) {
856 continue;
857 }
858 const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
859 recordCancelledBackgroundItem(item);
860 events.push({
861 id: yield* allocateEventId(),
862 type: "turn-item.updated",
863 threadId: projection.thread.id,
864 ...(item.runId === null ? {} : { runId: item.runId }),
865 ...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
866 providerInstanceId,
867 occurredAt: now,
868 payload: cancelledItem(item, now),
869 });
870 if (item.nodeId !== null && item.nodeId !== undefined) {
871 const staleItemNode = projection.nodes.find(
872 (candidate) =>
873 candidate.id === item.nodeId && isNonterminalTurnItemStatus(candidate.status),
874 );
875 if (staleItemNode !== undefined && !cancelledStaleNodeIds.has(staleItemNode.id)) {
876 cancelledStaleNodeIds.add(staleItemNode.id);
877 events.push({
878 id: yield* allocateEventId(),
879 type: "node.updated",
880 threadId: projection.thread.id,
881 ...(item.runId === null ? {} : { runId: item.runId }),
882 nodeId: staleItemNode.id,
883 providerInstanceId,
884 occurredAt: now,
885 payload: { ...staleItemNode, status: "cancelled", completedAt: now },
886 });
887 }
888 }
889 }
890 // No provider process survives the server; open native subagents can never report completion.
891 for (const subagent of projection.subagents ?? []) {
892 events.push(
893 ...(yield* endOrphanedNativeSubagent({
894 projection,
895 subagentId: subagent.id,
896 status: "cancelled",
897 now,
898 emitted: events,
899 allocateEventId,
900 })),
901 );
902 }
903 // Native subagent threads have no runs to settle their runless root turns.
904 events.push(
905 ...(yield* endRunlessRootTurns({
906 threadId: projection.thread.id,
907 providerInstanceId: projection.thread.providerInstanceId,
908 projection,
909 status: "cancelled",
910 now,
911 emitted: events,
912 allocateEventId,
913 })),
914 );
915 for (const providerThread of projection.providerThreads ?? []) {
916 const needsIdle = providerThread.status === "active";
917 const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
918 if (!needsIdle && !needsRosterClear) {
919 continue;
920 }
921 if (providerThread.ownerNodeId === null) {
922 for (const task of providerThread.pendingBackgroundTasks ?? []) {
923 // A subagent already recorded covers the shells it started.
924 if (
925 cancelledBackgroundNativeIds.has(task.taskId) ||
926 (task.parentTaskId !== undefined &&
927 cancelledBackgroundNativeIds.has(task.parentTaskId))
928 )
929 continue;
930 cancelledBackgroundNativeIds.add(task.taskId);
931 recordCancelledBackgroundWork(providerThread.id, cancelledRosterTaskWork(task));
932 }
933 }
934 events.push({
935 id: yield* allocateEventId(),
936 type: "provider-thread.updated",
937 threadId: projection.thread.id,
938 driver: providerThread.driver,
939 providerInstanceId: providerThread.providerInstanceId,
940 occurredAt: now,
941 payload: {
942 ...providerThread,
943 status: needsIdle ? "idle" : providerThread.status,
944 pendingBackgroundTasks: [],
945 updatedAt: now,
946 },
947 });
948 }
949 for (const session of projection.providerSessions.filter(
950 (candidate) =>
951 (candidate.status !== "stopped" && candidate.status !== "error") ||
952 (candidate.status === "error" && (candidate.extensionStatuses?.length ?? 0) > 0),
953 )) {
954 events.push({
955 id: yield* allocateEventId(),
956 type: "provider-session.updated",
957 threadId: projection.thread.id,
958 driver: session.driver,
959 providerInstanceId: session.providerInstanceId,
960 occurredAt: now,
961 payload: {
962 ...session,
963 status: session.status === "error" ? "error" : "stopped",
964 ...(session.extensionStatuses === undefined ? {} : { extensionStatuses: [] }),
965 updatedAt: now,
966 lastError: session.status === "error" ? session.lastError : null,
967 },
968 });
969 }
970 for (const [providerThreadId, work] of cancelledBackgroundWork) {
971 const noteRun = latestStartedRun(projection.runs, providerThreadId);
972 if (noteRun === undefined) continue;
973 // Use a separate event; stale run snapshots can overwrite intervening lifecycle changes.
974 events.push({
975 id: yield* allocateEventId(),
976 type: "run.background-work-cancelled",
977 threadId: projection.thread.id,
978 runId: noteRun.id,
979 providerInstanceId: noteRun.providerInstanceId,
980 occurredAt: now,
981 payload: {
982 runId: noteRun.id,
983 restartCancelledBackgroundWork: mergeRestartCancelledBackgroundWork(
984 noteRun.restartCancelledBackgroundWork ?? [],
985 work,
986 ),
987 },
988 });
989 }
990 const continuationRun =
991 continueAfterRestart && trigger === "startup"
992 ? restartContinuationRun(
993 { ...projection, providerSessions: sessionsLiveAtStart(projection, stoppedThisPass) },
994 now,
995 )
996 : undefined;
997 let processLossCount = 1;
998 // Normal upgrades must not exhaust an unfinished turn's crash allowance.
999 if (
1000 continuationRun?.restartContinuationOfRunId !== undefined &&
1001 continuationRun.status !== "completed" &&
1002 continuationRun.status !== "waiting"
1003 ) {
1004 const previous = yield* outbox
1005 .get(`effect:restart-continuation:${continuationRun.restartContinuationOfRunId}`)
1006 .pipe(
1007 Effect.mapError(
1008 (cause) =>
1009 new ProviderRuntimeRecoveryError({
1010 operation: "reconcile",
1011 threadId: projection.thread.id,
1012 cause,
1013 }),
1014 ),
1015 );
1016 if (Option.isSome(previous) && previous.value.request.type === "provider-runtime.continue")
1017 processLossCount += previous.value.request.processLossCount ?? 0;
1018 }
1019 const effects: Array<EffectOutbox.PendingOrchestrationEffectV2> = continuationRun
1020 ? [
1021 {
1022 id: `effect:restart-continuation:${continuationRun.id}`,
1023 commandId,
1024 threadId: projection.thread.id,
1025 request: {
1026 type: "provider-runtime.continue",
1027 sourceRunId: continuationRun.id,
1028 processLossCount,
1029 },
1030 },
1031 ]
1032 : [];
1033 const stoppedSessions = projection.providerSessions.filter(
1034 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
1035 ).length;
1036 let retiredEffects: number;
1037 let cancelledEffectIds: ReadonlyArray<string> = [];
1038 if (events.length === 0) {
1039 const retiredEffectIds = yield* outbox
1040 .cancelUnsettled({
1041 threadId: projection.thread.id,
1042 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
1043 reason: detail,
1044 })
1045 .pipe(
1046 Effect.mapError(
1047 (cause) =>
1048 new ProviderRuntimeRecoveryError({
1049 operation: "reconcile",
1050 threadId: projection.thread.id,
1051 cause: { detail, cause },
1052 }),
1053 ),
1054 );
1055 cancelledEffectIds = retiredEffectIds;
1056 retiredEffects = retiredEffectIds.length;
1057 } else {
1058 const result = yield* eventSink
1059 .commitCommand({
1060 commandId,
1061 threadId: projection.thread.id,
1062 commandType: "provider-runtime.reconcile",
1063 acceptedAt: now,
1064 events,
1065 effects,
1066 cancelUnsettledEffects: {
1067 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
1068 reason: detail,
1069 },
1070 })
1071 .pipe(
1072 Effect.mapError(
1073 (cause) =>
1074 new ProviderRuntimeRecoveryError({
1075 operation: "reconcile",
1076 threadId: projection.thread.id,
1077 cause,
1078 }),
1079 ),
1080 );
1081 retiredEffects = result.cancelledEffectCount;
1082 }
1083 return {
1084 terminalizedRuns: runs.length,
1085 stoppedSessions,
1086 closedRequests: requests.length,
1087 retiredEffects,
1088 cancelledEffectIds,
1089 resends,
1090 };
1091 },
1092 );
1093
1094 const reconcile = Effect.fn("ProviderRuntimeRecoveryService.reconcile")(function* (
1095 trigger: "startup" | "shutdown",
1096 ) {
1097 const continueAfterRestart = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
1098 const threadIds = yield* projections
1099 .getRecoveryThreadIds("runtime")
1100 .pipe(
1101 Effect.mapError(
1102 (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
1103 ),
1104 );
1105 let terminalizedRuns = 0;
1106 let stoppedSessions = 0;
1107 let closedRequests = 0;
1108 let retiredEffects = 0;
1109 const resends: Array<EffectOutbox.PendingOrchestrationEffectV2> = [];
1110 const stoppedThisPass = new Map<string, RecoverySession>();
1111 const grouped = trigger === "shutdown" && threadIds.length > 1;
1112 const groupSize = grouped ? 32 : 1;
1113 for (let offset = 0; offset < threadIds.length; offset += groupSize) {
1114 const cancelledEffectIds: string[] = [];
1115 // Read and decide on the writer so shared sessions see earlier updates in this group.
1116 const reconcileGroup = Effect.gen(function* () {
1117 for (const threadId of threadIds.slice(offset, offset + groupSize)) {
1118 const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
1119 Effect.mapError(
1120 (cause) =>
1121 new ProviderRuntimeRecoveryError({
1122 operation: "read-projections",
1123 threadId,
1124 cause,
1125 }),
1126 ),
1127 );
1128 const enabled =
1129 continueAfterRestart !== null &&
1130 resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
1131 .continueThreadsAfterServerUpdate;
1132 const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
1133 for (const session of projection.providerSessions) {
1134 if (session.status !== "stopped" && session.status !== "error") {
1135 stoppedThisPass.set(session.id, session);
1136 }
1137 }
1138 cancelledEffectIds.push(...result.cancelledEffectIds);
1139 resends.push(...result.resends);
1140 terminalizedRuns += result.terminalizedRuns;
1141 stoppedSessions += result.stoppedSessions;
1142 closedRequests += result.closedRequests;
1143 retiredEffects += result.retiredEffects;
1144 }
1145 });
1146 yield* (grouped ? eventSink.withProviderBatch(reconcileGroup) : reconcileGroup).pipe(
1147 Effect.mapError((cause) =>
1148 isProviderRuntimeRecoveryError(cause)
1149 ? cause
1150 : new ProviderRuntimeRecoveryError({ operation: "reconcile", cause }),
1151 ),
1152 );
1153 // Eventless outbox cancellations also wait for the group's durable commit.
1154 if (cancelledEffectIds.length > 0) yield* outbox.signalCancellations(cancelledEffectIds);
1155 }
1156 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
1157 Effect.mapError(
1158 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
1159 ),
1160 );
1161 // After the drain, which cancels every unsettled provider start. A crash before this write
1162 // leaves the run unstarted, so the next recovery sends it again.
1163 if (resends.length > 0) {
1164 yield* eventSink
1165 .writeWithEffects({ events: [], effects: resends })
1166 .pipe(
1167 Effect.mapError(
1168 (cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause }),
1169 ),
1170 );
1171 }
1172 return {
1173 terminalizedRuns,
1174 stoppedSessions,
1175 closedRequests,
1176 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
1177 requeuedEffects: outboxReconciliation.requeued,
1178 } satisfies ProviderRuntimeReconciliationSummary;
1179 });
1180
1181 const prepareForShutdown = Effect.gen(function* () {
1182 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
1183 if (!enabled) return;
1184 const enabledProjects = Object.entries(enabled.projectSettingsOverrides)
1185 .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === true)
1186 .map(([id]) => id);
1187 if (!enabled.continueThreadsAfterServerUpdate && enabledProjects.length === 0) return;
1188 const disabledProjects = Object.entries(enabled.projectSettingsOverrides)
1189 .filter(([, overrides]) => overrides.continueThreadsAfterServerUpdate === false)
1190 .map(([id]) => id);
1191 const threadIds = yield* projections.getRecoveryThreadIds(
1192 "restart-continuations",
1193 enabled.continueThreadsAfterServerUpdate
1194 ? { exclude: disabledProjects }
1195 : { include: enabledProjects },
1196 );
1197 yield* Effect.forEach(
1198 threadIds,
1199 (threadId) =>
1200 Effect.gen(function* () {
1201 const projection = yield* projections.getRuntimeRecoveryProjection(threadId);
1202 if (
1203 !resolveProjectSettings(enabled, projection.thread.projectId).settings
1204 .continueThreadsAfterServerUpdate
1205 )
1206 return;
1207 const run = restartContinuationRun(
1208 yield* rewindUnacceptedRuns(projection),
1209 yield* DateTime.now,
1210 );
1211 if (!run) return;
1212 const commandId = CommandId.make(`command:restart-prepare:${run.id}`);
1213 yield* eventSink.writeWithEffects({
1214 commandId,
1215 events: [],
1216 effects: [
1217 {
1218 id: `effect:restart-continuation:${run.id}`,
1219 commandId,
1220 threadId,
1221 request: {
1222 type: "provider-runtime.continue",
1223 sourceRunId: run.id,
1224 processLossCount: 0,
1225 },
1226 },
1227 ],
1228 });
1229 }).pipe(
1230 Effect.catchCauseIf(
1231 (cause) => !Cause.hasInterruptsOnly(cause),
1232 (cause) =>
1233 Effect.logWarning("Failed to prepare a restart continuation", { threadId, cause }),
1234 ),
1235 ),
1236 // Leave room in the four-reader pool for other shutdown reads.
1237 { concurrency: 2, discard: true },
1238 );
1239 }).pipe(
1240 Effect.withSpan("ProviderRuntimeRecoveryService.prepareForShutdown"),
1241 Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })),
1242 );
1243
1244 const recover = Effect.gen(function* () {
1245 return (yield* reconcile("startup")) satisfies ProviderRuntimeRecoverySummary;
1246 });
1247
1248 return ProviderRuntimeRecoveryService.of({ reconcile, prepareForShutdown, recover });
1249});
1250
1251export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);