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

ProviderRuntimeRecoveryService.ts

960 lines37.1 KB

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