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