@timmyjl12/pi-subagents 0.0.0-stage → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,872 @@
1
+ /**
2
+ * agent-manager.ts — Tracks agents, background execution, resume support.
3
+ *
4
+ * There are two independent concurrency pools, never one:
5
+ *
6
+ * - Background (`maxConcurrent`, default 10) bounds detached agents.
7
+ * - Foreground (`maxConcurrentForeground`, default 0 = unlimited) bounds
8
+ * agents a caller is blocking on inline — `spawnAndWait`.
9
+ *
10
+ * Independent by design: a foreground agent blocks the parent anyway, so
11
+ * charging it to the background pool would let a saturated pool starve the main
12
+ * session of work it could have done itself. Excess agents in either pool are
13
+ * queued and auto-started as slots free up. Nested children take no slot in
14
+ * either — see `occupiesPoolSlot` / `occupiesForegroundSlot`.
15
+ */
16
+ import type { Model } from "@earendil-works/pi-ai";
17
+ import type { AgentSession, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
18
+ import { type ToolActivity } from "./agent-runner.ts";
19
+ import { type ChildShutdownStatus } from "./child-session-shutdown.ts";
20
+ import type { ArchivedReportReader } from "./nested-tools.ts";
21
+ import type { AgentConfig, AgentInvocation, AgentRecord, AgentTombstone, IsolationMode, MentionResolution, SubagentType, ThinkingLevel } from "./types.ts";
22
+ import { type LifetimeUsage } from "./usage.ts";
23
+ import type { CompiledSchema } from "./workflow/json-schema.ts";
24
+ export type OnAgentComplete = (record: AgentRecord) => void;
25
+ export type OnAgentStart = (record: AgentRecord) => void;
26
+ export type OnAgentCompact = (record: AgentRecord, info: CompactionInfo) => void;
27
+ /**
28
+ * Fired once per assistant `message_end`, for EVERY agent this manager owns —
29
+ * top-level and nested alike, spawns and resumes. The one place where each
30
+ * message is seen exactly once: `AgentRecord.lifetimeUsage` is deliberately
31
+ * double-booked into ancestors (see `nested-tools.ts`) so a hidden child's spend
32
+ * shows up on the record a human can see, which makes those records useless as
33
+ * a basis for anything that must not count a message twice — parent-session
34
+ * accounting above all.
35
+ */
36
+ export type OnAgentUsage = (record: AgentRecord, usage: LifetimeUsage) => void;
37
+ export type CompactionInfo = {
38
+ reason: "manual" | "threshold" | "overflow";
39
+ tokensBefore: number;
40
+ };
41
+ /**
42
+ * Purpose-specific hook for durable reports.
43
+ *
44
+ * Deliberately not a general observer: the manager calls it exactly once per
45
+ * terminal generation, synchronously, BEFORE any completion notification or
46
+ * other caller callback can re-enter `resume()`. An adapter must therefore
47
+ * copy whatever it keeps immediately — a report store does — rather than hold
48
+ * the live record, whose `status`/`result` a resume can overwrite.
49
+ *
50
+ * Unlike `OnAgentComplete`, this fires for foreground resumes (which have no
51
+ * completion notification), queued cancellations and shutdown sweeps.
52
+ */
53
+ export interface AgentReportArchiver {
54
+ save(record: AgentRecord): void;
55
+ }
56
+ /** A teardown that did not prove quiescence; cleanup must keep its paths protected. */
57
+ export interface UncertainTeardown {
58
+ agentId: string;
59
+ /**
60
+ * `pending` means the bounded teardown is still in flight. It is protection,
61
+ * not an outcome: cleanup must treat it exactly like a timeout.
62
+ */
63
+ status: ChildShutdownStatus | "pending";
64
+ /** Whether the unfinished work is child-session teardown or a run finalizer. */
65
+ phase?: "session" | "run";
66
+ /** Per-session-instance identity; never reuse this across reopen attempts. */
67
+ teardownId?: string;
68
+ sessionFile?: string;
69
+ sessionId?: string;
70
+ rootSessionId?: string;
71
+ rootCwd?: string;
72
+ rootSessionFile?: string;
73
+ reason?: string;
74
+ at: number;
75
+ }
76
+ /** Result of disposing a manager: what was torn down and what remains uncertain. */
77
+ export interface AgentManagerShutdown {
78
+ status: ChildShutdownStatus;
79
+ uncertain: UncertainTeardown[];
80
+ }
81
+ /**
82
+ * The manager half of a cleanup preparation pass: which requested reports and
83
+ * session files proved quiescent, and an explicit reason for every one that did
84
+ * not. Each requested item appears on exactly one side.
85
+ */
86
+ export interface AgentCleanupPreparation {
87
+ readyAgentIds: string[];
88
+ blockedAgentIds: Record<string, string>;
89
+ readySessionFiles: string[];
90
+ blockedSessionFiles: Record<string, string>;
91
+ }
92
+ /**
93
+ * Whether a record is one of the session's own agents, rather than something
94
+ * another agent or a workflow owns.
95
+ *
96
+ * The single definition behind every user-facing surface — the fleet list, the
97
+ * widget, the `/agents` menus, `@handle` resolution, and the completion events
98
+ * and session entries. An owned child reports through its owner, so surfacing
99
+ * it separately would double-count the same work in the places a person reads.
100
+ */
101
+ export declare function isTopLevelAgent(record: Pick<AgentRecord, "parentAgentId" | "workflowId">): boolean;
102
+ type ArtifactAccessGuard = (record: AgentRecord) => void | Promise<void>;
103
+ interface SpawnOptions {
104
+ description: string;
105
+ /**
106
+ * Optional memorable name for this instance, becoming a second handle
107
+ * (`@auth-audit`) alongside the type-derived one. Slugged, not validated —
108
+ * anything unusable degrades via `handleBase` rather than failing the spawn.
109
+ */
110
+ name?: string;
111
+ /**
112
+ * Reopen this pi session file instead of starting a fresh conversation, so a
113
+ * mention of an evicted agent continues where it left off. The agent's
114
+ * definition is still resolved from its type, so the continuation runs under
115
+ * the type's CURRENT config.
116
+ */
117
+ resumeSessionFile?: string;
118
+ /**
119
+ * Internal, manager-only: the definition admitted for this spawn. Callers
120
+ * that resolve against a scoped registry (nested delegation, RPC, the root
121
+ * Agent tool) capture it before their own admission await and pass it here;
122
+ * omitted, `spawn()` snapshots the process-global registry synchronously,
123
+ * before the spawn is queued or starts awaiting work.
124
+ */
125
+ agentDefinition?: AgentConfig;
126
+ /**
127
+ * Take an evicted agent's names back verbatim instead of allocating fresh
128
+ * ones, so a resumed conversation keeps the handle the user just typed —
129
+ * `handleBase(type)` cannot reproduce a numbered `explore-2`. Safe without an
130
+ * `assignHandle` pass because tombstoned names are excluded from allocation
131
+ * (`takenHandles`), so nothing live can be holding them.
132
+ *
133
+ * Internal capability, like `resumeSessionFile`: a forged handle would
134
+ * duplicate a live agent's name and make `resolveMention` ambiguous, so
135
+ * `spawnTopLevel` strips it from anything a caller sends.
136
+ */
137
+ reclaim?: {
138
+ handle: string;
139
+ alias?: string;
140
+ };
141
+ model?: Model<any>;
142
+ maxTurns?: number;
143
+ isolated?: boolean;
144
+ inheritContext?: boolean;
145
+ thinkingLevel?: ThinkingLevel;
146
+ isBackground?: boolean;
147
+ /**
148
+ * Skip whichever pool's queue check applies to this spawn — start immediately
149
+ * even if the configured concurrency limit would otherwise queue it. The slot
150
+ * is still COUNTED once the run starts, so a bypassing spawn transiently
151
+ * exceeds the limit rather than being invisible to it.
152
+ *
153
+ * Used by the scheduler, so a fired job can't be deferred past its trigger
154
+ * window, and by the `/agents` agent-file generator, which has no way to
155
+ * cancel a wait (see its call site).
156
+ */
157
+ bypassQueue?: boolean;
158
+ /**
159
+ * A caller is awaiting this record inline (`spawnAndWait`) — what
160
+ * `maxConcurrentForeground` bounds. Set only by `spawnAndWait`; stripped from
161
+ * caller-supplied options by `spawnTopLevel`, since a forged `blocking` would
162
+ * defer a detached start behind a queue its caller cannot see or release.
163
+ */
164
+ blocking?: boolean;
165
+ /**
166
+ * The workflow run this child belongs to, when a workflow spawned it.
167
+ *
168
+ * Ownership, not decoration. A workflow's children are the workflow's — they
169
+ * report through its card, its notification and its dialog, so they are
170
+ * filtered out of every top-level surface exactly as nested children are, and
171
+ * they take no `maxConcurrent` slot: the run has its own concurrency cap, and
172
+ * counting them twice would let one workflow starve the whole session.
173
+ */
174
+ workflowId?: string;
175
+ /**
176
+ * Make the child report through a `StructuredOutput` tool built from this
177
+ * compiled schema. Set only by the workflow host, for `agent({ schema })`.
178
+ */
179
+ structuredOutput?: CompiledSchema;
180
+ /** Isolation mode — "worktree" creates a temp git worktree for the agent. */
181
+ isolation?: IsolationMode;
182
+ /**
183
+ * Working directory for the agent (absolute path). Default: parent session
184
+ * cwd. The agent's tools operate here, but .pi config (extensions, skills,
185
+ * settings, memory) still loads from the parent session's project — the
186
+ * target directory's `.pi` extensions never execute. With isolation:
187
+ * "worktree", the worktree is created FROM this directory and the result
188
+ * branch lands in that repo.
189
+ */
190
+ cwd?: string;
191
+ /**
192
+ * Last chance to look at an isolated agent's worktree, awaited immediately
193
+ * before it is committed to a branch and removed.
194
+ *
195
+ * Exists because that removal happens inside the settle path, before
196
+ * `spawnAndWait` resolves: by the time a caller has the finished record, the
197
+ * directory the child actually wrote in is gone. Anything that must inspect
198
+ * or verify that tree — a workflow `gate` is the motivating case — has to run
199
+ * here or it silently inspects the main tree instead.
200
+ *
201
+ * Fires only on the normal settle path, and only when a worktree was created.
202
+ * Not on the error path and not on the stop-during-copy guard: those are
203
+ * already failing, and delaying cleanup there would leak a copy for no gain.
204
+ * A rejection is swallowed — the hook can never keep the worktree alive.
205
+ */
206
+ onBeforeWorktreeCleanup?: (worktreePath: string, terminalStatus: AgentRecord["status"]) => Promise<void>;
207
+ /** Resolved invocation snapshot captured for UI display. */
208
+ invocation?: AgentInvocation;
209
+ /** Parent abort signal — when aborted, the subagent is also stopped. */
210
+ signal?: AbortSignal;
211
+ /**
212
+ * Called synchronously once the record is in the map and its promise is set,
213
+ * before `onSessionCreated` fires — where callers attach the output file.
214
+ *
215
+ * Carried on the options rather than parked on the manager for the duration
216
+ * of a spawn: with a foreground queue, `startAgent` can run at drain time,
217
+ * long after any such field would have been restored, and the callback would
218
+ * silently never fire (or fire into an unrelated caller's closure).
219
+ */
220
+ onSpawned?: (id: string) => void;
221
+ /**
222
+ * Called synchronously when the spawn is queued instead of started, with how
223
+ * many entries in its own pool are ahead of it. The foreground UI uses it to
224
+ * say so while it waits; nothing else needs it.
225
+ */
226
+ onQueued?: (id: string, ahead: number) => void;
227
+ /** Called on tool start/end with activity info (for streaming progress to UI). */
228
+ onToolActivity?: (activity: ToolActivity) => void;
229
+ /** Called on streaming text deltas from the assistant response. */
230
+ onTextDelta?: (delta: string, fullText: string) => void;
231
+ /** Called when the agent session is created (for accessing session stats). */
232
+ onSessionCreated?: (session: AgentSession) => void;
233
+ /** Called at the end of each agentic turn with the cumulative count. */
234
+ onTurnEnd?: (turnCount: number) => void;
235
+ /** Called once per assistant message_end with that message's usage delta. */
236
+ onAssistantUsage?: (usage: {
237
+ input: number;
238
+ output: number;
239
+ cacheWrite: number;
240
+ }) => void;
241
+ /** Called when the session successfully compacts. */
242
+ onCompaction?: (info: CompactionInfo) => void;
243
+ /** Nesting depth: top-level subagent = 1. */
244
+ depth?: number;
245
+ /** Parent agent ID for ownership-scoped nested controls. */
246
+ parentAgentId?: string;
247
+ /** Effective inherited nesting cap for this branch. */
248
+ maxSubagentDepth?: number;
249
+ /** Config-discovery root inherited by nested launches when it differs from the working directory. */
250
+ configCwd?: string;
251
+ /** Root session id, inherited by nested launches so transcripts stay grouped. */
252
+ rootSessionId?: string;
253
+ /** Stable root project dir, inherited by owned children (never a worktree cwd). */
254
+ rootCwd?: string;
255
+ /** Root session file, inherited by owned children for durable provenance. */
256
+ rootSessionFile?: string;
257
+ /**
258
+ * Internal ownership lineage, derived by the manager from the live parent
259
+ * chain. Never accepted from an external caller (`spawnTopLevel` strips it).
260
+ */
261
+ ownerIds?: string[];
262
+ }
263
+ interface ResumeOptions {
264
+ /**
265
+ * Run the resumed turn detached in the background: return immediately with
266
+ * the record still "running" (or "queued" at the concurrency limit) and
267
+ * notify on completion via onComplete, exactly like a background spawn.
268
+ * Default (false/undefined) runs the resume inline and returns the settled
269
+ * record — the historical behavior.
270
+ */
271
+ isBackground?: boolean;
272
+ /** Called on tool start/end with activity info (for streaming progress to UI). */
273
+ onToolActivity?: (activity: ToolActivity) => void;
274
+ /** Called once per assistant message_end with that message's usage delta. */
275
+ onAssistantUsage?: (usage: {
276
+ input: number;
277
+ output: number;
278
+ cacheWrite: number;
279
+ }) => void;
280
+ /** Called when the session successfully compacts. */
281
+ onCompaction?: (info: CompactionInfo) => void;
282
+ /**
283
+ * Background resume only: called synchronously when the run actually starts —
284
+ * immediately, or later from drainQueue. Callers wire per-run side effects
285
+ * (output-file streaming) here rather than at the call site, so a resume that
286
+ * is stopped while still queued never leaves a subscription behind: `abort()`
287
+ * drops a queued record without reaching `settle()`, which is what would have
288
+ * torn that subscription down.
289
+ */
290
+ onStarted?: () => void;
291
+ /**
292
+ * Called synchronously exactly once by the WINNING resume, while the
293
+ * manager's exclusive per-record admission claim is still held: after the
294
+ * acquire guard and every identity revalidation, before the generation is
295
+ * stamped or any terminal/run bookkeeping begins. A losing concurrent caller,
296
+ * a refused guard, an evicted/disposed record or a superseded admission never
297
+ * reaches it.
298
+ *
299
+ * This is the ownership boundary for caller-visible per-run wiring (tool call
300
+ * id, join mode, output path/cleanup, anchors): mutation before this point can
301
+ * make a refused request masquerade as the accepted one. A throw is treated as
302
+ * a refusal — the claim is released and the record keeps its previous terminal
303
+ * state, so a later resume is not wedged.
304
+ */
305
+ onAdmitted?: (record: AgentRecord) => void;
306
+ }
307
+ export declare class AgentManager {
308
+ private agents;
309
+ private activeRuns;
310
+ private disposed;
311
+ private shutdown?;
312
+ private pruned;
313
+ private cleanupInterval;
314
+ private onComplete?;
315
+ private onStart?;
316
+ private onCompact?;
317
+ private onUsage?;
318
+ private reportArchiver?;
319
+ private archivedReportReader?;
320
+ /** Highest run generation already handed to the archiver, per agent id. */
321
+ private archivedGenerations;
322
+ /**
323
+ * Full run finalizers still in flight, per record. A finalizer is the spawn or
324
+ * resume promise INCLUDING its output flush and worktree cleanup. One record
325
+ * can hold several: a newer resume may settle while an older generation's
326
+ * flush is still pending, so replacing `record.promise` must not lose the
327
+ * older work. Entries are removed on either resolution branch.
328
+ */
329
+ private pendingFinalizers;
330
+ /**
331
+ * Proof that a prepareCleanup pass found a live record settled and quiescent.
332
+ * forgetCleanup only forgets records with a matching generation here, so new
333
+ * work or a stale pass can never remove a report. Bounded by live records:
334
+ * cleared with the record, on a new run, on disposal and on forget.
335
+ */
336
+ private cleanupQuiescence;
337
+ /** Acquire-side artifact barrier; see setArtifactAccessGuard. */
338
+ private artifactAccessGuard?;
339
+ /**
340
+ * Every session-instance teardown that is pending or never proved quiescence,
341
+ * plus unfinished run finalizers. Rows are lightweight plain data; unresolved
342
+ * rows are NEVER capped or dropped (their paths stay protected).
343
+ */
344
+ private teardowns;
345
+ /** One teardown identity per SDK session instance (not per session file). */
346
+ private teardownIds;
347
+ /** Sessions allocated before `onSessionCreated`, keyed by agent id. */
348
+ private allocations;
349
+ /** Readiness of each pre-ready allocation (bind/session_start settlement). */
350
+ private allocationStates;
351
+ private teardownSequence;
352
+ private maxConcurrent;
353
+ private maxConcurrentForeground;
354
+ /** Base repos worktrees were created from — so dispose() can prune them all,
355
+ * not just the parent repo (caller-supplied cwd can target other repos). */
356
+ private worktreeRepos;
357
+ /**
358
+ * Startup phases, keyed by agent id. `spawn()` still returns synchronously,
359
+ * but an agent using worktree isolation is not running yet when it does —
360
+ * copying the repo is an awaited git call. This is what `awaitStartup` hands
361
+ * callers that must fail their tool call on a startup failure, and what
362
+ * `waitForAll` waits on while a record is "running" with no `promise` yet.
363
+ * Entries are dropped once the run is underway, and kept (rejected) after a
364
+ * startup failure so a late `awaitStartup` still sees it.
365
+ */
366
+ private startups;
367
+ /**
368
+ * Evicted agents that can still be reached by name, keyed by handle. Outlives
369
+ * the 10-minute record cleanup — that timer exists to bound memory, not to
370
+ * expire a conversation the user might still want — and is cleared alongside
371
+ * completed records on session start/switch.
372
+ */
373
+ private tombstones;
374
+ /**
375
+ * Agents waiting to start, tagged with the pool they wait on. One queue for
376
+ * both pools: `drainQueue` picks the earliest entry whose own pool has room,
377
+ * so neither can head-of-line-block the other, and every removal path
378
+ * (`abort`, `abortAll`, `dispose`) stays a single filter.
379
+ *
380
+ * `release` wakes a caller blocked in `spawnAndWait`, and is fired once the
381
+ * entry's `start` has SETTLED rather than at drain time: startup is async
382
+ * now, so releasing earlier would wake the caller before `record.promise`
383
+ * exists and it would read a still-starting agent as one that never ran.
384
+ * Removing an entry from this array MUST release it — a queued record has no
385
+ * promise to await, and pi has no tool-execution timeout to bail the caller
386
+ * out.
387
+ */
388
+ private queue;
389
+ /** Number of currently running background agents. */
390
+ private runningBackground;
391
+ /** Number of currently running foreground (blocking) agents. */
392
+ private runningForeground;
393
+ /**
394
+ * Capacity claimed by a start that has not reached its run yet (it is still
395
+ * awaiting an async acquire guard, a worktree copy or a cwd re-check).
396
+ * `poolHasRoom` counts these, so a synchronous queue drain can never start
397
+ * more runs than the limit while earlier starts are suspended.
398
+ */
399
+ private pendingBackground;
400
+ private pendingForeground;
401
+ /**
402
+ * Pending capacity claims, keyed by the record that owns them. A cancellation
403
+ * releases the claim still pending here at once; a TRANSFERRED claim is gone
404
+ * from this map and is a running charge the run's own finalizer releases, so
405
+ * abort can never free a slot that real work still occupies. A later claim
406
+ * for the same record replaces the entry: an older continuation that settles
407
+ * afterwards releases only its own already-idempotent claim.
408
+ */
409
+ private pendingClaims;
410
+ /**
411
+ * Resume admission, claimed synchronously before the acquire guard awaits.
412
+ * A settled record can be resumed by two callers in the same tick; only the
413
+ * first may mutate its generation and terminal fields. Cleared on refusal or
414
+ * once the record is queued/running (status then provides exclusivity).
415
+ */
416
+ private resumeAdmissions;
417
+ /** Individual queued aborts already delivered completion for this generation. */
418
+ private notifiedQueuedAborts;
419
+ /**
420
+ * The parent-signal abort listener currently owned by a record, with the
421
+ * generation that attached it. A start wires its signal BEFORE the acquire
422
+ * guard can suspend, so abort()/abortAll()/dispose() must be able to detach it
423
+ * immediately: a guard that never settles must not leave the manager reachable
424
+ * from a live parent signal. One wire per record — only the current generation
425
+ * is wired, and detach is identity-aware, so a stale continuation can never
426
+ * remove a newer generation's listener.
427
+ */
428
+ private signalWires;
429
+ constructor(onComplete?: OnAgentComplete, maxConcurrent?: number, onStart?: OnAgentStart, onCompact?: OnAgentCompact, onUsage?: OnAgentUsage);
430
+ /** Update the max concurrent background agents limit. */
431
+ setMaxConcurrent(n: number): void;
432
+ getMaxConcurrent(): number;
433
+ /** Wire durable report capture; see {@link AgentReportArchiver}. */
434
+ setReportArchiver(archiver: AgentReportArchiver | undefined): void;
435
+ /** Wire the async parent-scoped archived reader injected into nested tools. */
436
+ setArchivedReportReader(reader: ArchivedReportReader | undefined): void;
437
+ /**
438
+ * Wire the acquire-side artifact barrier. The callback runs at the ACTUAL
439
+ * boundaries where a run would first touch artifacts: the real start of
440
+ * `startAgent` (before the running slot is transferred), again immediately
441
+ * before `runAgent` (after an awaited worktree copy and/or assert), at resume
442
+ * acquisition before any run bookkeeping, and at a queued resume's actual
443
+ * start. The pool capacity itself is reserved synchronously in `launch` /
444
+ * the queued start BEFORE this callback can suspend, so awaiting a guard can
445
+ * never let a queue drain oversubscribe its pool.
446
+ *
447
+ * A throw (or a rejected promise) is an ordinary startup/refusal failure: no
448
+ * model starts, no pool slot or record generation is mutated, and a fresh
449
+ * worktree copy is released. The callback owns any ownership/lock check; the
450
+ * manager never inspects the filesystem or an SDK session here.
451
+ *
452
+ * A callback that returns a promise is awaited before worktree creation, and
453
+ * again immediately before `runAgent`. A callback that returns `void` keeps
454
+ * the historical synchronous start path unchanged (no extra suspension, so a
455
+ * spawn that has room starts in the same tick).
456
+ */
457
+ setArtifactAccessGuard(guard: ArtifactAccessGuard | undefined): void;
458
+ /** Invoke the configured acquire-side barrier; original behavior when unset. */
459
+ private assertArtifactAccess;
460
+ /** Teardowns that did not prove quiescence, newest first. Cleanup keeps them leased. */
461
+ listUncertainTeardowns(): UncertainTeardown[];
462
+ hasUncertainTeardowns(): boolean;
463
+ /**
464
+ * Every agent whose work is not quiescent. Includes running/queued records,
465
+ * startup work (an awaited worktree copy), in-flight run finalizers (output
466
+ * flush and worktree cleanup) and older-generation finalizers that outlived a
467
+ * newer settled run. Cleanup callers combine this with
468
+ * {@link listUncertainTeardowns} for evicted-record protection; nothing here
469
+ * aborts, evicts or notifies anything.
470
+ */
471
+ getBusyAgentIds(): string[];
472
+ /**
473
+ * Decide which requested reports and session files may be deleted, and close
474
+ * the settled SDK sessions that make them quiescent.
475
+ *
476
+ * Synchronous-before-await guarantees: the readiness recheck, the session
477
+ * detach and the bounded teardown registration all happen before the first
478
+ * `await`. A resume therefore sees `record.session === undefined` for every
479
+ * session this pass is closing, and work that starts during the await is
480
+ * refused by the second readiness check rather than reported ready.
481
+ *
482
+ * Never aborts/stops running work, never evicts records, never disposes or
483
+ * clears the manager, and never consumes a result or fires a notification.
484
+ * A settled record stays in the manager; {@link forgetCleanup} removes it only
485
+ * after the backend actually deleted its files.
486
+ */
487
+ prepareCleanup(agentIds: readonly string[], sessionFiles: readonly string[]): Promise<AgentCleanupPreparation>;
488
+ /**
489
+ * Drop manager-side traces of cleanup items the backend ACTUALLY deleted.
490
+ *
491
+ * A live record is forgotten only when a prepareCleanup pass proved it
492
+ * quiescent, it is still on that same run generation, its session was
493
+ * detached by that pass, and nothing is busy or uncertain now. Nothing is
494
+ * tombstoned and no teardown is started: the report was deliberately deleted
495
+ * and must not resurrect through a mention or a late archive.
496
+ *
497
+ * Tombstones are dropped by the actual deleted agent id or the actual deleted
498
+ * session file, and a surviving record's session pointer is cleared only for
499
+ * a path that was actually deleted. Unrelated records, tombstones and failed
500
+ * deletions are never touched.
501
+ */
502
+ forgetCleanup(deletedAgentIds: readonly string[], deletedSessionFiles: readonly string[]): void;
503
+ /** Why a live record is not quiescent, or undefined when it is settled and idle. */
504
+ private busyReason;
505
+ /** Explicit reason an unresolved teardown row blocks deletion. */
506
+ private uncertaintyReason;
507
+ private cleanupGuardSnapshot;
508
+ private cleanupAgentRefusal;
509
+ private cleanupPathRefusal;
510
+ /**
511
+ * Refuse readiness for an attachment that appeared while the pass awaited.
512
+ *
513
+ * The pre-check deliberately allows settled attached sessions so this pass can
514
+ * detach and tear them down. That proof covers only the attachments in the
515
+ * initial snapshot: a record that attaches the same report/history during the
516
+ * await was never detached by this pass and stays resumable. Refuse it; the
517
+ * newly attached handle is not closed.
518
+ */
519
+ private attachedDuringCleanupRefusal;
520
+ /**
521
+ * Detach a record's session synchronously and attach it to the pass's unique
522
+ * teardown job. The detach MUST precede the first await and the SDK teardown:
523
+ * a resume during shutdown then has no session to reopen.
524
+ */
525
+ private attachCleanupTeardown;
526
+ private teardownRefusal;
527
+ private teardownRefusalForAgent;
528
+ private teardownRefusalForSessionFile;
529
+ /** Update the max concurrent foreground (blocking) agents limit. 0 = unlimited. */
530
+ setMaxConcurrentForeground(n: number): void;
531
+ getMaxConcurrentForeground(): number;
532
+ /**
533
+ * Which pool a spawn is charged to, or undefined for one that is charged to
534
+ * neither (nested children, detached non-background spawns).
535
+ *
536
+ * Nothing here queues when the limit is unset — `poolHasRoom` reports an
537
+ * unlimited pool as always having room, so that alone is what keeps the
538
+ * default path identical. The `> 0` guard is belt and braces on top: it also
539
+ * keeps the counter from churning and the settle path from calling a drain
540
+ * that would find nothing to do. Both are unobservable, which is why no test
541
+ * pins them; the observable half — that the default start stays synchronous —
542
+ * is pinned in `test/foreground-concurrency.test.ts`.
543
+ */
544
+ private poolFor;
545
+ private poolHasRoom;
546
+ /**
547
+ * Claim one slot for a start that is about to await work, synchronously.
548
+ * `transfer()` moves the claim to the running counter before the run is
549
+ * launched; `releasePending()` gives it back when acquisition is refused or
550
+ * the record was superseded. Repeated calls are no-ops, so a refusal that
551
+ * unwinds through `launch` cannot decrement twice.
552
+ *
553
+ * The claim is associated with `record` while pending so `abort()`/`abortAll()`
554
+ * can release it without waiting for the suspended continuation.
555
+ */
556
+ private reservePoolSlot;
557
+ /**
558
+ * Free a record's still-PENDING capacity claim, immediately and exactly once.
559
+ * A transferred claim is absent from the map, so a real run's charge is never
560
+ * touched here — that is released only by its finalizer.
561
+ *
562
+ * `drain` is false while a bulk cancellation is still marking entries: freeing
563
+ * one entry's capacity must not start another entry that has not been canceled
564
+ * yet. Individual cancellation drains as soon as the record is stopped.
565
+ */
566
+ private releasePendingClaim;
567
+ /**
568
+ * The pending claim a record holds RIGHT NOW, captured before anything the
569
+ * caller is about to do can re-enter the manager. abort() hands this exact
570
+ * reservation back afterwards: its completion callback is free to resume the
571
+ * same record, and that newer generation installs its OWN claim in the map.
572
+ * Freeing by lookup at the tail would free that one instead — a running charge
573
+ * the new generation still owns, whose transfer then no-ops and whose
574
+ * finalizer underflows the pool counter (oversubscription).
575
+ */
576
+ private capturePendingClaim;
577
+ /**
578
+ * Release the exact claim {@link capturePendingClaim} captured. The map entry
579
+ * is forgotten only if it still names that object, and a claim that already
580
+ * transferred or was already released is an idempotent no-op, so a transferred
581
+ * running charge is never freed here.
582
+ */
583
+ private releaseCapturedClaim;
584
+ /**
585
+ * Attach the parent-signal abort listener owned by `generation` and register
586
+ * it where abort()/abortAll()/dispose() can detach it immediately. Only one
587
+ * wire exists per record: an older generation's listener (a queued start's, or
588
+ * the previous run's) is detached first, so a late abort of THAT signal can
589
+ * never stop this run. A detached start (`undefined`) stays detached, and an
590
+ * already-aborted signal is left to its caller's explicit `abort()` call.
591
+ */
592
+ private attachSignalWire;
593
+ /**
594
+ * Detach one CAPTURED wire. The registry entry is forgotten only if it still
595
+ * names that wire, and `detach` is idempotent, so a stale continuation — or an
596
+ * old abort resuming after its callbacks — cannot remove a newer generation's
597
+ * listener.
598
+ */
599
+ private detachSignalWire;
600
+ /** Detach whatever parent-signal listener the record's current generation owns. */
601
+ private releaseSignalWire;
602
+ /**
603
+ * Spawn an agent and return its ID immediately (for background use).
604
+ * If the concurrency limit is reached, the agent is queued.
605
+ *
606
+ * The id comes back synchronously, but with `isolation: "worktree"` the agent
607
+ * is not running yet when it does — the repo copy is an awaited git call.
608
+ * Callers that must fail a tool call on a startup failure await
609
+ * `awaitStartup(id)`; everyone else sees it on the record (status "error").
610
+ */
611
+ spawn(pi: ExtensionAPI, ctx: ExtensionContext, type: SubagentType, prompt: string, options: SpawnOptions): string;
612
+ /**
613
+ * Wire a parent abort signal for a record that is about to be QUEUED.
614
+ * `startAgent` does this for running agents, and a queued record never gets
615
+ * there, so without this Esc could not release a queue position.
616
+ *
617
+ * Returns false when the signal is ALREADY aborted, in which case the record
618
+ * is stopped here and must not be enqueued: `addEventListener` never fires on
619
+ * an aborted signal, so a `spawnAndWait` on it would wait forever — pi has no
620
+ * tool-execution timeout to bail it out.
621
+ *
622
+ * The wire is generation-owned and registered for immediate detach: the start
623
+ * that leaves the queue REPLACES it with its own run wire, and
624
+ * abort()/abortAll()/dispose() detach it at once — so this listener never
625
+ * outlives the generation that armed it, and a late abort of the queue signal
626
+ * cannot stop a later resumed generation.
627
+ */
628
+ private armQueuedAbort;
629
+ /**
630
+ * Kick off an agent's startup and register it under `startups`. The returned
631
+ * promise never rejects — the failure is delivered through `awaitStartup`,
632
+ * and to the record. Background startup failures use ordinary completion;
633
+ * callers delivering the failure inline consume it themselves.
634
+ *
635
+ * @param queuedPool - The pool this start was QUEUED on, or undefined for an
636
+ * immediate start. A queue drain can be minutes after `spawn()` returned,
637
+ * and nobody is awaiting `awaitStartup` by then, so a failure has to live
638
+ * on the record as status "error" — what drainQueue did when the throw was
639
+ * still synchronous. Immediate foreground failures drop the unreturned
640
+ * record; detached callers keep a retrievable failure and ordinary wakeup.
641
+ */
642
+ private launch;
643
+ /**
644
+ * Resolves once the agent is actually running, and rejects with the startup
645
+ * failure (strict worktree isolation) that `spawn()` used to throw before the
646
+ * repo copy became async. Resolves immediately for an agent that is already
647
+ * running, still queued, or unknown — so callers can await it unconditionally.
648
+ *
649
+ * Call it in the same tick as the `spawn()` it belongs to: a settled startup
650
+ * removes this promise entry. Detached failures remain on their records.
651
+ */
652
+ awaitStartup(id: string): Promise<void>;
653
+ /**
654
+ * Whether a start that suspended on an acquire guard still owns the record.
655
+ * A stop, dispose, eviction or newer run during the await must not create a
656
+ * worktree, child session or model call afterwards.
657
+ */
658
+ private startIsCurrent;
659
+ /** Same check once the start has claimed "running" and begun worktree work. */
660
+ private runIsCurrent;
661
+ /** Actually start an agent (called immediately or from queue drain). */
662
+ private startAgent;
663
+ /**
664
+ * The shared tail of both settle paths: release whatever pool slot the run
665
+ * held, notify, and let the queue drain into the freed slot.
666
+ *
667
+ * The decrement lives HERE and nowhere else. `abort()` on a running record
668
+ * only fires its controller and leaves the run to settle normally, so
669
+ * decrementing there too would double-free — permanently lifting the limit.
670
+ *
671
+ * Foreground agents fire `onComplete` for lifecycle symmetry, with
672
+ * `resultConsumed` set so the callback skips notifications the inline result
673
+ * already delivered.
674
+ *
675
+ * @param guardCallback swallow a throwing `onComplete` (the success path does;
676
+ * the error path historically did not, and keeps not doing so).
677
+ * @param pool the pool this run was CHARGED TO at start time — passed in, not
678
+ * recomputed, so a mid-run change to `maxConcurrentForeground` can't make
679
+ * the release disagree with the acquire.
680
+ */
681
+ private settleRun;
682
+ /**
683
+ * Hand one settled generation to the durable-report archiver exactly once.
684
+ *
685
+ * Every terminal path calls this — fresh runs, foreground/background resumes,
686
+ * queued cancellations, startup failures and the dispose sweep. Generation
687
+ * dedupe matters because a run can be stopped while queued and then swept by
688
+ * `dispose`: the first snapshot is the truthful one. A deadline FALLBACK may
689
+ * still be replaced by the real same-generation finalizer (never the reverse),
690
+ * so a run that settles just after the bounded window is not lost forever.
691
+ */
692
+ private archiveTerminal;
693
+ /**
694
+ * Track a full run finalizer (output flush and worktree cleanup included) as
695
+ * pending work for this record. Removed on either resolution branch; a record
696
+ * can hold more than one because a newer generation settles first and
697
+ * overwrites `record.promise` while the older flush is still in flight.
698
+ */
699
+ private trackPendingFinalizer;
700
+ private identityFromRecord;
701
+ /**
702
+ * One protection identity per SDK session INSTANCE. The same session file can
703
+ * be reopened as a different instance (A timed out, B later succeeds): B's
704
+ * completion must not delete A's still-unresolved protection row.
705
+ */
706
+ private ensureSessionTeardown;
707
+ private applyTeardownOutcome;
708
+ /**
709
+ * Register protection synchronously, then start the bounded shutdown. The row
710
+ * exists BEFORE the first await: an immediate dispose after eviction sees the
711
+ * pending promise and cannot report `completed` for an unresolved handler.
712
+ */
713
+ private startSessionTeardown;
714
+ private trackSessionShutdown;
715
+ /** Record the allocated instance before binding; no ready announcement yet. */
716
+ private noteSessionAllocated;
717
+ /** Bind/session_start settled (successfully, or its failure teardown ran). */
718
+ private settleAllocation;
719
+ /** The session is now a live, addressable record; teardown is not in flight. */
720
+ private markSessionReady;
721
+ /** Bind-failure (or equivalent partial startup) outcome handed back by runner. */
722
+ private noteSessionTeardown;
723
+ private releaseAllocation;
724
+ /** Protection row for a run/finalizer that outlived the shutdown deadline. */
725
+ private recordRunUncertainty;
726
+ /**
727
+ * Release protection for exactly the run generation whose COMPLETE disposal
728
+ * aggregate (including every generation's output flush) settled. Called only
729
+ * by dispose/reconcileLateFinalizer, never by an individual run finalizer: a
730
+ * newer generation must not release an older generation's pending flush.
731
+ */
732
+ private clearRunUncertainty;
733
+ /**
734
+ * A captured startup/run finalizer that outlived dispose's sweep still owes a
735
+ * real report and the release of its provisional run protection. This runs
736
+ * independently of map membership and never calls settleRun/callbacks or
737
+ * releases a pool slot again.
738
+ */
739
+ private reconcileLateFinalizer;
740
+ /**
741
+ * Stop the nested children a settled parent owns. Nested records are hidden
742
+ * from the UI and only their owner can consume them, so a child outliving its
743
+ * parent would burn tokens unseen with no way to reach it. Grandchildren are
744
+ * covered transitively — each abort lands in that child's own settle path.
745
+ */
746
+ private abortOwnedChildren;
747
+ /**
748
+ * Start queued agents up to each pool's concurrency limit.
749
+ *
750
+ * `findIndex` on the entry's OWN pool rather than `shift`: with one queue
751
+ * serving two independent limits, a saturated foreground pool at the head
752
+ * would otherwise stall every background agent behind it. Taking the earliest
753
+ * eligible entry keeps FIFO within each pool, which is what callers see.
754
+ */
755
+ private drainQueue;
756
+ /**
757
+ * Remove queued entries and wake anyone blocked on them. The single point
758
+ * that enforces "leaving the queue releases the waiter" — a missed release is
759
+ * an unbounded hang, not a failed call.
760
+ */
761
+ private dequeue;
762
+ /**
763
+ * Spawn an agent and wait for completion (foreground use).
764
+ * Charged to the foreground pool (`maxConcurrentForeground`), which is
765
+ * unlimited by default; never to the background one.
766
+ * Returns { id, record } so callers can access the agent ID.
767
+ *
768
+ * @param onSpawned - Called synchronously once the run is kicked off, before
769
+ * onSessionCreated fires. Use this to set record.outputFile so
770
+ * streamToOutputFile can pick it up.
771
+ */
772
+ spawnAndWait(pi: ExtensionAPI, ctx: ExtensionContext, type: SubagentType, prompt: string, options: Omit<SpawnOptions, "isBackground">, onSpawned?: (id: string) => void): Promise<{
773
+ id: string;
774
+ record: AgentRecord;
775
+ }>;
776
+ /**
777
+ * Resume an existing agent session with a new prompt.
778
+ */
779
+ resume(id: string, prompt: string, signal?: AbortSignal, options?: ResumeOptions): Promise<AgentRecord | undefined>;
780
+ /**
781
+ * A resume that suspended on its acquire guard still owns the record only if
782
+ * nothing terminal happened while it waited. Kept separate from the queued
783
+ * variant: a queued resume legitimately sits in "queued" while admitting.
784
+ */
785
+ private resumeAdmissionIsCurrent;
786
+ /** Same revalidation for a resume whose queued start just awaited its guard. */
787
+ private queuedResumeIsCurrent;
788
+ /** The queued-start refusal path: this generation is terminal, no run began. */
789
+ private failQueuedResume;
790
+ /**
791
+ * Start a background resume run: detached, settling and notifying like
792
+ * startAgent's background path. Invoked immediately, or from drainQueue when
793
+ * a concurrency slot frees. The session already exists (resume reuses it), so
794
+ * there is no onSessionCreated to hang per-run wiring off — callers use
795
+ * `options.onStarted`, which fires on both the immediate and the drained path.
796
+ */
797
+ private startResume;
798
+ /**
799
+ * Send a steering message to an agent from the UI (mirrors the steer_subagent
800
+ * tool). A live session delivers it now — it interrupts the agent after its
801
+ * current tool execution and appears as a user message. If the session isn't
802
+ * ready yet, the message is queued on `pendingSteers` and flushed when the
803
+ * session is created. Returns false if the agent can't accept steering
804
+ * (unknown id, or no longer running/queued).
805
+ */
806
+ steer(id: string, message: string): boolean;
807
+ /** Interactive send path: report an SDK rejection instead of pretending it queued. */
808
+ steerAcknowledged(id: string, message: string): Promise<boolean>;
809
+ getRecord(id: string): AgentRecord | undefined;
810
+ /** Handles already in use, so a fresh spawn can pick an unclaimed one. */
811
+ private takenHandles;
812
+ /**
813
+ * Resolve an `@name` from the prompt. Matches a top-level agent's handle
814
+ * case-insensitively, preferring active work, then the newest usable session.
815
+ * A failed startup cannot shadow a saved conversation. Exact ids still name
816
+ * their own record, including a retained startup failure.
817
+ */
818
+ resolveMention(name: string): MentionResolution | undefined;
819
+ /**
820
+ * Forget an evicted agent, by handle. For the case where its session file has
821
+ * gone: the entry can then only ever fail, while still holding the name
822
+ * against the type that would otherwise start a fresh agent under it.
823
+ *
824
+ * A *successful* resume does not drop its tombstone — the live record it
825
+ * creates already wins in `resolveMention`, and overwrites the entry in place
826
+ * when it is itself evicted.
827
+ */
828
+ dropTombstone(handle: string): void;
829
+ /** Evicted agents whose conversation can still be reopened, newest first. */
830
+ listTombstones(): AgentTombstone[];
831
+ /** Actual pool queue membership, excluding a start suspended on its guard. */
832
+ isQueued(id: string): boolean;
833
+ listAgents(): AgentRecord[];
834
+ abort(id: string): boolean;
835
+ /** Dispose a record's session and remove it from the map. */
836
+ private removeRecord;
837
+ /**
838
+ * Preserve enough of a departing record for `@handle` to reopen its
839
+ * conversation later. Nothing to keep unless it has both a handle to be
840
+ * addressed by and a session file to reopen — an in-memory session leaves no
841
+ * transcript, so the mention would have nothing to continue from.
842
+ */
843
+ private tombstone;
844
+ private cleanup;
845
+ /**
846
+ * Remove all completed/stopped/errored records immediately.
847
+ * Called on session start/switch so tasks from a prior session don't persist.
848
+ * Pass skipUnconsumed=true to preserve records the LLM hasn't read yet
849
+ * (resultConsumed=false) — they will be evicted by the 10-minute cleanup timer instead.
850
+ */
851
+ clearCompleted(skipUnconsumed?: boolean): void;
852
+ /** Whether any agents are still running or queued. */
853
+ hasRunning(): boolean;
854
+ /** Abort all running and queued agents immediately. */
855
+ abortAll(): number;
856
+ /** Wait for all running and queued agents to complete (including queued ones). */
857
+ waitForAll(): Promise<void>;
858
+ /**
859
+ * @param pi - Needed to run `git worktree prune`, which is async now and so
860
+ * cannot be reached through a stored spawn argument at shutdown. Omitting
861
+ * it (tests, teardown of a manager that never spawned) skips the prune.
862
+ */
863
+ dispose(pi?: ExtensionAPI): Promise<AgentManagerShutdown>;
864
+ }
865
+ /**
866
+ * Whether a child session will still consume a steering message. A session
867
+ * that has stopped streaming, with no managed prompt (or fallback recovery)
868
+ * still in flight, would only park the message in its queue — reported as
869
+ * "sent" but never read. Stubs without `isStreaming` are treated as live.
870
+ */
871
+ export declare function sessionAcceptsSteer(session: AgentSession): boolean;
872
+ export {};