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