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