ultimate-pi 0.11.0 → 0.13.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 (137) hide show
  1. package/.agents/skills/ck-search/SKILL.md +11 -87
  2. package/.agents/skills/cocoindex-search/SKILL.md +35 -0
  3. package/.agents/skills/harness-debate-plan/SKILL.md +44 -0
  4. package/.agents/skills/harness-decisions/SKILL.md +1 -1
  5. package/.agents/skills/harness-orchestration/SKILL.md +54 -28
  6. package/.agents/skills/harness-plan/SKILL.md +15 -20
  7. package/.pi/PACKAGING.md +1 -0
  8. package/.pi/SYSTEM.md +21 -20
  9. package/.pi/agents/harness/adversary.md +0 -1
  10. package/.pi/agents/harness/evaluator.md +0 -1
  11. package/.pi/agents/harness/executor.md +1 -2
  12. package/.pi/agents/harness/incident-recorder.md +0 -1
  13. package/.pi/agents/harness/meta-optimizer.md +0 -1
  14. package/.pi/agents/harness/planning/decompose.md +3 -4
  15. package/.pi/agents/harness/planning/execution-plan-author.md +30 -0
  16. package/.pi/agents/harness/planning/hypothesis-validator.md +23 -0
  17. package/.pi/agents/harness/planning/hypothesis.md +3 -4
  18. package/.pi/agents/harness/planning/plan-adversary.md +10 -42
  19. package/.pi/agents/harness/planning/plan-evaluator.md +18 -0
  20. package/.pi/agents/harness/planning/review-integrator.md +23 -0
  21. package/.pi/agents/harness/planning/scout-graphify.md +13 -5
  22. package/.pi/agents/harness/planning/scout-semantic.md +23 -11
  23. package/.pi/agents/harness/planning/scout-structure.md +12 -6
  24. package/.pi/agents/harness/planning/sprint-contract-auditor.md +18 -0
  25. package/.pi/agents/harness/planning/stack-researcher.md +24 -0
  26. package/.pi/agents/harness/tie-breaker.md +0 -1
  27. package/.pi/agents/harness/trace-librarian.md +0 -1
  28. package/.pi/extensions/debate-orchestrator.ts +90 -53
  29. package/.pi/extensions/harness-plan-approval.ts +2 -2
  30. package/.pi/extensions/harness-run-context.ts +150 -5
  31. package/.pi/extensions/harness-subagents.ts +17 -6
  32. package/.pi/extensions/lib/harness-cocoindex-refresh.ts +49 -0
  33. package/.pi/extensions/lib/harness-posthog.ts +6 -1
  34. package/.pi/extensions/lib/harness-spawn-budget.ts +75 -0
  35. package/.pi/extensions/lib/harness-subagent-auth.ts +123 -0
  36. package/.pi/extensions/lib/{harness-subagents/harness-subagent-policy.ts → harness-subagent-policy.ts} +8 -7
  37. package/.pi/extensions/lib/harness-subagent-precheck.ts +95 -0
  38. package/.pi/extensions/lib/harness-subagents-bridge.ts +122 -0
  39. package/.pi/extensions/lib/plan-approval/create-plan.ts +4 -7
  40. package/.pi/extensions/lib/plan-approval/plan-review.ts +1 -1
  41. package/.pi/extensions/lib/plan-approval/types.ts +7 -1
  42. package/.pi/extensions/lib/plan-debate-envelope.ts +84 -0
  43. package/.pi/extensions/lib/{harness-subagents/spawn-policy.ts → spawn-policy.ts} +1 -0
  44. package/.pi/extensions/policy-gate.ts +1 -1
  45. package/.pi/extensions/review-integrity.ts +48 -29
  46. package/.pi/harness/agents.manifest.json +37 -25
  47. package/.pi/harness/docs/adrs/0032-harness-command-orchestration.md +4 -3
  48. package/.pi/harness/docs/adrs/0033-parent-orchestrated-planning.md +2 -2
  49. package/.pi/harness/docs/adrs/0035-plan-phase-review-gate.md +27 -0
  50. package/.pi/harness/evals/smoke/fixtures/plan-phase/minimal-med/artifacts/review-round-r1.yaml +25 -0
  51. package/.pi/harness/evals/smoke/fixtures/plan-phase/minimal-med/artifacts/review-round-r4.yaml +26 -0
  52. package/.pi/harness/evals/smoke/fixtures/plan-phase/minimal-med/artifacts/sprint-audit-r4.yaml +5 -0
  53. package/.pi/harness/evals/smoke/fixtures/plan-phase/minimal-med/plan-packet.yaml +196 -0
  54. package/.pi/harness/evals/smoke/fixtures/plan-phase/minimal-med/plan-review.md +14 -0
  55. package/.pi/harness/evals/smoke/fixtures/plan-phase/minimal-med/research-brief.yaml +32 -0
  56. package/.pi/harness/evals/smoke/run-context.fixture.json +1 -1
  57. package/.pi/harness/evals/smoke/smoke-harness-plan.mjs +88 -0
  58. package/.pi/harness/specs/harness-posthog-event.schema.json +6 -1
  59. package/.pi/harness/specs/plan-execution-plan-brief.schema.json +13 -0
  60. package/.pi/harness/specs/plan-execution-plan.schema.json +255 -0
  61. package/.pi/harness/specs/plan-packet.schema.json +14 -5
  62. package/.pi/harness/specs/plan-review-round-draft.schema.json +68 -0
  63. package/.pi/harness/specs/plan-sprint-audit-turn.schema.json +29 -0
  64. package/.pi/harness/specs/plan-stack-brief.schema.json +65 -0
  65. package/.pi/harness/specs/plan-validation-turn.schema.json +42 -0
  66. package/.pi/harness/specs/round-result.schema.json +16 -9
  67. package/.pi/lib/debate-orchestrator-types.ts +38 -0
  68. package/.pi/lib/harness-agent-discovery.mjs +81 -0
  69. package/.pi/lib/harness-run-context.ts +64 -38
  70. package/.pi/lib/harness-yaml.mjs +73 -0
  71. package/.pi/lib/harness-yaml.ts +90 -0
  72. package/.pi/prompts/harness-auto.md +13 -11
  73. package/.pi/prompts/harness-critic.md +2 -2
  74. package/.pi/prompts/harness-eval.md +3 -3
  75. package/.pi/prompts/harness-incident.md +2 -2
  76. package/.pi/prompts/harness-plan.md +83 -92
  77. package/.pi/prompts/harness-review.md +2 -2
  78. package/.pi/prompts/harness-router-tune.md +1 -1
  79. package/.pi/prompts/harness-run.md +2 -2
  80. package/.pi/prompts/harness-setup.md +30 -17
  81. package/.pi/prompts/harness-trace.md +2 -2
  82. package/.pi/scripts/README.md +1 -0
  83. package/.pi/scripts/harness-agents-manifest.mjs +1 -1
  84. package/.pi/scripts/harness-cli-verify.sh +24 -14
  85. package/.pi/scripts/harness-cocoindex-bootstrap.sh +182 -0
  86. package/.pi/scripts/harness-verify.mjs +38 -19
  87. package/.pi/scripts/validate-plan-dag.mjs +258 -0
  88. package/.pi/scripts/vendor-sync-pi-subagents.sh +19 -0
  89. package/.pi/skills/ast-grep/SKILL.md +2 -2
  90. package/.pi/skills/ccc/SKILL.md +142 -0
  91. package/.pi/skills/ccc/references/management.md +110 -0
  92. package/CHANGELOG.md +22 -0
  93. package/THIRD_PARTY_NOTICES.md +15 -0
  94. package/biome.json +2 -2
  95. package/package.json +7 -4
  96. package/vendor/pi-subagents/LICENSE +21 -0
  97. package/vendor/pi-subagents/UPSTREAM_PIN.md +11 -0
  98. package/vendor/pi-subagents/src/agents.ts +357 -0
  99. package/vendor/pi-subagents/src/subagents.ts +1463 -0
  100. package/.pi/agents/harness/planner.md +0 -13
  101. package/.pi/agents/harness/planning/hypothesis-eval.md +0 -59
  102. package/.pi/agents/harness/planning/planner.md +0 -20
  103. package/.pi/extensions/lib/harness-subagents/agent-loader.ts +0 -126
  104. package/.pi/extensions/lib/harness-subagents/agent-manifest.ts +0 -119
  105. package/.pi/extensions/lib/harness-subagents/agent-parser.ts +0 -87
  106. package/.pi/extensions/lib/harness-subagents/blackboard-tool.ts +0 -118
  107. package/.pi/extensions/lib/harness-subagents/blackboard.ts +0 -175
  108. package/.pi/extensions/lib/harness-subagents/parent-ask-user-bridge.ts +0 -10
  109. package/.pi/extensions/lib/harness-subagents/parent-harness-ui-bridge.ts +0 -137
  110. package/.pi/extensions/lib/harness-subagents/parent-harness-ui-hooks.ts +0 -77
  111. package/.pi/extensions/lib/harness-subagents/types-blackboard.ts +0 -27
  112. package/.pi/extensions/lib/harness-subagents/vendored/agent-manager.ts +0 -558
  113. package/.pi/extensions/lib/harness-subagents/vendored/agent-runner.ts +0 -666
  114. package/.pi/extensions/lib/harness-subagents/vendored/agent-types.ts +0 -175
  115. package/.pi/extensions/lib/harness-subagents/vendored/context.ts +0 -59
  116. package/.pi/extensions/lib/harness-subagents/vendored/cross-extension-rpc.ts +0 -134
  117. package/.pi/extensions/lib/harness-subagents/vendored/custom-agents.ts +0 -5
  118. package/.pi/extensions/lib/harness-subagents/vendored/default-agents.ts +0 -123
  119. package/.pi/extensions/lib/harness-subagents/vendored/env.ts +0 -43
  120. package/.pi/extensions/lib/harness-subagents/vendored/group-join.ts +0 -144
  121. package/.pi/extensions/lib/harness-subagents/vendored/index.ts +0 -2460
  122. package/.pi/extensions/lib/harness-subagents/vendored/invocation-config.ts +0 -52
  123. package/.pi/extensions/lib/harness-subagents/vendored/memory.ts +0 -182
  124. package/.pi/extensions/lib/harness-subagents/vendored/model-resolver.ts +0 -92
  125. package/.pi/extensions/lib/harness-subagents/vendored/output-file.ts +0 -115
  126. package/.pi/extensions/lib/harness-subagents/vendored/prompts.ts +0 -103
  127. package/.pi/extensions/lib/harness-subagents/vendored/schedule-store.ts +0 -177
  128. package/.pi/extensions/lib/harness-subagents/vendored/schedule.ts +0 -416
  129. package/.pi/extensions/lib/harness-subagents/vendored/settings.ts +0 -210
  130. package/.pi/extensions/lib/harness-subagents/vendored/skill-loader.ts +0 -108
  131. package/.pi/extensions/lib/harness-subagents/vendored/types.ts +0 -187
  132. package/.pi/extensions/lib/harness-subagents/vendored/ui/agent-widget.ts +0 -639
  133. package/.pi/extensions/lib/harness-subagents/vendored/ui/conversation-viewer.ts +0 -324
  134. package/.pi/extensions/lib/harness-subagents/vendored/ui/schedule-menu.ts +0 -110
  135. package/.pi/extensions/lib/harness-subagents/vendored/usage.ts +0 -71
  136. package/.pi/extensions/lib/harness-subagents/vendored/worktree.ts +0 -195
  137. /package/.pi/extensions/{00-ultimate-pi-system-prompt.ts → custom-system-prompt.ts} +0 -0
