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