@timmyjl12/pi-subagents 0.0.0-stage → 0.21.0

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.
Files changed (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,3312 @@
1
+ /**
2
+ * agent-manager.ts — Tracks agents, background execution, resume support.
3
+ *
4
+ * There are two independent concurrency pools, never one:
5
+ *
6
+ * - Background (`maxConcurrent`, default 10) bounds detached agents.
7
+ * - Foreground (`maxConcurrentForeground`, default 0 = unlimited) bounds
8
+ * agents a caller is blocking on inline — `spawnAndWait`.
9
+ *
10
+ * Independent by design: a foreground agent blocks the parent anyway, so
11
+ * charging it to the background pool would let a saturated pool starve the main
12
+ * session of work it could have done itself. Excess agents in either pool are
13
+ * queued and auto-started as slots free up. Nested children take no slot in
14
+ * either — see `occupiesPoolSlot` / `occupiesForegroundSlot`.
15
+ */
16
+
17
+ import { randomUUID } from "node:crypto";
18
+ import { statSync } from "node:fs";
19
+ import { isAbsolute, resolve } from "node:path";
20
+ import type { Model } from "@earendil-works/pi-ai";
21
+ import type { AgentSession, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
22
+ import { resumeAgent, runAgent, type ToolActivity } from "./agent-runner.ts";
23
+ import { cloneAgentDefinition, getAgentConfig } from "./agent-types.ts";
24
+ import { type ChildShutdownOutcome, type ChildShutdownStatus, shutdownChildSession } from "./child-session-shutdown.ts";
25
+ import { assignHandle, handleBase } from "./mention.ts";
26
+ import { describeModel } from "./model-resolver.ts";
27
+ import type { ArchivedReportReader } from "./nested-tools.ts";
28
+ import { isChildRequestActive } from "./recovery.ts";
29
+ import type { AgentConfig, AgentInvocation, AgentRecord, AgentTombstone, IsolationMode, MentionResolution, SubagentType, ThinkingLevel } from "./types.ts";
30
+ import { releaseToolProgress } from "./ui/tool-progress.ts";
31
+ import { addUsage, type LifetimeUsage } from "./usage.ts";
32
+ import type { CompiledSchema } from "./workflow/json-schema.ts";
33
+ import { cleanupWorktree, createWorktree, isWorktreeIsolationEnabled, pruneWorktrees, type WorktreeInfo } from "./worktree.ts";
34
+
35
+ export type OnAgentComplete = (record: AgentRecord) => void;
36
+ export type OnAgentStart = (record: AgentRecord) => void;
37
+ export type OnAgentCompact = (record: AgentRecord, info: CompactionInfo) => void;
38
+ /**
39
+ * Fired once per assistant `message_end`, for EVERY agent this manager owns —
40
+ * top-level and nested alike, spawns and resumes. The one place where each
41
+ * message is seen exactly once: `AgentRecord.lifetimeUsage` is deliberately
42
+ * double-booked into ancestors (see `nested-tools.ts`) so a hidden child's spend
43
+ * shows up on the record a human can see, which makes those records useless as
44
+ * a basis for anything that must not count a message twice — parent-session
45
+ * accounting above all.
46
+ */
47
+ export type OnAgentUsage = (record: AgentRecord, usage: LifetimeUsage) => void;
48
+ export type CompactionInfo = { reason: "manual" | "threshold" | "overflow"; tokensBefore: number };
49
+
50
+ /**
51
+ * Purpose-specific hook for durable reports.
52
+ *
53
+ * Deliberately not a general observer: the manager calls it exactly once per
54
+ * terminal generation, synchronously, BEFORE any completion notification or
55
+ * other caller callback can re-enter `resume()`. An adapter must therefore
56
+ * copy whatever it keeps immediately — a report store does — rather than hold
57
+ * the live record, whose `status`/`result` a resume can overwrite.
58
+ *
59
+ * Unlike `OnAgentComplete`, this fires for foreground resumes (which have no
60
+ * completion notification), queued cancellations and shutdown sweeps.
61
+ */
62
+ export interface AgentReportArchiver {
63
+ save(record: AgentRecord): void;
64
+ }
65
+
66
+ /** A teardown that did not prove quiescence; cleanup must keep its paths protected. */
67
+ export interface UncertainTeardown {
68
+ agentId: string;
69
+ /**
70
+ * `pending` means the bounded teardown is still in flight. It is protection,
71
+ * not an outcome: cleanup must treat it exactly like a timeout.
72
+ */
73
+ status: ChildShutdownStatus | "pending";
74
+ /** Whether the unfinished work is child-session teardown or a run finalizer. */
75
+ phase?: "session" | "run";
76
+ /** Per-session-instance identity; never reuse this across reopen attempts. */
77
+ teardownId?: string;
78
+ sessionFile?: string;
79
+ sessionId?: string;
80
+ rootSessionId?: string;
81
+ rootCwd?: string;
82
+ rootSessionFile?: string;
83
+ reason?: string;
84
+ at: number;
85
+ }
86
+
87
+ /** Result of disposing a manager: what was torn down and what remains uncertain. */
88
+ export interface AgentManagerShutdown {
89
+ status: ChildShutdownStatus;
90
+ uncertain: UncertainTeardown[];
91
+ }
92
+
93
+ /**
94
+ * The manager half of a cleanup preparation pass: which requested reports and
95
+ * session files proved quiescent, and an explicit reason for every one that did
96
+ * not. Each requested item appears on exactly one side.
97
+ */
98
+ export interface AgentCleanupPreparation {
99
+ readyAgentIds: string[];
100
+ blockedAgentIds: Record<string, string>;
101
+ readySessionFiles: string[];
102
+ blockedSessionFiles: Record<string, string>;
103
+ }
104
+
105
+ /**
106
+ * Default max concurrent background agents.
107
+ *
108
+ * Raised from 4 when top-level spawns started defaulting to background
109
+ * (`backgroundByDefault`): foreground agents bypass this pool entirely, so
110
+ * while foreground was the default a fan-out of six ran six. With background
111
+ * as the default every top-level agent takes a slot, and a limit of 4 would
112
+ * have silently queued the tail of exactly the parallel fan-outs the `Agent`
113
+ * tool description tells the model to send.
114
+ */
115
+ const DEFAULT_MAX_CONCURRENT = 10;
116
+
117
+ /**
118
+ * Default max concurrent foreground (blocking) agents — `0` = unlimited, the
119
+ * extension's existing convention for "no ceiling" (`defaultMaxTurns`).
120
+ *
121
+ * Off by default because nothing here ever bounded foreground work, and pi
122
+ * dispatches a message's tool calls through `Promise.all`, so an unqualified
123
+ * fan-out of blocking `Agent` calls has always run all at once. Users who want
124
+ * it bounded — chiefly local models, where parallel agents thrash the prompt
125
+ * cache (#253) — opt in; everyone else keeps today's behaviour exactly.
126
+ */
127
+ const DEFAULT_MAX_CONCURRENT_FOREGROUND = 0;
128
+
129
+ /**
130
+ * How many evicted agents stay addressable by name. Only a bound on memory —
131
+ * a session that spawns hundreds of agents shouldn't retain every one — and
132
+ * far above the handful anyone keeps in their head.
133
+ */
134
+ const MAX_TOMBSTONES = 100;
135
+
136
+ /**
137
+ * Bound on the COMMON shutdown window: SDK session handlers and run/startup/
138
+ * finalizer promises are awaited together for at most this long. Past it, the
139
+ * manager reports explicit uncertainty rather than claiming quiescence.
140
+ */
141
+ const MANAGER_SHUTDOWN_DEADLINE_MS = 3_000;
142
+
143
+ /**
144
+ * Path identity for cleanup readiness. Deliberately the same normalization the
145
+ * report store uses for its lock and inventory keys — absolute, case-folded on
146
+ * Windows — so the manager and the cleanup backend never disagree about whether
147
+ * two requested history files are the same file. No filesystem lookup: symlink
148
+ * proof and deletion belong to the backend.
149
+ */
150
+ function cleanupPathKey(path: string): string {
151
+ const resolved = resolve(path);
152
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
153
+ }
154
+
155
+ /** Plain identity a teardown must keep even after its runtime record is gone. */
156
+ interface TeardownIdentity {
157
+ agentId: string;
158
+ sessionFile?: string;
159
+ sessionId?: string;
160
+ rootSessionId?: string;
161
+ rootCwd?: string;
162
+ rootSessionFile?: string;
163
+ }
164
+
165
+ interface TrackedTeardown extends TeardownIdentity {
166
+ id: string;
167
+ phase: "session" | "run";
168
+ status: ChildShutdownStatus | "pending";
169
+ reason?: string;
170
+ at: number;
171
+ /** In-memory only: never exported and never written to a report store. */
172
+ session?: AgentSession;
173
+ promise?: Promise<ChildShutdownOutcome>;
174
+ }
175
+
176
+ /**
177
+ * One readiness snapshot; not mutated after capture. The pre-await instance is
178
+ * kept only to compare which sessions were already attached.
179
+ */
180
+ interface CleanupGuardSnapshot {
181
+ records: AgentRecord[];
182
+ rows: TrackedTeardown[];
183
+ /** Sessions of records whose work is not quiescent. */
184
+ busySessions: Set<AgentSession>;
185
+ /** Every session attached to a record at snapshot time. */
186
+ attachedSessions: Map<AgentRecord, AgentSession>;
187
+ }
188
+
189
+ /** One unique SDK session instance a cleanup pass has to tear down. */
190
+ interface CleanupTeardownJob {
191
+ record: AgentRecord;
192
+ session: AgentSession;
193
+ agentIds: Set<string>;
194
+ sessionFiles: Set<string>;
195
+ }
196
+
197
+ /**
198
+ * A session created before `onSessionCreated`. Teardown of this instance must
199
+ * wait for the active bind/session_start to settle: an SDK emit during that
200
+ * window can run before a late handler allocates the resource it would clean.
201
+ */
202
+ interface AllocationState {
203
+ session: AgentSession;
204
+ identity: TeardownIdentity;
205
+ ready: Promise<void>;
206
+ resolveReady: () => void;
207
+ settled: boolean;
208
+ }
209
+
210
+ /**
211
+ * Validate a caller-supplied SpawnOptions.cwd. `undefined`/`null` mean "unset"
212
+ * (parent cwd). Anything else must be an absolute path to an existing
213
+ * directory — curated errors instead of TypeErrors from path/fs internals
214
+ * (RPC callers send arbitrary JSON: null, numbers, file paths).
215
+ */
216
+ function assertValidSpawnCwd(cwd: unknown): asserts cwd is string | undefined | null {
217
+ if (cwd == null) return;
218
+ if (typeof cwd !== "string" || !isAbsolute(cwd)) {
219
+ throw new Error(`SpawnOptions.cwd must be an absolute path: "${String(cwd)}"`);
220
+ }
221
+ let isDirectory = false;
222
+ try {
223
+ isDirectory = statSync(cwd).isDirectory();
224
+ } catch {
225
+ throw new Error(`SpawnOptions.cwd does not exist: "${cwd}"`);
226
+ }
227
+ if (!isDirectory) {
228
+ throw new Error(`SpawnOptions.cwd is not a directory: "${cwd}"`);
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Whether a record occupies one of the `maxConcurrent` background slots.
234
+ * Nested children don't: their parent already holds a slot, so counting (and
235
+ * therefore queueing) them would deadlock a parent that waits on its own child.
236
+ *
237
+ * Note this bounds nothing horizontally — the depth cap limits how DEEP nesting
238
+ * goes, not how WIDE. A parent's only limit on concurrent children is that each
239
+ * spawn costs it a turn, which is unbounded when max turns is unlimited.
240
+ */
241
+ function occupiesPoolSlot(
242
+ record: Pick<AgentRecord, "isBackground" | "parentAgentId" | "workflowId">,
243
+ ): boolean {
244
+ return !!record.isBackground && isTopLevelAgent(record);
245
+ }
246
+
247
+ /**
248
+ * Whether a record is one of the session's own agents, rather than something
249
+ * another agent or a workflow owns.
250
+ *
251
+ * The single definition behind every user-facing surface — the fleet list, the
252
+ * widget, the `/agents` menus, `@handle` resolution, and the completion events
253
+ * and session entries. An owned child reports through its owner, so surfacing
254
+ * it separately would double-count the same work in the places a person reads.
255
+ */
256
+ export function isTopLevelAgent(
257
+ record: Pick<AgentRecord, "parentAgentId" | "workflowId">,
258
+ ): boolean {
259
+ return record.parentAgentId === undefined && record.workflowId === undefined;
260
+ }
261
+
262
+ /**
263
+ * Whether a record occupies one of the `maxConcurrentForeground` slots.
264
+ *
265
+ * Keyed on `blocking` — a caller awaiting this record inline — rather than on
266
+ * `isBackground === false`, because `spawn()` is also the funnel for DETACHED
267
+ * starts (cross-extension RPC, `@handle` mentions, the registry) that may pass
268
+ * `isBackground: false` and are documented to run immediately regardless. Those
269
+ * block nobody, so bounding them buys nothing and would park a record with no
270
+ * one waiting to release it.
271
+ *
272
+ * Nested children are excluded for the same reason as `occupiesPoolSlot`, and
273
+ * more sharply: their parent is blocked *awaiting them*, so queueing a child
274
+ * behind its own parent is a guaranteed deadlock rather than a possible one.
275
+ * Enforced here rather than at the call site so no caller can reintroduce it.
276
+ *
277
+ * A workflow's children go out through `spawnAndWait` and so are `blocking`
278
+ * too, and are excluded on the same `isTopLevelAgent` test as the background
279
+ * pool: the run already caps how many of its agents run at once, and charging
280
+ * them here as well would let one fan-out queue behind a limit meant for the
281
+ * session's own work.
282
+ *
283
+ * Like the background pool this bounds width at the top level only — a parent's
284
+ * own fan-out is limited by nothing but its turn budget.
285
+ */
286
+ function occupiesForegroundSlot(
287
+ record: Pick<AgentRecord, "blocking" | "parentAgentId" | "workflowId">,
288
+ ): boolean {
289
+ return !!record.blocking && isTopLevelAgent(record);
290
+ }
291
+
292
+ /** Which concurrency pool a spawn is charged to, if any. */
293
+ type Pool = "background" | "foreground";
294
+
295
+ /**
296
+ * Pending capacity claimed synchronously before a start awaits anything, then
297
+ * transferred to the running counter (or released on refusal/supersession).
298
+ * Exactly one of the two terminal transitions happens, once.
299
+ *
300
+ * The claim is also registered against its record while it is still pending, so
301
+ * a cancellation can hand the capacity back immediately instead of waiting for
302
+ * a suspended acquire guard to settle. Each claim owns its own bookkeeping: a
303
+ * late continuation can only release ITS claim, never a newer one registered
304
+ * by a later generation.
305
+ */
306
+ interface SlotReservation {
307
+ transfer(): void;
308
+ releasePending(): void;
309
+ }
310
+
311
+ /**
312
+ * A parent-signal abort listener owned by ONE run generation. It is registered
313
+ * with the record that generation runs for, so a cancellation can detach it
314
+ * synchronously instead of waiting for the continuation that attached it. The
315
+ * generation is part of the wire because only the current generation may own a
316
+ * listener: a late old abort must never silence a newer generation's.
317
+ */
318
+ interface SignalWire {
319
+ readonly generation: number;
320
+ detach(): void;
321
+ }
322
+
323
+ type ArtifactAccessGuard = (record: AgentRecord) => void | Promise<void>;
324
+
325
+ interface SpawnArgs {
326
+ pi: ExtensionAPI;
327
+ ctx: ExtensionContext;
328
+ type: SubagentType;
329
+ prompt: string;
330
+ options: SpawnOptions;
331
+ }
332
+
333
+ interface SpawnOptions {
334
+ description: string;
335
+ /**
336
+ * Optional memorable name for this instance, becoming a second handle
337
+ * (`@auth-audit`) alongside the type-derived one. Slugged, not validated —
338
+ * anything unusable degrades via `handleBase` rather than failing the spawn.
339
+ */
340
+ name?: string;
341
+ /**
342
+ * Reopen this pi session file instead of starting a fresh conversation, so a
343
+ * mention of an evicted agent continues where it left off. The agent's
344
+ * definition is still resolved from its type, so the continuation runs under
345
+ * the type's CURRENT config.
346
+ */
347
+ resumeSessionFile?: string;
348
+ /**
349
+ * Internal, manager-only: the definition admitted for this spawn. Callers
350
+ * that resolve against a scoped registry (nested delegation, RPC, the root
351
+ * Agent tool) capture it before their own admission await and pass it here;
352
+ * omitted, `spawn()` snapshots the process-global registry synchronously,
353
+ * before the spawn is queued or starts awaiting work.
354
+ */
355
+ agentDefinition?: AgentConfig;
356
+ /**
357
+ * Take an evicted agent's names back verbatim instead of allocating fresh
358
+ * ones, so a resumed conversation keeps the handle the user just typed —
359
+ * `handleBase(type)` cannot reproduce a numbered `explore-2`. Safe without an
360
+ * `assignHandle` pass because tombstoned names are excluded from allocation
361
+ * (`takenHandles`), so nothing live can be holding them.
362
+ *
363
+ * Internal capability, like `resumeSessionFile`: a forged handle would
364
+ * duplicate a live agent's name and make `resolveMention` ambiguous, so
365
+ * `spawnTopLevel` strips it from anything a caller sends.
366
+ */
367
+ reclaim?: { handle: string; alias?: string };
368
+ model?: Model<any>;
369
+ maxTurns?: number;
370
+ isolated?: boolean;
371
+ inheritContext?: boolean;
372
+ thinkingLevel?: ThinkingLevel;
373
+ isBackground?: boolean;
374
+ /**
375
+ * Skip whichever pool's queue check applies to this spawn — start immediately
376
+ * even if the configured concurrency limit would otherwise queue it. The slot
377
+ * is still COUNTED once the run starts, so a bypassing spawn transiently
378
+ * exceeds the limit rather than being invisible to it.
379
+ *
380
+ * Used by the scheduler, so a fired job can't be deferred past its trigger
381
+ * window, and by the `/agents` agent-file generator, which has no way to
382
+ * cancel a wait (see its call site).
383
+ */
384
+ bypassQueue?: boolean;
385
+ /**
386
+ * A caller is awaiting this record inline (`spawnAndWait`) — what
387
+ * `maxConcurrentForeground` bounds. Set only by `spawnAndWait`; stripped from
388
+ * caller-supplied options by `spawnTopLevel`, since a forged `blocking` would
389
+ * defer a detached start behind a queue its caller cannot see or release.
390
+ */
391
+ blocking?: boolean;
392
+ /**
393
+ * The workflow run this child belongs to, when a workflow spawned it.
394
+ *
395
+ * Ownership, not decoration. A workflow's children are the workflow's — they
396
+ * report through its card, its notification and its dialog, so they are
397
+ * filtered out of every top-level surface exactly as nested children are, and
398
+ * they take no `maxConcurrent` slot: the run has its own concurrency cap, and
399
+ * counting them twice would let one workflow starve the whole session.
400
+ */
401
+ workflowId?: string;
402
+ /**
403
+ * Make the child report through a `StructuredOutput` tool built from this
404
+ * compiled schema. Set only by the workflow host, for `agent({ schema })`.
405
+ */
406
+ structuredOutput?: CompiledSchema;
407
+ /** Isolation mode — "worktree" creates a temp git worktree for the agent. */
408
+ isolation?: IsolationMode;
409
+ /**
410
+ * Working directory for the agent (absolute path). Default: parent session
411
+ * cwd. The agent's tools operate here, but .pi config (extensions, skills,
412
+ * settings, memory) still loads from the parent session's project — the
413
+ * target directory's `.pi` extensions never execute. With isolation:
414
+ * "worktree", the worktree is created FROM this directory and the result
415
+ * branch lands in that repo.
416
+ */
417
+ cwd?: string;
418
+ /**
419
+ * Last chance to look at an isolated agent's worktree, awaited immediately
420
+ * before it is committed to a branch and removed.
421
+ *
422
+ * Exists because that removal happens inside the settle path, before
423
+ * `spawnAndWait` resolves: by the time a caller has the finished record, the
424
+ * directory the child actually wrote in is gone. Anything that must inspect
425
+ * or verify that tree — a workflow `gate` is the motivating case — has to run
426
+ * here or it silently inspects the main tree instead.
427
+ *
428
+ * Fires only on the normal settle path, and only when a worktree was created.
429
+ * Not on the error path and not on the stop-during-copy guard: those are
430
+ * already failing, and delaying cleanup there would leak a copy for no gain.
431
+ * A rejection is swallowed — the hook can never keep the worktree alive.
432
+ */
433
+ onBeforeWorktreeCleanup?: (worktreePath: string, terminalStatus: AgentRecord["status"]) => Promise<void>;
434
+ /** Resolved invocation snapshot captured for UI display. */
435
+ invocation?: AgentInvocation;
436
+ /** Parent abort signal — when aborted, the subagent is also stopped. */
437
+ signal?: AbortSignal;
438
+ /**
439
+ * Called synchronously once the record is in the map and its promise is set,
440
+ * before `onSessionCreated` fires — where callers attach the output file.
441
+ *
442
+ * Carried on the options rather than parked on the manager for the duration
443
+ * of a spawn: with a foreground queue, `startAgent` can run at drain time,
444
+ * long after any such field would have been restored, and the callback would
445
+ * silently never fire (or fire into an unrelated caller's closure).
446
+ */
447
+ onSpawned?: (id: string) => void;
448
+ /**
449
+ * Called synchronously when the spawn is queued instead of started, with how
450
+ * many entries in its own pool are ahead of it. The foreground UI uses it to
451
+ * say so while it waits; nothing else needs it.
452
+ */
453
+ onQueued?: (id: string, ahead: number) => void;
454
+ /** Called on tool start/end with activity info (for streaming progress to UI). */
455
+ onToolActivity?: (activity: ToolActivity) => void;
456
+ /** Called on streaming text deltas from the assistant response. */
457
+ onTextDelta?: (delta: string, fullText: string) => void;
458
+ /** Called when the agent session is created (for accessing session stats). */
459
+ onSessionCreated?: (session: AgentSession) => void;
460
+ /** Called at the end of each agentic turn with the cumulative count. */
461
+ onTurnEnd?: (turnCount: number) => void;
462
+ /** Called once per assistant message_end with that message's usage delta. */
463
+ onAssistantUsage?: (usage: { input: number; output: number; cacheWrite: number }) => void;
464
+ /** Called when the session successfully compacts. */
465
+ onCompaction?: (info: CompactionInfo) => void;
466
+ /** Nesting depth: top-level subagent = 1. */
467
+ depth?: number;
468
+ /** Parent agent ID for ownership-scoped nested controls. */
469
+ parentAgentId?: string;
470
+ /** Effective inherited nesting cap for this branch. */
471
+ maxSubagentDepth?: number;
472
+ /** Config-discovery root inherited by nested launches when it differs from the working directory. */
473
+ configCwd?: string;
474
+ /** Root session id, inherited by nested launches so transcripts stay grouped. */
475
+ rootSessionId?: string;
476
+ /** Stable root project dir, inherited by owned children (never a worktree cwd). */
477
+ rootCwd?: string;
478
+ /** Root session file, inherited by owned children for durable provenance. */
479
+ rootSessionFile?: string;
480
+ /**
481
+ * Internal ownership lineage, derived by the manager from the live parent
482
+ * chain. Never accepted from an external caller (`spawnTopLevel` strips it).
483
+ */
484
+ ownerIds?: string[];
485
+ }
486
+
487
+ interface ResumeOptions {
488
+ /**
489
+ * Run the resumed turn detached in the background: return immediately with
490
+ * the record still "running" (or "queued" at the concurrency limit) and
491
+ * notify on completion via onComplete, exactly like a background spawn.
492
+ * Default (false/undefined) runs the resume inline and returns the settled
493
+ * record — the historical behavior.
494
+ */
495
+ isBackground?: boolean;
496
+ /** Called on tool start/end with activity info (for streaming progress to UI). */
497
+ onToolActivity?: (activity: ToolActivity) => void;
498
+ /** Called once per assistant message_end with that message's usage delta. */
499
+ onAssistantUsage?: (usage: { input: number; output: number; cacheWrite: number }) => void;
500
+ /** Called when the session successfully compacts. */
501
+ onCompaction?: (info: CompactionInfo) => void;
502
+ /**
503
+ * Background resume only: called synchronously when the run actually starts —
504
+ * immediately, or later from drainQueue. Callers wire per-run side effects
505
+ * (output-file streaming) here rather than at the call site, so a resume that
506
+ * is stopped while still queued never leaves a subscription behind: `abort()`
507
+ * drops a queued record without reaching `settle()`, which is what would have
508
+ * torn that subscription down.
509
+ */
510
+ onStarted?: () => void;
511
+ /**
512
+ * Called synchronously exactly once by the WINNING resume, while the
513
+ * manager's exclusive per-record admission claim is still held: after the
514
+ * acquire guard and every identity revalidation, before the generation is
515
+ * stamped or any terminal/run bookkeeping begins. A losing concurrent caller,
516
+ * a refused guard, an evicted/disposed record or a superseded admission never
517
+ * reaches it.
518
+ *
519
+ * This is the ownership boundary for caller-visible per-run wiring (tool call
520
+ * id, join mode, output path/cleanup, anchors): mutation before this point can
521
+ * make a refused request masquerade as the accepted one. A throw is treated as
522
+ * a refusal — the claim is released and the record keeps its previous terminal
523
+ * state, so a later resume is not wedged.
524
+ */
525
+ onAdmitted?: (record: AgentRecord) => void;
526
+ }
527
+
528
+ function updateEffectiveModel(record: AgentRecord, session: AgentSession): void {
529
+ if (!session.model) return;
530
+ record.invocation ??= {};
531
+ const requested = record.invocation.requestedThinking ?? record.invocation.thinking;
532
+ Object.assign(record.invocation, describeModel(session.model));
533
+ if (session.thinkingLevel) {
534
+ record.invocation.thinking = session.thinkingLevel;
535
+ if (requested && requested !== session.thinkingLevel) record.invocation.requestedThinking = requested;
536
+ }
537
+ }
538
+
539
+ export class AgentManager {
540
+ private agents = new Map<string, AgentRecord>();
541
+ private activeRuns = new WeakSet<AgentRecord>();
542
+ private disposed = false;
543
+ private shutdown?: Promise<AgentManagerShutdown>;
544
+ private pruned = false;
545
+ private cleanupInterval: ReturnType<typeof setInterval>;
546
+ private onComplete?: OnAgentComplete;
547
+ private onStart?: OnAgentStart;
548
+ private onCompact?: OnAgentCompact;
549
+ private onUsage?: OnAgentUsage;
550
+ private reportArchiver?: AgentReportArchiver;
551
+ private archivedReportReader?: ArchivedReportReader;
552
+ /** Highest run generation already handed to the archiver, per agent id. */
553
+ private archivedGenerations = new Map<string, { generation: number; fallback: boolean }>();
554
+ /**
555
+ * Full run finalizers still in flight, per record. A finalizer is the spawn or
556
+ * resume promise INCLUDING its output flush and worktree cleanup. One record
557
+ * can hold several: a newer resume may settle while an older generation's
558
+ * flush is still pending, so replacing `record.promise` must not lose the
559
+ * older work. Entries are removed on either resolution branch.
560
+ */
561
+ private pendingFinalizers = new Map<AgentRecord, Set<Promise<unknown>>>();
562
+ /**
563
+ * Proof that a prepareCleanup pass found a live record settled and quiescent.
564
+ * forgetCleanup only forgets records with a matching generation here, so new
565
+ * work or a stale pass can never remove a report. Bounded by live records:
566
+ * cleared with the record, on a new run, on disposal and on forget.
567
+ */
568
+ private cleanupQuiescence = new Map<string, { generation: number }>();
569
+ /** Acquire-side artifact barrier; see setArtifactAccessGuard. */
570
+ private artifactAccessGuard?: ArtifactAccessGuard;
571
+ /**
572
+ * Every session-instance teardown that is pending or never proved quiescence,
573
+ * plus unfinished run finalizers. Rows are lightweight plain data; unresolved
574
+ * rows are NEVER capped or dropped (their paths stay protected).
575
+ */
576
+ private teardowns = new Map<string, TrackedTeardown>();
577
+ /** One teardown identity per SDK session instance (not per session file). */
578
+ private teardownIds = new WeakMap<AgentSession, string>();
579
+ /** Sessions allocated before `onSessionCreated`, keyed by agent id. */
580
+ private allocations = new Map<string, Set<AgentSession>>();
581
+ /** Readiness of each pre-ready allocation (bind/session_start settlement). */
582
+ private allocationStates = new WeakMap<AgentSession, AllocationState>();
583
+ private teardownSequence = 0;
584
+ private maxConcurrent: number;
585
+ private maxConcurrentForeground = DEFAULT_MAX_CONCURRENT_FOREGROUND;
586
+ /** Base repos worktrees were created from — so dispose() can prune them all,
587
+ * not just the parent repo (caller-supplied cwd can target other repos). */
588
+ private worktreeRepos = new Set<string>();
589
+
590
+ /**
591
+ * Startup phases, keyed by agent id. `spawn()` still returns synchronously,
592
+ * but an agent using worktree isolation is not running yet when it does —
593
+ * copying the repo is an awaited git call. This is what `awaitStartup` hands
594
+ * callers that must fail their tool call on a startup failure, and what
595
+ * `waitForAll` waits on while a record is "running" with no `promise` yet.
596
+ * Entries are dropped once the run is underway, and kept (rejected) after a
597
+ * startup failure so a late `awaitStartup` still sees it.
598
+ */
599
+ private startups = new Map<string, Promise<void>>();
600
+
601
+ /**
602
+ * Evicted agents that can still be reached by name, keyed by handle. Outlives
603
+ * the 10-minute record cleanup — that timer exists to bound memory, not to
604
+ * expire a conversation the user might still want — and is cleared alongside
605
+ * completed records on session start/switch.
606
+ */
607
+ private tombstones = new Map<string, AgentTombstone>();
608
+
609
+ /**
610
+ * Agents waiting to start, tagged with the pool they wait on. One queue for
611
+ * both pools: `drainQueue` picks the earliest entry whose own pool has room,
612
+ * so neither can head-of-line-block the other, and every removal path
613
+ * (`abort`, `abortAll`, `dispose`) stays a single filter.
614
+ *
615
+ * `release` wakes a caller blocked in `spawnAndWait`, and is fired once the
616
+ * entry's `start` has SETTLED rather than at drain time: startup is async
617
+ * now, so releasing earlier would wake the caller before `record.promise`
618
+ * exists and it would read a still-starting agent as one that never ran.
619
+ * Removing an entry from this array MUST release it — a queued record has no
620
+ * promise to await, and pi has no tool-execution timeout to bail the caller
621
+ * out.
622
+ */
623
+ private queue: { id: string; pool: Pool; start: () => Promise<void>; release: () => void }[] = [];
624
+ /** Number of currently running background agents. */
625
+ private runningBackground = 0;
626
+ /** Number of currently running foreground (blocking) agents. */
627
+ private runningForeground = 0;
628
+ /**
629
+ * Capacity claimed by a start that has not reached its run yet (it is still
630
+ * awaiting an async acquire guard, a worktree copy or a cwd re-check).
631
+ * `poolHasRoom` counts these, so a synchronous queue drain can never start
632
+ * more runs than the limit while earlier starts are suspended.
633
+ */
634
+ private pendingBackground = 0;
635
+ private pendingForeground = 0;
636
+ /**
637
+ * Pending capacity claims, keyed by the record that owns them. A cancellation
638
+ * releases the claim still pending here at once; a TRANSFERRED claim is gone
639
+ * from this map and is a running charge the run's own finalizer releases, so
640
+ * abort can never free a slot that real work still occupies. A later claim
641
+ * for the same record replaces the entry: an older continuation that settles
642
+ * afterwards releases only its own already-idempotent claim.
643
+ */
644
+ private pendingClaims = new WeakMap<AgentRecord, SlotReservation>();
645
+ /**
646
+ * Resume admission, claimed synchronously before the acquire guard awaits.
647
+ * A settled record can be resumed by two callers in the same tick; only the
648
+ * first may mutate its generation and terminal fields. Cleared on refusal or
649
+ * once the record is queued/running (status then provides exclusivity).
650
+ */
651
+ private resumeAdmissions = new WeakSet<AgentRecord>();
652
+ /** Individual queued aborts already delivered completion for this generation. */
653
+ private notifiedQueuedAborts = new WeakMap<AgentRecord, number>();
654
+ /**
655
+ * The parent-signal abort listener currently owned by a record, with the
656
+ * generation that attached it. A start wires its signal BEFORE the acquire
657
+ * guard can suspend, so abort()/abortAll()/dispose() must be able to detach it
658
+ * immediately: a guard that never settles must not leave the manager reachable
659
+ * from a live parent signal. One wire per record — only the current generation
660
+ * is wired, and detach is identity-aware, so a stale continuation can never
661
+ * remove a newer generation's listener.
662
+ */
663
+ private signalWires = new WeakMap<AgentRecord, SignalWire>();
664
+
665
+ constructor(
666
+ onComplete?: OnAgentComplete,
667
+ maxConcurrent = DEFAULT_MAX_CONCURRENT,
668
+ onStart?: OnAgentStart,
669
+ onCompact?: OnAgentCompact,
670
+ onUsage?: OnAgentUsage,
671
+ ) {
672
+ this.onComplete = onComplete;
673
+ this.onStart = onStart;
674
+ this.onCompact = onCompact;
675
+ this.onUsage = onUsage;
676
+ this.maxConcurrent = maxConcurrent;
677
+ // Cleanup completed agents after 10 minutes (but keep sessions for resume)
678
+ this.cleanupInterval = setInterval(() => this.cleanup(), 60_000);
679
+ this.cleanupInterval.unref();
680
+ }
681
+
682
+ /** Update the max concurrent background agents limit. */
683
+ setMaxConcurrent(n: number) {
684
+ this.maxConcurrent = Math.max(1, n);
685
+ // Start queued agents if the new limit allows
686
+ this.drainQueue();
687
+ }
688
+
689
+ getMaxConcurrent(): number {
690
+ return this.maxConcurrent;
691
+ }
692
+
693
+ /** Wire durable report capture; see {@link AgentReportArchiver}. */
694
+ setReportArchiver(archiver: AgentReportArchiver | undefined): void {
695
+ this.reportArchiver = archiver;
696
+ }
697
+
698
+ /** Wire the async parent-scoped archived reader injected into nested tools. */
699
+ setArchivedReportReader(reader: ArchivedReportReader | undefined): void {
700
+ this.archivedReportReader = reader;
701
+ }
702
+
703
+ /**
704
+ * Wire the acquire-side artifact barrier. The callback runs at the ACTUAL
705
+ * boundaries where a run would first touch artifacts: the real start of
706
+ * `startAgent` (before the running slot is transferred), again immediately
707
+ * before `runAgent` (after an awaited worktree copy and/or assert), at resume
708
+ * acquisition before any run bookkeeping, and at a queued resume's actual
709
+ * start. The pool capacity itself is reserved synchronously in `launch` /
710
+ * the queued start BEFORE this callback can suspend, so awaiting a guard can
711
+ * never let a queue drain oversubscribe its pool.
712
+ *
713
+ * A throw (or a rejected promise) is an ordinary startup/refusal failure: no
714
+ * model starts, no pool slot or record generation is mutated, and a fresh
715
+ * worktree copy is released. The callback owns any ownership/lock check; the
716
+ * manager never inspects the filesystem or an SDK session here.
717
+ *
718
+ * A callback that returns a promise is awaited before worktree creation, and
719
+ * again immediately before `runAgent`. A callback that returns `void` keeps
720
+ * the historical synchronous start path unchanged (no extra suspension, so a
721
+ * spawn that has room starts in the same tick).
722
+ */
723
+ setArtifactAccessGuard(guard: ArtifactAccessGuard | undefined): void {
724
+ this.artifactAccessGuard = guard;
725
+ }
726
+
727
+ /** Invoke the configured acquire-side barrier; original behavior when unset. */
728
+ private assertArtifactAccess(record: AgentRecord): void | Promise<void> {
729
+ return this.artifactAccessGuard?.(record);
730
+ }
731
+
732
+ /** Teardowns that did not prove quiescence, newest first. Cleanup keeps them leased. */
733
+ listUncertainTeardowns(): UncertainTeardown[] {
734
+ return [...this.teardowns.values()]
735
+ .map(row => ({
736
+ agentId: row.agentId,
737
+ status: row.status,
738
+ phase: row.phase,
739
+ teardownId: row.id,
740
+ ...(row.sessionFile === undefined ? {} : { sessionFile: row.sessionFile }),
741
+ ...(row.sessionId === undefined ? {} : { sessionId: row.sessionId }),
742
+ ...(row.rootSessionId === undefined ? {} : { rootSessionId: row.rootSessionId }),
743
+ ...(row.rootCwd === undefined ? {} : { rootCwd: row.rootCwd }),
744
+ ...(row.rootSessionFile === undefined ? {} : { rootSessionFile: row.rootSessionFile }),
745
+ ...(row.reason === undefined ? {} : { reason: row.reason }),
746
+ at: row.at,
747
+ }))
748
+ .sort((a, b) => b.at - a.at);
749
+ }
750
+
751
+ hasUncertainTeardowns(): boolean {
752
+ return this.teardowns.size > 0;
753
+ }
754
+
755
+ /**
756
+ * Every agent whose work is not quiescent. Includes running/queued records,
757
+ * startup work (an awaited worktree copy), in-flight run finalizers (output
758
+ * flush and worktree cleanup) and older-generation finalizers that outlived a
759
+ * newer settled run. Cleanup callers combine this with
760
+ * {@link listUncertainTeardowns} for evicted-record protection; nothing here
761
+ * aborts, evicts or notifies anything.
762
+ */
763
+ getBusyAgentIds(): string[] {
764
+ const busy = new Set<string>();
765
+ for (const record of this.agents.values()) {
766
+ if (this.busyReason(record) !== undefined) busy.add(record.id);
767
+ }
768
+ // dispose() clears `agents` before its bounded sweep; a finalizer/startup
769
+ // still running in that window is still busy for an observer.
770
+ for (const record of this.pendingFinalizers.keys()) busy.add(record.id);
771
+ for (const id of this.startups.keys()) busy.add(id);
772
+ return [...busy];
773
+ }
774
+
775
+ /**
776
+ * Decide which requested reports and session files may be deleted, and close
777
+ * the settled SDK sessions that make them quiescent.
778
+ *
779
+ * Synchronous-before-await guarantees: the readiness recheck, the session
780
+ * detach and the bounded teardown registration all happen before the first
781
+ * `await`. A resume therefore sees `record.session === undefined` for every
782
+ * session this pass is closing, and work that starts during the await is
783
+ * refused by the second readiness check rather than reported ready.
784
+ *
785
+ * Never aborts/stops running work, never evicts records, never disposes or
786
+ * clears the manager, and never consumes a result or fires a notification.
787
+ * A settled record stays in the manager; {@link forgetCleanup} removes it only
788
+ * after the backend actually deleted its files.
789
+ */
790
+ async prepareCleanup(
791
+ agentIds: readonly string[],
792
+ sessionFiles: readonly string[],
793
+ ): Promise<AgentCleanupPreparation> {
794
+ const blockedAgentIds: Record<string, string> = {};
795
+ const blockedSessionFiles: Record<string, string> = {};
796
+ const readyAgentIds: string[] = [];
797
+ const readySessionFiles: string[] = [];
798
+ const requestedAgentIds = [...new Set(agentIds)];
799
+ const requestedSessionFiles: string[] = [];
800
+ const seenPaths = new Set<string>();
801
+ for (const path of sessionFiles) {
802
+ const key = cleanupPathKey(path);
803
+ if (seenPaths.has(key)) continue;
804
+ seenPaths.add(key);
805
+ requestedSessionFiles.push(path);
806
+ }
807
+
808
+ if (this.disposed) {
809
+ for (const id of requestedAgentIds) blockedAgentIds[id] = "manager is disposed";
810
+ for (const path of requestedSessionFiles) blockedSessionFiles[path] = "manager is disposed";
811
+ return { readyAgentIds, blockedAgentIds, readySessionFiles, blockedSessionFiles };
812
+ }
813
+
814
+ // ---- synchronous pre-check, against every record (selected or not) ----
815
+ const initialGuard = this.cleanupGuardSnapshot();
816
+ let guard = initialGuard;
817
+ const agentCandidates: string[] = [];
818
+ for (const id of requestedAgentIds) {
819
+ const reason = this.cleanupAgentRefusal(id, guard);
820
+ if (reason !== undefined) {
821
+ blockedAgentIds[id] = reason;
822
+ this.cleanupQuiescence.delete(id);
823
+ } else {
824
+ agentCandidates.push(id);
825
+ }
826
+ }
827
+ const sessionCandidates: string[] = [];
828
+ for (const path of requestedSessionFiles) {
829
+ const reason = this.cleanupPathRefusal(path, guard);
830
+ if (reason !== undefined) blockedSessionFiles[path] = reason;
831
+ else sessionCandidates.push(path);
832
+ }
833
+
834
+ // ---- synchronous detach + register: still nothing awaited ----
835
+ const jobs = new Map<AgentSession, CleanupTeardownJob>();
836
+ const jobsByRecord = new Map<AgentRecord, CleanupTeardownJob>();
837
+ for (const id of agentCandidates) {
838
+ const record = this.agents.get(id);
839
+ if (record) this.attachCleanupTeardown(jobs, jobsByRecord, record, { agentId: id });
840
+ }
841
+ for (const path of sessionCandidates) {
842
+ const key = cleanupPathKey(path);
843
+ for (const record of this.agents.values()) {
844
+ if (record.sessionFile === undefined || cleanupPathKey(record.sessionFile) !== key) continue;
845
+ this.attachCleanupTeardown(jobs, jobsByRecord, record, { sessionFile: path });
846
+ }
847
+ }
848
+ const outcomes = new Map<AgentSession, ChildShutdownOutcome>();
849
+ await Promise.all(
850
+ [...jobs.values()].map(async job => {
851
+ try {
852
+ outcomes.set(job.session, await this.trackSessionShutdown(job.record, job.session));
853
+ } catch (error) {
854
+ outcomes.set(job.session, {
855
+ status: "failed",
856
+ timedOut: false,
857
+ reason: error instanceof Error ? error.message : String(error),
858
+ });
859
+ }
860
+ }),
861
+ );
862
+
863
+ // ---- post-check: work that appeared while awaiting must not slip through ----
864
+ guard = this.cleanupGuardSnapshot();
865
+ for (const id of agentCandidates) {
866
+ const record = this.agents.get(id);
867
+ const reason = this.teardownRefusalForAgent(jobs, outcomes, id)
868
+ ?? this.cleanupAgentRefusal(id, guard)
869
+ ?? this.attachedDuringCleanupRefusal({ agentId: id }, initialGuard, guard, jobs);
870
+ if (reason !== undefined) {
871
+ blockedAgentIds[id] = reason;
872
+ this.cleanupQuiescence.delete(id);
873
+ continue;
874
+ }
875
+ readyAgentIds.push(id);
876
+ if (record) this.cleanupQuiescence.set(id, { generation: record.runGeneration ?? 0 });
877
+ }
878
+ for (const path of sessionCandidates) {
879
+ const reason = this.teardownRefusalForSessionFile(jobs, outcomes, path)
880
+ ?? this.cleanupPathRefusal(path, guard)
881
+ ?? this.attachedDuringCleanupRefusal({ sessionFile: path }, initialGuard, guard, jobs);
882
+ if (reason !== undefined) {
883
+ blockedSessionFiles[path] = reason;
884
+ continue;
885
+ }
886
+ readySessionFiles.push(path);
887
+ }
888
+
889
+ return { readyAgentIds, blockedAgentIds, readySessionFiles, blockedSessionFiles };
890
+ }
891
+
892
+ /**
893
+ * Drop manager-side traces of cleanup items the backend ACTUALLY deleted.
894
+ *
895
+ * A live record is forgotten only when a prepareCleanup pass proved it
896
+ * quiescent, it is still on that same run generation, its session was
897
+ * detached by that pass, and nothing is busy or uncertain now. Nothing is
898
+ * tombstoned and no teardown is started: the report was deliberately deleted
899
+ * and must not resurrect through a mention or a late archive.
900
+ *
901
+ * Tombstones are dropped by the actual deleted agent id or the actual deleted
902
+ * session file, and a surviving record's session pointer is cleared only for
903
+ * a path that was actually deleted. Unrelated records, tombstones and failed
904
+ * deletions are never touched.
905
+ */
906
+ forgetCleanup(deletedAgentIds: readonly string[], deletedSessionFiles: readonly string[]): void {
907
+ const deletedIds = new Set(deletedAgentIds);
908
+ const deletedPaths = new Set<string>();
909
+ for (const path of deletedSessionFiles) deletedPaths.add(cleanupPathKey(path));
910
+
911
+ for (const id of deletedIds) {
912
+ const proof = this.cleanupQuiescence.get(id);
913
+ this.cleanupQuiescence.delete(id);
914
+ const record = this.agents.get(id);
915
+ if (record === undefined || proof === undefined) continue;
916
+ if (proof.generation !== (record.runGeneration ?? 0)) continue;
917
+ // prepareCleanup always detaches before it reports ready; a live session
918
+ // here means this record was not closed by that pass (no async disposal).
919
+ if (record.session !== undefined) continue;
920
+ if (this.busyReason(record) !== undefined) continue;
921
+ if ([...this.teardowns.values()].some(row => row.agentId === id && this.uncertaintyReason(row) !== undefined)) {
922
+ continue;
923
+ }
924
+ this.pendingFinalizers.delete(record);
925
+ this.archivedGenerations.delete(id);
926
+ this.releaseAllocation(id);
927
+ this.startups.delete(id);
928
+ this.agents.delete(id);
929
+ }
930
+
931
+ for (const [handle, entry] of [...this.tombstones]) {
932
+ if (deletedIds.has(entry.id) || deletedPaths.has(cleanupPathKey(entry.sessionFile))) {
933
+ this.tombstones.delete(handle);
934
+ }
935
+ }
936
+
937
+ for (const record of this.agents.values()) {
938
+ if (record.sessionFile !== undefined && deletedPaths.has(cleanupPathKey(record.sessionFile))) {
939
+ record.sessionFile = undefined;
940
+ }
941
+ }
942
+ }
943
+
944
+ /** Why a live record is not quiescent, or undefined when it is settled and idle. */
945
+ private busyReason(record: AgentRecord): string | undefined {
946
+ if (this.startups.has(record.id)) return "agent startup is in flight";
947
+ if (record.status === "running" || this.activeRuns.has(record)) return "agent is running";
948
+ if (record.status === "queued") return "agent is queued";
949
+ if (record.outputCleanup !== undefined) return "output finalizer is pending";
950
+ if (this.pendingFinalizers.has(record)) return "run finalizer is pending";
951
+ return undefined;
952
+ }
953
+
954
+ /** Explicit reason an unresolved teardown row blocks deletion. */
955
+ private uncertaintyReason(row: TrackedTeardown): string | undefined {
956
+ if (row.status === "completed") return undefined;
957
+ const phase = row.phase === "run" ? "run finalizer" : "session teardown";
958
+ if (row.status === "pending") return `${phase} is still pending`;
959
+ if (row.status === "timed_out") return `${phase} timed out`;
960
+ return `${phase} failed`;
961
+ }
962
+
963
+ private cleanupGuardSnapshot(): CleanupGuardSnapshot {
964
+ const records = [...this.agents.values()];
965
+ const busySessions = new Set<AgentSession>();
966
+ const attachedSessions = new Map<AgentRecord, AgentSession>();
967
+ for (const record of records) {
968
+ const session = record.session;
969
+ if (session === undefined) continue;
970
+ attachedSessions.set(record, session);
971
+ if (this.busyReason(record) !== undefined) busySessions.add(session);
972
+ }
973
+ return { records, rows: [...this.teardowns.values()], busySessions, attachedSessions };
974
+ }
975
+
976
+ private cleanupAgentRefusal(agentId: string, guard: CleanupGuardSnapshot): string | undefined {
977
+ const record = this.agents.get(agentId);
978
+ if (record !== undefined) {
979
+ const busy = this.busyReason(record);
980
+ if (busy !== undefined) return busy;
981
+ }
982
+ // An evicted record leaves a tombstone, which still names the history file
983
+ // a later reopen would share. Archive-only ids (no record, no tombstone)
984
+ // have no live reference and stay ready.
985
+ const tombstone = record === undefined
986
+ ? [...this.tombstones.values()].find(entry => entry.id === agentId)
987
+ : undefined;
988
+ const sessionFile = record?.sessionFile ?? tombstone?.sessionFile;
989
+ const sessionKey = sessionFile === undefined ? undefined : cleanupPathKey(sessionFile);
990
+ // Sharing is checked against ALL busy records, including ones the caller
991
+ // did not select: deleting this report's history would catch them too.
992
+ for (const other of guard.records) {
993
+ if (other === record || this.busyReason(other) === undefined) continue;
994
+ if (sessionKey !== undefined && other.sessionFile !== undefined
995
+ && cleanupPathKey(other.sessionFile) === sessionKey) {
996
+ return "session file is shared with a busy agent";
997
+ }
998
+ if (record?.session !== undefined && other.session === record.session) {
999
+ return "session instance is shared with a busy agent";
1000
+ }
1001
+ }
1002
+ for (const row of guard.rows) {
1003
+ if (row.agentId !== agentId) continue;
1004
+ const reason = this.uncertaintyReason(row);
1005
+ if (reason !== undefined) return reason;
1006
+ }
1007
+ return undefined;
1008
+ }
1009
+
1010
+ private cleanupPathRefusal(path: string, guard: CleanupGuardSnapshot): string | undefined {
1011
+ const key = cleanupPathKey(path);
1012
+ for (const row of guard.rows) {
1013
+ const namesPath = (value: string | undefined) => value !== undefined && cleanupPathKey(value) === key;
1014
+ if (!namesPath(row.sessionFile) && !namesPath(row.rootSessionFile)) continue;
1015
+ const reason = this.uncertaintyReason(row);
1016
+ if (reason !== undefined) return reason;
1017
+ }
1018
+ for (const record of guard.records) {
1019
+ if (record.sessionFile === undefined || cleanupPathKey(record.sessionFile) !== key) continue;
1020
+ if (this.busyReason(record) !== undefined) return "session file is shared with a busy agent";
1021
+ if (record.session !== undefined && guard.busySessions.has(record.session)) {
1022
+ return "session instance is shared with a busy agent";
1023
+ }
1024
+ }
1025
+ return undefined;
1026
+ }
1027
+
1028
+ /**
1029
+ * Refuse readiness for an attachment that appeared while the pass awaited.
1030
+ *
1031
+ * The pre-check deliberately allows settled attached sessions so this pass can
1032
+ * detach and tear them down. That proof covers only the attachments in the
1033
+ * initial snapshot: a record that attaches the same report/history during the
1034
+ * await was never detached by this pass and stays resumable. Refuse it; the
1035
+ * newly attached handle is not closed.
1036
+ */
1037
+ private attachedDuringCleanupRefusal(
1038
+ target: { agentId?: string; sessionFile?: string },
1039
+ before: CleanupGuardSnapshot,
1040
+ after: CleanupGuardSnapshot,
1041
+ jobs: Map<AgentSession, CleanupTeardownJob>,
1042
+ ): string | undefined {
1043
+ const record = target.agentId === undefined ? undefined : this.agents.get(target.agentId);
1044
+ const sessionFile = target.sessionFile ?? record?.sessionFile;
1045
+ const sessionKey = sessionFile === undefined ? undefined : cleanupPathKey(sessionFile);
1046
+ for (const other of after.records) {
1047
+ const session = other.session;
1048
+ if (session === undefined || jobs.has(session)) continue;
1049
+ if (before.attachedSessions.get(other) === session) continue;
1050
+ if (other === record) return "session was attached during cleanup";
1051
+ if (sessionKey !== undefined && other.sessionFile !== undefined
1052
+ && cleanupPathKey(other.sessionFile) === sessionKey) {
1053
+ return "session file was attached during cleanup";
1054
+ }
1055
+ }
1056
+ return undefined;
1057
+ }
1058
+
1059
+ /**
1060
+ * Detach a record's session synchronously and attach it to the pass's unique
1061
+ * teardown job. The detach MUST precede the first await and the SDK teardown:
1062
+ * a resume during shutdown then has no session to reopen.
1063
+ */
1064
+ private attachCleanupTeardown(
1065
+ jobs: Map<AgentSession, CleanupTeardownJob>,
1066
+ jobsByRecord: Map<AgentRecord, CleanupTeardownJob>,
1067
+ record: AgentRecord,
1068
+ target: { agentId?: string; sessionFile?: string },
1069
+ ): void {
1070
+ const session = record.session;
1071
+ let job = jobsByRecord.get(record) ?? (session === undefined ? undefined : jobs.get(session));
1072
+ if (job === undefined) {
1073
+ if (session === undefined) return;
1074
+ record.session = undefined;
1075
+ job = { record, session, agentIds: new Set(), sessionFiles: new Set() };
1076
+ jobs.set(session, job);
1077
+ // A record is free to share one SDK instance with a settled sibling.
1078
+ // Once that instance is being closed, no handle may keep it for resume.
1079
+ for (const other of this.agents.values()) {
1080
+ if (other.session !== session) continue;
1081
+ other.session = undefined;
1082
+ jobsByRecord.set(other, job);
1083
+ }
1084
+ } else if (session !== undefined) {
1085
+ record.session = undefined;
1086
+ }
1087
+ // Pin the most descriptive identity for a teardown protection row: a
1088
+ // shared instance must still protect a file name known by any handle.
1089
+ if (job.record.sessionFile === undefined && record.sessionFile !== undefined) job.record = record;
1090
+ jobsByRecord.set(record, job);
1091
+ if (target.agentId !== undefined) job.agentIds.add(target.agentId);
1092
+ if (target.sessionFile !== undefined) job.sessionFiles.add(target.sessionFile);
1093
+ }
1094
+
1095
+ private teardownRefusal(outcome: ChildShutdownOutcome | undefined): string | undefined {
1096
+ // Fail closed: a job that never produced an outcome is not proof of
1097
+ // quiescence, and a missing key must never read as "completed".
1098
+ if (outcome === undefined) return "session teardown did not prove completion";
1099
+ if (outcome.status === "completed") return undefined;
1100
+ return outcome.reason
1101
+ ?? (outcome.status === "timed_out" ? "session teardown timed out" : "session teardown failed");
1102
+ }
1103
+
1104
+ private teardownRefusalForAgent(
1105
+ jobs: Map<AgentSession, CleanupTeardownJob>,
1106
+ outcomes: Map<AgentSession, ChildShutdownOutcome>,
1107
+ agentId: string,
1108
+ ): string | undefined {
1109
+ for (const job of jobs.values()) {
1110
+ if (!job.agentIds.has(agentId)) continue;
1111
+ const reason = this.teardownRefusal(outcomes.get(job.session));
1112
+ if (reason !== undefined) return reason;
1113
+ }
1114
+ return undefined;
1115
+ }
1116
+
1117
+ private teardownRefusalForSessionFile(
1118
+ jobs: Map<AgentSession, CleanupTeardownJob>,
1119
+ outcomes: Map<AgentSession, ChildShutdownOutcome>,
1120
+ path: string,
1121
+ ): string | undefined {
1122
+ for (const job of jobs.values()) {
1123
+ if (!job.sessionFiles.has(path)) continue;
1124
+ const reason = this.teardownRefusal(outcomes.get(job.session));
1125
+ if (reason !== undefined) return reason;
1126
+ }
1127
+ return undefined;
1128
+ }
1129
+
1130
+ /** Update the max concurrent foreground (blocking) agents limit. 0 = unlimited. */
1131
+ setMaxConcurrentForeground(n: number) {
1132
+ // Floor 0, not 1: unlimited is a meaningful value here and the default.
1133
+ this.maxConcurrentForeground = Math.max(0, n);
1134
+ // Start queued agents if the new limit allows — including everything, when
1135
+ // the limit is cleared back to unlimited mid-run.
1136
+ this.drainQueue();
1137
+ }
1138
+
1139
+ getMaxConcurrentForeground(): number {
1140
+ return this.maxConcurrentForeground;
1141
+ }
1142
+
1143
+ /**
1144
+ * Which pool a spawn is charged to, or undefined for one that is charged to
1145
+ * neither (nested children, detached non-background spawns).
1146
+ *
1147
+ * Nothing here queues when the limit is unset — `poolHasRoom` reports an
1148
+ * unlimited pool as always having room, so that alone is what keeps the
1149
+ * default path identical. The `> 0` guard is belt and braces on top: it also
1150
+ * keeps the counter from churning and the settle path from calling a drain
1151
+ * that would find nothing to do. Both are unobservable, which is why no test
1152
+ * pins them; the observable half — that the default start stays synchronous —
1153
+ * is pinned in `test/foreground-concurrency.test.ts`.
1154
+ */
1155
+ private poolFor(record: AgentRecord): Pool | undefined {
1156
+ if (occupiesPoolSlot(record)) return "background";
1157
+ if (this.maxConcurrentForeground > 0 && occupiesForegroundSlot(record)) return "foreground";
1158
+ return undefined;
1159
+ }
1160
+
1161
+ private poolHasRoom(pool: Pool): boolean {
1162
+ return pool === "background"
1163
+ ? this.runningBackground + this.pendingBackground < this.maxConcurrent
1164
+ : this.maxConcurrentForeground === 0
1165
+ || this.runningForeground + this.pendingForeground < this.maxConcurrentForeground;
1166
+ }
1167
+
1168
+ /**
1169
+ * Claim one slot for a start that is about to await work, synchronously.
1170
+ * `transfer()` moves the claim to the running counter before the run is
1171
+ * launched; `releasePending()` gives it back when acquisition is refused or
1172
+ * the record was superseded. Repeated calls are no-ops, so a refusal that
1173
+ * unwinds through `launch` cannot decrement twice.
1174
+ *
1175
+ * The claim is associated with `record` while pending so `abort()`/`abortAll()`
1176
+ * can release it without waiting for the suspended continuation.
1177
+ */
1178
+ private reservePoolSlot(pool: Pool | undefined, record?: AgentRecord): SlotReservation | undefined {
1179
+ if (pool === undefined) return undefined;
1180
+ if (pool === "background") this.pendingBackground++;
1181
+ else this.pendingForeground++;
1182
+ let claimed = true;
1183
+ // Declared before the closures below read it; only referenced after the
1184
+ // object exists, so the claim can compare its own identity.
1185
+ let reservation: SlotReservation | undefined;
1186
+ const forget = () => {
1187
+ if (record !== undefined && this.pendingClaims.get(record) === reservation) {
1188
+ this.pendingClaims.delete(record);
1189
+ }
1190
+ };
1191
+ reservation = {
1192
+ transfer: () => {
1193
+ if (!claimed) return;
1194
+ claimed = false;
1195
+ forget();
1196
+ if (pool === "background") {
1197
+ this.pendingBackground--;
1198
+ this.runningBackground++;
1199
+ } else {
1200
+ this.pendingForeground--;
1201
+ this.runningForeground++;
1202
+ }
1203
+ },
1204
+ releasePending: () => {
1205
+ if (!claimed) return;
1206
+ claimed = false;
1207
+ forget();
1208
+ if (pool === "background") this.pendingBackground--;
1209
+ else this.pendingForeground--;
1210
+ },
1211
+ };
1212
+ if (record !== undefined) this.pendingClaims.set(record, reservation);
1213
+ return reservation;
1214
+ }
1215
+
1216
+ /**
1217
+ * Free a record's still-PENDING capacity claim, immediately and exactly once.
1218
+ * A transferred claim is absent from the map, so a real run's charge is never
1219
+ * touched here — that is released only by its finalizer.
1220
+ *
1221
+ * `drain` is false while a bulk cancellation is still marking entries: freeing
1222
+ * one entry's capacity must not start another entry that has not been canceled
1223
+ * yet. Individual cancellation drains as soon as the record is stopped.
1224
+ */
1225
+ private releasePendingClaim(record: AgentRecord, drain: boolean): boolean {
1226
+ const claim = this.pendingClaims.get(record);
1227
+ if (claim === undefined) return false;
1228
+ this.pendingClaims.delete(record);
1229
+ claim.releasePending();
1230
+ if (drain) this.drainQueue();
1231
+ return true;
1232
+ }
1233
+
1234
+ /**
1235
+ * The pending claim a record holds RIGHT NOW, captured before anything the
1236
+ * caller is about to do can re-enter the manager. abort() hands this exact
1237
+ * reservation back afterwards: its completion callback is free to resume the
1238
+ * same record, and that newer generation installs its OWN claim in the map.
1239
+ * Freeing by lookup at the tail would free that one instead — a running charge
1240
+ * the new generation still owns, whose transfer then no-ops and whose
1241
+ * finalizer underflows the pool counter (oversubscription).
1242
+ */
1243
+ private capturePendingClaim(record: AgentRecord): SlotReservation | undefined {
1244
+ return this.pendingClaims.get(record);
1245
+ }
1246
+
1247
+ /**
1248
+ * Release the exact claim {@link capturePendingClaim} captured. The map entry
1249
+ * is forgotten only if it still names that object, and a claim that already
1250
+ * transferred or was already released is an idempotent no-op, so a transferred
1251
+ * running charge is never freed here.
1252
+ */
1253
+ private releaseCapturedClaim(record: AgentRecord, claim: SlotReservation | undefined, drain: boolean): boolean {
1254
+ if (claim === undefined) return false;
1255
+ if (this.pendingClaims.get(record) === claim) this.pendingClaims.delete(record);
1256
+ claim.releasePending();
1257
+ if (drain) this.drainQueue();
1258
+ return true;
1259
+ }
1260
+
1261
+ /**
1262
+ * Attach the parent-signal abort listener owned by `generation` and register
1263
+ * it where abort()/abortAll()/dispose() can detach it immediately. Only one
1264
+ * wire exists per record: an older generation's listener (a queued start's, or
1265
+ * the previous run's) is detached first, so a late abort of THAT signal can
1266
+ * never stop this run. A detached start (`undefined`) stays detached, and an
1267
+ * already-aborted signal is left to its caller's explicit `abort()` call.
1268
+ */
1269
+ private attachSignalWire(
1270
+ record: AgentRecord,
1271
+ signal: AbortSignal | undefined,
1272
+ generation: number,
1273
+ ): SignalWire | undefined {
1274
+ if (signal === undefined || signal.aborted) return undefined;
1275
+ // Only the record's current generation may own the wire: a superseded
1276
+ // caller arming one would let a stale signal stop a later run.
1277
+ if ((record.runGeneration ?? 0) !== generation) return undefined;
1278
+ this.detachSignalWire(record, this.signalWires.get(record));
1279
+ const onParentAbort = () => this.abort(record.id);
1280
+ signal.addEventListener("abort", onParentAbort, { once: true });
1281
+ const wire: SignalWire = {
1282
+ generation,
1283
+ detach: () => signal.removeEventListener("abort", onParentAbort),
1284
+ };
1285
+ this.signalWires.set(record, wire);
1286
+ return wire;
1287
+ }
1288
+
1289
+ /**
1290
+ * Detach one CAPTURED wire. The registry entry is forgotten only if it still
1291
+ * names that wire, and `detach` is idempotent, so a stale continuation — or an
1292
+ * old abort resuming after its callbacks — cannot remove a newer generation's
1293
+ * listener.
1294
+ */
1295
+ private detachSignalWire(record: AgentRecord, wire: SignalWire | undefined): void {
1296
+ if (wire === undefined) return;
1297
+ if (this.signalWires.get(record) === wire) this.signalWires.delete(record);
1298
+ wire.detach();
1299
+ }
1300
+
1301
+ /** Detach whatever parent-signal listener the record's current generation owns. */
1302
+ private releaseSignalWire(record: AgentRecord): void {
1303
+ this.detachSignalWire(record, this.signalWires.get(record));
1304
+ }
1305
+
1306
+ /**
1307
+ * Spawn an agent and return its ID immediately (for background use).
1308
+ * If the concurrency limit is reached, the agent is queued.
1309
+ *
1310
+ * The id comes back synchronously, but with `isolation: "worktree"` the agent
1311
+ * is not running yet when it does — the repo copy is an awaited git call.
1312
+ * Callers that must fail a tool call on a startup failure await
1313
+ * `awaitStartup(id)`; everyone else sees it on the record (status "error").
1314
+ */
1315
+ spawn(
1316
+ pi: ExtensionAPI,
1317
+ ctx: ExtensionContext,
1318
+ type: SubagentType,
1319
+ prompt: string,
1320
+ options: SpawnOptions,
1321
+ ): string {
1322
+ if (this.disposed) throw new Error("Agent manager is disposed");
1323
+ // Validate before the queue branch — a queued spawn should fail at the
1324
+ // call, not minutes later at drain. Throw (not warn): programmatic callers
1325
+ // can fix and retry; the RPC layer converts throws into error envelopes.
1326
+ assertValidSpawnCwd(options.cwd);
1327
+
1328
+ const id = randomUUID().slice(0, 17);
1329
+ const abortController = new AbortController();
1330
+ // Ownership and root provenance are pinned at SPAWN, from the live parent
1331
+ // chain when one exists — not reconstructed from whatever still lives at
1332
+ // settle time. Cleanup later needs an ancestor that may itself have been
1333
+ // evicted, and a child session's worktree cwd is not the root project.
1334
+ const parentRecord = options.parentAgentId === undefined ? undefined : this.agents.get(options.parentAgentId);
1335
+ const ownerIds = options.parentAgentId === undefined
1336
+ ? undefined
1337
+ : [options.parentAgentId, ...(parentRecord?.ownerIds ?? [])];
1338
+ const rootSessionId = options.rootSessionId
1339
+ ?? parentRecord?.rootSessionId
1340
+ ?? ctx.sessionManager?.getSessionId?.();
1341
+ const rootCwd = options.rootCwd ?? parentRecord?.rootCwd ?? ctx.cwd;
1342
+ const rootSessionFile = options.rootSessionFile
1343
+ ?? parentRecord?.rootSessionFile
1344
+ ?? ctx.sessionManager?.getSessionFile?.();
1345
+ const record: AgentRecord = {
1346
+ id,
1347
+ type,
1348
+ // Owned children — nested, or a workflow's — are filtered out of every
1349
+ // top-level surface, so no handle: nothing can address them and they must
1350
+ // not consume a name a top-level sibling could otherwise take.
1351
+ handle: !isTopLevelAgent(options)
1352
+ ? undefined
1353
+ // A reclaimed handle is used as-is: it belongs to the conversation this
1354
+ // spawn is reopening, and re-deriving it would lose the numbering.
1355
+ : options.reclaim?.handle ?? assignHandle(handleBase(type), this.takenHandles()),
1356
+ description: options.description,
1357
+ // Reclaimed here, or filled in below from `name` — in which case it must
1358
+ // see the handle this record just took, since both come out of the same
1359
+ // namespace.
1360
+ alias: isTopLevelAgent(options) ? options.reclaim?.alias : undefined,
1361
+ // Overwritten below when the spawn is actually queued; a foreground spawn
1362
+ // that queues flips to "queued" there rather than being guessed at here,
1363
+ // since the pool decision needs the finished record.
1364
+ status: options.isBackground ? "queued" : "running",
1365
+ toolUses: 0,
1366
+ startedAt: Date.now(),
1367
+ abortController,
1368
+ lifetimeUsage: { input: 0, output: 0, cacheWrite: 0, cost: 0 },
1369
+ compactionCount: 0,
1370
+ // Raw tri-state (not coerced to a boolean): true = background, false =
1371
+ // foreground (has an inline tool-result surface), undefined = caller never
1372
+ // declared it (e.g. a cross-extension RPC spawn). The widget's background-
1373
+ // only filter excludes only explicit `false`, so undefined agents — which
1374
+ // have no inline surface — stay visible instead of vanishing.
1375
+ isBackground: options.isBackground,
1376
+ // Whether anyone is awaiting this agent is a property of the agent, not
1377
+ // of the call that made it — and both settle paths need it long after
1378
+ // `options` has stopped being the interesting object.
1379
+ blocking: options.blocking,
1380
+ invocation: options.invocation,
1381
+ depth: options.depth ?? 1,
1382
+ parentAgentId: options.parentAgentId,
1383
+ // A workflow's descendant is still the workflow's: keep the owner id
1384
+ // separate from the agent lineage so both protections apply.
1385
+ workflowId: options.workflowId ?? parentRecord?.workflowId,
1386
+ ownerIds,
1387
+ maxSubagentDepth: options.maxSubagentDepth,
1388
+ rootSessionId,
1389
+ rootCwd,
1390
+ rootSessionFile,
1391
+ // The reopen source is known before the session object exists. Pinning it
1392
+ // here lets cleanup protect the shared history during a tombstone reopen.
1393
+ sessionFile: options.resumeSessionFile,
1394
+ };
1395
+ this.agents.set(id, record);
1396
+ // After the insert, so `takenHandles()` already counts this record's own
1397
+ // handle — a spawn named after its own type gets `explore-2`, not a
1398
+ // duplicate `explore` that would make resolution ambiguous.
1399
+ if (record.handle !== undefined && record.alias === undefined && options.name !== undefined) {
1400
+ record.alias = assignHandle(handleBase(options.name), this.takenHandles());
1401
+ }
1402
+
1403
+ // Admission snapshot: queued spawns and async acquire guards can start long
1404
+ // after this call, so the definition that named this agent is pinned now.
1405
+ // A caller that resolved against a scoped registry supplies its own; only
1406
+ // a caller that did not gets the process-global definition read here.
1407
+ const agentDefinition = options.agentDefinition === undefined
1408
+ ? cloneAgentDefinition(getAgentConfig(type))
1409
+ : cloneAgentDefinition(options.agentDefinition);
1410
+
1411
+ const args: SpawnArgs = { pi, ctx, type, prompt, options: { ...options, agentDefinition } };
1412
+
1413
+ const pool = this.poolFor(record);
1414
+ if (pool !== undefined && !options.bypassQueue && !this.poolHasRoom(pool)) {
1415
+ // Queue it — started when a running agent in the same pool completes.
1416
+ // Idempotent for background (already "queued"); the flip that matters is
1417
+ // a blocking foreground spawn, optimistically marked "running" above.
1418
+ record.status = "queued";
1419
+ // A queued record never reaches startAgent's signal wiring, so arm the
1420
+ // parent abort here or Esc could not release the position.
1421
+ if (!this.armQueuedAbort(record, options.signal)) return id;
1422
+ let release!: () => void;
1423
+ record.startGate = new Promise<void>(resolve => { release = resolve; });
1424
+ this.queue.push({
1425
+ id,
1426
+ pool,
1427
+ start: () => this.launch(id, record, args, pool),
1428
+ release: () => release(),
1429
+ });
1430
+ options.onQueued?.(id, this.queue.filter(e => e.pool === pool).length - 1);
1431
+ return id;
1432
+ }
1433
+
1434
+ this.launch(id, record, args, undefined);
1435
+ return id;
1436
+ }
1437
+
1438
+ /**
1439
+ * Wire a parent abort signal for a record that is about to be QUEUED.
1440
+ * `startAgent` does this for running agents, and a queued record never gets
1441
+ * there, so without this Esc could not release a queue position.
1442
+ *
1443
+ * Returns false when the signal is ALREADY aborted, in which case the record
1444
+ * is stopped here and must not be enqueued: `addEventListener` never fires on
1445
+ * an aborted signal, so a `spawnAndWait` on it would wait forever — pi has no
1446
+ * tool-execution timeout to bail it out.
1447
+ *
1448
+ * The wire is generation-owned and registered for immediate detach: the start
1449
+ * that leaves the queue REPLACES it with its own run wire, and
1450
+ * abort()/abortAll()/dispose() detach it at once — so this listener never
1451
+ * outlives the generation that armed it, and a late abort of the queue signal
1452
+ * cannot stop a later resumed generation.
1453
+ */
1454
+ private armQueuedAbort(record: AgentRecord, signal?: AbortSignal): boolean {
1455
+ if (signal === undefined) return true;
1456
+ if (signal.aborted) {
1457
+ record.status = "stopped";
1458
+ record.completedAt = Date.now();
1459
+ if (!record.isBackground) record.resultConsumed = true;
1460
+ this.archiveTerminal(record);
1461
+ return false;
1462
+ }
1463
+ this.attachSignalWire(record, signal, record.runGeneration ?? 0);
1464
+ return true;
1465
+ }
1466
+
1467
+ /**
1468
+ * Kick off an agent's startup and register it under `startups`. The returned
1469
+ * promise never rejects — the failure is delivered through `awaitStartup`,
1470
+ * and to the record. Background startup failures use ordinary completion;
1471
+ * callers delivering the failure inline consume it themselves.
1472
+ *
1473
+ * @param queuedPool - The pool this start was QUEUED on, or undefined for an
1474
+ * immediate start. A queue drain can be minutes after `spawn()` returned,
1475
+ * and nobody is awaiting `awaitStartup` by then, so a failure has to live
1476
+ * on the record as status "error" — what drainQueue did when the throw was
1477
+ * still synchronous. Immediate foreground failures drop the unreturned
1478
+ * record; detached callers keep a retrievable failure and ordinary wakeup.
1479
+ */
1480
+ private launch(id: string, record: AgentRecord, args: SpawnArgs, queuedPool: Pool | undefined): Promise<void> {
1481
+ // Claim the pool slot BEFORE `startAgent` can await an async guard or a
1482
+ // worktree copy. `drainQueue` walks the queue synchronously and checks the
1483
+ // same counters, so without this reservation two entries would both pass
1484
+ // `poolHasRoom` while the first is still suspended — oversubscribing a
1485
+ // maxConcurrent of 1 by the whole backlog. The pool is resolved here (not
1486
+ // later in startAgent) so the reservation, the run's charge and its release
1487
+ // all name the same pool even if the user changes a limit mid-run.
1488
+ const pool = this.poolFor(record);
1489
+ const reservation = this.reservePoolSlot(pool, record);
1490
+ const generation = record.runGeneration ?? 0;
1491
+ const startup = this.startAgent(id, record, args, pool, reservation).then(
1492
+ (settledOnQueuedStop) => {
1493
+ this.startups.delete(id);
1494
+ if (record.status === "stopped" && !record.promise) {
1495
+ // An abort that landed while this record was still QUEUED already
1496
+ // archived and notified it; startAgent says so to avoid a second
1497
+ // completion callback here. A stop during the worktree copy has not
1498
+ // been notified yet, so it still settles through the normal path.
1499
+ if (settledOnQueuedStop !== false && this.agents.get(id) === record) {
1500
+ this.settleRun(record, true, undefined);
1501
+ }
1502
+ this.drainQueue();
1503
+ }
1504
+ },
1505
+ (err) => {
1506
+ this.startups.delete(id);
1507
+ // No-op once transferred; covers every pre-run refusal path.
1508
+ reservation?.releasePending();
1509
+ // abort() can land after startAgent rejected but before this callback.
1510
+ // Its queued generation is already archived/notified; do not settle it again.
1511
+ if (this.notifiedQueuedAborts.get(record) === generation) {
1512
+ this.drainQueue();
1513
+ return;
1514
+ }
1515
+ if (this.agents.get(id) === record) {
1516
+ if (queuedPool !== undefined || record.isBackground || record.status === "stopped") {
1517
+ if (record.status !== "stopped") {
1518
+ record.status = "error";
1519
+ record.error = err instanceof Error ? err.message : String(err);
1520
+ }
1521
+ record.completedAt ??= Date.now();
1522
+ // Startup already released its slot; reuse normal consumption,
1523
+ // disposal suppression and completion routing.
1524
+ this.settleRun(record, true, undefined);
1525
+ } else {
1526
+ // Immediate foreground failure: the caller gets the throw and the
1527
+ // row is not kept, but the terminal generation is still archived
1528
+ // honestly as an error rather than silently disappearing.
1529
+ record.status = "error";
1530
+ record.error = err instanceof Error ? err.message : String(err);
1531
+ record.completedAt ??= Date.now();
1532
+ this.archiveTerminal(record);
1533
+ this.agents.delete(id);
1534
+ }
1535
+ }
1536
+ // The agent never kept its slot (startAgent gives it back on failure),
1537
+ // so anything queued behind it can go now.
1538
+ this.drainQueue();
1539
+ throw err;
1540
+ },
1541
+ );
1542
+ this.startups.set(id, startup);
1543
+ // Nothing is obliged to await `startups` — swallow the rejection once here
1544
+ // so an unawaited startup can't take the process down, and hand callers
1545
+ // (drainQueue) that swallowed promise.
1546
+ return startup.catch(() => {});
1547
+ }
1548
+
1549
+ /**
1550
+ * Resolves once the agent is actually running, and rejects with the startup
1551
+ * failure (strict worktree isolation) that `spawn()` used to throw before the
1552
+ * repo copy became async. Resolves immediately for an agent that is already
1553
+ * running, still queued, or unknown — so callers can await it unconditionally.
1554
+ *
1555
+ * Call it in the same tick as the `spawn()` it belongs to: a settled startup
1556
+ * removes this promise entry. Detached failures remain on their records.
1557
+ */
1558
+ awaitStartup(id: string): Promise<void> {
1559
+ return this.startups.get(id) ?? Promise.resolve();
1560
+ }
1561
+
1562
+ /**
1563
+ * Whether a start that suspended on an acquire guard still owns the record.
1564
+ * A stop, dispose, eviction or newer run during the await must not create a
1565
+ * worktree, child session or model call afterwards.
1566
+ */
1567
+ private startIsCurrent(
1568
+ id: string,
1569
+ record: AgentRecord,
1570
+ session: AgentSession | undefined,
1571
+ generation: number,
1572
+ ): boolean {
1573
+ return !this.disposed
1574
+ && this.agents.get(id) === record
1575
+ && record.session === session
1576
+ && (record.runGeneration ?? 0) === generation
1577
+ && (record.status === "queued" || record.status === "running")
1578
+ && record.abortController?.signal.aborted !== true;
1579
+ }
1580
+
1581
+ /** Same check once the start has claimed "running" and begun worktree work. */
1582
+ private runIsCurrent(id: string, record: AgentRecord, generation: number): boolean {
1583
+ return !this.disposed
1584
+ && this.agents.get(id) === record
1585
+ && (record.runGeneration ?? 0) === generation
1586
+ && record.status === "running"
1587
+ && record.abortController?.signal.aborted !== true;
1588
+ }
1589
+
1590
+ /** Actually start an agent (called immediately or from queue drain). */
1591
+ private async startAgent(
1592
+ id: string,
1593
+ record: AgentRecord,
1594
+ { pi, ctx, type, prompt, options }: SpawnArgs,
1595
+ pool: Pool | undefined,
1596
+ reservation: SlotReservation | undefined,
1597
+ ) {
1598
+ // Capture admission identity before the guard can suspend. Any stop,
1599
+ // dispose or newer run is then detectable on the far side of the await.
1600
+ const generation = record.runGeneration ?? 0;
1601
+ const admittedSession = record.session;
1602
+ // A queued record that a stop reaches has already been archived and
1603
+ // notified by abort(); tell launch() not to settle it a second time.
1604
+ const queuedAtEntry = record.status === "queued";
1605
+
1606
+ // Wire the caller's abort signal BEFORE the first acquire await. Aborting a
1607
+ // supplied controller must reach `abort()` while the start is still only
1608
+ // CLAIMING capacity: otherwise a start suspended on a guard keeps its claim
1609
+ // (and every job behind it) until that guard settles, however long stalled
1610
+ // I/O takes. A detached, signal-less launch stays detached.
1611
+ let signalWire: SignalWire | undefined;
1612
+ if (options.signal) {
1613
+ if (options.signal.aborted) this.abort(id);
1614
+ else {
1615
+ // Replaces a queued start's early listener rather than stacking on it:
1616
+ // a stale queue signal must not be able to stop this run, and the
1617
+ // registry lets abort()/dispose() detach this one immediately.
1618
+ signalWire = this.attachSignalWire(record, options.signal, generation);
1619
+ }
1620
+ }
1621
+ const detach = () => {
1622
+ this.detachSignalWire(record, signalWire);
1623
+ signalWire = undefined;
1624
+ };
1625
+
1626
+ // Already aborted before any work: abort() released the pending claim and
1627
+ // made the record terminal; do not enter an acquire guard for it.
1628
+ if (!this.startIsCurrent(id, record, admittedSession, generation)) {
1629
+ detach();
1630
+ // Idempotent for the abort path, and the safety net for any other way a
1631
+ // start can arrive already superseded: a claim must never outlive it.
1632
+ reservation?.releasePending();
1633
+ this.drainQueue();
1634
+ return queuedAtEntry && record.status === "stopped" ? false : undefined;
1635
+ }
1636
+
1637
+ // Acquire-side barrier at the ACTUAL start: before a pool slot is taken and
1638
+ // before any worktree/session/model work. A throw follows the ordinary
1639
+ // startup-failure path, leaving counters and the record unmutated here.
1640
+ // A guard returning void keeps the whole path synchronous; only a real
1641
+ // promise suspends, and launch() has already reserved the slot for it.
1642
+ try {
1643
+ const guard = this.assertArtifactAccess(record);
1644
+ if (guard !== undefined) await guard;
1645
+ } catch (error) {
1646
+ detach();
1647
+ reservation?.releasePending();
1648
+ this.drainQueue();
1649
+ if (options.signal?.aborted) this.abort(id);
1650
+ // Rejection owns no more authority than success after suspension. A
1651
+ // cancelled/superseded admission must not deliver another completion.
1652
+ if (!this.startIsCurrent(id, record, admittedSession, generation)) {
1653
+ return queuedAtEntry && record.status === "stopped" ? false : undefined;
1654
+ }
1655
+ throw error;
1656
+ }
1657
+
1658
+ // Revalidate after the guard's suspension. A stop, dispose or superseded
1659
+ // record must not create a late worktree, child session or model call.
1660
+ if (options.signal?.aborted) this.abort(id);
1661
+ if (!this.startIsCurrent(id, record, admittedSession, generation)) {
1662
+ detach();
1663
+ reservation?.releasePending();
1664
+ this.drainQueue();
1665
+ return queuedAtEntry && record.status === "stopped" ? false : undefined;
1666
+ }
1667
+
1668
+ // Re-validate a caller-supplied cwd: queued spawns can start minutes after
1669
+ // spawn()'s check, and the directory may be gone by then (TOCTOU). Same
1670
+ // curated errors; drainQueue parks a throw on the record as an error.
1671
+ try {
1672
+ assertValidSpawnCwd(options.cwd);
1673
+ } catch (error) {
1674
+ detach();
1675
+ reservation?.releasePending();
1676
+ this.drainQueue();
1677
+ throw error;
1678
+ }
1679
+ // Single resolution point for the caller-supplied cwd — the worktree base
1680
+ // repo and both cleanup calls below MUST agree on this value forever.
1681
+ const customCwd = options.cwd ?? undefined; // null (RPC "unset") → undefined
1682
+ const baseCwd = customCwd ?? ctx.cwd;
1683
+
1684
+ // Take the running state — and with it the concurrency slot — AFTER the
1685
+ // acquire barrier but BEFORE any worktree/session/model work. The pending
1686
+ // claim made synchronously in launch() transfers here. The pool is pinned
1687
+ // there and carried to `settleRun`: recomputing it at settle time would
1688
+ // decrement a pool this run never charged (counter underflow, limit
1689
+ // silently lifted) or skip the decrement for one it did (leaked slot —
1690
+ // every later blocking spawn queues forever).
1691
+ reservation?.transfer();
1692
+ const releaseSlot = () => {
1693
+ if (pool === "background") this.runningBackground--;
1694
+ else if (pool === "foreground") this.runningForeground--;
1695
+ };
1696
+ record.status = "running";
1697
+ record.startedAt = Date.now();
1698
+ record.startGate = undefined;
1699
+
1700
+ // Discard a copy created for a start that turned out to be superseded. The
1701
+ // copy is by definition unchanged, so it is safe to remove; a cleanup
1702
+ // failure never masks the refusal that got us here.
1703
+ const discardWorktree = async (): Promise<void> => {
1704
+ const worktree = record.worktree;
1705
+ record.worktree = undefined;
1706
+ if (!worktree) return;
1707
+ try {
1708
+ record.worktreeResult = await cleanupWorktree(pi, baseCwd, worktree, options.description);
1709
+ } catch { /* never mask the refusal */ }
1710
+ };
1711
+
1712
+ // Worktree isolation: try to create a temporary git worktree. Strict —
1713
+ // fail loud if not possible (no silent fallback to main tree). Done BEFORE
1714
+ // the run is kicked off so a failure doesn't leave a half-running agent.
1715
+ // The project switch is enforced here as well as at the tool boundary
1716
+ // because cross-extension RPC forwards its options unvalidated — a schema
1717
+ // that omits the field can't stop a caller that never saw the schema.
1718
+ let worktreeCwd: string | undefined;
1719
+ if (options.isolation === "worktree" && isWorktreeIsolationEnabled()) {
1720
+ let wt: WorktreeInfo | undefined;
1721
+ try {
1722
+ wt = await createWorktree(pi, baseCwd, id);
1723
+ } catch (error) {
1724
+ detach();
1725
+ releaseSlot();
1726
+ throw error;
1727
+ }
1728
+ if (!wt) {
1729
+ detach();
1730
+ releaseSlot();
1731
+ throw new Error(
1732
+ 'Cannot run with isolation: "worktree" — not a git repo, no commits yet, or `git worktree add` failed. ' +
1733
+ 'Initialize git and commit at least once, or omit `isolation`.',
1734
+ );
1735
+ }
1736
+ record.worktree = wt;
1737
+ // workPath preserves subdirectory scoping for caller-supplied cwds: a
1738
+ // cwd deep in a monorepo maps to the same subdir inside the copy, not
1739
+ // the copied repo's root. Plain worktree spawns keep the historical
1740
+ // behavior (agent at the copy's root) — moving them to workPath would
1741
+ // also move .pi config discovery when the parent session sits in a repo
1742
+ // subdirectory, silently dropping extensions/skills.
1743
+ worktreeCwd = customCwd !== undefined ? wt.workPath : wt.path;
1744
+ this.worktreeRepos.add(baseCwd);
1745
+
1746
+ // No longer current means a stop/dispose/supersession landed while the
1747
+ // copy was being made (abort(), abortAll(), a cleared session). The
1748
+ // record is already terminal, so launching the run would burn tokens on
1749
+ // work nobody is waiting for: discard the fresh (and by definition
1750
+ // unchanged) worktree instead.
1751
+ if (options.signal?.aborted) this.abort(id);
1752
+ if (!this.runIsCurrent(id, record, generation)) {
1753
+ detach();
1754
+ releaseSlot();
1755
+ await discardWorktree();
1756
+ this.drainQueue();
1757
+ return;
1758
+ }
1759
+ }
1760
+
1761
+ // Re-check immediately before the run: the awaited worktree copy and an
1762
+ // async acquire guard are suspensions between the first check and the
1763
+ // first artifact/model work, and acquisition can be revoked while they
1764
+ // run. A refusal releases the slot and the fresh copy instead of leaving
1765
+ // either behind; a supersession does the same without starting anything.
1766
+ try {
1767
+ const guard = this.assertArtifactAccess(record);
1768
+ if (guard !== undefined) await guard;
1769
+ } catch (error) {
1770
+ detach();
1771
+ releaseSlot();
1772
+ await discardWorktree();
1773
+ this.drainQueue();
1774
+ throw error;
1775
+ }
1776
+ if (options.signal?.aborted) this.abort(id);
1777
+ if (!this.runIsCurrent(id, record, generation)) {
1778
+ detach();
1779
+ releaseSlot();
1780
+ await discardWorktree();
1781
+ this.drainQueue();
1782
+ return;
1783
+ }
1784
+
1785
+ this.onStart?.(record);
1786
+
1787
+ this.activeRuns.add(record);
1788
+ const promise = runAgent(ctx, type, prompt, {
1789
+ pi,
1790
+ agentId: id,
1791
+ agentDefinition: options.agentDefinition,
1792
+ model: options.model,
1793
+ maxTurns: options.maxTurns,
1794
+ isolated: options.isolated,
1795
+ inheritContext: options.inheritContext,
1796
+ thinkingLevel: options.thinkingLevel,
1797
+ structuredOutput: options.structuredOutput,
1798
+ resumeSessionFile: options.resumeSessionFile,
1799
+ nested: options.parentAgentId !== undefined,
1800
+ workflow: options.workflowId !== undefined,
1801
+ // Worktree wins for the working dir (the agent must run in the copy —
1802
+ // which, with a custom cwd, was created from that target). Config stays
1803
+ // with the parent project when a caller-supplied cwd is in play; it must
1804
+ // stay undefined otherwise so plain worktree runs keep resolving config
1805
+ // (incl. relative extension paths and memory) inside the worktree copy.
1806
+ cwd: worktreeCwd ?? customCwd,
1807
+ // Set iff a worktree was created (see above) — names the directory the
1808
+ // copy came from, so the prompt can tell the agent not to work there.
1809
+ worktreeBase: worktreeCwd ? baseCwd : undefined,
1810
+ configCwd: options.configCwd ?? (customCwd !== undefined ? ctx.cwd : undefined),
1811
+ signal: record.abortController!.signal,
1812
+ onToolActivity: (activity) => {
1813
+ if (activity.type === "end") record.toolUses++;
1814
+ options.onToolActivity?.(activity);
1815
+ },
1816
+ onTurnEnd: options.onTurnEnd,
1817
+ onTextDelta: options.onTextDelta,
1818
+ onModelChange: session => updateEffectiveModel(record, session),
1819
+ onAdvisorStatus: status => { record.advisorStatus = status; },
1820
+ onAssistantUsage: (usage) => {
1821
+ addUsage(record.lifetimeUsage, usage);
1822
+ this.onUsage?.(record, usage);
1823
+ options.onAssistantUsage?.(usage);
1824
+ },
1825
+ onCompaction: (info) => {
1826
+ record.compactionCount++;
1827
+ this.onCompact?.(record, info);
1828
+ options.onCompaction?.(info);
1829
+ },
1830
+ rootSessionId: record.rootSessionId,
1831
+ rootCwd: record.rootCwd,
1832
+ rootSessionFile: record.rootSessionFile,
1833
+ nestedRuntime: {
1834
+ manager: this,
1835
+ parentAgentId: id,
1836
+ depth: record.depth ?? 1,
1837
+ maxSubagentDepth: record.maxSubagentDepth,
1838
+ archive: this.archivedReportReader,
1839
+ },
1840
+ onSessionCreated: (session) => {
1841
+ if (record.session && record.session !== session) releaseToolProgress(record.session);
1842
+ record.session = session;
1843
+ // Capture now, while the session object exists: after eviction this
1844
+ // path is the only thing that can reopen the conversation, and an
1845
+ // in-memory session reports undefined, which correctly means
1846
+ // "nothing to come back to".
1847
+ // Optional chaining, not defensiveness for its own sake: this is the
1848
+ // only field read off the session at creation, so an older pi or a
1849
+ // stubbed session must degrade to "not resumable" rather than throw
1850
+ // and take the whole spawn down with it.
1851
+ record.sessionFile = session.sessionManager?.getSessionFile?.();
1852
+ record.sessionId = session.sessionManager?.getSessionId?.();
1853
+ // Same reason, different field: the model and thinking level are only
1854
+ // knowable once pi has resolved its defaults and clamped the level to
1855
+ // what the model supports. Writing them back here makes the record
1856
+ // authoritative, so every surface reads one place instead of each
1857
+ // re-deriving "session, else the request" for itself.
1858
+ updateEffectiveModel(record, session);
1859
+ if (this.disposed) {
1860
+ record.pendingSteers = undefined;
1861
+ void this.trackSessionShutdown(record, session);
1862
+ return;
1863
+ }
1864
+ // Ready now: the live record itself protects this session until its
1865
+ // teardown actually starts, so a provisional allocation row must go.
1866
+ this.markSessionReady(record, session);
1867
+ if (record.status === "stopped") {
1868
+ record.pendingSteers = undefined;
1869
+ return;
1870
+ }
1871
+ // Flush any steers that arrived before the session was ready
1872
+ if (record.pendingSteers?.length) {
1873
+ for (const msg of record.pendingSteers) {
1874
+ session.steer(msg).catch(() => {});
1875
+ }
1876
+ record.pendingSteers = undefined;
1877
+ }
1878
+ options.onSessionCreated?.(session);
1879
+ },
1880
+ onSessionAllocated: (session) => this.noteSessionAllocated(record, session),
1881
+ onSessionTeardown: (session, outcome) => this.noteSessionTeardown(record, session, outcome),
1882
+ })
1883
+ .then(({ responseText, session, aborted, steered, failure, structuredJson, structuredRetried }) => {
1884
+ // Keep the record running through cleanup: terminal status promises a
1885
+ // complete result, including its worktree note and exactly-once flush.
1886
+ const status: AgentRecord["status"] = aborted ? "aborted" : failure ? "error" : steered ? "steered" : "completed";
1887
+ if (failure && record.status !== "stopped" && !aborted) record.error = failure;
1888
+ record.result = responseText;
1889
+ // Kept beside `result`, never inside it: `result` is prose meant for a
1890
+ // reader — it is previewed, transcribed, and appended to below — while
1891
+ // this is a machine-readable payload one caller asked for by schema.
1892
+ record.structuredJson = structuredJson;
1893
+ record.structuredRetried = structuredRetried;
1894
+ if (record.session && record.session !== session) releaseToolProgress(record.session);
1895
+ // `RunResult.session` is always set by the real runner, but a stubbed
1896
+ // or mocked runner may omit it. Degrade the same way `onSessionCreated`
1897
+ // does for stubbed sessions — keep whatever that callback captured
1898
+ // instead of clobbering the record (and crashing updateEffectiveModel,
1899
+ // whose model read assumes a session object) with undefined.
1900
+ if (session) {
1901
+ record.session = session;
1902
+ updateEffectiveModel(record, session);
1903
+ }
1904
+ return { text: responseText, succeeded: true, status };
1905
+ })
1906
+ .catch((err) => {
1907
+ if (record.status !== "stopped") record.error = err instanceof Error ? err.message : String(err);
1908
+ return { text: "", succeeded: false, status: "error" as AgentRecord["status"] };
1909
+ })
1910
+ .then(async ({ text, succeeded, status }) => {
1911
+ // One finalizer, outside the run's catch: a cleanup/callback error must
1912
+ // never re-enter cleanup or release this invocation's slot twice.
1913
+ detach();
1914
+ if (record.outputCleanup) {
1915
+ const cleanup = record.outputCleanup;
1916
+ record.outputCleanup = undefined;
1917
+ // Awaited: a settled agent's transcript must be on disk before the
1918
+ // run resolves — completion notifications and hosts read it after.
1919
+ try { await cleanup(); } catch { /* ignore output side-effect errors */ }
1920
+ }
1921
+ if (record.worktree) {
1922
+ if (succeeded && options.onBeforeWorktreeCleanup) {
1923
+ try {
1924
+ // The record stays running until cleanup is complete. Let the hook
1925
+ // inspect the computed outcome without publishing it prematurely.
1926
+ await options.onBeforeWorktreeCleanup(record.worktree.path, status);
1927
+ } catch { /* ignore — never block cleanup */ }
1928
+ }
1929
+ try {
1930
+ const wtResult = await cleanupWorktree(pi, baseCwd, record.worktree, options.description);
1931
+ record.worktreeResult = wtResult;
1932
+ if (succeeded && wtResult.hasChanges && wtResult.branch) {
1933
+ const repoNote = customCwd !== undefined ? ` in \`${baseCwd}\`` : "";
1934
+ record.result = (record.result ?? "") +
1935
+ `\n\n---\nChanges saved to branch \`${wtResult.branch}\`${repoNote}. Merge with: \`git merge ${wtResult.branch}\`${customCwd !== undefined ? ` (run in \`${baseCwd}\`)` : ""}`;
1936
+ }
1937
+ } catch (err) {
1938
+ status = "error";
1939
+ record.error ??= err instanceof Error ? err.message : String(err);
1940
+ text = "";
1941
+ }
1942
+ }
1943
+ discardStaleSteers(record);
1944
+ if (record.status !== "stopped") record.status = status;
1945
+ record.completedAt ??= Date.now();
1946
+ this.abortOwnedChildren(id);
1947
+ this.activeRuns.delete(record);
1948
+ if (this.disposed) await this.trackSessionShutdown(record, record.session);
1949
+ this.settleRun(record, succeeded, pool);
1950
+ return text;
1951
+ });
1952
+
1953
+ record.promise = promise;
1954
+ this.trackPendingFinalizer(record, promise);
1955
+
1956
+ // Notify caller that spawn is complete (record is in the map, promise is set).
1957
+ // Called synchronously — onSessionCreated fires asynchronously inside runAgent.
1958
+ // Used by spawnAndWait to let the caller set up output files before streaming
1959
+ // starts. Read off the options, so a spawn that started from a queue drain
1960
+ // still reaches the caller that queued it.
1961
+ options.onSpawned?.(id);
1962
+ }
1963
+
1964
+ /**
1965
+ * The shared tail of both settle paths: release whatever pool slot the run
1966
+ * held, notify, and let the queue drain into the freed slot.
1967
+ *
1968
+ * The decrement lives HERE and nowhere else. `abort()` on a running record
1969
+ * only fires its controller and leaves the run to settle normally, so
1970
+ * decrementing there too would double-free — permanently lifting the limit.
1971
+ *
1972
+ * Foreground agents fire `onComplete` for lifecycle symmetry, with
1973
+ * `resultConsumed` set so the callback skips notifications the inline result
1974
+ * already delivered.
1975
+ *
1976
+ * @param guardCallback swallow a throwing `onComplete` (the success path does;
1977
+ * the error path historically did not, and keeps not doing so).
1978
+ * @param pool the pool this run was CHARGED TO at start time — passed in, not
1979
+ * recomputed, so a mid-run change to `maxConcurrentForeground` can't make
1980
+ * the release disagree with the acquire.
1981
+ */
1982
+ private settleRun(record: AgentRecord, guardCallback: boolean, pool: Pool | undefined): void {
1983
+ if (!record.isBackground) record.resultConsumed = true;
1984
+ // Before every completion callback: a durable copy of THIS generation's
1985
+ // report, while the record still describes the run that just settled.
1986
+ // Run protection is released separately, only after the COMPLETE finalizer
1987
+ // promise (including any output flush) settles.
1988
+ this.archiveTerminal(record);
1989
+ if (pool === "background") this.runningBackground--;
1990
+ else if (pool === "foreground") this.runningForeground--;
1991
+
1992
+ try {
1993
+ if (!this.disposed) {
1994
+ if (guardCallback) {
1995
+ try { this.onComplete?.(record); } catch { /* ignore completion side-effect errors */ }
1996
+ } else {
1997
+ this.onComplete?.(record);
1998
+ }
1999
+ }
2000
+ } finally {
2001
+ // Even a failing observer cannot strand the next queued child.
2002
+ if (record.isBackground || pool !== undefined) this.drainQueue();
2003
+ }
2004
+
2005
+ // The isBackground half reproduces the pre-pool condition exactly — a
2006
+ // background settle has always drained, even for a nested child that held
2007
+ // no slot — so that path is unchanged whether or not the foreground pool is
2008
+ // on. The `pool` half only adds the drain a freed FOREGROUND slot needs.
2009
+ // A drain with nothing freed is a no-op anyway, but "no-op" is a claim
2010
+ // about reachability, and matching the old condition needs no such claim.
2011
+ }
2012
+
2013
+ /**
2014
+ * Hand one settled generation to the durable-report archiver exactly once.
2015
+ *
2016
+ * Every terminal path calls this — fresh runs, foreground/background resumes,
2017
+ * queued cancellations, startup failures and the dispose sweep. Generation
2018
+ * dedupe matters because a run can be stopped while queued and then swept by
2019
+ * `dispose`: the first snapshot is the truthful one. A deadline FALLBACK may
2020
+ * still be replaced by the real same-generation finalizer (never the reverse),
2021
+ * so a run that settles just after the bounded window is not lost forever.
2022
+ */
2023
+ private archiveTerminal(record: AgentRecord, options: { fallback?: boolean } = {}): void {
2024
+ if (record.status === "running" || record.status === "queued") return;
2025
+ const generation = record.runGeneration ?? 0;
2026
+ const fallback = options.fallback === true;
2027
+ const prior = this.archivedGenerations.get(record.id);
2028
+ if (prior !== undefined) {
2029
+ if (prior.generation > generation) return;
2030
+ if (prior.generation === generation) {
2031
+ // Same generation: only a provisional fallback may be upgraded. A real
2032
+ // snapshot must never be replaced by a partial/stopped view.
2033
+ if (!(prior.fallback && !fallback)) return;
2034
+ }
2035
+ }
2036
+ this.archivedGenerations.set(record.id, { generation, fallback });
2037
+ try {
2038
+ this.reportArchiver?.save(record);
2039
+ } catch (error) {
2040
+ // Report durability is never allowed to break settlement or shutdown.
2041
+ console.warn("[pi-subagents] durable report archive failed:", error);
2042
+ }
2043
+ }
2044
+
2045
+ /**
2046
+ * Track a full run finalizer (output flush and worktree cleanup included) as
2047
+ * pending work for this record. Removed on either resolution branch; a record
2048
+ * can hold more than one because a newer generation settles first and
2049
+ * overwrites `record.promise` while the older flush is still in flight.
2050
+ */
2051
+ private trackPendingFinalizer(record: AgentRecord, promise: Promise<unknown>): void {
2052
+ let pending = this.pendingFinalizers.get(record);
2053
+ if (pending === undefined) {
2054
+ pending = new Set();
2055
+ this.pendingFinalizers.set(record, pending);
2056
+ }
2057
+ pending.add(promise);
2058
+ const release = () => {
2059
+ const current = this.pendingFinalizers.get(record);
2060
+ if (current === undefined) return;
2061
+ current.delete(promise);
2062
+ if (current.size === 0) this.pendingFinalizers.delete(record);
2063
+ };
2064
+ void promise.then(release, release);
2065
+ }
2066
+
2067
+ private identityFromRecord(record: AgentRecord): TeardownIdentity {
2068
+ return {
2069
+ agentId: record.id,
2070
+ ...(record.sessionFile === undefined ? {} : { sessionFile: record.sessionFile }),
2071
+ ...(record.sessionId === undefined ? {} : { sessionId: record.sessionId }),
2072
+ ...(record.rootSessionId === undefined ? {} : { rootSessionId: record.rootSessionId }),
2073
+ ...(record.rootCwd === undefined ? {} : { rootCwd: record.rootCwd }),
2074
+ ...(record.rootSessionFile === undefined ? {} : { rootSessionFile: record.rootSessionFile }),
2075
+ };
2076
+ }
2077
+
2078
+ /**
2079
+ * One protection identity per SDK session INSTANCE. The same session file can
2080
+ * be reopened as a different instance (A timed out, B later succeeds): B's
2081
+ * completion must not delete A's still-unresolved protection row.
2082
+ */
2083
+ private ensureSessionTeardown(identity: TeardownIdentity, session: AgentSession): TrackedTeardown {
2084
+ const knownId = this.teardownIds.get(session);
2085
+ if (knownId !== undefined) {
2086
+ const known = this.teardowns.get(knownId);
2087
+ if (known) return known;
2088
+ }
2089
+ const id = `session:${++this.teardownSequence}`;
2090
+ this.teardownIds.set(session, id);
2091
+ const row: TrackedTeardown = {
2092
+ id,
2093
+ phase: "session",
2094
+ status: "pending",
2095
+ at: Date.now(),
2096
+ ...identity,
2097
+ session,
2098
+ };
2099
+ this.teardowns.set(id, row);
2100
+ return row;
2101
+ }
2102
+
2103
+ private applyTeardownOutcome(row: TrackedTeardown, outcome: ChildShutdownOutcome): void {
2104
+ row.status = outcome.status;
2105
+ row.reason = outcome.reason;
2106
+ // The SDK object must not outlive its teardown, even when the row is kept
2107
+ // forever as protection.
2108
+ row.session = undefined;
2109
+ if (outcome.status === "completed") {
2110
+ this.teardowns.delete(row.id);
2111
+ } else {
2112
+ row.at = Date.now();
2113
+ }
2114
+ }
2115
+
2116
+ /**
2117
+ * Register protection synchronously, then start the bounded shutdown. The row
2118
+ * exists BEFORE the first await: an immediate dispose after eviction sees the
2119
+ * pending promise and cannot report `completed` for an unresolved handler.
2120
+ */
2121
+ private startSessionTeardown(
2122
+ identity: TeardownIdentity,
2123
+ session: AgentSession | undefined,
2124
+ ): Promise<ChildShutdownOutcome> {
2125
+ if (!session) return Promise.resolve({ status: "completed", timedOut: false });
2126
+ const row = this.ensureSessionTeardown(identity, session);
2127
+ if (row.promise) return row.promise;
2128
+ if (row.status !== "pending") {
2129
+ return Promise.resolve({
2130
+ status: row.status,
2131
+ timedOut: row.status === "timed_out",
2132
+ ...(row.reason === undefined ? {} : { reason: row.reason }),
2133
+ });
2134
+ }
2135
+ row.promise = shutdownChildSession(session).then(
2136
+ outcome => {
2137
+ this.applyTeardownOutcome(row, outcome);
2138
+ return outcome;
2139
+ },
2140
+ (error: unknown) => {
2141
+ const outcome: ChildShutdownOutcome = {
2142
+ status: "failed",
2143
+ timedOut: false,
2144
+ reason: error instanceof Error ? error.message : String(error),
2145
+ };
2146
+ this.applyTeardownOutcome(row, outcome);
2147
+ return outcome;
2148
+ },
2149
+ );
2150
+ return row.promise;
2151
+ }
2152
+
2153
+ private trackSessionShutdown(
2154
+ record: AgentRecord,
2155
+ session: AgentSession | undefined,
2156
+ ): Promise<ChildShutdownOutcome> {
2157
+ return this.startSessionTeardown(this.identityFromRecord(record), session);
2158
+ }
2159
+
2160
+ /** Record the allocated instance before binding; no ready announcement yet. */
2161
+ private noteSessionAllocated(record: AgentRecord, session: AgentSession): void {
2162
+ record.sessionFile ??= session.sessionManager?.getSessionFile?.();
2163
+ record.sessionId ??= session.sessionManager?.getSessionId?.();
2164
+ const identity = this.identityFromRecord(record);
2165
+ this.ensureSessionTeardown(identity, session);
2166
+ if (!this.allocationStates.has(session)) {
2167
+ let resolveReady!: () => void;
2168
+ const ready = new Promise<void>(resolve => { resolveReady = resolve; });
2169
+ this.allocationStates.set(session, {
2170
+ session,
2171
+ identity,
2172
+ ready,
2173
+ resolveReady,
2174
+ settled: false,
2175
+ });
2176
+ }
2177
+ let allocated = this.allocations.get(record.id);
2178
+ if (!allocated) {
2179
+ allocated = new Set();
2180
+ this.allocations.set(record.id, allocated);
2181
+ }
2182
+ allocated.add(session);
2183
+ }
2184
+
2185
+ /** Bind/session_start settled (successfully, or its failure teardown ran). */
2186
+ private settleAllocation(session: AgentSession): void {
2187
+ const state = this.allocationStates.get(session);
2188
+ if (!state || state.settled) return;
2189
+ state.settled = true;
2190
+ state.resolveReady();
2191
+ }
2192
+
2193
+ /** The session is now a live, addressable record; teardown is not in flight. */
2194
+ private markSessionReady(record: AgentRecord, session: AgentSession): void {
2195
+ const knownId = this.teardownIds.get(session);
2196
+ const row = knownId === undefined ? undefined : this.teardowns.get(knownId);
2197
+ if (row && row.promise === undefined && row.status === "pending") {
2198
+ this.teardowns.delete(row.id);
2199
+ }
2200
+ this.settleAllocation(session);
2201
+ this.releaseAllocation(record.id, session);
2202
+ }
2203
+
2204
+ /** Bind-failure (or equivalent partial startup) outcome handed back by runner. */
2205
+ private noteSessionTeardown(
2206
+ record: AgentRecord,
2207
+ session: AgentSession,
2208
+ outcome: ChildShutdownOutcome,
2209
+ ): void {
2210
+ this.ensureSessionTeardown(this.identityFromRecord(record), session);
2211
+ const knownId = this.teardownIds.get(session);
2212
+ const row = knownId === undefined ? undefined : this.teardowns.get(knownId);
2213
+ if (row) this.applyTeardownOutcome(row, outcome);
2214
+ this.settleAllocation(session);
2215
+ this.releaseAllocation(record.id, session);
2216
+ }
2217
+
2218
+ private releaseAllocation(agentId: string, session?: AgentSession): void {
2219
+ const allocated = this.allocations.get(agentId);
2220
+ if (!allocated) return;
2221
+ if (session) allocated.delete(session);
2222
+ else allocated.clear();
2223
+ if (allocated.size === 0) this.allocations.delete(agentId);
2224
+ }
2225
+
2226
+ /** Protection row for a run/finalizer that outlived the shutdown deadline. */
2227
+ private recordRunUncertainty(record: AgentRecord, generation = record.runGeneration ?? 0): void {
2228
+ const id = `run:${record.id}:${generation}`;
2229
+ const existing = this.teardowns.get(id);
2230
+ if (existing) return;
2231
+ this.teardowns.set(id, {
2232
+ id,
2233
+ phase: "run",
2234
+ status: "timed_out",
2235
+ at: Date.now(),
2236
+ reason: `run finalizer did not settle within ${MANAGER_SHUTDOWN_DEADLINE_MS}ms`,
2237
+ ...this.identityFromRecord(record),
2238
+ });
2239
+ }
2240
+
2241
+ /**
2242
+ * Release protection for exactly the run generation whose COMPLETE disposal
2243
+ * aggregate (including every generation's output flush) settled. Called only
2244
+ * by dispose/reconcileLateFinalizer, never by an individual run finalizer: a
2245
+ * newer generation must not release an older generation's pending flush.
2246
+ */
2247
+ private clearRunUncertainty(agentId: string, generation: number): void {
2248
+ this.teardowns.delete(`run:${agentId}:${generation}`);
2249
+ }
2250
+
2251
+ /**
2252
+ * A captured startup/run finalizer that outlived dispose's sweep still owes a
2253
+ * real report and the release of its provisional run protection. This runs
2254
+ * independently of map membership and never calls settleRun/callbacks or
2255
+ * releases a pool slot again.
2256
+ */
2257
+ private reconcileLateFinalizer(record: AgentRecord, generation: number): void {
2258
+ if ((record.runGeneration ?? 0) !== generation) return;
2259
+ if (record.status === "running" || record.status === "queued") return;
2260
+ this.archiveTerminal(record);
2261
+ this.clearRunUncertainty(record.id, generation);
2262
+ }
2263
+
2264
+ /**
2265
+ * Stop the nested children a settled parent owns. Nested records are hidden
2266
+ * from the UI and only their owner can consume them, so a child outliving its
2267
+ * parent would burn tokens unseen with no way to reach it. Grandchildren are
2268
+ * covered transitively — each abort lands in that child's own settle path.
2269
+ */
2270
+ private abortOwnedChildren(parentId: string): void {
2271
+ for (const [id, record] of this.agents) {
2272
+ if (record.parentAgentId === parentId) this.abort(id);
2273
+ }
2274
+ }
2275
+
2276
+ /**
2277
+ * Start queued agents up to each pool's concurrency limit.
2278
+ *
2279
+ * `findIndex` on the entry's OWN pool rather than `shift`: with one queue
2280
+ * serving two independent limits, a saturated foreground pool at the head
2281
+ * would otherwise stall every background agent behind it. Taking the earliest
2282
+ * eligible entry keeps FIFO within each pool, which is what callers see.
2283
+ */
2284
+ private drainQueue() {
2285
+ for (;;) {
2286
+ const i = this.queue.findIndex(e => this.poolHasRoom(e.pool));
2287
+ if (i === -1) return;
2288
+ const [next] = this.queue.splice(i, 1);
2289
+ const record = this.agents.get(next.id);
2290
+ // Stale entries (aborted while queued) are not started — but are still
2291
+ // released, since nothing else will.
2292
+ if (!record || record.status !== "queued") { next.release(); continue; }
2293
+ // Detached, and never rejects: a late failure (e.g. strict worktree
2294
+ // isolation) lands on the record inside `launch`, exactly as the
2295
+ // synchronous throw did here before, and draining continues either way.
2296
+ //
2297
+ // The release waits for that startup to SETTLE rather than firing here.
2298
+ // Startup is async now, so a release at drain time would wake a blocked
2299
+ // `spawnAndWait` while `record.promise` was still undefined, and it would
2300
+ // read a perfectly healthy agent as one that never ran.
2301
+ void next.start().then(() => next.release(), () => next.release());
2302
+ }
2303
+ }
2304
+
2305
+ /**
2306
+ * Remove queued entries and wake anyone blocked on them. The single point
2307
+ * that enforces "leaving the queue releases the waiter" — a missed release is
2308
+ * an unbounded hang, not a failed call.
2309
+ */
2310
+ private dequeue(pred: (entry: { id: string; pool: Pool }) => boolean): void {
2311
+ const kept: typeof this.queue = [];
2312
+ for (const entry of this.queue) {
2313
+ if (pred(entry)) entry.release();
2314
+ else kept.push(entry);
2315
+ }
2316
+ this.queue = kept;
2317
+ }
2318
+
2319
+ /**
2320
+ * Spawn an agent and wait for completion (foreground use).
2321
+ * Charged to the foreground pool (`maxConcurrentForeground`), which is
2322
+ * unlimited by default; never to the background one.
2323
+ * Returns { id, record } so callers can access the agent ID.
2324
+ *
2325
+ * @param onSpawned - Called synchronously once the run is kicked off, before
2326
+ * onSessionCreated fires. Use this to set record.outputFile so
2327
+ * streamToOutputFile can pick it up.
2328
+ */
2329
+ async spawnAndWait(
2330
+ pi: ExtensionAPI,
2331
+ ctx: ExtensionContext,
2332
+ type: SubagentType,
2333
+ prompt: string,
2334
+ options: Omit<SpawnOptions, "isBackground">,
2335
+ onSpawned?: (id: string) => void,
2336
+ ): Promise<{ id: string; record: AgentRecord }> {
2337
+ // `blocking` is what maxConcurrentForeground bounds, and this is its only
2338
+ // source. onSpawned rides on the options rather than on a field of this
2339
+ // manager: a queued spawn starts at drain time, long after any install/
2340
+ // restore pair around this call would have put the field back — and it now
2341
+ // fires after an await (worktree creation) even on the immediate path.
2342
+ const id = this.spawn(pi, ctx, type, prompt, {
2343
+ ...options,
2344
+ isBackground: false,
2345
+ blocking: true,
2346
+ onSpawned,
2347
+ });
2348
+ const record = this.agents.get(id)!;
2349
+
2350
+ // Queued: nothing to await yet — the promise appears when the drain starts
2351
+ // it. The gate resolves (never rejects) on every path out of the queue,
2352
+ // start and abort alike, so a rejection can never escape into the caller's
2353
+ // tool `execute` and take down pi's whole Promise.all tool batch.
2354
+ if (record.status === "queued") await record.startGate;
2355
+
2356
+ // The run promise only exists once startup is past its awaited repo copy —
2357
+ // without this the call would return before the agent had started at all.
2358
+ // A startup failure (strict worktree isolation) rejects here, which is what
2359
+ // the immediate path owes its caller: pi only marks a tool result failed
2360
+ // when `execute` throws. A queued spawn's failure landed on the record
2361
+ // instead (nobody was awaiting `startups` at drain time) and is rethrown
2362
+ // below, so the contract is the same either way.
2363
+ await this.awaitStartup(id);
2364
+
2365
+ // undefined when it was aborted while queued, or stopped mid-copy, and so
2366
+ // never ran — the record is already terminal with a completedAt, which is
2367
+ // what the caller renders.
2368
+ if (record.promise) await record.promise;
2369
+
2370
+ // A record that ended "error" without ever getting a promise never ran: the
2371
+ // same startup failure spawn() rethrows on the immediate path (#179). Keep
2372
+ // one contract rather than letting queue pressure decide whether a strict
2373
+ // worktree failure throws or returns as a result.
2374
+ if (record.promise === undefined && record.status === "error") {
2375
+ throw new Error(record.error ?? "Agent failed to start");
2376
+ }
2377
+ return { id, record };
2378
+ }
2379
+
2380
+ /**
2381
+ * Resume an existing agent session with a new prompt.
2382
+ */
2383
+ async resume(
2384
+ id: string,
2385
+ prompt: string,
2386
+ signal?: AbortSignal,
2387
+ options?: ResumeOptions,
2388
+ ): Promise<AgentRecord | undefined> {
2389
+ const record = this.agents.get(id);
2390
+ if (!record?.session || this.disposed || this.activeRuns.has(record)
2391
+ || record.status === "running" || record.status === "queued") return undefined;
2392
+
2393
+ // Admission exclusivity is claimed SYNCHRONOUSLY, before the acquire guard
2394
+ // can suspend. Two callers can otherwise pass the settled-state check in
2395
+ // the same tick and both stamp a generation. The loser returns undefined
2396
+ // without touching terminal data; the winner releases the claim once the
2397
+ // record is queued/running (status carries exclusivity from then on) or
2398
+ // when admission is refused.
2399
+ if (this.resumeAdmissions.has(record)) return undefined;
2400
+ this.resumeAdmissions.add(record);
2401
+ const admittedSession = record.session;
2402
+ const admittedGeneration = record.runGeneration ?? 0;
2403
+
2404
+ // Acquire-side barrier BEFORE any run bookkeeping: a refusal leaves the
2405
+ // settled record (status, result, generation, session) exactly as it was.
2406
+ // An async guard is awaited here; everything below is the acceptance
2407
+ // decision, taken atomically in one synchronous continuation.
2408
+ try {
2409
+ const guard = this.assertArtifactAccess(record);
2410
+ if (guard !== undefined) await guard;
2411
+ } catch (error) {
2412
+ this.resumeAdmissions.delete(record);
2413
+ throw error;
2414
+ }
2415
+
2416
+ // Revalidate after the guard's suspension: a dispose, eviction, newer run
2417
+ // or changed session must not be resumed by stale admission state.
2418
+ if (!this.resumeAdmissionIsCurrent(id, record, admittedSession, admittedGeneration)) {
2419
+ this.resumeAdmissions.delete(record);
2420
+ return undefined;
2421
+ }
2422
+
2423
+ // Every guarded identity check has passed and the synchronous claim is
2424
+ // still held: this caller is the sole accepted resume. Hand it the record
2425
+ // NOW — before the generation stamp, terminal reset or any start — so shared
2426
+ // per-run wiring belongs to the winner only. A throwing hook is an ordinary
2427
+ // refusal: release the claim and leave the settled record untouched rather
2428
+ // than leaking admission and blocking every later resume.
2429
+ try {
2430
+ options?.onAdmitted?.(record);
2431
+ } catch (error) {
2432
+ this.resumeAdmissions.delete(record);
2433
+ throw error;
2434
+ }
2435
+
2436
+ // The hook is caller code running while the claim is held: it may
2437
+ // synchronously dispose the manager, evict the record or replace its
2438
+ // session. Repeat the WHOLE admission identity check AFTER it — the same
2439
+ // capture the guard's suspension is revalidated against — so a
2440
+ // shutting-down record is never stamped, reset, queued or resumed, and hand
2441
+ // the claim back when the admission is refused.
2442
+ if (!this.resumeAdmissionIsCurrent(id, record, admittedSession, admittedGeneration)) {
2443
+ this.resumeAdmissions.delete(record);
2444
+ return undefined;
2445
+ }
2446
+
2447
+ // A resume is a new run of the same record. Stamp it before any state is
2448
+ // reset so a superseded completion (held group, pending nudge) can be told
2449
+ // apart from this run's — a timestamp cannot, since a resume can land in
2450
+ // the same millisecond as the settle it replaces. Any earlier cleanup
2451
+ // readiness proof is now stale.
2452
+ record.runGeneration = admittedGeneration + 1;
2453
+ const generation = record.runGeneration;
2454
+ this.cleanupQuiescence.delete(id);
2455
+
2456
+ // Background resume: settle asynchronously and notify on completion exactly
2457
+ // like a background spawn, returning immediately with the record still
2458
+ // "running" — or "queued" when at the concurrency limit. Previously
2459
+ // run_in_background was ignored on resume (the Agent tool's resume branch
2460
+ // returned before its background branch, and resume() only ever awaited
2461
+ // inline), so a resumed agent always blocked the caller until it finished.
2462
+ if (options?.isBackground) {
2463
+ // Never re-enter a run that is still in flight. Detaching means the caller
2464
+ // gets control back while the record stays "running", so nothing stops the
2465
+ // model from resuming the same agent again. Starting a second run would
2466
+ // overwrite record.abortController — orphaning the live run beyond the
2467
+ // reach of `/agents` stop and abortAll() — double-count the pool slot, and
2468
+ // then reject from session.prompt() with "Agent is already processing",
2469
+ // whose settle path would abort the LIVE run's children and report a
2470
+ // failure for a run that is still going. Refuse instead, leaving the
2471
+ // record untouched; the caller decides whether to wait or steer.
2472
+ record.isBackground = true;
2473
+ record.resultConsumed = false;
2474
+ record.result = undefined;
2475
+ record.error = undefined;
2476
+ record.completedAt = undefined;
2477
+ record.status = "queued";
2478
+
2479
+ const start = () => this.startResume(id, record, prompt, signal, options);
2480
+ if (occupiesPoolSlot(record) && !this.poolHasRoom("background")) {
2481
+ if (!this.armQueuedAbort(record, signal)) {
2482
+ this.resumeAdmissions.delete(record);
2483
+ return record;
2484
+ }
2485
+ // At the concurrency limit — queue it, drains when a slot frees. A
2486
+ // detached resume has no inline caller, hence nothing to release. The
2487
+ // queue is shared with spawns, whose startup is async, so entries are
2488
+ // promise-shaped even though a resume starts synchronously; failures
2489
+ // land on the record here, since drainQueue no longer catches.
2490
+ this.queue.push({
2491
+ id,
2492
+ pool: "background",
2493
+ start: () => {
2494
+ const startup = (async () => {
2495
+ // Reserve capacity SYNCHRONOUSLY, before the acquire guard can
2496
+ // suspend. drainQueue checked this entry's pool a moment ago, but
2497
+ // a sync-guard sibling started earlier in the same drain would
2498
+ // otherwise still be invisible here and the backlog would all
2499
+ // start at once.
2500
+ const reservation = this.reservePoolSlot("background", record);
2501
+ try {
2502
+ // Actual (drained) start: acquisition was checked when the resume
2503
+ // was requested, but the reserved root may have changed while this
2504
+ // waited for a slot. A refusal follows this catch's ordinary
2505
+ // queued-start failure path; no model starts.
2506
+ const guard = this.assertArtifactAccess(record);
2507
+ if (guard !== undefined) await guard;
2508
+ } catch (err) {
2509
+ reservation?.releasePending();
2510
+ this.failQueuedResume(id, record, admittedSession, generation, err);
2511
+ return;
2512
+ }
2513
+ // Revalidate after the guard's suspension: abort while queued sets
2514
+ // "stopped", and a dispose or newer generation must not start a
2515
+ // late child on this session.
2516
+ if (!this.queuedResumeIsCurrent(id, record, admittedSession, generation)) {
2517
+ reservation?.releasePending();
2518
+ this.drainQueue();
2519
+ return;
2520
+ }
2521
+ try {
2522
+ this.startResume(id, record, prompt, signal, options, reservation);
2523
+ } catch (err) {
2524
+ this.failQueuedResume(id, record, admittedSession, generation, err);
2525
+ }
2526
+ })();
2527
+ // Expose the real start as pending startup work even though it is
2528
+ // routed from the queue, not launch(): waitForAll and dispose must
2529
+ // not treat a guard-suspended record as idle. Never left behind.
2530
+ this.startups.set(id, startup);
2531
+ const settle = () => {
2532
+ if (this.startups.get(id) === startup) this.startups.delete(id);
2533
+ };
2534
+ void startup.then(settle, settle);
2535
+ return startup;
2536
+ },
2537
+ release: () => {},
2538
+ });
2539
+ } else {
2540
+ start();
2541
+ }
2542
+ this.resumeAdmissions.delete(record);
2543
+ return record;
2544
+ }
2545
+
2546
+ // Foreground resumes use the same controller and stopped-state guard, but
2547
+ // keep their historical inline-only result (no background notification/pool).
2548
+ this.startResume(id, record, prompt, signal, { ...options, isBackground: false });
2549
+ this.resumeAdmissions.delete(record);
2550
+ await record.promise;
2551
+ return record;
2552
+ }
2553
+
2554
+ /**
2555
+ * A resume that suspended on its acquire guard still owns the record only if
2556
+ * nothing terminal happened while it waited. Kept separate from the queued
2557
+ * variant: a queued resume legitimately sits in "queued" while admitting.
2558
+ */
2559
+ private resumeAdmissionIsCurrent(
2560
+ id: string,
2561
+ record: AgentRecord,
2562
+ session: AgentSession,
2563
+ generation: number,
2564
+ ): boolean {
2565
+ return !this.disposed
2566
+ && this.agents.get(id) === record
2567
+ && record.session === session
2568
+ && (record.runGeneration ?? 0) === generation
2569
+ && record.status !== "running"
2570
+ && record.status !== "queued"
2571
+ && !this.activeRuns.has(record);
2572
+ }
2573
+
2574
+ /** Same revalidation for a resume whose queued start just awaited its guard. */
2575
+ private queuedResumeIsCurrent(
2576
+ id: string,
2577
+ record: AgentRecord,
2578
+ session: AgentSession,
2579
+ generation: number,
2580
+ ): boolean {
2581
+ return !this.disposed
2582
+ && this.agents.get(id) === record
2583
+ && record.session === session
2584
+ && (record.runGeneration ?? 0) === generation
2585
+ && record.status === "queued"
2586
+ && !this.activeRuns.has(record);
2587
+ }
2588
+
2589
+ /** The queued-start refusal path: this generation is terminal, no run began. */
2590
+ private failQueuedResume(id: string, record: AgentRecord, session: AgentSession, generation: number, error: unknown): void {
2591
+ // A dispose, eviction, abort or newer generation during the guard owns the
2592
+ // record now. A late rejection must not overwrite that generation's state.
2593
+ if (!this.queuedResumeIsCurrent(id, record, session, generation)) {
2594
+ this.drainQueue();
2595
+ return;
2596
+ }
2597
+ // No run finalizer will detach this queued wire. Retire it before any
2598
+ // terminal observer can resume the record without a parent signal.
2599
+ this.releaseSignalWire(record);
2600
+ record.status = "error";
2601
+ record.error = error instanceof Error ? error.message : String(error);
2602
+ record.completedAt = Date.now();
2603
+ // The refusal is this generation's terminal report. No pool slot was
2604
+ // claimed, so archive before notifying without settling.
2605
+ this.archiveTerminal(record);
2606
+ try {
2607
+ this.onComplete?.(record);
2608
+ } finally {
2609
+ // An observer failure must not strand siblings behind this refused start.
2610
+ this.drainQueue();
2611
+ }
2612
+ }
2613
+
2614
+ /**
2615
+ * Start a background resume run: detached, settling and notifying like
2616
+ * startAgent's background path. Invoked immediately, or from drainQueue when
2617
+ * a concurrency slot frees. The session already exists (resume reuses it), so
2618
+ * there is no onSessionCreated to hang per-run wiring off — callers use
2619
+ * `options.onStarted`, which fires on both the immediate and the drained path.
2620
+ */
2621
+ private startResume(
2622
+ id: string,
2623
+ record: AgentRecord,
2624
+ prompt: string,
2625
+ parentSignal: AbortSignal | undefined,
2626
+ options: ResumeOptions,
2627
+ reservation?: SlotReservation,
2628
+ ) {
2629
+ if (!record.session) {
2630
+ reservation?.releasePending();
2631
+ return;
2632
+ }
2633
+
2634
+ const background = options.isBackground === true;
2635
+ const holdsSlot = background && occupiesPoolSlot(record);
2636
+ this.activeRuns.add(record);
2637
+ record.status = "running";
2638
+ record.startedAt = Date.now();
2639
+ record.completedAt = undefined;
2640
+ record.result = undefined;
2641
+ record.error = undefined;
2642
+ if (holdsSlot) {
2643
+ // A queued start reserved this capacity before its guard awaited; an
2644
+ // immediate start increments it here, still synchronously with the
2645
+ // capacity decision made by resume().
2646
+ if (reservation) reservation.transfer();
2647
+ else this.runningBackground++;
2648
+ } else {
2649
+ reservation?.releasePending();
2650
+ }
2651
+ if (background) this.onStart?.(record);
2652
+
2653
+ // Fresh abort controller so /agents stop and steering target THIS run rather
2654
+ // than the previous one's settled controller.
2655
+ const abortController = new AbortController();
2656
+ record.abortController = abortController;
2657
+ // Optional, and NOT what the Agent tool passes for a detached resume: a
2658
+ // parent signal aborts on the parent's own interrupt (user Esc), which is
2659
+ // right for a foreground run whose result the caller is awaiting, and wrong
2660
+ // for a detached one — background spawns omit it for exactly this reason.
2661
+ // Generation-owned: this replaces the queued wire this resume carried, and
2662
+ // abort()/abortAll()/dispose() can detach it without waiting for `settle`.
2663
+ const generation = record.runGeneration ?? 0;
2664
+ let signalWire: SignalWire | undefined;
2665
+ if (parentSignal) {
2666
+ if (parentSignal.aborted) this.abort(id);
2667
+ else signalWire = this.attachSignalWire(record, parentSignal, generation);
2668
+ }
2669
+
2670
+ // Per-run side effects (output streaming) — see ResumeOptions.onStarted.
2671
+ // After the record is in its running shape, before the run is kicked off.
2672
+ try { options.onStarted?.(); } catch { /* ignore caller wiring errors */ }
2673
+
2674
+ let settled = false;
2675
+ // Returns the final transcript flush when it ran, so the run's completion
2676
+ // can await it: a settled agent's transcript is on disk before its result
2677
+ // reaches the parent (same contract as the spawn path's finalizer).
2678
+ const settle = (): Promise<void> | undefined => {
2679
+ if (settled) return undefined;
2680
+ settled = true;
2681
+ // Synchronous terminal bookkeeping FIRST: a foreground resume has no
2682
+ // onComplete, so its archived snapshot is the only report — it must not
2683
+ // omit discarded steers or the model the resumed turn actually used.
2684
+ discardStaleSteers(record);
2685
+ if (record.session) updateEffectiveModel(record, record.session);
2686
+ this.detachSignalWire(record, signalWire);
2687
+ signalWire = undefined;
2688
+ // Then clone/archive, still before any awaited flush or caller callback.
2689
+ this.archiveTerminal(record);
2690
+ // Final flush of streaming output file
2691
+ let flushed: Promise<void> | undefined;
2692
+ if (record.outputCleanup) {
2693
+ const cleanup = record.outputCleanup;
2694
+ record.outputCleanup = undefined;
2695
+ try { flushed = Promise.resolve(cleanup()); } catch { /* ignore */ }
2696
+ }
2697
+ // Children spawned during the resumed turn must not outlive it.
2698
+ this.abortOwnedChildren(id);
2699
+ this.activeRuns.delete(record);
2700
+ if (holdsSlot) this.runningBackground--;
2701
+ if (background && !this.disposed) {
2702
+ try { this.onComplete?.(record); } catch { /* ignore completion side-effect errors */ }
2703
+ }
2704
+ this.drainQueue();
2705
+ return flushed;
2706
+ };
2707
+
2708
+ // Steers that arrived while this resume was queued: deliver them with the
2709
+ // resumed prompt rather than relying on the idle session's steering queue.
2710
+ const queuedSteers = record.pendingSteers ?? [];
2711
+ record.pendingSteers = undefined;
2712
+ const resumePrompt = queuedSteers.length === 0
2713
+ ? prompt
2714
+ : `${prompt}\n\n[Messages received while this agent was queued]\n${queuedSteers.map(m => `- ${m}`).join("\n")}`;
2715
+
2716
+ const promise = resumeAgent(record.session, resumePrompt, {
2717
+ onToolActivity: (activity) => {
2718
+ if (activity.type === "end") record.toolUses++;
2719
+ options.onToolActivity?.(activity);
2720
+ },
2721
+ onAssistantUsage: (usage) => {
2722
+ addUsage(record.lifetimeUsage, usage);
2723
+ this.onUsage?.(record, usage);
2724
+ options.onAssistantUsage?.(usage);
2725
+ },
2726
+ onCompaction: (info) => {
2727
+ record.compactionCount++;
2728
+ this.onCompact?.(record, info);
2729
+ options.onCompaction?.(info);
2730
+ },
2731
+ signal: abortController.signal,
2732
+ })
2733
+ .then(async ({ text, failure }) => {
2734
+ // Don't overwrite status if externally stopped via abort().
2735
+ if (record.status !== "stopped") {
2736
+ // Same contract as the spawn path (#144): a failed final turn is an
2737
+ // error, not a completion — but the resumed text stays available.
2738
+ record.status = failure ? "error" : "completed";
2739
+ if (failure) record.error = failure;
2740
+ }
2741
+ record.result = text;
2742
+ record.completedAt ??= Date.now();
2743
+ await settle();
2744
+ return text;
2745
+ })
2746
+ .catch(async (err) => {
2747
+ if (record.status !== "stopped") {
2748
+ record.status = "error";
2749
+ record.error = err instanceof Error ? err.message : String(err);
2750
+ }
2751
+ record.completedAt ??= Date.now();
2752
+ await settle();
2753
+ return "";
2754
+ });
2755
+
2756
+ record.promise = promise;
2757
+ this.trackPendingFinalizer(record, promise);
2758
+ }
2759
+
2760
+ /**
2761
+ * Send a steering message to an agent from the UI (mirrors the steer_subagent
2762
+ * tool). A live session delivers it now — it interrupts the agent after its
2763
+ * current tool execution and appears as a user message. If the session isn't
2764
+ * ready yet, the message is queued on `pendingSteers` and flushed when the
2765
+ * session is created. Returns false if the agent can't accept steering
2766
+ * (unknown id, or no longer running/queued).
2767
+ */
2768
+ steer(id: string, message: string): boolean {
2769
+ const record = this.agents.get(id);
2770
+ if (!record) return false;
2771
+ if (record.status !== "running" && record.status !== "queued") return false;
2772
+ // A queued agent holds its message until it starts — including a queued
2773
+ // resume, whose previous session exists but is idle (startResume folds
2774
+ // pendingSteers into the resumed prompt).
2775
+ if (record.status === "queued") {
2776
+ record.pendingSteers ??= [];
2777
+ record.pendingSteers.push(message);
2778
+ return true;
2779
+ }
2780
+ if (record.session && !sessionAcceptsSteer(record.session)) return false;
2781
+ if (record.session) {
2782
+ record.session.steer(message).catch(() => {});
2783
+ } else {
2784
+ if (!record.pendingSteers) record.pendingSteers = [];
2785
+ record.pendingSteers.push(message);
2786
+ }
2787
+ return true;
2788
+ }
2789
+
2790
+ /** Interactive send path: report an SDK rejection instead of pretending it queued. */
2791
+ async steerAcknowledged(id: string, message: string): Promise<boolean> {
2792
+ const record = this.agents.get(id);
2793
+ if (!record || this.disposed || (record.status !== "running" && record.status !== "queued")) return false;
2794
+ if (record.status === "queued") {
2795
+ record.pendingSteers ??= [];
2796
+ record.pendingSteers.push(message);
2797
+ return true;
2798
+ }
2799
+ if (record.session && !sessionAcceptsSteer(record.session)) return false;
2800
+ if (!record.session) {
2801
+ record.pendingSteers ??= [];
2802
+ record.pendingSteers.push(message);
2803
+ return true;
2804
+ }
2805
+ try {
2806
+ await record.session.steer(message);
2807
+ return true;
2808
+ } catch {
2809
+ return false;
2810
+ }
2811
+ }
2812
+
2813
+ getRecord(id: string): AgentRecord | undefined {
2814
+ return this.agents.get(id);
2815
+ }
2816
+
2817
+ /** Handles already in use, so a fresh spawn can pick an unclaimed one. */
2818
+ private takenHandles(): Set<string> {
2819
+ const taken = new Set<string>();
2820
+ for (const record of this.agents.values()) {
2821
+ if (record.handle) taken.add(record.handle);
2822
+ if (record.alias) taken.add(record.alias);
2823
+ }
2824
+ // Tombstones hold their names too: an evicted `@explore` is still
2825
+ // resurrectable, so a later Explore must become `explore-2` rather than
2826
+ // shadowing a conversation the user can still reach.
2827
+ for (const entry of this.tombstones.values()) {
2828
+ taken.add(entry.handle);
2829
+ if (entry.alias) taken.add(entry.alias);
2830
+ }
2831
+ return taken;
2832
+ }
2833
+
2834
+ /**
2835
+ * Resolve an `@name` from the prompt. Matches a top-level agent's handle
2836
+ * case-insensitively, preferring active work, then the newest usable session.
2837
+ * A failed startup cannot shadow a saved conversation. Exact ids still name
2838
+ * their own record, including a retained startup failure.
2839
+ */
2840
+ resolveMention(name: string): MentionResolution | undefined {
2841
+ const wanted = name.toLowerCase();
2842
+ let fallback: AgentRecord | undefined;
2843
+ let resumable: AgentRecord | undefined;
2844
+ for (const record of this.agents.values()) {
2845
+ if (record.parentAgentId !== undefined) continue;
2846
+ // Reclaimed names can have older failed records; active work or an
2847
+ // established session takes precedence over those sessionless attempts.
2848
+ if (record.handle?.toLowerCase() !== wanted && record.alias?.toLowerCase() !== wanted) continue;
2849
+ if (record.status === "running" || record.status === "queued") return { kind: "live", record };
2850
+ if (!fallback || record.startedAt > fallback.startedAt) fallback = record;
2851
+ if (record.session && (!resumable || record.startedAt > resumable.startedAt)) resumable = record;
2852
+ }
2853
+ if (resumable) return { kind: "live", record: resumable };
2854
+ const byId = this.agents.get(name);
2855
+ if (!fallback && byId?.parentAgentId === undefined && byId !== undefined) return { kind: "live", record: byId };
2856
+ // A failed startup has no session to continue. Do not let its retained
2857
+ // error record shadow the last usable conversation under the same name.
2858
+ for (const entry of this.tombstones.values()) {
2859
+ if (entry.handle.toLowerCase() === wanted || entry.alias?.toLowerCase() === wanted || entry.id === name) {
2860
+ return { kind: "tombstone", entry };
2861
+ }
2862
+ }
2863
+ return fallback ? { kind: "live", record: fallback } : undefined;
2864
+ }
2865
+
2866
+ /**
2867
+ * Forget an evicted agent, by handle. For the case where its session file has
2868
+ * gone: the entry can then only ever fail, while still holding the name
2869
+ * against the type that would otherwise start a fresh agent under it.
2870
+ *
2871
+ * A *successful* resume does not drop its tombstone — the live record it
2872
+ * creates already wins in `resolveMention`, and overwrites the entry in place
2873
+ * when it is itself evicted.
2874
+ */
2875
+ dropTombstone(handle: string): void {
2876
+ this.tombstones.delete(handle);
2877
+ }
2878
+
2879
+ /** Evicted agents whose conversation can still be reopened, newest first. */
2880
+ listTombstones(): AgentTombstone[] {
2881
+ return [...this.tombstones.values()].sort((a, b) => b.completedAt - a.completedAt);
2882
+ }
2883
+
2884
+ /** Actual pool queue membership, excluding a start suspended on its guard. */
2885
+ isQueued(id: string): boolean {
2886
+ return this.queue.some(entry => entry.id === id);
2887
+ }
2888
+
2889
+ listAgents(): AgentRecord[] {
2890
+ return [...this.agents.values()].sort(
2891
+ (a, b) => b.startedAt - a.startedAt,
2892
+ );
2893
+ }
2894
+
2895
+ abort(id: string): boolean {
2896
+ const record = this.agents.get(id);
2897
+ if (!record) return false;
2898
+
2899
+ // Capture both generation-owned resources BEFORE any callback, signal or
2900
+ // archive can re-enter. A completion observer may immediately resume this
2901
+ // same record — its admission is free, the status is already terminal — and
2902
+ // that newer generation installs its OWN pending claim and its own parent
2903
+ // signal wire. Freeing by lookup afterwards would free those instead: a
2904
+ // running charge the new generation still owns, whose transfer would then
2905
+ // no-op and whose finalizer would underflow the pool counter.
2906
+ const pendingClaim = this.capturePendingClaim(record);
2907
+ const signalWire = this.signalWires.get(record);
2908
+ // Reach the parent signal FIRST: a start suspended on a guard that never
2909
+ // settles must not keep this manager reachable from a live parent signal,
2910
+ // and the identity-aware detach cannot silence a newer generation's
2911
+ // listener installed later in this call.
2912
+ this.detachSignalWire(record, signalWire);
2913
+
2914
+ // Remove from queue if queued. No decrement — the slot was never taken.
2915
+ // It still settles through the ordinary completion path, so a yielded
2916
+ // result wait (and every lifecycle listener) hears about the stop; a
2917
+ // foreground record suppresses that notification exactly as a foreground
2918
+ // settle does, since its inline caller gets the outcome itself.
2919
+ if (record.status === "queued") {
2920
+ this.dequeue(q => q.id === id);
2921
+ record.status = "stopped";
2922
+ record.completedAt = Date.now();
2923
+ if (!record.isBackground) record.resultConsumed = true;
2924
+ this.archiveTerminal(record);
2925
+ if (!this.disposed) {
2926
+ this.notifiedQueuedAborts.set(record, record.runGeneration ?? 0);
2927
+ try {
2928
+ this.onComplete?.(record);
2929
+ } catch {
2930
+ console.warn(`[pi-subagents] Completion callback failed for stopped queued agent ${record.id}.`);
2931
+ }
2932
+ }
2933
+ // A start suspended on its acquire guard has no queue entry but still
2934
+ // owns pending capacity. Free it NOW — the guard may never settle — so
2935
+ // the next queued job can start; a real run's charge is not in this map.
2936
+ // Only the claim captured above: a callback that resumed this record has
2937
+ // already given its newer generation one of its own.
2938
+ this.releaseCapturedClaim(record, pendingClaim, true);
2939
+ return true;
2940
+ }
2941
+
2942
+ if (record.status !== "running") return false;
2943
+ record.abortController?.abort();
2944
+ record.status = "stopped";
2945
+ record.completedAt = Date.now();
2946
+ // Marked stopped first, then drain: a start suspended on its acquire guard
2947
+ // may still be "running" here with only a pending claim. Release only that
2948
+ // captured claim; a real run's charge remains with its finalizer, and a
2949
+ // claim a re-entrant callback installed for a newer generation is not ours.
2950
+ this.releaseCapturedClaim(record, pendingClaim, true);
2951
+ return true;
2952
+ }
2953
+
2954
+ /** Dispose a record's session and remove it from the map. */
2955
+ private removeRecord(id: string, record: AgentRecord): void {
2956
+ this.tombstone(record);
2957
+ const session = record.session;
2958
+ // Detached before the shutdown starts, so the record leaves the map at once and
2959
+ // nothing can observe a session that is half torn down.
2960
+ record.session = undefined;
2961
+ this.agents.delete(id);
2962
+ this.archivedGenerations.delete(id);
2963
+ this.cleanupQuiescence.delete(id);
2964
+ this.releaseAllocation(id);
2965
+ // A failed startup keeps its (rejected) entry so a late awaitStartup still
2966
+ // sees it; drop it with the record so the map can't grow unbounded.
2967
+ this.startups.delete(id);
2968
+ // Fire-and-forget is right here and only here: this runs from the 60s cleanup timer
2969
+ // and from `clearCompleted()` on session boundaries, with the process staying alive,
2970
+ // so handlers get their full window. The quit path awaits instead — see dispose().
2971
+ // The outcome is still tracked: an evicted row whose teardown timed out must
2972
+ // remain protected even though nothing is left to resume.
2973
+ void this.trackSessionShutdown(record, session);
2974
+ }
2975
+
2976
+ /**
2977
+ * Preserve enough of a departing record for `@handle` to reopen its
2978
+ * conversation later. Nothing to keep unless it has both a handle to be
2979
+ * addressed by and a session file to reopen — an in-memory session leaves no
2980
+ * transcript, so the mention would have nothing to continue from.
2981
+ */
2982
+ private tombstone(record: AgentRecord): void {
2983
+ if (!record.handle || !record.sessionFile) return;
2984
+ this.tombstones.set(record.handle, {
2985
+ handle: record.handle,
2986
+ alias: record.alias,
2987
+ id: record.id,
2988
+ type: record.type,
2989
+ description: record.description,
2990
+ sessionFile: record.sessionFile,
2991
+ completedAt: record.completedAt ?? Date.now(),
2992
+ });
2993
+ // Bound the memory a long session can accumulate. Oldest first, since the
2994
+ // agent someone still wants to reach is the one they used most recently.
2995
+ while (this.tombstones.size > MAX_TOMBSTONES) {
2996
+ const oldest = [...this.tombstones.values()].reduce((a, b) => (a.completedAt <= b.completedAt ? a : b));
2997
+ this.tombstones.delete(oldest.handle);
2998
+ }
2999
+ }
3000
+
3001
+ private cleanup() {
3002
+ const cutoff = Date.now() - 10 * 60_000;
3003
+ for (const [id, record] of this.agents) {
3004
+ if (this.activeRuns.has(record) || record.status === "running" || record.status === "queued") continue;
3005
+ // A settled record can still own a pending output/worktree finalizer.
3006
+ // Evicting it would drop the only handle to that work.
3007
+ if (this.pendingFinalizers.has(record)) continue;
3008
+ if ((record.completedAt ?? 0) >= cutoff) continue;
3009
+ this.removeRecord(id, record);
3010
+ }
3011
+ }
3012
+
3013
+ /**
3014
+ * Remove all completed/stopped/errored records immediately.
3015
+ * Called on session start/switch so tasks from a prior session don't persist.
3016
+ * Pass skipUnconsumed=true to preserve records the LLM hasn't read yet
3017
+ * (resultConsumed=false) — they will be evicted by the 10-minute cleanup timer instead.
3018
+ */
3019
+ clearCompleted(skipUnconsumed = false): void {
3020
+ for (const [id, record] of this.agents) {
3021
+ if (this.activeRuns.has(record) || record.status === "running" || record.status === "queued") continue;
3022
+ // Same rule as the 10-minute sweep: a still-finalizing settled record is
3023
+ // not evictable until its output/worktree finalizer settles.
3024
+ if (this.pendingFinalizers.has(record)) continue;
3025
+ if (skipUnconsumed && !record.resultConsumed) continue;
3026
+ this.removeRecord(id, record);
3027
+ }
3028
+ // Unconditional: both callers are session boundaries (`session_start` and
3029
+ // `session_before_switch`), and `skipUnconsumed` only spares records whose
3030
+ // results the LLM has yet to read — it does not make the sweep partial in
3031
+ // the sense that matters here. A new session means new handles, or
3032
+ // `@explore` would silently reach an agent the user never started. Claude
3033
+ // Code resets its registry on `/clear` for the same reason.
3034
+ this.tombstones.clear();
3035
+ }
3036
+
3037
+ /** Whether any agents are still running or queued. */
3038
+ hasRunning(): boolean {
3039
+ return [...this.agents.values()].some(
3040
+ r => r.status === "running" || r.status === "queued",
3041
+ );
3042
+ }
3043
+
3044
+ /** Abort all running and queued agents immediately. */
3045
+ abortAll(): number {
3046
+ let count = 0;
3047
+ // Clear queued agents first. Claims are released WITHOUT draining: a drain
3048
+ // here could start an entry this same loop has not canceled yet.
3049
+ for (const queued of this.queue) {
3050
+ const record = this.agents.get(queued.id);
3051
+ if (record) {
3052
+ // Generation-owned cleanup is reachable immediately: a start suspended
3053
+ // on a guard that never settles must not keep a live parent signal
3054
+ // pointing at this manager after the bulk cancel.
3055
+ this.releaseSignalWire(record);
3056
+ record.status = "stopped";
3057
+ record.completedAt = Date.now();
3058
+ if (!record.isBackground) record.resultConsumed = true;
3059
+ this.archiveTerminal(record);
3060
+ this.releasePendingClaim(record, false);
3061
+ count++;
3062
+ }
3063
+ }
3064
+ this.dequeue(() => true);
3065
+ // A start that was already spliced out of the queue (or launched while it
3066
+ // had room) may still be "queued" while it awaits an async acquire guard.
3067
+ // It has no queue entry for the loop above to reach, but it is still queued
3068
+ // work and must be stopped before the guard resolves — otherwise the start
3069
+ // would continue after abortAll and burn a run nobody can reach. Its pending
3070
+ // claim is freed too, still without draining anything mid-cancel.
3071
+ for (const record of this.agents.values()) {
3072
+ if (record.status !== "queued") continue;
3073
+ this.releaseSignalWire(record);
3074
+ record.status = "stopped";
3075
+ record.completedAt = Date.now();
3076
+ if (!record.isBackground) record.resultConsumed = true;
3077
+ this.archiveTerminal(record);
3078
+ this.releasePendingClaim(record, false);
3079
+ count++;
3080
+ }
3081
+ // Abort running agents. A "running" record suspended in its guard still
3082
+ // owns only a pending claim (released here); a transferred claim is a real
3083
+ // charge and stays until that run's finalizer settles.
3084
+ for (const record of this.agents.values()) {
3085
+ if (record.status === "running") {
3086
+ this.releaseSignalWire(record);
3087
+ this.releasePendingClaim(record, false);
3088
+ record.abortController?.abort();
3089
+ record.status = "stopped";
3090
+ record.completedAt = Date.now();
3091
+ count++;
3092
+ }
3093
+ }
3094
+ // Everything is stopped now; only here may freed capacity let a queued
3095
+ // entry through. Nothing is left in the queue, so this is a no-op drain
3096
+ // kept for symmetry with the individual cancellation path.
3097
+ this.drainQueue();
3098
+ return count;
3099
+ }
3100
+
3101
+ /** Wait for all running and queued agents to complete (including queued ones). */
3102
+ async waitForAll(): Promise<void> {
3103
+ // Loop because drainQueue respects the concurrency limit — as running
3104
+ // agents finish they start queued ones, which need awaiting too.
3105
+ while (true) {
3106
+ this.drainQueue();
3107
+ const pending: Promise<unknown>[] = [];
3108
+ for (const record of this.agents.values()) {
3109
+ if (!this.activeRuns.has(record) && record.status !== "running" && record.status !== "queued") continue;
3110
+ // An agent whose worktree is still being created is "running" with no
3111
+ // `promise` yet — without its startup the wait would return too early.
3112
+ const startup = this.startups.get(record.id);
3113
+ if (startup) pending.push(startup);
3114
+ if (record.promise) pending.push(record.promise);
3115
+ }
3116
+ if (pending.length === 0) break;
3117
+ await Promise.allSettled(pending);
3118
+ }
3119
+ }
3120
+
3121
+ /**
3122
+ * @param pi - Needed to run `git worktree prune`, which is async now and so
3123
+ * cannot be reached through a stored spawn argument at shutdown. Omitting
3124
+ * it (tests, teardown of a manager that never spawned) skips the prune.
3125
+ */
3126
+ async dispose(pi?: ExtensionAPI): Promise<AgentManagerShutdown> {
3127
+ // A caller may supply Pi only on a later dispose. Preserve that prune,
3128
+ // while every session and notification still tears down exactly once.
3129
+ if (pi && !this.pruned) {
3130
+ this.pruned = true;
3131
+ // Prune any orphaned git worktrees (crash recovery). Detached: dispose runs
3132
+ // on the shutdown path, which cannot wait for git. Started before the awaited
3133
+ // shutdown below rather than after it, so the git calls have that window to
3134
+ // finish in instead of racing the process exit that follows.
3135
+ const prune = (repo: string) => { pruneWorktrees(pi, repo).catch(() => {}); };
3136
+ prune(process.cwd());
3137
+ // Also prune repos that caller-supplied cwds created worktrees in — a clean
3138
+ // exit with in-flight agents would otherwise leave stale registrations there.
3139
+ for (const repo of this.worktreeRepos) prune(repo);
3140
+ }
3141
+ if (this.disposed) {
3142
+ return this.shutdown ?? { status: "completed", uncertain: this.listUncertainTeardowns() };
3143
+ }
3144
+ this.disposed = true;
3145
+ clearInterval(this.cleanupInterval);
3146
+ // Publish the shutdown promise BEFORE aborting: abort/archiver callbacks can
3147
+ // re-enter dispose() synchronously, and must observe this teardown rather
3148
+ // than an early "completed" snapshot.
3149
+ let resolveShutdown!: (result: AgentManagerShutdown) => void;
3150
+ this.shutdown = new Promise<AgentManagerShutdown>(resolve => {
3151
+ resolveShutdown = resolve;
3152
+ });
3153
+ const shutdown = this.shutdown;
3154
+ this.abortAll();
3155
+ // Capture every promise BEFORE the maps are cleared: an agent whose run,
3156
+ // startup or output/worktree finalizer is still pending owes this manager a
3157
+ // terminal report, and its teardown outcome must not be forgotten.
3158
+ const entries = [...this.agents.values()].map(record => ({
3159
+ record,
3160
+ session: record.session,
3161
+ startup: this.startups.get(record.id),
3162
+ run: record.promise,
3163
+ // EVERY generation's finalizer, not just the one currently published on
3164
+ // the record: a resumed run can replace `record.promise` while an older
3165
+ // generation still owes its output flush.
3166
+ finalizers: [...(this.pendingFinalizers.get(record) ?? [])],
3167
+ allocations: [...(this.allocations.get(record.id) ?? [])],
3168
+ }));
3169
+ // Every pre-ready allocation, including one whose record was already
3170
+ // evicted. Teardown must wait for its active bind/session_start.
3171
+ const allocationSessions: AgentSession[] = [
3172
+ ...entries.flatMap(entry => entry.allocations),
3173
+ ...Array.from(this.allocations.values()).flatMap(allocated => [...allocated]),
3174
+ ];
3175
+ const allocationStates = [...new Set(allocationSessions)]
3176
+ .map(session => this.allocationStates.get(session))
3177
+ .filter((state): state is AllocationState => state !== undefined);
3178
+ this.agents.clear();
3179
+ this.startups.clear();
3180
+ this.allocations.clear();
3181
+ this.cleanupQuiescence.clear();
3182
+ void (async () => {
3183
+ const jobs = new Set<Promise<ChildShutdownOutcome>>();
3184
+ // Already-evicted teardowns still in flight (finding 2): include them even
3185
+ // though no runtime record remains to consult.
3186
+ for (const row of this.teardowns.values()) {
3187
+ if (row.promise) jobs.add(row.promise);
3188
+ }
3189
+ for (const entry of entries) {
3190
+ if (entry.session) {
3191
+ jobs.add(this.trackSessionShutdown(entry.record, entry.session));
3192
+ }
3193
+ }
3194
+ // Pre-ready allocations are sequenced AFTER bind/session_start settles.
3195
+ // Emitting shutdown into an active bind can miss a resource the handler
3196
+ // allocates later; a hang stays pending/uncertain instead of `completed`.
3197
+ for (const state of allocationStates) {
3198
+ jobs.add(state.ready.then(() => this.startSessionTeardown(state.identity, state.session)));
3199
+ }
3200
+ // If the run settles before `onSessionCreated` (for example a non-bind
3201
+ // failure after allocation), the bind phase is over and teardown may run.
3202
+ for (const entry of entries) {
3203
+ const release = () => {
3204
+ for (const allocated of entry.allocations) this.settleAllocation(allocated);
3205
+ };
3206
+ if (entry.run) void entry.run.then(release, release);
3207
+ }
3208
+ // Other pending rows: never start one owned by a pre-ready allocation —
3209
+ // its gated job above decides when that instance may be torn down.
3210
+ for (const row of [...this.teardowns.values()]) {
3211
+ if (row.promise || !row.session) continue;
3212
+ if (this.allocationStates.has(row.session)) continue;
3213
+ jobs.add(this.startSessionTeardown(row, row.session));
3214
+ }
3215
+
3216
+ const finalizers = entries.map(entry => {
3217
+ const generation = entry.record.runGeneration ?? 0;
3218
+ const finalized = (async () => {
3219
+ if (entry.startup) await entry.startup.catch(() => {});
3220
+ // A run can be created while startup settles (worktree copy), so read
3221
+ // the record after the startup promise rather than only the snapshot.
3222
+ const pending = new Set<Promise<unknown>>(entry.finalizers);
3223
+ const run = entry.run ?? entry.record.promise;
3224
+ if (run) pending.add(run);
3225
+ // Finalizers can be registered while the startup awaited above.
3226
+ for (const promise of this.pendingFinalizers.get(entry.record) ?? []) pending.add(promise);
3227
+ await Promise.allSettled([...pending]);
3228
+ })();
3229
+ return { entry, generation, promise: finalized.then(() => true, () => true) };
3230
+ });
3231
+ const finished = entries.map(() => false);
3232
+ finalizers.forEach((finalized, index) => {
3233
+ void finalized.promise.then(() => { finished[index] = true; });
3234
+ });
3235
+
3236
+ let timer: ReturnType<typeof setTimeout> | undefined;
3237
+ const deadline = new Promise<"deadline">(resolve => {
3238
+ timer = setTimeout(() => resolve("deadline"), MANAGER_SHUTDOWN_DEADLINE_MS);
3239
+ timer.unref?.();
3240
+ });
3241
+ // One COMMON deadline for SDK handlers, bind jobs, run promises and
3242
+ // finalizers. A live worker is never awaited indefinitely.
3243
+ try {
3244
+ await Promise.race([
3245
+ Promise.all([...jobs, ...finalizers.map(finalizer => finalizer.promise)]),
3246
+ deadline,
3247
+ ]);
3248
+ } finally {
3249
+ if (timer !== undefined) clearTimeout(timer);
3250
+ }
3251
+
3252
+ finalizers.forEach(({ entry, generation, promise }, index) => {
3253
+ if (finished[index]) {
3254
+ // Real terminal state and result, after every finalizer had its turn.
3255
+ this.archiveTerminal(entry.record);
3256
+ this.clearRunUncertainty(entry.record.id, generation);
3257
+ } else {
3258
+ // Explicit uncertainty, never "completed": the run still owns its
3259
+ // agent/root/path protection. A later same-generation finalizer may
3260
+ // upgrade this provisional stopped view.
3261
+ this.recordRunUncertainty(entry.record, generation);
3262
+ this.archiveTerminal(entry.record, { fallback: true });
3263
+ void promise.then(() => this.reconcileLateFinalizer(entry.record, generation));
3264
+ }
3265
+ });
3266
+
3267
+ let status: ChildShutdownStatus = "completed";
3268
+ for (const row of this.teardowns.values()) {
3269
+ if (row.status === "pending" || row.status === "timed_out") {
3270
+ status = "timed_out";
3271
+ break;
3272
+ }
3273
+ if (row.status === "failed") status = "failed";
3274
+ }
3275
+ resolveShutdown({ status, uncertain: this.listUncertainTeardowns() });
3276
+ })().catch(error => {
3277
+ // A teardown failure is uncertainty, never a completed shutdown.
3278
+ console.warn("[pi-subagents] manager shutdown bookkeeping failed:", error);
3279
+ resolveShutdown({
3280
+ status: "failed",
3281
+ uncertain: this.listUncertainTeardowns(),
3282
+ });
3283
+ });
3284
+ return shutdown;
3285
+ }
3286
+ }
3287
+
3288
+ /**
3289
+ * Whether a child session will still consume a steering message. A session
3290
+ * that has stopped streaming, with no managed prompt (or fallback recovery)
3291
+ * still in flight, would only park the message in its queue — reported as
3292
+ * "sent" but never read. Stubs without `isStreaming` are treated as live.
3293
+ */
3294
+ export function sessionAcceptsSteer(session: AgentSession): boolean {
3295
+ const streaming = (session as { isStreaming?: unknown }).isStreaming;
3296
+ if (typeof streaming !== "boolean" || streaming) return true;
3297
+ return isChildRequestActive(session);
3298
+ }
3299
+
3300
+ /**
3301
+ * Drop steering messages still queued in a finished child session so a later
3302
+ * resume of the same session object cannot replay stale instructions, and
3303
+ * count them on the record so the result can mention it.
3304
+ */
3305
+ function discardStaleSteers(record: AgentRecord): void {
3306
+ const session = record.session;
3307
+ if (typeof session?.getSteeringMessages !== "function" || typeof session.clearQueue !== "function") return;
3308
+ const queued = session.getSteeringMessages().length;
3309
+ if (queued === 0) return;
3310
+ session.clearQueue();
3311
+ record.droppedSteers = (record.droppedSteers ?? 0) + queued;
3312
+ }