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