@timmyjl12/pi-subagents 0.0.0-stage → 0.20.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 (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  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 +18 -0
  9. package/dist/active-agents-prompt.js +34 -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 +123 -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 +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,1380 @@
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 } from "node:path";
19
+ import { resumeAgent, runAgent } from "./agent-runner.js";
20
+ import { shutdownChildSession } from "./child-session-shutdown.js";
21
+ import { assignHandle, handleBase } from "./mention.js";
22
+ import { describeModel } from "./model-resolver.js";
23
+ import { isChildRequestActive } from "./recovery.js";
24
+ import { releaseToolProgress } from "./ui/tool-progress.js";
25
+ import { addUsage } from "./usage.js";
26
+ import { cleanupWorktree, createWorktree, isWorktreeIsolationEnabled, pruneWorktrees, } from "./worktree.js";
27
+ /**
28
+ * Default max concurrent background agents.
29
+ *
30
+ * Raised from 4 when top-level spawns started defaulting to background
31
+ * (`backgroundByDefault`): foreground agents bypass this pool entirely, so
32
+ * while foreground was the default a fan-out of six ran six. With background
33
+ * as the default every top-level agent takes a slot, and a limit of 4 would
34
+ * have silently queued the tail of exactly the parallel fan-outs the `Agent`
35
+ * tool description tells the model to send.
36
+ */
37
+ const DEFAULT_MAX_CONCURRENT = 10;
38
+ /**
39
+ * Default max concurrent foreground (blocking) agents — `0` = unlimited, the
40
+ * extension's existing convention for "no ceiling" (`defaultMaxTurns`).
41
+ *
42
+ * Off by default because nothing here ever bounded foreground work, and pi
43
+ * dispatches a message's tool calls through `Promise.all`, so an unqualified
44
+ * fan-out of blocking `Agent` calls has always run all at once. Users who want
45
+ * it bounded — chiefly local models, where parallel agents thrash the prompt
46
+ * cache (#253) — opt in; everyone else keeps today's behaviour exactly.
47
+ */
48
+ const DEFAULT_MAX_CONCURRENT_FOREGROUND = 0;
49
+ /**
50
+ * How many evicted agents stay addressable by name. Only a bound on memory —
51
+ * a session that spawns hundreds of agents shouldn't retain every one — and
52
+ * far above the handful anyone keeps in their head.
53
+ */
54
+ const MAX_TOMBSTONES = 100;
55
+ /**
56
+ * Validate a caller-supplied SpawnOptions.cwd. `undefined`/`null` mean "unset"
57
+ * (parent cwd). Anything else must be an absolute path to an existing
58
+ * directory — curated errors instead of TypeErrors from path/fs internals
59
+ * (RPC callers send arbitrary JSON: null, numbers, file paths).
60
+ */
61
+ function assertValidSpawnCwd(cwd) {
62
+ if (cwd == null)
63
+ return;
64
+ if (typeof cwd !== "string" || !isAbsolute(cwd)) {
65
+ throw new Error(`SpawnOptions.cwd must be an absolute path: "${String(cwd)}"`);
66
+ }
67
+ let isDirectory = false;
68
+ try {
69
+ isDirectory = statSync(cwd).isDirectory();
70
+ }
71
+ catch {
72
+ throw new Error(`SpawnOptions.cwd does not exist: "${cwd}"`);
73
+ }
74
+ if (!isDirectory) {
75
+ throw new Error(`SpawnOptions.cwd is not a directory: "${cwd}"`);
76
+ }
77
+ }
78
+ /**
79
+ * Whether a record occupies one of the `maxConcurrent` background slots.
80
+ * Nested children don't: their parent already holds a slot, so counting (and
81
+ * therefore queueing) them would deadlock a parent that waits on its own child.
82
+ *
83
+ * Note this bounds nothing horizontally — the depth cap limits how DEEP nesting
84
+ * goes, not how WIDE. A parent's only limit on concurrent children is that each
85
+ * spawn costs it a turn, which is unbounded when max turns is unlimited.
86
+ */
87
+ function occupiesPoolSlot(record) {
88
+ return !!record.isBackground && isTopLevelAgent(record);
89
+ }
90
+ /**
91
+ * Whether a record is one of the session's own agents, rather than something
92
+ * another agent or a workflow owns.
93
+ *
94
+ * The single definition behind every user-facing surface — the fleet list, the
95
+ * widget, the `/agents` menus, `@handle` resolution, and the completion events
96
+ * and session entries. An owned child reports through its owner, so surfacing
97
+ * it separately would double-count the same work in the places a person reads.
98
+ */
99
+ export function isTopLevelAgent(record) {
100
+ return record.parentAgentId === undefined && record.workflowId === undefined;
101
+ }
102
+ /**
103
+ * Whether a record occupies one of the `maxConcurrentForeground` slots.
104
+ *
105
+ * Keyed on `blocking` — a caller awaiting this record inline — rather than on
106
+ * `isBackground === false`, because `spawn()` is also the funnel for DETACHED
107
+ * starts (cross-extension RPC, `@handle` mentions, the registry) that may pass
108
+ * `isBackground: false` and are documented to run immediately regardless. Those
109
+ * block nobody, so bounding them buys nothing and would park a record with no
110
+ * one waiting to release it.
111
+ *
112
+ * Nested children are excluded for the same reason as `occupiesPoolSlot`, and
113
+ * more sharply: their parent is blocked *awaiting them*, so queueing a child
114
+ * behind its own parent is a guaranteed deadlock rather than a possible one.
115
+ * Enforced here rather than at the call site so no caller can reintroduce it.
116
+ *
117
+ * A workflow's children go out through `spawnAndWait` and so are `blocking`
118
+ * too, and are excluded on the same `isTopLevelAgent` test as the background
119
+ * pool: the run already caps how many of its agents run at once, and charging
120
+ * them here as well would let one fan-out queue behind a limit meant for the
121
+ * session's own work.
122
+ *
123
+ * Like the background pool this bounds width at the top level only — a parent's
124
+ * own fan-out is limited by nothing but its turn budget.
125
+ */
126
+ function occupiesForegroundSlot(record) {
127
+ return !!record.blocking && isTopLevelAgent(record);
128
+ }
129
+ function updateEffectiveModel(record, session) {
130
+ if (!session.model)
131
+ return;
132
+ record.invocation ??= {};
133
+ const requested = record.invocation.requestedThinking ?? record.invocation.thinking;
134
+ Object.assign(record.invocation, describeModel(session.model));
135
+ if (session.thinkingLevel) {
136
+ record.invocation.thinking = session.thinkingLevel;
137
+ if (requested && requested !== session.thinkingLevel)
138
+ record.invocation.requestedThinking = requested;
139
+ }
140
+ }
141
+ export class AgentManager {
142
+ agents = new Map();
143
+ activeRuns = new WeakSet();
144
+ disposed = false;
145
+ shutdown;
146
+ pruned = false;
147
+ cleanupInterval;
148
+ onComplete;
149
+ onStart;
150
+ onCompact;
151
+ onUsage;
152
+ maxConcurrent;
153
+ maxConcurrentForeground = DEFAULT_MAX_CONCURRENT_FOREGROUND;
154
+ /** Base repos worktrees were created from — so dispose() can prune them all,
155
+ * not just the parent repo (caller-supplied cwd can target other repos). */
156
+ worktreeRepos = new Set();
157
+ /**
158
+ * Startup phases, keyed by agent id. `spawn()` still returns synchronously,
159
+ * but an agent using worktree isolation is not running yet when it does —
160
+ * copying the repo is an awaited git call. This is what `awaitStartup` hands
161
+ * callers that must fail their tool call on a startup failure, and what
162
+ * `waitForAll` waits on while a record is "running" with no `promise` yet.
163
+ * Entries are dropped once the run is underway, and kept (rejected) after a
164
+ * startup failure so a late `awaitStartup` still sees it.
165
+ */
166
+ startups = new Map();
167
+ /**
168
+ * Evicted agents that can still be reached by name, keyed by handle. Outlives
169
+ * the 10-minute record cleanup — that timer exists to bound memory, not to
170
+ * expire a conversation the user might still want — and is cleared alongside
171
+ * completed records on session start/switch.
172
+ */
173
+ tombstones = new Map();
174
+ /**
175
+ * Agents waiting to start, tagged with the pool they wait on. One queue for
176
+ * both pools: `drainQueue` picks the earliest entry whose own pool has room,
177
+ * so neither can head-of-line-block the other, and every removal path
178
+ * (`abort`, `abortAll`, `dispose`) stays a single filter.
179
+ *
180
+ * `release` wakes a caller blocked in `spawnAndWait`, and is fired once the
181
+ * entry's `start` has SETTLED rather than at drain time: startup is async
182
+ * now, so releasing earlier would wake the caller before `record.promise`
183
+ * exists and it would read a still-starting agent as one that never ran.
184
+ * Removing an entry from this array MUST release it — a queued record has no
185
+ * promise to await, and pi has no tool-execution timeout to bail the caller
186
+ * out.
187
+ */
188
+ queue = [];
189
+ /** Number of currently running background agents. */
190
+ runningBackground = 0;
191
+ /** Number of currently running foreground (blocking) agents. */
192
+ runningForeground = 0;
193
+ constructor(onComplete, maxConcurrent = DEFAULT_MAX_CONCURRENT, onStart, onCompact, onUsage) {
194
+ this.onComplete = onComplete;
195
+ this.onStart = onStart;
196
+ this.onCompact = onCompact;
197
+ this.onUsage = onUsage;
198
+ this.maxConcurrent = maxConcurrent;
199
+ // Cleanup completed agents after 10 minutes (but keep sessions for resume)
200
+ this.cleanupInterval = setInterval(() => this.cleanup(), 60_000);
201
+ this.cleanupInterval.unref();
202
+ }
203
+ /** Update the max concurrent background agents limit. */
204
+ setMaxConcurrent(n) {
205
+ this.maxConcurrent = Math.max(1, n);
206
+ // Start queued agents if the new limit allows
207
+ this.drainQueue();
208
+ }
209
+ getMaxConcurrent() {
210
+ return this.maxConcurrent;
211
+ }
212
+ /** Update the max concurrent foreground (blocking) agents limit. 0 = unlimited. */
213
+ setMaxConcurrentForeground(n) {
214
+ // Floor 0, not 1: unlimited is a meaningful value here and the default.
215
+ this.maxConcurrentForeground = Math.max(0, n);
216
+ // Start queued agents if the new limit allows — including everything, when
217
+ // the limit is cleared back to unlimited mid-run.
218
+ this.drainQueue();
219
+ }
220
+ getMaxConcurrentForeground() {
221
+ return this.maxConcurrentForeground;
222
+ }
223
+ /**
224
+ * Which pool a spawn is charged to, or undefined for one that is charged to
225
+ * neither (nested children, detached non-background spawns).
226
+ *
227
+ * Nothing here queues when the limit is unset — `poolHasRoom` reports an
228
+ * unlimited pool as always having room, so that alone is what keeps the
229
+ * default path identical. The `> 0` guard is belt and braces on top: it also
230
+ * keeps the counter from churning and the settle path from calling a drain
231
+ * that would find nothing to do. Both are unobservable, which is why no test
232
+ * pins them; the observable half — that the default start stays synchronous —
233
+ * is pinned in `test/foreground-concurrency.test.ts`.
234
+ */
235
+ poolFor(record) {
236
+ if (occupiesPoolSlot(record))
237
+ return "background";
238
+ if (this.maxConcurrentForeground > 0 && occupiesForegroundSlot(record))
239
+ return "foreground";
240
+ return undefined;
241
+ }
242
+ poolHasRoom(pool) {
243
+ return pool === "background"
244
+ ? this.runningBackground < this.maxConcurrent
245
+ : this.maxConcurrentForeground === 0 || this.runningForeground < this.maxConcurrentForeground;
246
+ }
247
+ /**
248
+ * Spawn an agent and return its ID immediately (for background use).
249
+ * If the concurrency limit is reached, the agent is queued.
250
+ *
251
+ * The id comes back synchronously, but with `isolation: "worktree"` the agent
252
+ * is not running yet when it does — the repo copy is an awaited git call.
253
+ * Callers that must fail a tool call on a startup failure await
254
+ * `awaitStartup(id)`; everyone else sees it on the record (status "error").
255
+ */
256
+ spawn(pi, ctx, type, prompt, options) {
257
+ if (this.disposed)
258
+ throw new Error("Agent manager is disposed");
259
+ // Validate before the queue branch — a queued spawn should fail at the
260
+ // call, not minutes later at drain. Throw (not warn): programmatic callers
261
+ // can fix and retry; the RPC layer converts throws into error envelopes.
262
+ assertValidSpawnCwd(options.cwd);
263
+ const id = randomUUID().slice(0, 17);
264
+ const abortController = new AbortController();
265
+ const record = {
266
+ id,
267
+ type,
268
+ // Owned children — nested, or a workflow's — are filtered out of every
269
+ // top-level surface, so no handle: nothing can address them and they must
270
+ // not consume a name a top-level sibling could otherwise take.
271
+ handle: !isTopLevelAgent(options)
272
+ ? undefined
273
+ // A reclaimed handle is used as-is: it belongs to the conversation this
274
+ // spawn is reopening, and re-deriving it would lose the numbering.
275
+ : options.reclaim?.handle ?? assignHandle(handleBase(type), this.takenHandles()),
276
+ description: options.description,
277
+ // Reclaimed here, or filled in below from `name` — in which case it must
278
+ // see the handle this record just took, since both come out of the same
279
+ // namespace.
280
+ alias: isTopLevelAgent(options) ? options.reclaim?.alias : undefined,
281
+ // Overwritten below when the spawn is actually queued; a foreground spawn
282
+ // that queues flips to "queued" there rather than being guessed at here,
283
+ // since the pool decision needs the finished record.
284
+ status: options.isBackground ? "queued" : "running",
285
+ toolUses: 0,
286
+ startedAt: Date.now(),
287
+ abortController,
288
+ lifetimeUsage: { input: 0, output: 0, cacheWrite: 0, cost: 0 },
289
+ compactionCount: 0,
290
+ // Raw tri-state (not coerced to a boolean): true = background, false =
291
+ // foreground (has an inline tool-result surface), undefined = caller never
292
+ // declared it (e.g. a cross-extension RPC spawn). The widget's background-
293
+ // only filter excludes only explicit `false`, so undefined agents — which
294
+ // have no inline surface — stay visible instead of vanishing.
295
+ isBackground: options.isBackground,
296
+ // Whether anyone is awaiting this agent is a property of the agent, not
297
+ // of the call that made it — and both settle paths need it long after
298
+ // `options` has stopped being the interesting object.
299
+ blocking: options.blocking,
300
+ invocation: options.invocation,
301
+ depth: options.depth ?? 1,
302
+ parentAgentId: options.parentAgentId,
303
+ workflowId: options.workflowId,
304
+ maxSubagentDepth: options.maxSubagentDepth,
305
+ rootSessionId: options.rootSessionId,
306
+ };
307
+ this.agents.set(id, record);
308
+ // After the insert, so `takenHandles()` already counts this record's own
309
+ // handle — a spawn named after its own type gets `explore-2`, not a
310
+ // duplicate `explore` that would make resolution ambiguous.
311
+ if (record.handle !== undefined && record.alias === undefined && options.name !== undefined) {
312
+ record.alias = assignHandle(handleBase(options.name), this.takenHandles());
313
+ }
314
+ const args = { pi, ctx, type, prompt, options };
315
+ const pool = this.poolFor(record);
316
+ if (pool !== undefined && !options.bypassQueue && !this.poolHasRoom(pool)) {
317
+ // Queue it — started when a running agent in the same pool completes.
318
+ // Idempotent for background (already "queued"); the flip that matters is
319
+ // a blocking foreground spawn, optimistically marked "running" above.
320
+ record.status = "queued";
321
+ // A queued record never reaches startAgent's signal wiring, so arm the
322
+ // parent abort here or Esc could not release the position.
323
+ if (!this.armQueuedAbort(id, options.signal))
324
+ return id;
325
+ let release;
326
+ record.startGate = new Promise(resolve => { release = resolve; });
327
+ this.queue.push({
328
+ id,
329
+ pool,
330
+ start: () => this.launch(id, record, args, pool),
331
+ release: () => release(),
332
+ });
333
+ options.onQueued?.(id, this.queue.filter(e => e.pool === pool).length - 1);
334
+ return id;
335
+ }
336
+ this.launch(id, record, args, undefined);
337
+ return id;
338
+ }
339
+ /**
340
+ * Wire a parent abort signal for a record that is about to be QUEUED.
341
+ * `startAgent` does this for running agents, and a queued record never gets
342
+ * there, so without this Esc could not release a queue position.
343
+ *
344
+ * Returns false when the signal is ALREADY aborted, in which case the record
345
+ * is stopped here and must not be enqueued: `addEventListener` never fires on
346
+ * an aborted signal, so a `spawnAndWait` on it would wait forever — pi has no
347
+ * tool-execution timeout to bail it out.
348
+ *
349
+ * The listener is left in place when the agent starts. `startAgent` adds its
350
+ * own, so both fire on a later abort, but `abort()` on an already-stopped
351
+ * record is a no-op — so detaching would only be tidiness, and tidiness the
352
+ * `abortAll`/`dispose` paths could not offer anyway.
353
+ */
354
+ armQueuedAbort(id, signal) {
355
+ if (signal === undefined)
356
+ return true;
357
+ if (signal.aborted) {
358
+ const record = this.agents.get(id);
359
+ if (record) {
360
+ record.status = "stopped";
361
+ record.completedAt = Date.now();
362
+ }
363
+ return false;
364
+ }
365
+ signal.addEventListener("abort", () => this.abort(id), { once: true });
366
+ return true;
367
+ }
368
+ /**
369
+ * Kick off an agent's startup and register it under `startups`. The returned
370
+ * promise never rejects — the failure is delivered through `awaitStartup`,
371
+ * and to the record.
372
+ *
373
+ * @param queuedPool - The pool this start was QUEUED on, or undefined for an
374
+ * immediate start. A queue drain can be minutes after `spawn()` returned,
375
+ * and nobody is awaiting `awaitStartup` by then, so a failure has to live
376
+ * on the record as status "error" — what drainQueue did when the throw was
377
+ * still synchronous. An immediate start instead drops the record, exactly
378
+ * as the throw out of `spawn()` did: no orphan in `listAgents()`, and the
379
+ * handle goes back.
380
+ */
381
+ launch(id, record, args, queuedPool) {
382
+ const startup = this.startAgent(id, record, args).then(() => { this.startups.delete(id); }, (err) => {
383
+ this.startups.delete(id);
384
+ if (queuedPool !== undefined) {
385
+ // Mirrors settleRun: an inline caller gets this failure as a throw
386
+ // out of spawnAndWait, so an unconsumed record would ALSO nudge the
387
+ // session about it — the same failure reported twice.
388
+ if (queuedPool === "foreground")
389
+ record.resultConsumed = true;
390
+ record.status = "error";
391
+ record.error = err instanceof Error ? err.message : String(err);
392
+ record.completedAt = Date.now();
393
+ this.onComplete?.(record);
394
+ }
395
+ else {
396
+ this.agents.delete(id);
397
+ }
398
+ // The agent never kept its slot (startAgent gives it back on failure),
399
+ // so anything queued behind it can go now.
400
+ this.drainQueue();
401
+ throw err;
402
+ });
403
+ this.startups.set(id, startup);
404
+ // Nothing is obliged to await `startups` — swallow the rejection once here
405
+ // so an unawaited startup can't take the process down, and hand callers
406
+ // (drainQueue) that swallowed promise.
407
+ return startup.catch(() => { });
408
+ }
409
+ /**
410
+ * Resolves once the agent is actually running, and rejects with the startup
411
+ * failure (strict worktree isolation) that `spawn()` used to throw before the
412
+ * repo copy became async. Resolves immediately for an agent that is already
413
+ * running, still queued, or unknown — so callers can await it unconditionally.
414
+ *
415
+ * Call it in the same tick as the `spawn()` it belongs to: a failed startup
416
+ * takes its record (and this entry) with it, exactly as the throw did.
417
+ */
418
+ awaitStartup(id) {
419
+ return this.startups.get(id) ?? Promise.resolve();
420
+ }
421
+ /** Actually start an agent (called immediately or from queue drain). */
422
+ async startAgent(id, record, { pi, ctx, type, prompt, options }) {
423
+ // Re-validate a caller-supplied cwd: queued spawns can start minutes after
424
+ // spawn()'s check, and the directory may be gone by then (TOCTOU). Same
425
+ // curated errors; drainQueue parks a throw on the record as an error.
426
+ assertValidSpawnCwd(options.cwd);
427
+ // Single resolution point for the caller-supplied cwd — the worktree base
428
+ // repo and both cleanup calls below MUST agree on this value forever.
429
+ const customCwd = options.cwd ?? undefined; // null (RPC "unset") → undefined
430
+ const baseCwd = customCwd ?? ctx.cwd;
431
+ // Take the running state — and with it the concurrency slot — BEFORE the
432
+ // first await. Creating a worktree is an awaited git call, and drainQueue
433
+ // reads the pool counters synchronously in a loop: incrementing after the
434
+ // await would let it start every queued agent at once while the first is
435
+ // still copying its repo. Claiming "running" here also keeps abort() and
436
+ // abortAll() able to reach an agent whose worktree is still being created.
437
+ //
438
+ // The pool is resolved ONCE, here, and carried to `settleRun` below:
439
+ // `poolFor` reads `maxConcurrentForeground`, which the user can change from
440
+ // `/agents → Settings` mid-run, so recomputing it at settle time would
441
+ // decrement a pool this run never charged (counter underflow, limit
442
+ // silently lifted) or skip the decrement for one it did (leaked slot —
443
+ // every later blocking spawn queues forever). The two startup exits below
444
+ // never reach `settleRun`, so they hand the slot back themselves.
445
+ const pool = this.poolFor(record);
446
+ const releaseSlot = () => {
447
+ if (pool === "background")
448
+ this.runningBackground--;
449
+ else if (pool === "foreground")
450
+ this.runningForeground--;
451
+ };
452
+ record.status = "running";
453
+ record.startedAt = Date.now();
454
+ record.startGate = undefined;
455
+ if (pool === "background")
456
+ this.runningBackground++;
457
+ else if (pool === "foreground")
458
+ this.runningForeground++;
459
+ // Worktree isolation: try to create a temporary git worktree. Strict —
460
+ // fail loud if not possible (no silent fallback to main tree). Done BEFORE
461
+ // the run is kicked off so a failure doesn't leave a half-running agent.
462
+ // The project switch is enforced here as well as at the tool boundary
463
+ // because cross-extension RPC forwards its options unvalidated — a schema
464
+ // that omits the field can't stop a caller that never saw the schema.
465
+ let worktreeCwd;
466
+ if (options.isolation === "worktree" && isWorktreeIsolationEnabled()) {
467
+ const wt = await createWorktree(pi, baseCwd, id);
468
+ if (!wt) {
469
+ releaseSlot();
470
+ throw new Error('Cannot run with isolation: "worktree" — not a git repo, no commits yet, or `git worktree add` failed. ' +
471
+ 'Initialize git and commit at least once, or omit `isolation`.');
472
+ }
473
+ record.worktree = wt;
474
+ // workPath preserves subdirectory scoping for caller-supplied cwds: a
475
+ // cwd deep in a monorepo maps to the same subdir inside the copy, not
476
+ // the copied repo's root. Plain worktree spawns keep the historical
477
+ // behavior (agent at the copy's root) — moving them to workPath would
478
+ // also move .pi config discovery when the parent session sits in a repo
479
+ // subdirectory, silently dropping extensions/skills.
480
+ worktreeCwd = customCwd !== undefined ? wt.workPath : wt.path;
481
+ this.worktreeRepos.add(baseCwd);
482
+ // No longer "running" means a stop landed while the copy was being made
483
+ // (abort(), abortAll()) — a window that did not exist when creation was
484
+ // synchronous. The record is already terminal, so launching the run would
485
+ // burn tokens on work nobody is waiting for: discard the fresh (and by
486
+ // definition unchanged) worktree instead.
487
+ if (record.status !== "running") {
488
+ releaseSlot();
489
+ record.worktreeResult = await cleanupWorktree(pi, baseCwd, wt, options.description);
490
+ this.drainQueue();
491
+ return;
492
+ }
493
+ }
494
+ this.onStart?.(record);
495
+ // Wire parent abort signal to stop the subagent when the parent is interrupted
496
+ let detachParentSignal;
497
+ if (options.signal) {
498
+ // A queued spawn can start minutes after the caller handed us its signal,
499
+ // by which time it may already be aborted — and `addEventListener` would
500
+ // never fire, leaving a child the parent can no longer reach.
501
+ if (options.signal.aborted)
502
+ this.abort(id);
503
+ else {
504
+ const onParentAbort = () => this.abort(id);
505
+ options.signal.addEventListener("abort", onParentAbort, { once: true });
506
+ detachParentSignal = () => options.signal.removeEventListener("abort", onParentAbort);
507
+ }
508
+ }
509
+ const detach = () => { detachParentSignal?.(); detachParentSignal = undefined; };
510
+ this.activeRuns.add(record);
511
+ const promise = runAgent(ctx, type, prompt, {
512
+ pi,
513
+ agentId: id,
514
+ model: options.model,
515
+ maxTurns: options.maxTurns,
516
+ isolated: options.isolated,
517
+ inheritContext: options.inheritContext,
518
+ thinkingLevel: options.thinkingLevel,
519
+ structuredOutput: options.structuredOutput,
520
+ resumeSessionFile: options.resumeSessionFile,
521
+ nested: options.parentAgentId !== undefined,
522
+ workflow: options.workflowId !== undefined,
523
+ // Worktree wins for the working dir (the agent must run in the copy —
524
+ // which, with a custom cwd, was created from that target). Config stays
525
+ // with the parent project when a caller-supplied cwd is in play; it must
526
+ // stay undefined otherwise so plain worktree runs keep resolving config
527
+ // (incl. relative extension paths and memory) inside the worktree copy.
528
+ cwd: worktreeCwd ?? customCwd,
529
+ // Set iff a worktree was created (see above) — names the directory the
530
+ // copy came from, so the prompt can tell the agent not to work there.
531
+ worktreeBase: worktreeCwd ? baseCwd : undefined,
532
+ configCwd: options.configCwd ?? (customCwd !== undefined ? ctx.cwd : undefined),
533
+ signal: record.abortController.signal,
534
+ onToolActivity: (activity) => {
535
+ if (activity.type === "end")
536
+ record.toolUses++;
537
+ options.onToolActivity?.(activity);
538
+ },
539
+ onTurnEnd: options.onTurnEnd,
540
+ onTextDelta: options.onTextDelta,
541
+ onModelChange: session => updateEffectiveModel(record, session),
542
+ onAdvisorStatus: status => { record.advisorStatus = status; },
543
+ onAssistantUsage: (usage) => {
544
+ addUsage(record.lifetimeUsage, usage);
545
+ this.onUsage?.(record, usage);
546
+ options.onAssistantUsage?.(usage);
547
+ },
548
+ onCompaction: (info) => {
549
+ record.compactionCount++;
550
+ this.onCompact?.(record, info);
551
+ options.onCompaction?.(info);
552
+ },
553
+ nestedRuntime: {
554
+ manager: this,
555
+ parentAgentId: id,
556
+ depth: record.depth ?? 1,
557
+ maxSubagentDepth: record.maxSubagentDepth,
558
+ },
559
+ onSessionCreated: (session) => {
560
+ if (record.session && record.session !== session)
561
+ releaseToolProgress(record.session);
562
+ record.session = session;
563
+ // Capture now, while the session object exists: after eviction this
564
+ // path is the only thing that can reopen the conversation, and an
565
+ // in-memory session reports undefined, which correctly means
566
+ // "nothing to come back to".
567
+ // Optional chaining, not defensiveness for its own sake: this is the
568
+ // only field read off the session at creation, so an older pi or a
569
+ // stubbed session must degrade to "not resumable" rather than throw
570
+ // and take the whole spawn down with it.
571
+ record.sessionFile = session.sessionManager?.getSessionFile?.();
572
+ // Same reason, different field: the model and thinking level are only
573
+ // knowable once pi has resolved its defaults and clamped the level to
574
+ // what the model supports. Writing them back here makes the record
575
+ // authoritative, so every surface reads one place instead of each
576
+ // re-deriving "session, else the request" for itself.
577
+ updateEffectiveModel(record, session);
578
+ if (this.disposed || record.status === "stopped") {
579
+ record.pendingSteers = undefined;
580
+ if (this.disposed)
581
+ void shutdownChildSession(session);
582
+ return;
583
+ }
584
+ // Flush any steers that arrived before the session was ready
585
+ if (record.pendingSteers?.length) {
586
+ for (const msg of record.pendingSteers) {
587
+ session.steer(msg).catch(() => { });
588
+ }
589
+ record.pendingSteers = undefined;
590
+ }
591
+ options.onSessionCreated?.(session);
592
+ },
593
+ })
594
+ .then(({ responseText, session, aborted, steered, failure, structuredJson, structuredRetried }) => {
595
+ // Keep the record running through cleanup: terminal status promises a
596
+ // complete result, including its worktree note and exactly-once flush.
597
+ const status = aborted ? "aborted" : failure ? "error" : steered ? "steered" : "completed";
598
+ if (failure && record.status !== "stopped" && !aborted)
599
+ record.error = failure;
600
+ record.result = responseText;
601
+ // Kept beside `result`, never inside it: `result` is prose meant for a
602
+ // reader — it is previewed, transcribed, and appended to below — while
603
+ // this is a machine-readable payload one caller asked for by schema.
604
+ record.structuredJson = structuredJson;
605
+ record.structuredRetried = structuredRetried;
606
+ if (record.session && record.session !== session)
607
+ releaseToolProgress(record.session);
608
+ // `RunResult.session` is always set by the real runner, but a stubbed
609
+ // or mocked runner may omit it. Degrade the same way `onSessionCreated`
610
+ // does for stubbed sessions — keep whatever that callback captured
611
+ // instead of clobbering the record (and crashing updateEffectiveModel,
612
+ // whose model read assumes a session object) with undefined.
613
+ if (session) {
614
+ record.session = session;
615
+ updateEffectiveModel(record, session);
616
+ }
617
+ return { text: responseText, succeeded: true, status };
618
+ })
619
+ .catch((err) => {
620
+ if (record.status !== "stopped")
621
+ record.error = err instanceof Error ? err.message : String(err);
622
+ return { text: "", succeeded: false, status: "error" };
623
+ })
624
+ .then(async ({ text, succeeded, status }) => {
625
+ // One finalizer, outside the run's catch: a cleanup/callback error must
626
+ // never re-enter cleanup or release this invocation's slot twice.
627
+ detach();
628
+ if (record.outputCleanup) {
629
+ const cleanup = record.outputCleanup;
630
+ record.outputCleanup = undefined;
631
+ // Awaited: a settled agent's transcript must be on disk before the
632
+ // run resolves — completion notifications and hosts read it after.
633
+ try {
634
+ await cleanup();
635
+ }
636
+ catch { /* ignore output side-effect errors */ }
637
+ }
638
+ if (record.worktree) {
639
+ if (succeeded && options.onBeforeWorktreeCleanup) {
640
+ try {
641
+ // The record stays running until cleanup is complete. Let the hook
642
+ // inspect the computed outcome without publishing it prematurely.
643
+ await options.onBeforeWorktreeCleanup(record.worktree.path, status);
644
+ }
645
+ catch { /* ignore — never block cleanup */ }
646
+ }
647
+ try {
648
+ const wtResult = await cleanupWorktree(pi, baseCwd, record.worktree, options.description);
649
+ record.worktreeResult = wtResult;
650
+ if (succeeded && wtResult.hasChanges && wtResult.branch) {
651
+ const repoNote = customCwd !== undefined ? ` in \`${baseCwd}\`` : "";
652
+ record.result = (record.result ?? "") +
653
+ `\n\n---\nChanges saved to branch \`${wtResult.branch}\`${repoNote}. Merge with: \`git merge ${wtResult.branch}\`${customCwd !== undefined ? ` (run in \`${baseCwd}\`)` : ""}`;
654
+ }
655
+ }
656
+ catch (err) {
657
+ status = "error";
658
+ record.error ??= err instanceof Error ? err.message : String(err);
659
+ text = "";
660
+ }
661
+ }
662
+ discardStaleSteers(record);
663
+ if (record.status !== "stopped")
664
+ record.status = status;
665
+ record.completedAt ??= Date.now();
666
+ this.abortOwnedChildren(id);
667
+ this.activeRuns.delete(record);
668
+ if (this.disposed)
669
+ await shutdownChildSession(record.session);
670
+ this.settleRun(record, succeeded, pool);
671
+ return text;
672
+ });
673
+ record.promise = promise;
674
+ // Notify caller that spawn is complete (record is in the map, promise is set).
675
+ // Called synchronously — onSessionCreated fires asynchronously inside runAgent.
676
+ // Used by spawnAndWait to let the caller set up output files before streaming
677
+ // starts. Read off the options, so a spawn that started from a queue drain
678
+ // still reaches the caller that queued it.
679
+ options.onSpawned?.(id);
680
+ }
681
+ /**
682
+ * The shared tail of both settle paths: release whatever pool slot the run
683
+ * held, notify, and let the queue drain into the freed slot.
684
+ *
685
+ * The decrement lives HERE and nowhere else. `abort()` on a running record
686
+ * only fires its controller and leaves the run to settle normally, so
687
+ * decrementing there too would double-free — permanently lifting the limit.
688
+ *
689
+ * Foreground agents fire `onComplete` for lifecycle symmetry, with
690
+ * `resultConsumed` set so the callback skips notifications the inline result
691
+ * already delivered.
692
+ *
693
+ * @param guardCallback swallow a throwing `onComplete` (the success path does;
694
+ * the error path historically did not, and keeps not doing so).
695
+ * @param pool the pool this run was CHARGED TO at start time — passed in, not
696
+ * recomputed, so a mid-run change to `maxConcurrentForeground` can't make
697
+ * the release disagree with the acquire.
698
+ */
699
+ settleRun(record, guardCallback, pool) {
700
+ if (!record.isBackground)
701
+ record.resultConsumed = true;
702
+ if (pool === "background")
703
+ this.runningBackground--;
704
+ else if (pool === "foreground")
705
+ this.runningForeground--;
706
+ try {
707
+ if (!this.disposed) {
708
+ if (guardCallback) {
709
+ try {
710
+ this.onComplete?.(record);
711
+ }
712
+ catch { /* ignore completion side-effect errors */ }
713
+ }
714
+ else {
715
+ this.onComplete?.(record);
716
+ }
717
+ }
718
+ }
719
+ finally {
720
+ // Even a failing observer cannot strand the next queued child.
721
+ if (record.isBackground || pool !== undefined)
722
+ this.drainQueue();
723
+ }
724
+ // The isBackground half reproduces the pre-pool condition exactly — a
725
+ // background settle has always drained, even for a nested child that held
726
+ // no slot — so that path is unchanged whether or not the foreground pool is
727
+ // on. The `pool` half only adds the drain a freed FOREGROUND slot needs.
728
+ // A drain with nothing freed is a no-op anyway, but "no-op" is a claim
729
+ // about reachability, and matching the old condition needs no such claim.
730
+ }
731
+ /**
732
+ * Stop the nested children a settled parent owns. Nested records are hidden
733
+ * from the UI and only their owner can consume them, so a child outliving its
734
+ * parent would burn tokens unseen with no way to reach it. Grandchildren are
735
+ * covered transitively — each abort lands in that child's own settle path.
736
+ */
737
+ abortOwnedChildren(parentId) {
738
+ for (const [id, record] of this.agents) {
739
+ if (record.parentAgentId === parentId)
740
+ this.abort(id);
741
+ }
742
+ }
743
+ /**
744
+ * Start queued agents up to each pool's concurrency limit.
745
+ *
746
+ * `findIndex` on the entry's OWN pool rather than `shift`: with one queue
747
+ * serving two independent limits, a saturated foreground pool at the head
748
+ * would otherwise stall every background agent behind it. Taking the earliest
749
+ * eligible entry keeps FIFO within each pool, which is what callers see.
750
+ */
751
+ drainQueue() {
752
+ for (;;) {
753
+ const i = this.queue.findIndex(e => this.poolHasRoom(e.pool));
754
+ if (i === -1)
755
+ return;
756
+ const [next] = this.queue.splice(i, 1);
757
+ const record = this.agents.get(next.id);
758
+ // Stale entries (aborted while queued) are not started — but are still
759
+ // released, since nothing else will.
760
+ if (!record || record.status !== "queued") {
761
+ next.release();
762
+ continue;
763
+ }
764
+ // Detached, and never rejects: a late failure (e.g. strict worktree
765
+ // isolation) lands on the record inside `launch`, exactly as the
766
+ // synchronous throw did here before, and draining continues either way.
767
+ //
768
+ // The release waits for that startup to SETTLE rather than firing here.
769
+ // Startup is async now, so a release at drain time would wake a blocked
770
+ // `spawnAndWait` while `record.promise` was still undefined, and it would
771
+ // read a perfectly healthy agent as one that never ran.
772
+ void next.start().then(() => next.release(), () => next.release());
773
+ }
774
+ }
775
+ /**
776
+ * Remove queued entries and wake anyone blocked on them. The single point
777
+ * that enforces "leaving the queue releases the waiter" — a missed release is
778
+ * an unbounded hang, not a failed call.
779
+ */
780
+ dequeue(pred) {
781
+ const kept = [];
782
+ for (const entry of this.queue) {
783
+ if (pred(entry))
784
+ entry.release();
785
+ else
786
+ kept.push(entry);
787
+ }
788
+ this.queue = kept;
789
+ }
790
+ /**
791
+ * Spawn an agent and wait for completion (foreground use).
792
+ * Charged to the foreground pool (`maxConcurrentForeground`), which is
793
+ * unlimited by default; never to the background one.
794
+ * Returns { id, record } so callers can access the agent ID.
795
+ *
796
+ * @param onSpawned - Called synchronously once the run is kicked off, before
797
+ * onSessionCreated fires. Use this to set record.outputFile so
798
+ * streamToOutputFile can pick it up.
799
+ */
800
+ async spawnAndWait(pi, ctx, type, prompt, options, onSpawned) {
801
+ // `blocking` is what maxConcurrentForeground bounds, and this is its only
802
+ // source. onSpawned rides on the options rather than on a field of this
803
+ // manager: a queued spawn starts at drain time, long after any install/
804
+ // restore pair around this call would have put the field back — and it now
805
+ // fires after an await (worktree creation) even on the immediate path.
806
+ const id = this.spawn(pi, ctx, type, prompt, {
807
+ ...options,
808
+ isBackground: false,
809
+ blocking: true,
810
+ onSpawned,
811
+ });
812
+ const record = this.agents.get(id);
813
+ // Queued: nothing to await yet — the promise appears when the drain starts
814
+ // it. The gate resolves (never rejects) on every path out of the queue,
815
+ // start and abort alike, so a rejection can never escape into the caller's
816
+ // tool `execute` and take down pi's whole Promise.all tool batch.
817
+ if (record.status === "queued")
818
+ await record.startGate;
819
+ // The run promise only exists once startup is past its awaited repo copy —
820
+ // without this the call would return before the agent had started at all.
821
+ // A startup failure (strict worktree isolation) rejects here, which is what
822
+ // the immediate path owes its caller: pi only marks a tool result failed
823
+ // when `execute` throws. A queued spawn's failure landed on the record
824
+ // instead (nobody was awaiting `startups` at drain time) and is rethrown
825
+ // below, so the contract is the same either way.
826
+ await this.awaitStartup(id);
827
+ // undefined when it was aborted while queued, or stopped mid-copy, and so
828
+ // never ran — the record is already terminal with a completedAt, which is
829
+ // what the caller renders.
830
+ if (record.promise)
831
+ await record.promise;
832
+ // A record that ended "error" without ever getting a promise never ran: the
833
+ // same startup failure spawn() rethrows on the immediate path (#179). Keep
834
+ // one contract rather than letting queue pressure decide whether a strict
835
+ // worktree failure throws or returns as a result.
836
+ if (record.promise === undefined && record.status === "error") {
837
+ throw new Error(record.error ?? "Agent failed to start");
838
+ }
839
+ return { id, record };
840
+ }
841
+ /**
842
+ * Resume an existing agent session with a new prompt.
843
+ */
844
+ async resume(id, prompt, signal, options) {
845
+ const record = this.agents.get(id);
846
+ if (!record?.session || this.disposed || this.activeRuns.has(record)
847
+ || record.status === "running" || record.status === "queued")
848
+ return undefined;
849
+ // Background resume: settle asynchronously and notify on completion exactly
850
+ // like a background spawn, returning immediately with the record still
851
+ // "running" — or "queued" when at the concurrency limit. Previously
852
+ // run_in_background was ignored on resume (the Agent tool's resume branch
853
+ // returned before its background branch, and resume() only ever awaited
854
+ // inline), so a resumed agent always blocked the caller until it finished.
855
+ if (options?.isBackground) {
856
+ // Never re-enter a run that is still in flight. Detaching means the caller
857
+ // gets control back while the record stays "running", so nothing stops the
858
+ // model from resuming the same agent again. Starting a second run would
859
+ // overwrite record.abortController — orphaning the live run beyond the
860
+ // reach of `/agents` stop and abortAll() — double-count the pool slot, and
861
+ // then reject from session.prompt() with "Agent is already processing",
862
+ // whose settle path would abort the LIVE run's children and report a
863
+ // failure for a run that is still going. Refuse instead, leaving the
864
+ // record untouched; the caller decides whether to wait or steer.
865
+ record.isBackground = true;
866
+ record.resultConsumed = false;
867
+ record.result = undefined;
868
+ record.error = undefined;
869
+ record.completedAt = undefined;
870
+ record.status = "queued";
871
+ const start = () => this.startResume(id, record, prompt, signal, options);
872
+ if (occupiesPoolSlot(record) && !this.poolHasRoom("background")) {
873
+ if (!this.armQueuedAbort(id, signal))
874
+ return record;
875
+ // At the concurrency limit — queue it, drains when a slot frees. A
876
+ // detached resume has no inline caller, hence nothing to release. The
877
+ // queue is shared with spawns, whose startup is async, so entries are
878
+ // promise-shaped even though a resume starts synchronously; failures
879
+ // land on the record here, since drainQueue no longer catches.
880
+ this.queue.push({
881
+ id,
882
+ pool: "background",
883
+ start: async () => {
884
+ try {
885
+ start();
886
+ }
887
+ catch (err) {
888
+ record.status = "error";
889
+ record.error = err instanceof Error ? err.message : String(err);
890
+ record.completedAt = Date.now();
891
+ this.onComplete?.(record);
892
+ }
893
+ },
894
+ release: () => { },
895
+ });
896
+ }
897
+ else {
898
+ start();
899
+ }
900
+ return record;
901
+ }
902
+ // Foreground resumes use the same controller and stopped-state guard, but
903
+ // keep their historical inline-only result (no background notification/pool).
904
+ this.startResume(id, record, prompt, signal, { ...options, isBackground: false });
905
+ await record.promise;
906
+ return record;
907
+ }
908
+ /**
909
+ * Start a background resume run: detached, settling and notifying like
910
+ * startAgent's background path. Invoked immediately, or from drainQueue when
911
+ * a concurrency slot frees. The session already exists (resume reuses it), so
912
+ * there is no onSessionCreated to hang per-run wiring off — callers use
913
+ * `options.onStarted`, which fires on both the immediate and the drained path.
914
+ */
915
+ startResume(id, record, prompt, parentSignal, options) {
916
+ if (!record.session)
917
+ return;
918
+ const background = options.isBackground === true;
919
+ const holdsSlot = background && occupiesPoolSlot(record);
920
+ this.activeRuns.add(record);
921
+ record.status = "running";
922
+ record.startedAt = Date.now();
923
+ record.completedAt = undefined;
924
+ record.result = undefined;
925
+ record.error = undefined;
926
+ if (holdsSlot)
927
+ this.runningBackground++;
928
+ if (background)
929
+ this.onStart?.(record);
930
+ // Fresh abort controller so /agents stop and steering target THIS run rather
931
+ // than the previous one's settled controller.
932
+ const abortController = new AbortController();
933
+ record.abortController = abortController;
934
+ // Optional, and NOT what the Agent tool passes for a detached resume: a
935
+ // parent signal aborts on the parent's own interrupt (user Esc), which is
936
+ // right for a foreground run whose result the caller is awaiting, and wrong
937
+ // for a detached one — background spawns omit it for exactly this reason.
938
+ let detachParentSignal;
939
+ if (parentSignal) {
940
+ const onParentAbort = () => this.abort(id);
941
+ if (parentSignal.aborted)
942
+ onParentAbort();
943
+ else {
944
+ parentSignal.addEventListener("abort", onParentAbort, { once: true });
945
+ detachParentSignal = () => parentSignal.removeEventListener("abort", onParentAbort);
946
+ }
947
+ }
948
+ // Per-run side effects (output streaming) — see ResumeOptions.onStarted.
949
+ // After the record is in its running shape, before the run is kicked off.
950
+ try {
951
+ options.onStarted?.();
952
+ }
953
+ catch { /* ignore caller wiring errors */ }
954
+ let settled = false;
955
+ // Returns the final transcript flush when it ran, so the run's completion
956
+ // can await it: a settled agent's transcript is on disk before its result
957
+ // reaches the parent (same contract as the spawn path's finalizer).
958
+ const settle = () => {
959
+ if (settled)
960
+ return undefined;
961
+ settled = true;
962
+ discardStaleSteers(record);
963
+ if (record.session)
964
+ updateEffectiveModel(record, record.session);
965
+ detachParentSignal?.();
966
+ detachParentSignal = undefined;
967
+ // Final flush of streaming output file
968
+ let flushed;
969
+ if (record.outputCleanup) {
970
+ const cleanup = record.outputCleanup;
971
+ record.outputCleanup = undefined;
972
+ try {
973
+ flushed = Promise.resolve(cleanup());
974
+ }
975
+ catch { /* ignore */ }
976
+ }
977
+ // Children spawned during the resumed turn must not outlive it.
978
+ this.abortOwnedChildren(id);
979
+ this.activeRuns.delete(record);
980
+ if (holdsSlot)
981
+ this.runningBackground--;
982
+ if (background && !this.disposed) {
983
+ try {
984
+ this.onComplete?.(record);
985
+ }
986
+ catch { /* ignore completion side-effect errors */ }
987
+ }
988
+ this.drainQueue();
989
+ return flushed;
990
+ };
991
+ // Steers that arrived while this resume was queued: deliver them with the
992
+ // resumed prompt rather than relying on the idle session's steering queue.
993
+ const queuedSteers = record.pendingSteers ?? [];
994
+ record.pendingSteers = undefined;
995
+ const resumePrompt = queuedSteers.length === 0
996
+ ? prompt
997
+ : `${prompt}\n\n[Messages received while this agent was queued]\n${queuedSteers.map(m => `- ${m}`).join("\n")}`;
998
+ const promise = resumeAgent(record.session, resumePrompt, {
999
+ onToolActivity: (activity) => {
1000
+ if (activity.type === "end")
1001
+ record.toolUses++;
1002
+ options.onToolActivity?.(activity);
1003
+ },
1004
+ onAssistantUsage: (usage) => {
1005
+ addUsage(record.lifetimeUsage, usage);
1006
+ this.onUsage?.(record, usage);
1007
+ options.onAssistantUsage?.(usage);
1008
+ },
1009
+ onCompaction: (info) => {
1010
+ record.compactionCount++;
1011
+ this.onCompact?.(record, info);
1012
+ options.onCompaction?.(info);
1013
+ },
1014
+ signal: abortController.signal,
1015
+ })
1016
+ .then(async ({ text, failure }) => {
1017
+ // Don't overwrite status if externally stopped via abort().
1018
+ if (record.status !== "stopped") {
1019
+ // Same contract as the spawn path (#144): a failed final turn is an
1020
+ // error, not a completion — but the resumed text stays available.
1021
+ record.status = failure ? "error" : "completed";
1022
+ if (failure)
1023
+ record.error = failure;
1024
+ }
1025
+ record.result = text;
1026
+ record.completedAt ??= Date.now();
1027
+ await settle();
1028
+ return text;
1029
+ })
1030
+ .catch(async (err) => {
1031
+ if (record.status !== "stopped") {
1032
+ record.status = "error";
1033
+ record.error = err instanceof Error ? err.message : String(err);
1034
+ }
1035
+ record.completedAt ??= Date.now();
1036
+ await settle();
1037
+ return "";
1038
+ });
1039
+ record.promise = promise;
1040
+ }
1041
+ /**
1042
+ * Send a steering message to an agent from the UI (mirrors the steer_subagent
1043
+ * tool). A live session delivers it now — it interrupts the agent after its
1044
+ * current tool execution and appears as a user message. If the session isn't
1045
+ * ready yet, the message is queued on `pendingSteers` and flushed when the
1046
+ * session is created. Returns false if the agent can't accept steering
1047
+ * (unknown id, or no longer running/queued).
1048
+ */
1049
+ steer(id, message) {
1050
+ const record = this.agents.get(id);
1051
+ if (!record)
1052
+ return false;
1053
+ if (record.status !== "running" && record.status !== "queued")
1054
+ return false;
1055
+ // A queued agent holds its message until it starts — including a queued
1056
+ // resume, whose previous session exists but is idle (startResume folds
1057
+ // pendingSteers into the resumed prompt).
1058
+ if (record.status === "queued") {
1059
+ record.pendingSteers ??= [];
1060
+ record.pendingSteers.push(message);
1061
+ return true;
1062
+ }
1063
+ if (record.session && !sessionAcceptsSteer(record.session))
1064
+ return false;
1065
+ if (record.session) {
1066
+ record.session.steer(message).catch(() => { });
1067
+ }
1068
+ else {
1069
+ if (!record.pendingSteers)
1070
+ record.pendingSteers = [];
1071
+ record.pendingSteers.push(message);
1072
+ }
1073
+ return true;
1074
+ }
1075
+ /** Interactive send path: report an SDK rejection instead of pretending it queued. */
1076
+ async steerAcknowledged(id, message) {
1077
+ const record = this.agents.get(id);
1078
+ if (!record || this.disposed || (record.status !== "running" && record.status !== "queued"))
1079
+ return false;
1080
+ if (record.status === "queued") {
1081
+ record.pendingSteers ??= [];
1082
+ record.pendingSteers.push(message);
1083
+ return true;
1084
+ }
1085
+ if (record.session && !sessionAcceptsSteer(record.session))
1086
+ return false;
1087
+ if (!record.session) {
1088
+ record.pendingSteers ??= [];
1089
+ record.pendingSteers.push(message);
1090
+ return true;
1091
+ }
1092
+ try {
1093
+ await record.session.steer(message);
1094
+ return true;
1095
+ }
1096
+ catch {
1097
+ return false;
1098
+ }
1099
+ }
1100
+ getRecord(id) {
1101
+ return this.agents.get(id);
1102
+ }
1103
+ /** Handles already in use, so a fresh spawn can pick an unclaimed one. */
1104
+ takenHandles() {
1105
+ const taken = new Set();
1106
+ for (const record of this.agents.values()) {
1107
+ if (record.handle)
1108
+ taken.add(record.handle);
1109
+ if (record.alias)
1110
+ taken.add(record.alias);
1111
+ }
1112
+ // Tombstones hold their names too: an evicted `@explore` is still
1113
+ // resurrectable, so a later Explore must become `explore-2` rather than
1114
+ // shadowing a conversation the user can still reach.
1115
+ for (const entry of this.tombstones.values()) {
1116
+ taken.add(entry.handle);
1117
+ if (entry.alias)
1118
+ taken.add(entry.alias);
1119
+ }
1120
+ return taken;
1121
+ }
1122
+ /**
1123
+ * Resolve an `@name` from the prompt. Matches a top-level agent's handle
1124
+ * case-insensitively, preferring one that can still be steered and otherwise
1125
+ * the most recently started (which is the one a resume should continue), then
1126
+ * falls back to an exact agent id so `@<agentId>` works too.
1127
+ */
1128
+ resolveMention(name) {
1129
+ const wanted = name.toLowerCase();
1130
+ let fallback;
1131
+ for (const record of this.agents.values()) {
1132
+ if (record.parentAgentId !== undefined)
1133
+ continue;
1134
+ // Handle and alias share one namespace, so at most one agent answers a
1135
+ // name and it makes no difference which of the two matched.
1136
+ if (record.handle?.toLowerCase() !== wanted && record.alias?.toLowerCase() !== wanted)
1137
+ continue;
1138
+ if (record.status === "running" || record.status === "queued")
1139
+ return { kind: "live", record };
1140
+ if (!fallback || record.startedAt > fallback.startedAt)
1141
+ fallback = record;
1142
+ }
1143
+ if (fallback)
1144
+ return { kind: "live", record: fallback };
1145
+ const byId = this.agents.get(name);
1146
+ if (byId?.parentAgentId === undefined && byId !== undefined)
1147
+ return { kind: "live", record: byId };
1148
+ // Only once nothing live answers: a tombstone is a conversation to reopen,
1149
+ // and reopening one while its record still exists would fork the session.
1150
+ for (const entry of this.tombstones.values()) {
1151
+ if (entry.handle.toLowerCase() === wanted || entry.alias?.toLowerCase() === wanted || entry.id === name) {
1152
+ return { kind: "tombstone", entry };
1153
+ }
1154
+ }
1155
+ return undefined;
1156
+ }
1157
+ /**
1158
+ * Forget an evicted agent, by handle. For the case where its session file has
1159
+ * gone: the entry can then only ever fail, while still holding the name
1160
+ * against the type that would otherwise start a fresh agent under it.
1161
+ *
1162
+ * A *successful* resume does not drop its tombstone — the live record it
1163
+ * creates already wins in `resolveMention`, and overwrites the entry in place
1164
+ * when it is itself evicted.
1165
+ */
1166
+ dropTombstone(handle) {
1167
+ this.tombstones.delete(handle);
1168
+ }
1169
+ /** Evicted agents whose conversation can still be reopened, newest first. */
1170
+ listTombstones() {
1171
+ return [...this.tombstones.values()].sort((a, b) => b.completedAt - a.completedAt);
1172
+ }
1173
+ listAgents() {
1174
+ return [...this.agents.values()].sort((a, b) => b.startedAt - a.startedAt);
1175
+ }
1176
+ abort(id) {
1177
+ const record = this.agents.get(id);
1178
+ if (!record)
1179
+ return false;
1180
+ // Remove from queue if queued. No decrement — the slot was never taken —
1181
+ // and no onComplete, matching what a queued background abort has always
1182
+ // done; a blocking caller learns of the stop from its own tool result.
1183
+ if (record.status === "queued") {
1184
+ this.dequeue(q => q.id === id);
1185
+ record.status = "stopped";
1186
+ record.completedAt = Date.now();
1187
+ return true;
1188
+ }
1189
+ if (record.status !== "running")
1190
+ return false;
1191
+ record.abortController?.abort();
1192
+ record.status = "stopped";
1193
+ record.completedAt = Date.now();
1194
+ return true;
1195
+ }
1196
+ /** Dispose a record's session and remove it from the map. */
1197
+ removeRecord(id, record) {
1198
+ this.tombstone(record);
1199
+ const session = record.session;
1200
+ // Detached before the shutdown starts, so the record leaves the map at once and
1201
+ // nothing can observe a session that is half torn down.
1202
+ record.session = undefined;
1203
+ this.agents.delete(id);
1204
+ // A failed startup keeps its (rejected) entry so a late awaitStartup still
1205
+ // sees it; drop it with the record so the map can't grow unbounded.
1206
+ this.startups.delete(id);
1207
+ // Fire-and-forget is right here and only here: this runs from the 60s cleanup timer
1208
+ // and from `clearCompleted()` on session boundaries, with the process staying alive,
1209
+ // so handlers get their full window. The quit path awaits instead — see dispose().
1210
+ void shutdownChildSession(session);
1211
+ }
1212
+ /**
1213
+ * Preserve enough of a departing record for `@handle` to reopen its
1214
+ * conversation later. Nothing to keep unless it has both a handle to be
1215
+ * addressed by and a session file to reopen — an in-memory session leaves no
1216
+ * transcript, so the mention would have nothing to continue from.
1217
+ */
1218
+ tombstone(record) {
1219
+ if (!record.handle || !record.sessionFile)
1220
+ return;
1221
+ this.tombstones.set(record.handle, {
1222
+ handle: record.handle,
1223
+ alias: record.alias,
1224
+ id: record.id,
1225
+ type: record.type,
1226
+ description: record.description,
1227
+ sessionFile: record.sessionFile,
1228
+ completedAt: record.completedAt ?? Date.now(),
1229
+ });
1230
+ // Bound the memory a long session can accumulate. Oldest first, since the
1231
+ // agent someone still wants to reach is the one they used most recently.
1232
+ while (this.tombstones.size > MAX_TOMBSTONES) {
1233
+ const oldest = [...this.tombstones.values()].reduce((a, b) => (a.completedAt <= b.completedAt ? a : b));
1234
+ this.tombstones.delete(oldest.handle);
1235
+ }
1236
+ }
1237
+ cleanup() {
1238
+ const cutoff = Date.now() - 10 * 60_000;
1239
+ for (const [id, record] of this.agents) {
1240
+ if (this.activeRuns.has(record) || record.status === "running" || record.status === "queued")
1241
+ continue;
1242
+ if ((record.completedAt ?? 0) >= cutoff)
1243
+ continue;
1244
+ this.removeRecord(id, record);
1245
+ }
1246
+ }
1247
+ /**
1248
+ * Remove all completed/stopped/errored records immediately.
1249
+ * Called on session start/switch so tasks from a prior session don't persist.
1250
+ * Pass skipUnconsumed=true to preserve records the LLM hasn't read yet
1251
+ * (resultConsumed=false) — they will be evicted by the 10-minute cleanup timer instead.
1252
+ */
1253
+ clearCompleted(skipUnconsumed = false) {
1254
+ for (const [id, record] of this.agents) {
1255
+ if (this.activeRuns.has(record) || record.status === "running" || record.status === "queued")
1256
+ continue;
1257
+ if (skipUnconsumed && !record.resultConsumed)
1258
+ continue;
1259
+ this.removeRecord(id, record);
1260
+ }
1261
+ // Unconditional: both callers are session boundaries (`session_start` and
1262
+ // `session_before_switch`), and `skipUnconsumed` only spares records whose
1263
+ // results the LLM has yet to read — it does not make the sweep partial in
1264
+ // the sense that matters here. A new session means new handles, or
1265
+ // `@explore` would silently reach an agent the user never started. Claude
1266
+ // Code resets its registry on `/clear` for the same reason.
1267
+ this.tombstones.clear();
1268
+ }
1269
+ /** Whether any agents are still running or queued. */
1270
+ hasRunning() {
1271
+ return [...this.agents.values()].some(r => r.status === "running" || r.status === "queued");
1272
+ }
1273
+ /** Abort all running and queued agents immediately. */
1274
+ abortAll() {
1275
+ let count = 0;
1276
+ // Clear queued agents first
1277
+ for (const queued of this.queue) {
1278
+ const record = this.agents.get(queued.id);
1279
+ if (record) {
1280
+ record.status = "stopped";
1281
+ record.completedAt = Date.now();
1282
+ count++;
1283
+ }
1284
+ }
1285
+ this.dequeue(() => true);
1286
+ // Abort running agents
1287
+ for (const record of this.agents.values()) {
1288
+ if (record.status === "running") {
1289
+ record.abortController?.abort();
1290
+ record.status = "stopped";
1291
+ record.completedAt = Date.now();
1292
+ count++;
1293
+ }
1294
+ }
1295
+ return count;
1296
+ }
1297
+ /** Wait for all running and queued agents to complete (including queued ones). */
1298
+ async waitForAll() {
1299
+ // Loop because drainQueue respects the concurrency limit — as running
1300
+ // agents finish they start queued ones, which need awaiting too.
1301
+ while (true) {
1302
+ this.drainQueue();
1303
+ const pending = [];
1304
+ for (const record of this.agents.values()) {
1305
+ if (!this.activeRuns.has(record) && record.status !== "running" && record.status !== "queued")
1306
+ continue;
1307
+ // An agent whose worktree is still being created is "running" with no
1308
+ // `promise` yet — without its startup the wait would return too early.
1309
+ const startup = this.startups.get(record.id);
1310
+ if (startup)
1311
+ pending.push(startup);
1312
+ if (record.promise)
1313
+ pending.push(record.promise);
1314
+ }
1315
+ if (pending.length === 0)
1316
+ break;
1317
+ await Promise.allSettled(pending);
1318
+ }
1319
+ }
1320
+ /**
1321
+ * @param pi - Needed to run `git worktree prune`, which is async now and so
1322
+ * cannot be reached through a stored spawn argument at shutdown. Omitting
1323
+ * it (tests, teardown of a manager that never spawned) skips the prune.
1324
+ */
1325
+ async dispose(pi) {
1326
+ // A caller may supply Pi only on a later dispose. Preserve that prune,
1327
+ // while every session and notification still tears down exactly once.
1328
+ if (pi && !this.pruned) {
1329
+ this.pruned = true;
1330
+ // Prune any orphaned git worktrees (crash recovery). Detached: dispose runs
1331
+ // on the shutdown path, which cannot wait for git. Started before the awaited
1332
+ // shutdown below rather than after it, so the git calls have that window to
1333
+ // finish in instead of racing the process exit that follows.
1334
+ const prune = (repo) => { pruneWorktrees(pi, repo).catch(() => { }); };
1335
+ prune(process.cwd());
1336
+ // Also prune repos that caller-supplied cwds created worktrees in — a clean
1337
+ // exit with in-flight agents would otherwise leave stale registrations there.
1338
+ for (const repo of this.worktreeRepos)
1339
+ prune(repo);
1340
+ }
1341
+ if (this.disposed)
1342
+ return this.shutdown;
1343
+ this.disposed = true;
1344
+ clearInterval(this.cleanupInterval);
1345
+ this.abortAll();
1346
+ const sessions = [...this.agents.values()].map(record => record.session);
1347
+ this.agents.clear();
1348
+ this.startups.clear();
1349
+ // Awaited, unlike eviction: bounded shutdown handlers run before Pi exits.
1350
+ this.shutdown = Promise.all(sessions.map(session => shutdownChildSession(session))).then(() => { });
1351
+ return this.shutdown;
1352
+ }
1353
+ }
1354
+ /**
1355
+ * Whether a child session will still consume a steering message. A session
1356
+ * that has stopped streaming, with no managed prompt (or fallback recovery)
1357
+ * still in flight, would only park the message in its queue — reported as
1358
+ * "sent" but never read. Stubs without `isStreaming` are treated as live.
1359
+ */
1360
+ export function sessionAcceptsSteer(session) {
1361
+ const streaming = session.isStreaming;
1362
+ if (typeof streaming !== "boolean" || streaming)
1363
+ return true;
1364
+ return isChildRequestActive(session);
1365
+ }
1366
+ /**
1367
+ * Drop steering messages still queued in a finished child session so a later
1368
+ * resume of the same session object cannot replay stale instructions, and
1369
+ * count them on the record so the result can mention it.
1370
+ */
1371
+ function discardStaleSteers(record) {
1372
+ const session = record.session;
1373
+ if (typeof session?.getSteeringMessages !== "function" || typeof session.clearQueue !== "function")
1374
+ return;
1375
+ const queued = session.getSteeringMessages().length;
1376
+ if (queued === 0)
1377
+ return;
1378
+ session.clearQueue();
1379
+ record.droppedSteers = (record.droppedSteers ?? 0) + queued;
1380
+ }