@ferris1225/pi-subagents 4.2.5 → 4.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtime.ts CHANGED
@@ -1,312 +1,315 @@
1
- /**
2
- * Shared per-session runtime state for pi-subagents.
3
- *
4
- * The extension registers several tools (subagent, subagent_control/stop)
5
- * that share the background queue, completion batcher, abort controllers per
6
- * run, and settled-results store.
7
- * `createRuntime` builds those once per extension load and hands the same object
8
- * to every registration site, so state stays in one place without globals.
9
- */
10
-
11
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
- import { rmSync } from "node:fs";
13
- import { resolveSubagentConcurrency, BackgroundTaskQueue } from "./background.ts";
14
- import {
15
- completionGroupTriggersTurn,
16
- createCompletionBatcher,
17
- formatActiveRunsFooter,
18
- formatCompletionMessage,
19
- type CompletionBatcher,
20
- type CompletionMessageItem,
21
- } from "./completion.ts";
22
- import { type ThinkingLevel } from "./config.ts";
23
- import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord, type ThreadRecord } from "./durable.ts";
24
- import { isRunActiveStatus, monitor } from "./monitor.ts";
25
- import type { RpcRunControl } from "./rpc-run.ts";
26
- import type { StartBackgroundInternal } from "./thread-lifecycle.ts";
27
- import { isFailedResult, type SingleResult } from "./spawn.ts";
28
- import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "./worktree.ts";
29
-
30
- export type ThreadState =
31
- | "queued"
32
- | "resuming"
33
- | "running"
34
- | "interrupting"
35
- | "parked"
36
- | "completed"
37
- | "failed"
38
- | "stopped";
39
-
40
- export type ThreadLifecycleOperation = "park" | "resume" | "stop" | "settle";
41
-
42
- export interface SubagentThread {
43
- id: number;
44
- generation: number;
45
- agentName: string;
46
- task: string;
47
- /** Caller-facing cwd in the original worktree. */
48
- cwd: string;
49
- /** Actual child cwd (the equivalent path inside an isolated worktree). */
50
- executionCwd: string;
51
- thinkingLevel?: ThinkingLevel;
52
- isolation: IsolationMode;
53
- worktree?: WorktreeIsolation;
54
- state: ThreadState;
55
- control: RpcRunControl;
56
- queueController?: AbortController;
57
- /** Resolves only after the current generation's child process, isolation
58
- * finalization, and queue work have fully quiesced and released their
59
- * concurrency slot. */
60
- generationCompletion: Promise<void>;
61
- /** Synchronous CAS used by lifecycle controls across their async preflight. */
62
- lifecycleVersion: number;
63
- lifecycleOperation?: ThreadLifecycleOperation;
64
- sessionId?: string;
65
- sessionDir?: string;
66
- /** Active execution time accumulated across retained resume generations. */
67
- elapsedMs: number;
68
- /** Most recent generation result, retained for parked destructive-stop output. */
69
- lastResult?: SingleResult;
70
- /** A destructive stop retires context even if the active child settles later. */
71
- retireOnSettle?: boolean;
72
- retired?: boolean;
73
- /** Installed by dispatch so the control tool can restart the same logical id. */
74
- resume: (objective?: string, ctx?: ExtensionContext) => Promise<SingleResult>;
75
- /** Dispatch-owned, generation-guarded worktree settlement hook. Its apply
76
- * runs under the canonical original-repository lane. */
77
- finalizeIsolation: (generation: number, result?: SingleResult) => Promise<WorktreeFinalization | undefined>;
78
- /** Best-effort shutdown notification for retained integration artifacts. */
79
- notifyIsolationFailure?: (finalization: WorktreeFinalization) => void;
80
- isolationFailureNotified?: boolean;
81
- }
82
-
83
- export interface SubagentRuntime {
84
- configPath: string;
85
- backgroundQueue: BackgroundTaskQueue;
86
- /** Live parent tool names from ExtensionAPI, read again for each child launch. */
87
- getActiveTools: () => string[];
88
- /** False after session_shutdown; guards delivery and queue work. */
89
- sessionActive: boolean;
90
- /** The process-wide background dispatcher. Set at tool registration so
91
- * threads restored from the durable manifest can resume before any dispatch. */
92
- dispatcher?: StartBackgroundInternal;
93
- /** Resolves when the load-time durable restore pass has finished. Everything
94
- * that answers "which threads exist" awaits it the lookup tools, a fresh
95
- * dispatch before it allocates a run id, and the restored-thread notice — so
96
- * a reload can never report parked work as missing, or hand a new run an id a
97
- * record still owns, while the manifest is being read. Resolved by default;
98
- * `bootstrapDurableState` publishes the real pass. */
99
- durableRestore: Promise<void>;
100
- /** Run ids restored from the durable manifest at load; consumed by the
101
- * one-time session-start notice. */
102
- restoredRunIds: number[];
103
- restoredNotified: boolean;
104
- /** Deliver a batch of completion messages to the main window, waking it only
105
- * when the batch needs a turn. */
106
- sendCompletionGroup: (items: CompletionMessageItem[]) => void;
107
- completionBatcher: CompletionBatcher<CompletionMessageItem>;
108
- /** Abort controllers per active run, so subagent_stop can cancel a run in-turn. */
109
- runControllers: Map<number, AbortController>;
110
- /** Final results keyed by run id, so a dispatch with wait: true can hand the
111
- * model the actual result in-turn instead of it sleeping/polling for a
112
- * wake-up message. */
113
- settledRuns: Map<number, SingleResult>;
114
- settledListeners: Map<number, Set<(result: SingleResult) => void>>;
115
- registerRunResult: (runId: number, result: SingleResult) => void;
116
- /** Logical threads outlive process attempts and completed generations. */
117
- threads: Map<number, SubagentThread>;
118
- /** Resume setup that has claimed a thread but has not yet enqueued its
119
- * next generation. Shutdown invalidates these claims and waits for cleanup. */
120
- preflightOperations: Set<Promise<void>>;
121
- /** Every session directory retained for this parent session. */
122
- sessionDirs: Set<string>;
123
- retainSession: (result: Pick<SingleResult, "sessionDir">) => void;
124
- retireThreadSession: (thread: SubagentThread) => void;
125
- /** Flip sessionActive off and release all session-scoped resources. */
126
- shutdown: () => Promise<void>;
127
- }
128
-
129
- export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
130
- const backgroundQueue = new BackgroundTaskQueue(resolveSubagentConcurrency());
131
-
132
- const runtime: SubagentRuntime = {
133
- configPath,
134
- backgroundQueue,
135
- getActiveTools: () => pi.getActiveTools(),
136
- sessionActive: true,
137
- durableRestore: Promise.resolve(),
138
- restoredRunIds: [],
139
- restoredNotified: false,
140
- sendCompletionGroup: (items) => {
141
- if (!runtime.sessionActive || items.length === 0) return;
142
- // A result arriving for one run does not mean sibling runs are done.
143
- // Computing this at delivery (emit) time — not when the item was
144
- // pushed reflects the current monitor state, since finishing runs
145
- // are removed from the monitor before their completion is pushed.
146
- const active = monitor
147
- .getRuns()
148
- .filter((run) => isRunActiveStatus(run.status))
149
- .map((run) => ({
150
- id: run.id,
151
- agent: run.agent,
152
- label: run.label,
153
- ...(run.status === "queued" && run.waitReason ? { wait: run.waitReason } : {}),
154
- }));
155
- const message = {
156
- customType: "subagent-result",
157
- content: formatCompletionMessage(items) + formatActiveRunsFooter(active),
158
- display: true,
159
- };
160
- if (completionGroupTriggersTurn(items)) {
161
- // steer: the result is injected after the current tool call even mid-turn,
162
- // or starts a new turn when idle. followUp would sit in the queue until the
163
- // whole turn ends — a main agent waiting for the result (sleep/poll) would
164
- // never see it delivered, which is exactly the "returned but never woken"
165
- // failure mode.
166
- pi.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
167
- } else {
168
- // No-wake delivery: nextTurn rides along with the next user turn and can
169
- // never start a continuation by itself. followUp would auto-continue
170
- // whenever pi is already streaming, defeating the opt-out.
171
- pi.sendMessage(message, { deliverAs: "nextTurn" });
172
- }
173
- },
174
- completionBatcher: undefined as unknown as CompletionBatcher<CompletionMessageItem>,
175
- runControllers: new Map<number, AbortController>(),
176
- settledRuns: new Map<number, SingleResult>(),
177
- settledListeners: new Map<number, Set<(result: SingleResult) => void>>(),
178
- threads: new Map<number, SubagentThread>(),
179
- preflightOperations: new Set<Promise<void>>(),
180
- sessionDirs: new Set<string>(),
181
- retainSession: (result) => {
182
- if (result.sessionDir) runtime.sessionDirs.add(result.sessionDir);
183
- },
184
- retireThreadSession: (thread) => {
185
- thread.retired = true;
186
- if (!thread.sessionDir) return;
187
- const sessionDir = thread.sessionDir;
188
- try {
189
- rmSync(sessionDir, { recursive: true, force: true });
190
- runtime.sessionDirs.delete(sessionDir);
191
- thread.sessionDir = undefined;
192
- thread.sessionId = undefined;
193
- } catch {
194
- /* best-effort; shutdown retries the still-retained directory */
195
- }
196
- },
197
- registerRunResult: (runId, result) => {
198
- runtime.settledRuns.set(runId, result);
199
- const listeners = runtime.settledListeners.get(runId);
200
- if (listeners) {
201
- runtime.settledListeners.delete(runId);
202
- for (const listener of listeners) {
203
- try {
204
- listener(result);
205
- } catch {
206
- /* listener errors must never break settling */
207
- }
208
- }
209
- }
210
- },
211
- shutdown: async () => {
212
- if (!runtime.sessionActive) return;
213
- runtime.sessionActive = false;
214
- const shutdownThreads = [...runtime.threads.values()];
215
- const liveStates = new Set(["queued", "resuming", "running", "interrupting"]);
216
- const previousStates = new Map(shutdownThreads.map((thread) => [thread.id, thread.state] as const));
217
- // Invalidate every lifecycle claim synchronously before the first await.
218
- // Resume preflight checks both this version and sessionActive, then
219
- // cleans any worktree/session it created before resolving its tracker.
220
- // A generation already inside its settlement keeps its own claim: it
221
- // finalizes its worktree and persists its terminal record itself.
222
- const interrupting = shutdownThreads.filter((thread) =>
223
- !thread.retired &&
224
- thread.lifecycleOperation !== "settle" &&
225
- liveStates.has(thread.state),
226
- );
227
- for (const thread of shutdownThreads) {
228
- thread.lifecycleVersion++;
229
- if (thread.retired) {
230
- thread.lifecycleOperation = "stop";
231
- continue;
232
- }
233
- if (thread.lifecycleOperation === "settle") continue;
234
- thread.lifecycleOperation = "stop";
235
- // Deliberately NOT retireOnSettle: shutdown interrupts to the last
236
- // checkpoint but keeps the session/worktree resumable across reload.
237
- thread.retireOnSettle = false;
238
- if (liveStates.has(thread.state)) thread.state = "stopped";
239
- }
240
- const preflights = [...runtime.preflightOperations];
241
- runtime.completionBatcher.dispose();
242
- runtime.backgroundQueue.cancelAll();
243
- // Await live RPC process-tree cleanup and continuation preflight rollback
244
- // before persisting records or releasing ownership maps.
245
- await Promise.all([
246
- Promise.all(
247
- interrupting.map((thread) =>
248
- thread.control.stop("Parent session shut down").catch(() => undefined),
249
- ),
250
- ),
251
- Promise.allSettled(preflights),
252
- runtime.backgroundQueue.waitForIdle(),
253
- ]);
254
- // Only interrupted (parked) threads stay resumable across reloads:
255
- // each keeps its durable record and retained artifacts. Settled
256
- // threads drop their record — the manifest exists only while
257
- // unfinished work needs it and their sessions are deleted now. A
258
- // thread whose settlement finished during the wait above already
259
- // wrote (or removed) its own record; the lastResult-derived state
260
- // below matches it.
261
- const settled: Array<{ runId: number; cwd: string }> = [];
262
- const records: ThreadRecord[] = [];
263
- for (const thread of runtime.threads.values()) {
264
- if (thread.retired) continue;
265
- const previous = previousStates.get(thread.id) ?? thread.state;
266
- let state: "parked" | "completed" | "failed";
267
- if (previous === "completed" || previous === "failed") {
268
- state = previous;
269
- } else if (thread.lifecycleOperation === "settle" && thread.lastResult) {
270
- state = isFailedResult(thread.lastResult) ? "failed" : "completed";
271
- } else {
272
- state = "parked";
273
- }
274
- if (state === "parked") records.push(threadRecordFromThread(thread, state));
275
- else settled.push({ runId: thread.id, cwd: thread.cwd });
276
- }
277
- await Promise.all([
278
- ...records.map((record) => upsertThreadRecord(runtime.configPath, record).catch(() => undefined)),
279
- ...settled.map(({ runId, cwd }) => removeThreadRecord(runtime.configPath, runId, cwd).catch(() => undefined)),
280
- ]);
281
- // Retained-failure recovery records are persisted by the finalization
282
- // itself; shutdown only drops sessions no record claims anymore.
283
- const referenced = new Set(
284
- records.flatMap((record) =>
285
- [record.sessionDir, record.worktree?.tempDir].filter(Boolean) as string[],
286
- ),
287
- );
288
- for (const sessionDir of runtime.sessionDirs) {
289
- if (referenced.has(sessionDir)) continue;
290
- try {
291
- rmSync(sessionDir, { recursive: true, force: true });
292
- } catch {
293
- /* best-effort; the state-root sweep catches leftovers later */
294
- }
295
- }
296
- runtime.settledRuns.clear();
297
- runtime.settledListeners.clear();
298
- runtime.runControllers.clear();
299
- // sessionDirs entries still referenced by records stay owned by the
300
- // manifest; the next process re-registers them at restore.
301
- runtime.sessionDirs.clear();
302
- runtime.preflightOperations.clear();
303
- runtime.threads.clear();
304
- monitor.clear();
305
- },
306
- };
307
-
308
- runtime.completionBatcher = createCompletionBatcher<CompletionMessageItem>({
309
- emit: runtime.sendCompletionGroup,
310
- });
311
- return runtime;
312
- }
1
+ /**
2
+ * Shared per-session runtime state for pi-subagents.
3
+ *
4
+ * The extension registers several tools (subagent, subagent_control/stop)
5
+ * that share the background queue, completion batcher, abort controllers per
6
+ * run, and settled-results store.
7
+ * `createRuntime` builds those once per extension load and hands the same object
8
+ * to every registration site, so state stays in one place without globals.
9
+ */
10
+
11
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
+ import { rmSync } from "node:fs";
13
+ import { resolveSubagentConcurrency, BackgroundTaskQueue } from "./background.ts";
14
+ import {
15
+ completionGroupTriggersTurn,
16
+ createCompletionBatcher,
17
+ formatActiveRunsFooter,
18
+ formatCompletionMessage,
19
+ type CompletionBatcher,
20
+ type CompletionMessageItem,
21
+ } from "./completion.ts";
22
+ import { type ThinkingLevel } from "./config.ts";
23
+ import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord, type ThreadRecord } from "./durable.ts";
24
+ import { isRunActiveStatus, monitor } from "./monitor.ts";
25
+ import type { RpcRunControl } from "./rpc-run.ts";
26
+ import type { StartBackgroundInternal } from "./thread-lifecycle.ts";
27
+ import { isFailedResult, type SingleResult } from "./spawn.ts";
28
+ import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "./worktree.ts";
29
+
30
+ export type ThreadState =
31
+ | "queued"
32
+ | "resuming"
33
+ | "running"
34
+ | "interrupting"
35
+ | "parked"
36
+ | "completed"
37
+ | "failed"
38
+ | "stopped";
39
+
40
+ export type ThreadLifecycleOperation = "park" | "resume" | "stop" | "settle";
41
+
42
+ export interface SubagentThread {
43
+ id: number;
44
+ generation: number;
45
+ agentName: string;
46
+ task: string;
47
+ /** Caller-facing cwd in the original worktree. */
48
+ cwd: string;
49
+ /** Actual child cwd (the equivalent path inside an isolated worktree). */
50
+ executionCwd: string;
51
+ /** Level actually used, after clamping to the effective model's capability. */
52
+ thinkingLevel?: ThinkingLevel;
53
+ /** Level the dispatch asked for, before clamping; replayed on every resume. */
54
+ requestedThinkingLevel?: ThinkingLevel;
55
+ isolation: IsolationMode;
56
+ worktree?: WorktreeIsolation;
57
+ state: ThreadState;
58
+ control: RpcRunControl;
59
+ queueController?: AbortController;
60
+ /** Resolves only after the current generation's child process, isolation
61
+ * finalization, and queue work have fully quiesced and released their
62
+ * concurrency slot. */
63
+ generationCompletion: Promise<void>;
64
+ /** Synchronous CAS used by lifecycle controls across their async preflight. */
65
+ lifecycleVersion: number;
66
+ lifecycleOperation?: ThreadLifecycleOperation;
67
+ sessionId?: string;
68
+ sessionDir?: string;
69
+ /** Active execution time accumulated across retained resume generations. */
70
+ elapsedMs: number;
71
+ /** Most recent generation result, retained for parked destructive-stop output. */
72
+ lastResult?: SingleResult;
73
+ /** A destructive stop retires context even if the active child settles later. */
74
+ retireOnSettle?: boolean;
75
+ retired?: boolean;
76
+ /** Installed by dispatch so the control tool can restart the same logical id. */
77
+ resume: (objective?: string, ctx?: ExtensionContext) => Promise<SingleResult>;
78
+ /** Dispatch-owned, generation-guarded worktree settlement hook. Its apply
79
+ * runs under the canonical original-repository lane. */
80
+ finalizeIsolation: (generation: number, result?: SingleResult) => Promise<WorktreeFinalization | undefined>;
81
+ /** Best-effort shutdown notification for retained integration artifacts. */
82
+ notifyIsolationFailure?: (finalization: WorktreeFinalization) => void;
83
+ isolationFailureNotified?: boolean;
84
+ }
85
+
86
+ export interface SubagentRuntime {
87
+ configPath: string;
88
+ backgroundQueue: BackgroundTaskQueue;
89
+ /** Live parent tool names from ExtensionAPI, read again for each child launch. */
90
+ getActiveTools: () => string[];
91
+ /** False after session_shutdown; guards delivery and queue work. */
92
+ sessionActive: boolean;
93
+ /** The process-wide background dispatcher. Set at tool registration so
94
+ * threads restored from the durable manifest can resume before any dispatch. */
95
+ dispatcher?: StartBackgroundInternal;
96
+ /** Resolves when the load-time durable restore pass has finished. Everything
97
+ * that answers "which threads exist" awaits it the lookup tools, a fresh
98
+ * dispatch before it allocates a run id, and the restored-thread notice — so
99
+ * a reload can never report parked work as missing, or hand a new run an id a
100
+ * record still owns, while the manifest is being read. Resolved by default;
101
+ * `bootstrapDurableState` publishes the real pass. */
102
+ durableRestore: Promise<void>;
103
+ /** Run ids restored from the durable manifest at load; consumed by the
104
+ * one-time session-start notice. */
105
+ restoredRunIds: number[];
106
+ restoredNotified: boolean;
107
+ /** Deliver a batch of completion messages to the main window, waking it only
108
+ * when the batch needs a turn. */
109
+ sendCompletionGroup: (items: CompletionMessageItem[]) => void;
110
+ completionBatcher: CompletionBatcher<CompletionMessageItem>;
111
+ /** Abort controllers per active run, so subagent_stop can cancel a run in-turn. */
112
+ runControllers: Map<number, AbortController>;
113
+ /** Final results keyed by run id, so a dispatch with wait: true can hand the
114
+ * model the actual result in-turn instead of it sleeping/polling for a
115
+ * wake-up message. */
116
+ settledRuns: Map<number, SingleResult>;
117
+ settledListeners: Map<number, Set<(result: SingleResult) => void>>;
118
+ registerRunResult: (runId: number, result: SingleResult) => void;
119
+ /** Logical threads outlive process attempts and completed generations. */
120
+ threads: Map<number, SubagentThread>;
121
+ /** Resume setup that has claimed a thread but has not yet enqueued its
122
+ * next generation. Shutdown invalidates these claims and waits for cleanup. */
123
+ preflightOperations: Set<Promise<void>>;
124
+ /** Every session directory retained for this parent session. */
125
+ sessionDirs: Set<string>;
126
+ retainSession: (result: Pick<SingleResult, "sessionDir">) => void;
127
+ retireThreadSession: (thread: SubagentThread) => void;
128
+ /** Flip sessionActive off and release all session-scoped resources. */
129
+ shutdown: () => Promise<void>;
130
+ }
131
+
132
+ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
133
+ const backgroundQueue = new BackgroundTaskQueue(resolveSubagentConcurrency());
134
+
135
+ const runtime: SubagentRuntime = {
136
+ configPath,
137
+ backgroundQueue,
138
+ getActiveTools: () => pi.getActiveTools(),
139
+ sessionActive: true,
140
+ durableRestore: Promise.resolve(),
141
+ restoredRunIds: [],
142
+ restoredNotified: false,
143
+ sendCompletionGroup: (items) => {
144
+ if (!runtime.sessionActive || items.length === 0) return;
145
+ // A result arriving for one run does not mean sibling runs are done.
146
+ // Computing this at delivery (emit) time — not when the item was
147
+ // pushed — reflects the current monitor state, since finishing runs
148
+ // are removed from the monitor before their completion is pushed.
149
+ const active = monitor
150
+ .getRuns()
151
+ .filter((run) => isRunActiveStatus(run.status))
152
+ .map((run) => ({
153
+ id: run.id,
154
+ agent: run.agent,
155
+ label: run.label,
156
+ ...(run.status === "queued" && run.waitReason ? { wait: run.waitReason } : {}),
157
+ }));
158
+ const message = {
159
+ customType: "subagent-result",
160
+ content: formatCompletionMessage(items) + formatActiveRunsFooter(active),
161
+ display: true,
162
+ };
163
+ if (completionGroupTriggersTurn(items)) {
164
+ // steer: the result is injected after the current tool call even mid-turn,
165
+ // or starts a new turn when idle. followUp would sit in the queue until the
166
+ // whole turn ends a main agent waiting for the result (sleep/poll) would
167
+ // never see it delivered, which is exactly the "returned but never woken"
168
+ // failure mode.
169
+ pi.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
170
+ } else {
171
+ // No-wake delivery: nextTurn rides along with the next user turn and can
172
+ // never start a continuation by itself. followUp would auto-continue
173
+ // whenever pi is already streaming, defeating the opt-out.
174
+ pi.sendMessage(message, { deliverAs: "nextTurn" });
175
+ }
176
+ },
177
+ completionBatcher: undefined as unknown as CompletionBatcher<CompletionMessageItem>,
178
+ runControllers: new Map<number, AbortController>(),
179
+ settledRuns: new Map<number, SingleResult>(),
180
+ settledListeners: new Map<number, Set<(result: SingleResult) => void>>(),
181
+ threads: new Map<number, SubagentThread>(),
182
+ preflightOperations: new Set<Promise<void>>(),
183
+ sessionDirs: new Set<string>(),
184
+ retainSession: (result) => {
185
+ if (result.sessionDir) runtime.sessionDirs.add(result.sessionDir);
186
+ },
187
+ retireThreadSession: (thread) => {
188
+ thread.retired = true;
189
+ if (!thread.sessionDir) return;
190
+ const sessionDir = thread.sessionDir;
191
+ try {
192
+ rmSync(sessionDir, { recursive: true, force: true });
193
+ runtime.sessionDirs.delete(sessionDir);
194
+ thread.sessionDir = undefined;
195
+ thread.sessionId = undefined;
196
+ } catch {
197
+ /* best-effort; shutdown retries the still-retained directory */
198
+ }
199
+ },
200
+ registerRunResult: (runId, result) => {
201
+ runtime.settledRuns.set(runId, result);
202
+ const listeners = runtime.settledListeners.get(runId);
203
+ if (listeners) {
204
+ runtime.settledListeners.delete(runId);
205
+ for (const listener of listeners) {
206
+ try {
207
+ listener(result);
208
+ } catch {
209
+ /* listener errors must never break settling */
210
+ }
211
+ }
212
+ }
213
+ },
214
+ shutdown: async () => {
215
+ if (!runtime.sessionActive) return;
216
+ runtime.sessionActive = false;
217
+ const shutdownThreads = [...runtime.threads.values()];
218
+ const liveStates = new Set(["queued", "resuming", "running", "interrupting"]);
219
+ const previousStates = new Map(shutdownThreads.map((thread) => [thread.id, thread.state] as const));
220
+ // Invalidate every lifecycle claim synchronously before the first await.
221
+ // Resume preflight checks both this version and sessionActive, then
222
+ // cleans any worktree/session it created before resolving its tracker.
223
+ // A generation already inside its settlement keeps its own claim: it
224
+ // finalizes its worktree and persists its terminal record itself.
225
+ const interrupting = shutdownThreads.filter((thread) =>
226
+ !thread.retired &&
227
+ thread.lifecycleOperation !== "settle" &&
228
+ liveStates.has(thread.state),
229
+ );
230
+ for (const thread of shutdownThreads) {
231
+ thread.lifecycleVersion++;
232
+ if (thread.retired) {
233
+ thread.lifecycleOperation = "stop";
234
+ continue;
235
+ }
236
+ if (thread.lifecycleOperation === "settle") continue;
237
+ thread.lifecycleOperation = "stop";
238
+ // Deliberately NOT retireOnSettle: shutdown interrupts to the last
239
+ // checkpoint but keeps the session/worktree resumable across reload.
240
+ thread.retireOnSettle = false;
241
+ if (liveStates.has(thread.state)) thread.state = "stopped";
242
+ }
243
+ const preflights = [...runtime.preflightOperations];
244
+ runtime.completionBatcher.dispose();
245
+ runtime.backgroundQueue.cancelAll();
246
+ // Await live RPC process-tree cleanup and continuation preflight rollback
247
+ // before persisting records or releasing ownership maps.
248
+ await Promise.all([
249
+ Promise.all(
250
+ interrupting.map((thread) =>
251
+ thread.control.stop("Parent session shut down").catch(() => undefined),
252
+ ),
253
+ ),
254
+ Promise.allSettled(preflights),
255
+ runtime.backgroundQueue.waitForIdle(),
256
+ ]);
257
+ // Only interrupted (parked) threads stay resumable across reloads:
258
+ // each keeps its durable record and retained artifacts. Settled
259
+ // threads drop their record the manifest exists only while
260
+ // unfinished work needs it — and their sessions are deleted now. A
261
+ // thread whose settlement finished during the wait above already
262
+ // wrote (or removed) its own record; the lastResult-derived state
263
+ // below matches it.
264
+ const settled: Array<{ runId: number; cwd: string }> = [];
265
+ const records: ThreadRecord[] = [];
266
+ for (const thread of runtime.threads.values()) {
267
+ if (thread.retired) continue;
268
+ const previous = previousStates.get(thread.id) ?? thread.state;
269
+ let state: "parked" | "completed" | "failed";
270
+ if (previous === "completed" || previous === "failed") {
271
+ state = previous;
272
+ } else if (thread.lifecycleOperation === "settle" && thread.lastResult) {
273
+ state = isFailedResult(thread.lastResult) ? "failed" : "completed";
274
+ } else {
275
+ state = "parked";
276
+ }
277
+ if (state === "parked") records.push(threadRecordFromThread(thread, state));
278
+ else settled.push({ runId: thread.id, cwd: thread.cwd });
279
+ }
280
+ await Promise.all([
281
+ ...records.map((record) => upsertThreadRecord(runtime.configPath, record).catch(() => undefined)),
282
+ ...settled.map(({ runId, cwd }) => removeThreadRecord(runtime.configPath, runId, cwd).catch(() => undefined)),
283
+ ]);
284
+ // Retained-failure recovery records are persisted by the finalization
285
+ // itself; shutdown only drops sessions no record claims anymore.
286
+ const referenced = new Set(
287
+ records.flatMap((record) =>
288
+ [record.sessionDir, record.worktree?.tempDir].filter(Boolean) as string[],
289
+ ),
290
+ );
291
+ for (const sessionDir of runtime.sessionDirs) {
292
+ if (referenced.has(sessionDir)) continue;
293
+ try {
294
+ rmSync(sessionDir, { recursive: true, force: true });
295
+ } catch {
296
+ /* best-effort; the state-root sweep catches leftovers later */
297
+ }
298
+ }
299
+ runtime.settledRuns.clear();
300
+ runtime.settledListeners.clear();
301
+ runtime.runControllers.clear();
302
+ // sessionDirs entries still referenced by records stay owned by the
303
+ // manifest; the next process re-registers them at restore.
304
+ runtime.sessionDirs.clear();
305
+ runtime.preflightOperations.clear();
306
+ runtime.threads.clear();
307
+ monitor.clear();
308
+ },
309
+ };
310
+
311
+ runtime.completionBatcher = createCompletionBatcher<CompletionMessageItem>({
312
+ emit: runtime.sendCompletionGroup,
313
+ });
314
+ return runtime;
315
+ }