@@ -1,558 +0,0 @@
1
- /**
2
- * agent-manager.ts — Tracks agents, background execution, resume support.
3
- *
4
- * Background agents are subject to a configurable concurrency limit (default: 4).
5
- * Excess agents are queued and auto-started as running agents complete.
6
- * Foreground agents bypass the queue (they block the parent anyway).
7
- */
8
-
9
- import { randomUUID } from "node:crypto";
10
- import type { Model } from "@earendil-works/pi-ai";
11
- import type {
12
- AgentSession,
13
- ExtensionAPI,
14
- ExtensionContext,
15
- } from "@earendil-works/pi-coding-agent";
16
- import type { ParentHarnessUiHooks } from "../parent-harness-ui-bridge.js";
17
- import { resumeAgent, runAgent, type ToolActivity } from "./agent-runner.js";
18
- import type {
19
- AgentInvocation,
20
- AgentRecord,
21
- IsolationMode,
22
- SubagentType,
23
- ThinkingLevel,
24
- } from "./types.js";
25
- import { addUsage } from "./usage.js";
26
- import { cleanupWorktree, createWorktree, pruneWorktrees } from "./worktree.js";
27
-
28
- export type OnAgentComplete = (record: AgentRecord) => void;
29
- export type OnAgentStart = (record: AgentRecord) => void;
30
- export type OnAgentCompact = (
31
- record: AgentRecord,
32
- info: CompactionInfo,
33
- ) => void;
34
- export type CompactionInfo = {
35
- reason: "manual" | "threshold" | "overflow";
36
- tokensBefore: number;
37
- };
38
-
39
- /** Default max concurrent background agents. */
40
- const DEFAULT_MAX_CONCURRENT = 4;
41
-
42
- interface SpawnArgs {
43
- pi: ExtensionAPI;
44
- ctx: ExtensionContext;
45
- type: SubagentType;
46
- prompt: string;
47
- options: SpawnOptions;
48
- }
49
-
50
- interface SpawnOptions {
51
- description: string;
52
- model?: Model<any>;
53
- maxTurns?: number;
54
- isolated?: boolean;
55
- inheritContext?: boolean;
56
- thinkingLevel?: ThinkingLevel;
57
- isBackground?: boolean;
58
- /**
59
- * Skip the maxConcurrent queue check for this spawn — start immediately even
60
- * if the configured concurrency limit would otherwise queue it. Used by the
61
- * scheduler so a fired job can't be deferred past its trigger window.
62
- */
63
- bypassQueue?: boolean;
64
- /** Isolation mode — "worktree" creates a temp git worktree for the agent. */
65
- isolation?: IsolationMode;
66
- /** Resolved invocation snapshot captured for UI display. */
67
- invocation?: AgentInvocation;
68
- /** Parent abort signal — when aborted, the subagent is also stopped. */
69
- signal?: AbortSignal;
70
- /** Called on tool start/end with activity info (for streaming progress to UI). */
71
- onToolActivity?: (activity: ToolActivity) => void;
72
- /** Called on streaming text deltas from the assistant response. */
73
- onTextDelta?: (delta: string, fullText: string) => void;
74
- /** Called when the agent session is created (for accessing session stats). */
75
- onSessionCreated?: (session: AgentSession) => void;
76
- /** Called at the end of each agentic turn with the cumulative count. */
77
- onTurnEnd?: (turnCount: number) => void;
78
- /** Called once per assistant message_end with that message's usage delta. */
79
- onAssistantUsage?: (usage: {
80
- input: number;
81
- output: number;
82
- cacheWrite: number;
83
- }) => void;
84
- /** Called when the session successfully compacts. */
85
- onCompaction?: (info: CompactionInfo) => void;
86
- /** Spawn context (blackboard injection) for subagent system prompt. */
87
- systemPromptAppendix?: string;
88
- /** Parent UI hooks for plan approval sync and draft transcript. */
89
- parentHarnessUiHooks?: ParentHarnessUiHooks;
90
- }
91
-
92
- export class AgentManager {
93
- private agents = new Map<string, AgentRecord>();
94
- private cleanupInterval: ReturnType<typeof setInterval>;
95
- private onComplete?: OnAgentComplete;
96
- private onStart?: OnAgentStart;
97
- private onCompact?: OnAgentCompact;
98
- private maxConcurrent: number;
99
-
100
- /** Queue of background agents waiting to start. */
101
- private queue: { id: string; args: SpawnArgs }[] = [];
102
- /** Number of currently running background agents. */
103
- private runningBackground = 0;
104
-
105
- constructor(
106
- onComplete?: OnAgentComplete,
107
- maxConcurrent = DEFAULT_MAX_CONCURRENT,
108
- onStart?: OnAgentStart,
109
- onCompact?: OnAgentCompact,
110
- ) {
111
- this.onComplete = onComplete;
112
- this.onStart = onStart;
113
- this.onCompact = onCompact;
114
- this.maxConcurrent = maxConcurrent;
115
- // Cleanup completed agents after 10 minutes (but keep sessions for resume)
116
- this.cleanupInterval = setInterval(() => this.cleanup(), 60_000);
117
- this.cleanupInterval.unref();
118
- }
119
-
120
- /** Update the max concurrent background agents limit. */
121
- setMaxConcurrent(n: number) {
122
- this.maxConcurrent = Math.max(1, n);
123
- // Start queued agents if the new limit allows
124
- this.drainQueue();
125
- }
126
-
127
- getMaxConcurrent(): number {
128
- return this.maxConcurrent;
129
- }
130
-
131
- /**
132
- * Spawn an agent and return its ID immediately (for background use).
133
- * If the concurrency limit is reached, the agent is queued.
134
- */
135
- spawn(
136
- pi: ExtensionAPI,
137
- ctx: ExtensionContext,
138
- type: SubagentType,
139
- prompt: string,
140
- options: SpawnOptions,
141
- ): string {
142
- const id = randomUUID().slice(0, 17);
143
- const abortController = new AbortController();
144
- const record: AgentRecord = {
145
- id,
146
- type,
147
- description: options.description,
148
- status: options.isBackground ? "queued" : "running",
149
- toolUses: 0,
150
- startedAt: Date.now(),
151
- abortController,
152
- lifetimeUsage: { input: 0, output: 0, cacheWrite: 0 },
153
- compactionCount: 0,
154
- invocation: options.invocation,
155
- };
156
- this.agents.set(id, record);
157
-
158
- const args: SpawnArgs = { pi, ctx, type, prompt, options };
159
-
160
- if (
161
- options.isBackground &&
162
- !options.bypassQueue &&
163
- this.runningBackground >= this.maxConcurrent
164
- ) {
165
- // Queue it — will be started when a running agent completes
166
- this.queue.push({ id, args });
167
- return id;
168
- }
169
-
170
- // startAgent can throw (e.g. strict worktree-isolation failure) — clean
171
- // up the record so callers don't see an orphan in `listAgents()`.
172
- try {
173
- this.startAgent(id, record, args);
174
- } catch (err) {
175
- this.agents.delete(id);
176
- throw err;
177
- }
178
- return id;
179
- }
180
-
181
- /** Actually start an agent (called immediately or from queue drain). */
182
- private startAgent(
183
- id: string,
184
- record: AgentRecord,
185
- { pi, ctx, type, prompt, options }: SpawnArgs,
186
- ) {
187
- // Worktree isolation: try to create a temporary git worktree. Strict —
188
- // fail loud if not possible (no silent fallback to main tree). Done
189
- // BEFORE state mutation so a throw doesn't leave the record half-running.
190
- let worktreeCwd: string | undefined;
191
- if (options.isolation === "worktree") {
192
- const wt = createWorktree(ctx.cwd, id);
193
- if (!wt) {
194
- throw new Error(
195
- 'Cannot run with isolation: "worktree" — not a git repo, no commits yet, or `git worktree add` failed. ' +
196
- "Initialize git and commit at least once, or omit `isolation`.",
197
- );
198
- }
199
- record.worktree = wt;
200
- worktreeCwd = wt.path;
201
- }
202
-
203
- record.status = "running";
204
- record.startedAt = Date.now();
205
- if (options.isBackground) this.runningBackground++;
206
- this.onStart?.(record);
207
-
208
- // Wire parent abort signal to stop the subagent when the parent is interrupted
209
- let detachParentSignal: (() => void) | undefined;
210
- if (options.signal) {
211
- const onParentAbort = () => this.abort(id);
212
- options.signal.addEventListener("abort", onParentAbort, { once: true });
213
- detachParentSignal = () =>
214
- options.signal?.removeEventListener("abort", onParentAbort);
215
- }
216
- const detach = () => {
217
- detachParentSignal?.();
218
- detachParentSignal = undefined;
219
- };
220
-
221
- const promise = runAgent(ctx, type, prompt, {
222
- pi,
223
- agentId: id,
224
- model: options.model,
225
- maxTurns: options.maxTurns,
226
- isolated: options.isolated,
227
- inheritContext: options.inheritContext,
228
- thinkingLevel: options.thinkingLevel,
229
- cwd: worktreeCwd,
230
- signal: record.abortController?.signal,
231
- onToolActivity: (activity) => {
232
- if (activity.type === "end") record.toolUses++;
233
- options.onToolActivity?.(activity);
234
- },
235
- onTurnEnd: options.onTurnEnd,
236
- onTextDelta: options.onTextDelta,
237
- onAssistantUsage: (usage) => {
238
- addUsage(record.lifetimeUsage, usage);
239
- options.onAssistantUsage?.(usage);
240
- },
241
- onCompaction: (info) => {
242
- record.compactionCount++;
243
- this.onCompact?.(record, info);
244
- options.onCompaction?.(info);
245
- },
246
- onSessionCreated: (session) => {
247
- record.session = session;
248
- // Flush any steers that arrived before the session was ready
249
- if (record.pendingSteers?.length) {
250
- for (const msg of record.pendingSteers) {
251
- session.steer(msg).catch(() => {});
252
- }
253
- record.pendingSteers = undefined;
254
- }
255
- options.onSessionCreated?.(session);
256
- },
257
- systemPromptAppendix: options.systemPromptAppendix,
258
- parentExtensionContext: ctx,
259
- parentHarnessUiHooks: options.parentHarnessUiHooks,
260
- })
261
- .then(({ responseText, session, aborted, steered }) => {
262
- // Don't overwrite status if externally stopped via abort()
263
- if (record.status !== "stopped") {
264
- record.status = aborted
265
- ? "aborted"
266
- : steered
267
- ? "steered"
268
- : "completed";
269
- }
270
- record.result = responseText;
271
- record.session = session;
272
- record.completedAt ??= Date.now();
273
-
274
- detach();
275
-
276
- // Final flush of streaming output file
277
- if (record.outputCleanup) {
278
- try {
279
- record.outputCleanup();
280
- } catch {
281
- /* ignore */
282
- }
283
- record.outputCleanup = undefined;
284
- }
285
-
286
- // Clean up worktree if used
287
- if (record.worktree) {
288
- const wtResult = cleanupWorktree(
289
- ctx.cwd,
290
- record.worktree,
291
- options.description,
292
- );
293
- record.worktreeResult = wtResult;
294
- if (wtResult.hasChanges && wtResult.branch) {
295
- record.result =
296
- (record.result ?? "") +
297
- `\n\n---\nChanges saved to branch \`${wtResult.branch}\`. Merge with: \`git merge ${wtResult.branch}\``;
298
- }
299
- }
300
-
301
- if (options.isBackground) {
302
- this.runningBackground--;
303
- try {
304
- this.onComplete?.(record);
305
- } catch {
306
- /* ignore completion side-effect errors */
307
- }
308
- this.drainQueue();
309
- }
310
- return responseText;
311
- })
312
- .catch((err) => {
313
- // Don't overwrite status if externally stopped via abort()
314
- if (record.status !== "stopped") {
315
- record.status = "error";
316
- }
317
- record.error = err instanceof Error ? err.message : String(err);
318
- record.completedAt ??= Date.now();
319
-
320
- detach();
321
-
322
- // Final flush of streaming output file on error
323
- if (record.outputCleanup) {
324
- try {
325
- record.outputCleanup();
326
- } catch {
327
- /* ignore */
328
- }
329
- record.outputCleanup = undefined;
330
- }
331
-
332
- // Best-effort worktree cleanup on error
333
- if (record.worktree) {
334
- try {
335
- const wtResult = cleanupWorktree(
336
- ctx.cwd,
337
- record.worktree,
338
- options.description,
339
- );
340
- record.worktreeResult = wtResult;
341
- } catch {
342
- /* ignore cleanup errors */
343
- }
344
- }
345
-
346
- if (options.isBackground) {
347
- this.runningBackground--;
348
- this.onComplete?.(record);
349
- this.drainQueue();
350
- }
351
- return "";
352
- });
353
-
354
- record.promise = promise;
355
- }
356
-
357
- /** Start queued agents up to the concurrency limit. */
358
- private drainQueue() {
359
- while (
360
- this.queue.length > 0 &&
361
- this.runningBackground < this.maxConcurrent
362
- ) {
363
- const next = this.queue.shift()!;
364
- const record = this.agents.get(next.id);
365
- if (!record || record.status !== "queued") continue;
366
- try {
367
- this.startAgent(next.id, record, next.args);
368
- } catch (err) {
369
- // Late failure (e.g. strict worktree-isolation) — surface on the record
370
- // so the user/agent can see it via /agents, then keep draining.
371
- record.status = "error";
372
- record.error = err instanceof Error ? err.message : String(err);
373
- record.completedAt = Date.now();
374
- this.onComplete?.(record);
375
- }
376
- }
377
- }
378
-
379
- /**
380
- * Spawn an agent and wait for completion (foreground use).
381
- * Foreground agents bypass the concurrency queue.
382
- */
383
- async spawnAndWait(
384
- pi: ExtensionAPI,
385
- ctx: ExtensionContext,
386
- type: SubagentType,
387
- prompt: string,
388
- options: Omit<SpawnOptions, "isBackground">,
389
- ): Promise<AgentRecord> {
390
- const id = this.spawn(pi, ctx, type, prompt, {
391
- ...options,
392
- isBackground: false,
393
- });
394
- const record = this.agents.get(id)!;
395
- await record.promise;
396
- return record;
397
- }
398
-
399
- /**
400
- * Resume an existing agent session with a new prompt.
401
- */
402
- async resume(
403
- id: string,
404
- prompt: string,
405
- signal?: AbortSignal,
406
- ): Promise<AgentRecord | undefined> {
407
- const record = this.agents.get(id);
408
- if (!record?.session) return undefined;
409
-
410
- record.status = "running";
411
- record.startedAt = Date.now();
412
- record.completedAt = undefined;
413
- record.result = undefined;
414
- record.error = undefined;
415
-
416
- try {
417
- const responseText = await resumeAgent(record.session, prompt, {
418
- onToolActivity: (activity) => {
419
- if (activity.type === "end") record.toolUses++;
420
- },
421
- onAssistantUsage: (usage) => {
422
- addUsage(record.lifetimeUsage, usage);
423
- },
424
- onCompaction: (info) => {
425
- record.compactionCount++;
426
- this.onCompact?.(record, info);
427
- },
428
- signal,
429
- });
430
- record.status = "completed";
431
- record.result = responseText;
432
- record.completedAt = Date.now();
433
- } catch (err) {
434
- record.status = "error";
435
- record.error = err instanceof Error ? err.message : String(err);
436
- record.completedAt = Date.now();
437
- }
438
-
439
- return record;
440
- }
441
-
442
- getRecord(id: string): AgentRecord | undefined {
443
- return this.agents.get(id);
444
- }
445
-
446
- listAgents(): AgentRecord[] {
447
- return [...this.agents.values()].sort((a, b) => b.startedAt - a.startedAt);
448
- }
449
-
450
- abort(id: string): boolean {
451
- const record = this.agents.get(id);
452
- if (!record) return false;
453
-
454
- // Remove from queue if queued
455
- if (record.status === "queued") {
456
- this.queue = this.queue.filter((q) => q.id !== id);
457
- record.status = "stopped";
458
- record.completedAt = Date.now();
459
- return true;
460
- }
461
-
462
- if (record.status !== "running") return false;
463
- record.abortController?.abort();
464
- record.status = "stopped";
465
- record.completedAt = Date.now();
466
- return true;
467
- }
468
-
469
- /** Dispose a record's session and remove it from the map. */
470
- private removeRecord(id: string, record: AgentRecord): void {
471
- record.session?.dispose?.();
472
- record.session = undefined;
473
- this.agents.delete(id);
474
- }
475
-
476
- private cleanup() {
477
- const cutoff = Date.now() - 10 * 60_000;
478
- for (const [id, record] of this.agents) {
479
- if (record.status === "running" || record.status === "queued") continue;
480
- if ((record.completedAt ?? 0) >= cutoff) continue;
481
- this.removeRecord(id, record);
482
- }
483
- }
484
-
485
- /**
486
- * Remove all completed/stopped/errored records immediately.
487
- * Called on session start/switch so tasks from a prior session don't persist.
488
- */
489
- clearCompleted(): void {
490
- for (const [id, record] of this.agents) {
491
- if (record.status === "running" || record.status === "queued") continue;
492
- this.removeRecord(id, record);
493
- }
494
- }
495
-
496
- /** Whether any agents are still running or queued. */
497
- hasRunning(): boolean {
498
- return [...this.agents.values()].some(
499
- (r) => r.status === "running" || r.status === "queued",
500
- );
501
- }
502
-
503
- /** Abort all running and queued agents immediately. */
504
- abortAll(): number {
505
- let count = 0;
506
- // Clear queued agents first
507
- for (const queued of this.queue) {
508
- const record = this.agents.get(queued.id);
509
- if (record) {
510
- record.status = "stopped";
511
- record.completedAt = Date.now();
512
- count++;
513
- }
514
- }
515
- this.queue = [];
516
- // Abort running agents
517
- for (const record of this.agents.values()) {
518
- if (record.status === "running") {
519
- record.abortController?.abort();
520
- record.status = "stopped";
521
- record.completedAt = Date.now();
522
- count++;
523
- }
524
- }
525
- return count;
526
- }
527
-
528
- /** Wait for all running and queued agents to complete (including queued ones). */
529
- async waitForAll(): Promise<void> {
530
- // Loop because drainQueue respects the concurrency limit — as running
531
- // agents finish they start queued ones, which need awaiting too.
532
- while (true) {
533
- this.drainQueue();
534
- const pending = [...this.agents.values()]
535
- .filter((r) => r.status === "running" || r.status === "queued")
536
- .map((r) => r.promise)
537
- .filter(Boolean);
538
- if (pending.length === 0) break;
539
- await Promise.allSettled(pending);
540
- }
541
- }
542
-
543
- dispose() {
544
- clearInterval(this.cleanupInterval);
545
- // Clear queue
546
- this.queue = [];
547
- for (const record of this.agents.values()) {
548
- record.session?.dispose();
549
- }
550
- this.agents.clear();
551
- // Prune any orphaned git worktrees (crash recovery)
552
- try {
553
- pruneWorktrees(process.cwd());
554
- } catch {
555
- /* ignore */
556
- }
557
- }
558
- }