Open History to see the last commit
1import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
2import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3import {
4 CommandId,
5 isProviderNativeSubagentThread,
6 type OrchestrationV2DomainEvent,
7 type ProviderThreadId,
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 Schema from "effect/Schema";
20
21import * as EffectOutbox from "./EffectOutbox.ts";
22import * as EventSink from "./EventSink.ts";
23import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
24import * as ProjectionStore from "./ProjectionStore.ts";
25import * as ServerSettings from "../serverSettings.ts";
26import { restartContinuationRun } from "./RestartContinuation.ts";
27import { isBufferedProviderNotification } from "./NotificationMailbox.ts";
28import { queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts";
29import {
30 endOrphanedNativeSubagent,
31 endRunlessRootTurns,
32} from "@t3tools/provider-core/server/subagentProjection";
33import {
34 awaitingProviderThreadId,
35 cancelledRosterTaskWork,
36 cancelledTurnItemWork,
37 mergeRestartCancelledBackgroundWork,
38 neverStarted,
39} from "./RestartBackgroundNote.ts";
40
41export class ProviderRuntimeRecoveryError extends Schema.TaggedError<ProviderRuntimeRecoveryError>()(
42 "ProviderRuntimeRecoveryError",
43 {
44 operation: Schema.Literals(["read-projections", "reconcile", "drain-outbox"]),
45 threadId: Schema.optional(ThreadId),
46 cause: Schema.Defect(),
47 },
48) {
49 override get message(): string {
50 return `Provider runtime recovery failed during ${this.operation}.`;
51 }
52}
53
54export interface ProviderRuntimeRecoverySummary {
55 readonly terminalizedRuns: number;
56 readonly stoppedSessions: number;
57 readonly closedRequests: number;
58 readonly retiredEffects: number;
59 readonly requeuedEffects: number;
60}
61
62export interface ProviderRuntimeReconciliationSummary {
63 readonly terminalizedRuns: number;
64 readonly stoppedSessions: number;
65 readonly closedRequests: number;
66 readonly retiredEffects: number;
67 readonly requeuedEffects: number;
68}
69
70export class ProviderRuntimeRecoveryService extends Context.Service<
71 ProviderRuntimeRecoveryService,
72 {
73 readonly reconcile: (
74 trigger: "startup" | "shutdown",
75 ) => Effect.Effect<ProviderRuntimeReconciliationSummary, ProviderRuntimeRecoveryError>;
76 readonly prepareForShutdown: Effect.Effect<void, ProviderRuntimeRecoveryError>;
77 readonly recover: Effect.Effect<ProviderRuntimeRecoverySummary, ProviderRuntimeRecoveryError>;
78 }
79>()("t3/orchestration-v2/ProviderRuntimeRecoveryService") {}
80
81function nonterminalRuns(projection: ProjectionStore.ProjectionRuntimeRecoveryState) {
82 return projection.runs.filter((run) => {
83 const status: string = run.status;
84 return (
85 status === "preparing" ||
86 run.status === "starting" ||
87 run.status === "running" ||
88 run.status === "waiting"
89 );
90 });
91}
92
93function isBackgroundCapableTurnItemType(type: string): boolean {
94 return type === "command_execution" || type === "dynamic_tool" || type === "subagent";
95}
96
97function isNonterminalTurnItemStatus(status: string): boolean {
98 return status === "pending" || status === "running" || status === "waiting";
99}
100
101/**
102 * A delegate_task child. Its own thread is reconciled and continued on its own
103 * (here, or in the linked environment it runs in) and reports back through
104 * the app, so it is not provider background work.
105 */
106function isAppOwnedDelegation(task: {
107 readonly origin: OrchestrationV2Subagent["origin"];
108 readonly childThreadId: ThreadId | null;
109 readonly remoteChild?: OrchestrationV2Subagent["remoteChild"];
110}): boolean {
111 return (
112 task.origin === "app_owned" && (task.childThreadId !== null || task.remoteChild !== undefined)
113 );
114}
115
116function isAppOwnedDelegationItem(
117 item: OrchestrationV2ThreadProjection["turnItems"][number],
118): boolean {
119 return item.type === "subagent" && isAppOwnedDelegation(item);
120}
121
122function providerThreadHasPendingBackgroundTasks(
123 providerThread: OrchestrationV2ThreadProjection["providerThreads"][number],
124): boolean {
125 return (providerThread.pendingBackgroundTasks?.length ?? 0) > 0;
126}
127
128function resolveStaleBackgroundItemProviderInstanceId(
129 item: OrchestrationV2ThreadProjection["turnItems"][number],
130 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
131): OrchestrationV2ThreadProjection["thread"]["providerInstanceId"] {
132 if (item.runId !== null) {
133 const run = projection.runs.find((candidate) => candidate.id === item.runId);
134 if (run !== undefined) {
135 return run.providerInstanceId;
136 }
137 }
138 if (item.type === "subagent") {
139 return item.providerInstanceId;
140 }
141 if (item.providerThreadId !== null && item.providerThreadId !== undefined) {
142 const providerThread = projection.providerThreads.find(
143 (candidate) => candidate.id === item.providerThreadId,
144 );
145 if (providerThread !== undefined) {
146 return providerThread.providerInstanceId;
147 }
148 }
149 return projection.providerThreads[0]?.providerInstanceId ?? projection.thread.providerInstanceId;
150}
151
152const cancelledItem = (
153 item: OrchestrationV2ThreadProjection["turnItems"][number],
154 now: DateTime.Utc,
155): OrchestrationV2ThreadProjection["turnItems"][number] =>
156 item.type === "secret_request" && item.secretStatus === "pending"
157 ? { ...item, status: "cancelled", secretStatus: "cancelled", completedAt: now, updatedAt: now }
158 : {
159 ...item,
160 ...("streaming" in item ? { streaming: false } : {}),
161 status: "cancelled",
162 completedAt: now,
163 updatedAt: now,
164 };
165
166function latestStartedRun(
167 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
168 providerThreadId: ProviderThreadId,
169) {
170 return projection.runs.reduce<OrchestrationV2ThreadProjection["runs"][number] | undefined>(
171 (latest, run) =>
172 run.providerThreadId === providerThreadId &&
173 run.status !== "queued" &&
174 run.status !== "rolled_back" &&
175 !neverStarted(run) &&
176 (latest === undefined || runRanAfter(run, latest))
177 ? run
178 : latest,
179 undefined,
180 );
181}
182
183export const make = Effect.gen(function* () {
184 const settings = yield* ServerSettings.ServerSettingsService;
185 const projections = yield* ProjectionStore.ProjectionStoreV2;
186 const eventSink = yield* EventSink.EventSinkV2;
187 const ids = yield* IdAllocator.IdAllocatorV2;
188 const outbox = yield* EffectOutbox.EffectOutboxV2;
189 type RecoverySession = ProjectionStore.ProjectionRuntimeRecoveryState["providerSessions"][number];
190 /** Shared sessions stop on their first recovered thread; later threads still decide wakes from pre-recovery liveness. */
191 const sessionsLiveAtStart = (
192 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
193 stoppedThisPass: ReadonlyMap<string, RecoverySession>,
194 ) => {
195 const sessions = new Map(projection.providerSessions.map((session) => [session.id, session]));
196 for (const providerThread of projection.providerThreads) {
197 const stopped =
198 providerThread.providerSessionId === null
199 ? undefined
200 : stoppedThisPass.get(providerThread.providerSessionId);
201 if (stopped !== undefined) sessions.set(stopped.id, stopped);
202 }
203 return [...sessions.values()];
204 };
205
206 const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
207 function* (
208 projection: ProjectionStore.ProjectionRuntimeRecoveryState,
209 trigger: "startup" | "shutdown",
210 continueAfterRestart: boolean,
211 stoppedThisPass: ReadonlyMap<string, RecoverySession> = new Map(),
212 ) {
213 const now = yield* DateTime.now;
214 let runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
215 for (const run of nonterminalRuns(projection)) {
216 if (run.status === "waiting") {
217 const checkpointEffects = yield* outbox
218 .listByCommandId(CommandId.make(`command:effect:checkpoint.capture:${run.id}`))
219 .pipe(
220 Effect.mapError(
221 (cause) =>
222 new ProviderRuntimeRecoveryError({
223 operation: "reconcile",
224 threadId: projection.thread.id,
225 cause,
226 }),
227 ),
228 );
229 const hasReplayableCheckpoint = checkpointEffects.some(
230 (effect) =>
231 effect.request.type === "checkpoint.capture" &&
232 effect.request.runId === run.id &&
233 (effect.status === "pending" || effect.status === "running"),
234 );
235 if (hasReplayableCheckpoint) continue;
236 }
237 runs.push(run);
238 }
239 const pendingRequests = projection.runtimeRequests.filter(
240 (request) => request.status === "pending",
241 );
242 // The lost provider callback cannot resume; persisted questions can be
243 // answered by a new user message in threads that accept messages.
244 const questions = pendingRequests.filter(
245 (request) =>
246 request.kind === "user_input" &&
247 request.responseCapability.type === "live" &&
248 projection.turnItems.some(
249 (item) =>
250 item.type === "user_input_request" &&
251 item.requestId === request.id &&
252 item.nodeId === request.nodeId &&
253 item.questions.length > 0 &&
254 item.questions.every((question) => question.question.trim().length > 0),
255 ) &&
256 !isProviderNativeSubagentThread(projection.thread),
257 );
258 const recoveredRequestIds = new Set(questions.map((request) => request.id));
259 const messageRequestNodeIds = new Set(
260 pendingRequests
261 .filter(
262 (request) =>
263 request.responseCapability.type === "message" || recoveredRequestIds.has(request.id),
264 )
265 .map((request) => request.nodeId),
266 );
267 const requests = pendingRequests.filter(
268 (request) =>
269 request.responseCapability.type !== "message" && !recoveredRequestIds.has(request.id),
270 );
271 // Delegated task rows, items and nodes stay open: the child settles them.
272 const delegatedTaskNodeIds = new Set<string>([
273 ...(projection.subagents ?? []).filter(isAppOwnedDelegation).map((subagent) => subagent.id),
274 ...(projection.turnItems ?? []).flatMap((item) =>
275 item.type === "subagent" && isAppOwnedDelegation(item) ? [item.subagentId] : [],
276 ),
277 ]);
278 const detail = `Cancelled because the server ${trigger === "startup" ? "restarted" : "shut down"} before the provider work completed.`;
279 const commandId = CommandId.make(
280 `command:runtime-reconcile:${trigger}:${projection.thread.id}:${DateTime.formatIso(now)}`,
281 );
282 const allocateEventId = () =>
283 ids.allocate.event({ threadId: projection.thread.id, commandId }).pipe(
284 Effect.mapError(
285 (cause) =>
286 new ProviderRuntimeRecoveryError({
287 operation: "reconcile",
288 threadId: projection.thread.id,
289 cause,
290 }),
291 ),
292 );
293 const events: Array<OrchestrationV2DomainEvent> = [];
294 const cancelledBackgroundWork = new Map<
295 ProviderThreadId,
296 Array<OrchestrationV2RestartCancelledBackgroundWork>
297 >();
298 const cancelledBackgroundNativeIds = new Set<string>();
299 const recordCancelledBackgroundWork = (
300 providerThreadId: ProviderThreadId | null | undefined,
301 work: OrchestrationV2RestartCancelledBackgroundWork,
302 ) => {
303 if (providerThreadId == null) return;
304 const existing = cancelledBackgroundWork.get(providerThreadId);
305 if (existing === undefined) cancelledBackgroundWork.set(providerThreadId, [work]);
306 else existing.push(work);
307 };
308 const recordCancelledBackgroundItem = (
309 item: OrchestrationV2ThreadProjection["turnItems"][number],
310 ) => {
311 if (!isBackgroundCapableTurnItemType(item.type)) return;
312 const awaitingId = awaitingProviderThreadId(item, projection.runs);
313 const ownProviderThread =
314 item.providerThreadId === awaitingId
315 ? undefined
316 : (projection.providerThreads ?? []).find(
317 (candidate) => candidate.id === item.providerThreadId,
318 );
319 const work = cancelledTurnItemWork(
320 item,
321 ownProviderThread?.nativeThreadRef?.nativeId ?? undefined,
322 );
323 if (work === undefined) return;
324 recordCancelledBackgroundWork(awaitingId, work);
325 if (item.nativeItemRef?.nativeId != null) {
326 cancelledBackgroundNativeIds.add(item.nativeItemRef.nativeId);
327 }
328 };
329 const unstartedRuns = runs.filter(
330 (run) =>
331 run.status === "starting" &&
332 neverStarted(run) &&
333 !projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) &&
334 !projection.runtimeRequests.some(
335 (request) =>
336 request.status === "pending" &&
337 projection.nodes.some((node) => node.id === request.nodeId && node.runId === run.id),
338 ),
339 );
340 const queuedRuns = projection.runs.filter((run) => run.status === "queued");
341 const pendingRuns = [...unstartedRuns, ...queuedRuns];
342 const queuedMessages =
343 pendingRuns.length === 0
344 ? []
345 : [
346 ...(yield* projections
347 .getMessagesById(
348 projection.thread.id,
349 pendingRuns.map((run) => run.userMessageId),
350 )
351 .pipe(
352 Effect.mapError(
353 (cause) =>
354 new ProviderRuntimeRecoveryError({
355 operation: "read-projections",
356 threadId: projection.thread.id,
357 cause,
358 }),
359 ),
360 )).values(),
361 ];
362 const bufferedMessageIds = new Set(
363 queuedMessages.filter(isBufferedProviderNotification).map((message) => message.id),
364 );
365 const retryableMessageIds = new Set(
366 queuedMessages
367 .filter(
368 (message) =>
369 message.createdBy === "user" &&
370 message.scheduledTaskId === undefined &&
371 message.notification === undefined &&
372 message.delegatedCompletion === undefined,
373 )
374 .map((message) => message.id),
375 );
376 // A saved user message the provider never accepted stays available through the held queue.
377 const retryableRuns = unstartedRuns.filter((run) =>
378 retryableMessageIds.has(run.userMessageId),
379 );
380 const retryableRunIds = new Set(retryableRuns.map((run) => run.id));
381 const retryableItems =
382 retryableRuns.length === 0
383 ? []
384 : (yield* projections
385 .getThreadRecords(projection.thread.id, ["turnItems"], {
386 turnItemTypes: ["user_message"],
387 turnItemRunIds: retryableRuns.map((run) => run.id),
388 })
389 .pipe(
390 Effect.mapError(
391 (cause) =>
392 new ProviderRuntimeRecoveryError({
393 operation: "read-projections",
394 threadId: projection.thread.id,
395 cause,
396 }),
397 ),
398 )).turnItems;
399 for (const item of retryableItems) {
400 if (item.type !== "user_message" || !retryableMessageIds.has(item.messageId)) continue;
401 events.push({
402 id: yield* allocateEventId(),
403 type: "turn-item.updated",
404 threadId: projection.thread.id,
405 ...(item.runId === null ? {} : { runId: item.runId }),
406 occurredAt: now,
407 payload: {
408 ...item,
409 inputIntent: "queued_turn",
410 status: "pending",
411 startedAt: null,
412 completedAt: null,
413 updatedAt: now,
414 },
415 });
416 }
417 runs = runs.filter((run) => !retryableRunIds.has(run.id));
418 const heldRuns = [
419 ...retryableRuns,
420 ...queuedRunsInDeliveryOrder({ runs: queuedRuns, messages: queuedMessages }),
421 ];
422 for (const [index, run] of heldRuns.entries()) {
423 if (bufferedMessageIds.has(run.userMessageId)) {
424 runs.push(run);
425 continue;
426 }
427 if (run.queueHeld === true && retryableRuns.length === 0) continue;
428 events.push({
429 id: yield* allocateEventId(),
430 type: "run.updated",
431 threadId: projection.thread.id,
432 runId: run.id,
433 providerInstanceId: run.providerInstanceId,
434 occurredAt: now,
435 payload: {
436 ...run,
437 status: "queued",
438 queueHeld: true,
439 ...(retryableRuns.length === 0 ? {} : { queuePosition: index + 1 }),
440 },
441 });
442 }
443 for (const question of questions) {
444 events.push({
445 id: yield* allocateEventId(),
446 type: "runtime-request.updated",
447 threadId: projection.thread.id,
448 nodeId: question.nodeId,
449 occurredAt: now,
450 payload: { ...question, responseCapability: { type: "message" } },
451 });
452 }
453 for (const request of requests) {
454 events.push({
455 id: yield* allocateEventId(),
456 type: "runtime-request.updated",
457 threadId: projection.thread.id,
458 nodeId: request.nodeId,
459 occurredAt: now,
460 payload: {
461 ...request,
462 status: trigger === "startup" ? "expired" : "cancelled",
463 responseCapability: {
464 type: "not_resumable",
465 reason: `The server ${trigger === "startup" ? "restarted" : "shut down"} before this runtime request was resolved.`,
466 },
467 resolvedAt: now,
468 },
469 });
470 }
471 for (const run of runs) {
472 events.push({
473 id: yield* allocateEventId(),
474 type: "run.updated",
475 threadId: projection.thread.id,
476 runId: run.id,
477 providerInstanceId: run.providerInstanceId,
478 occurredAt: now,
479 payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now },
480 });
481 for (const attempt of projection.attempts.filter(
482 (candidate) =>
483 candidate.runId === run.id &&
484 (candidate.status === "pending" || candidate.status === "running"),
485 )) {
486 events.push({
487 id: yield* allocateEventId(),
488 type: "run-attempt.updated",
489 threadId: projection.thread.id,
490 runId: run.id,
491 nodeId: attempt.rootNodeId,
492 providerInstanceId: run.providerInstanceId,
493 occurredAt: now,
494 payload: { ...attempt, status: "cancelled", completedAt: now },
495 });
496 }
497 for (const node of projection.nodes.filter(
498 (candidate) =>
499 candidate.runId === run.id &&
500 !messageRequestNodeIds.has(candidate.id) &&
501 !delegatedTaskNodeIds.has(candidate.id) &&
502 (candidate.status === "pending" ||
503 candidate.status === "running" ||
504 candidate.status === "waiting"),
505 )) {
506 events.push({
507 id: yield* allocateEventId(),
508 type: "node.updated",
509 threadId: projection.thread.id,
510 runId: run.id,
511 nodeId: node.id,
512 providerInstanceId: run.providerInstanceId,
513 occurredAt: now,
514 payload: { ...node, status: "cancelled", completedAt: now },
515 });
516 }
517 for (const providerTurn of projection.providerTurns.filter(
518 (candidate) =>
519 candidate.runAttemptId !== null &&
520 projection.attempts.some(
521 (attempt) => attempt.id === candidate.runAttemptId && attempt.runId === run.id,
522 ) &&
523 (candidate.status === "pending" || candidate.status === "running"),
524 )) {
525 events.push({
526 id: yield* allocateEventId(),
527 type: "provider-turn.updated",
528 threadId: projection.thread.id,
529 runId: run.id,
530 nodeId: providerTurn.nodeId,
531 providerInstanceId: run.providerInstanceId,
532 occurredAt: now,
533 payload: { ...providerTurn, status: "cancelled", completedAt: now },
534 });
535 }
536 for (const message of projection.messages.filter(
537 (candidate) => candidate.runId === run.id && candidate.streaming,
538 )) {
539 events.push({
540 id: yield* allocateEventId(),
541 type: "message.updated",
542 threadId: projection.thread.id,
543 runId: run.id,
544 ...(message.nodeId === null ? {} : { nodeId: message.nodeId }),
545 providerInstanceId: run.providerInstanceId,
546 occurredAt: now,
547 payload: { ...message, streaming: false, updatedAt: now },
548 });
549 }
550 for (const item of projection.turnItems.filter(
551 (candidate) =>
552 candidate.runId === run.id &&
553 (candidate.nodeId === null || !messageRequestNodeIds.has(candidate.nodeId)) &&
554 !isAppOwnedDelegationItem(candidate) &&
555 // A link card waits on the user, not the run, and answers by message.
556 candidate.type !== "link_request" &&
557 (candidate.status === "pending" ||
558 candidate.status === "running" ||
559 candidate.status === "waiting"),
560 )) {
561 // Cut native subagents do not resume; record them for the continuation to restart.
562 if (run.status === "waiting") recordCancelledBackgroundItem(item);
563 else if (item.type === "subagent" && item.origin === "provider_native")
564 recordCancelledBackgroundItem(item);
565 events.push({
566 id: yield* allocateEventId(),
567 type: "turn-item.updated",
568 threadId: projection.thread.id,
569 runId: run.id,
570 ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
571 providerInstanceId: run.providerInstanceId,
572 occurredAt: now,
573 payload: cancelledItem(item, now),
574 });
575 }
576 }
577 // Blocking waits die with their turn; let child results wake the parent continuation as async tasks.
578 const cutRunIds = new Set(runs.map((run) => run.id));
579 for (const task of projection.subagents ?? []) {
580 if (
581 task.origin !== "app_owned" ||
582 task.runId === null ||
583 !cutRunIds.has(task.runId) ||
584 task.completionWake !== "settled_only" ||
585 !isOrchestrationV2WorkActive(task.status)
586 )
587 continue;
588 events.push({
589 id: yield* allocateEventId(),
590 type: "subagent.updated",
591 threadId: projection.thread.id,
592 runId: task.runId,
593 nodeId: task.id,
594 driver: task.driver,
595 providerInstanceId: task.providerInstanceId,
596 occurredAt: now,
597 payload: { ...task, completionWake: "always", updatedAt: now },
598 });
599 }
600 const recoveredNonterminalRunIds = new Set(runs.map((run) => run.id));
601 const cancelledStaleNodeIds = new Set<string>();
602 for (const item of projection.turnItems ?? []) {
603 if (item.runId !== null && recoveredNonterminalRunIds.has(item.runId)) {
604 continue;
605 }
606 if (!isBackgroundCapableTurnItemType(item.type)) {
607 continue;
608 }
609 if (!isNonterminalTurnItemStatus(item.status) || isAppOwnedDelegationItem(item)) {
610 continue;
611 }
612 const providerInstanceId = resolveStaleBackgroundItemProviderInstanceId(item, projection);
613 recordCancelledBackgroundItem(item);
614 events.push({
615 id: yield* allocateEventId(),
616 type: "turn-item.updated",
617 threadId: projection.thread.id,
618 ...(item.runId === null ? {} : { runId: item.runId }),
619 ...(item.nodeId === null || item.nodeId === undefined ? {} : { nodeId: item.nodeId }),
620 providerInstanceId,
621 occurredAt: now,
622 payload: cancelledItem(item, now),
623 });
624 if (item.nodeId !== null && item.nodeId !== undefined) {
625 const staleItemNode = projection.nodes.find(
626 (candidate) =>
627 candidate.id === item.nodeId && isNonterminalTurnItemStatus(candidate.status),
628 );
629 if (staleItemNode !== undefined && !cancelledStaleNodeIds.has(staleItemNode.id)) {
630 cancelledStaleNodeIds.add(staleItemNode.id);
631 events.push({
632 id: yield* allocateEventId(),
633 type: "node.updated",
634 threadId: projection.thread.id,
635 ...(item.runId === null ? {} : { runId: item.runId }),
636 nodeId: staleItemNode.id,
637 providerInstanceId,
638 occurredAt: now,
639 payload: { ...staleItemNode, status: "cancelled", completedAt: now },
640 });
641 }
642 }
643 }
644 // No provider process survives the server; open native subagents can never report completion.
645 for (const subagent of projection.subagents ?? []) {
646 events.push(
647 ...(yield* endOrphanedNativeSubagent({
648 projection,
649 subagentId: subagent.id,
650 status: "cancelled",
651 now,
652 emitted: events,
653 allocateEventId,
654 })),
655 );
656 }
657 // Native subagent threads have no runs to settle their runless root turns.
658 events.push(
659 ...(yield* endRunlessRootTurns({
660 threadId: projection.thread.id,
661 providerInstanceId: projection.thread.providerInstanceId,
662 projection,
663 status: "cancelled",
664 now,
665 emitted: events,
666 allocateEventId,
667 })),
668 );
669 for (const providerThread of projection.providerThreads ?? []) {
670 const needsIdle = providerThread.status === "active";
671 const needsRosterClear = providerThreadHasPendingBackgroundTasks(providerThread);
672 if (!needsIdle && !needsRosterClear) {
673 continue;
674 }
675 if (providerThread.ownerNodeId === null) {
676 for (const task of providerThread.pendingBackgroundTasks ?? []) {
677 // A subagent already recorded covers the shells it started.
678 if (
679 cancelledBackgroundNativeIds.has(task.taskId) ||
680 (task.parentTaskId !== undefined &&
681 cancelledBackgroundNativeIds.has(task.parentTaskId))
682 )
683 continue;
684 cancelledBackgroundNativeIds.add(task.taskId);
685 recordCancelledBackgroundWork(providerThread.id, cancelledRosterTaskWork(task));
686 }
687 }
688 events.push({
689 id: yield* allocateEventId(),
690 type: "provider-thread.updated",
691 threadId: projection.thread.id,
692 driver: providerThread.driver,
693 providerInstanceId: providerThread.providerInstanceId,
694 occurredAt: now,
695 payload: {
696 ...providerThread,
697 status: needsIdle ? "idle" : providerThread.status,
698 pendingBackgroundTasks: [],
699 updatedAt: now,
700 },
701 });
702 }
703 for (const session of projection.providerSessions.filter(
704 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
705 )) {
706 events.push({
707 id: yield* allocateEventId(),
708 type: "provider-session.updated",
709 threadId: projection.thread.id,
710 driver: session.driver,
711 providerInstanceId: session.providerInstanceId,
712 occurredAt: now,
713 payload: { ...session, status: "stopped", updatedAt: now, lastError: null },
714 });
715 }
716 for (const [providerThreadId, work] of cancelledBackgroundWork) {
717 const noteRun = latestStartedRun(projection, providerThreadId);
718 if (noteRun === undefined) continue;
719 // Use a separate event; stale run snapshots can overwrite intervening lifecycle changes.
720 events.push({
721 id: yield* allocateEventId(),
722 type: "run.background-work-cancelled",
723 threadId: projection.thread.id,
724 runId: noteRun.id,
725 providerInstanceId: noteRun.providerInstanceId,
726 occurredAt: now,
727 payload: {
728 runId: noteRun.id,
729 restartCancelledBackgroundWork: mergeRestartCancelledBackgroundWork(
730 noteRun.restartCancelledBackgroundWork ?? [],
731 work,
732 ),
733 },
734 });
735 }
736 const continuationRun =
737 continueAfterRestart && trigger === "startup"
738 ? restartContinuationRun(
739 { ...projection, providerSessions: sessionsLiveAtStart(projection, stoppedThisPass) },
740 now,
741 )
742 : undefined;
743 const effects: Array<EffectOutbox.PendingOrchestrationEffectV2> = continuationRun
744 ? [
745 {
746 id: `effect:restart-continuation:${continuationRun.id}`,
747 commandId,
748 threadId: projection.thread.id,
749 request: { type: "provider-runtime.continue", sourceRunId: continuationRun.id },
750 },
751 ]
752 : [];
753 const stoppedSessions = projection.providerSessions.filter(
754 (candidate) => candidate.status !== "stopped" && candidate.status !== "error",
755 ).length;
756 let retiredEffects: number;
757 if (events.length === 0) {
758 const retiredEffectIds = yield* outbox
759 .cancelUnsettled({
760 threadId: projection.thread.id,
761 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
762 reason: detail,
763 })
764 .pipe(
765 Effect.mapError(
766 (cause) =>
767 new ProviderRuntimeRecoveryError({
768 operation: "reconcile",
769 threadId: projection.thread.id,
770 cause: { detail, cause },
771 }),
772 ),
773 );
774 yield* outbox.signalCancellations(retiredEffectIds);
775 retiredEffects = retiredEffectIds.length;
776 } else {
777 const result = yield* eventSink
778 .commitCommand({
779 commandId,
780 threadId: projection.thread.id,
781 commandType: "provider-runtime.reconcile",
782 acceptedAt: now,
783 events,
784 effects,
785 cancelUnsettledEffects: {
786 effectTypes: EffectOutbox.PROCESS_BOUND_EFFECT_TYPES,
787 reason: detail,
788 },
789 })
790 .pipe(
791 Effect.mapError(
792 (cause) =>
793 new ProviderRuntimeRecoveryError({
794 operation: "reconcile",
795 threadId: projection.thread.id,
796 cause,
797 }),
798 ),
799 );
800 retiredEffects = result.cancelledEffectCount;
801 }
802 return {
803 terminalizedRuns: runs.length,
804 stoppedSessions,
805 closedRequests: requests.length,
806 retiredEffects,
807 };
808 },
809 );
810
811 const reconcile = Effect.fn("ProviderRuntimeRecoveryService.reconcile")(function* (
812 trigger: "startup" | "shutdown",
813 ) {
814 const continueAfterRestart = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
815 const threadIds = yield* projections
816 .getRecoveryThreadIds("runtime")
817 .pipe(
818 Effect.mapError(
819 (cause) => new ProviderRuntimeRecoveryError({ operation: "read-projections", cause }),
820 ),
821 );
822 let terminalizedRuns = 0;
823 let stoppedSessions = 0;
824 let closedRequests = 0;
825 let retiredEffects = 0;
826 const stoppedThisPass = new Map<string, RecoverySession>();
827 for (const threadId of threadIds) {
828 const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
829 Effect.mapError(
830 (cause) =>
831 new ProviderRuntimeRecoveryError({
832 operation: "read-projections",
833 threadId,
834 cause,
835 }),
836 ),
837 );
838 const enabled =
839 continueAfterRestart !== null &&
840 resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
841 .continueThreadsAfterServerUpdate;
842 const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
843 for (const session of projection.providerSessions) {
844 if (session.status !== "stopped" && session.status !== "error") {
845 stoppedThisPass.set(session.id, session);
846 }
847 }
848 terminalizedRuns += result.terminalizedRuns;
849 stoppedSessions += result.stoppedSessions;
850 closedRequests += result.closedRequests;
851 retiredEffects += result.retiredEffects;
852 }
853 const outboxReconciliation = yield* outbox.reconcileAfterProcessLoss.pipe(
854 Effect.mapError(
855 (cause) => new ProviderRuntimeRecoveryError({ operation: "drain-outbox", cause }),
856 ),
857 );
858 return {
859 terminalizedRuns,
860 stoppedSessions,
861 closedRequests,
862 retiredEffects: retiredEffects + outboxReconciliation.cancelled,
863 requeuedEffects: outboxReconciliation.requeued,
864 } satisfies ProviderRuntimeReconciliationSummary;
865 });
866
867 const prepareForShutdown = Effect.gen(function* () {
868 const enabled = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null));
869 if (!enabled) return;
870 const threadIds = yield* projections.getRecoveryThreadIds("runtime");
871 for (const threadId of threadIds) {
872 yield* Effect.gen(function* () {
873 const projection = yield* projections.getRuntimeRecoveryProjection(threadId);
874 if (
875 !resolveProjectSettings(enabled, projection.thread.projectId).settings
876 .continueThreadsAfterServerUpdate
877 )
878 return;
879 const run = restartContinuationRun(projection, yield* DateTime.now);
880 if (!run) return;
881 const commandId = CommandId.make(`command:restart-prepare:${run.id}`);
882 yield* eventSink.writeWithEffects({
883 commandId,
884 events: [],
885 effects: [
886 {
887 id: `effect:restart-continuation:${run.id}`,
888 commandId,
889 threadId,
890 request: { type: "provider-runtime.continue", sourceRunId: run.id },
891 },
892 ],
893 });
894 }).pipe(
895 Effect.catchCauseIf(
896 (cause) => !Cause.hasInterruptsOnly(cause),
897 (cause) =>
898 Effect.logWarning("Failed to prepare a restart continuation", { threadId, cause }),
899 ),
900 );
901 }
902 }).pipe(
903 Effect.mapError((cause) => new ProviderRuntimeRecoveryError({ operation: "reconcile", cause })),
904 );
905
906 const recover = Effect.gen(function* () {
907 return (yield* reconcile("startup")) satisfies ProviderRuntimeRecoverySummary;
908 });
909
910 return ProviderRuntimeRecoveryService.of({ reconcile, prepareForShutdown, recover });
911});
912
913export const layer = Layer.effect(ProviderRuntimeRecoveryService, make);