@by-lua/lspec-subagents 1.0.1

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 (86) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/LICENSE +21 -0
  3. package/README.md +123 -0
  4. package/dist/agent-manager.d.ts +108 -0
  5. package/dist/agent-manager.js +391 -0
  6. package/dist/agent-runner.d.ts +95 -0
  7. package/dist/agent-runner.js +377 -0
  8. package/dist/agent-types.d.ts +58 -0
  9. package/dist/agent-types.js +157 -0
  10. package/dist/context.d.ts +12 -0
  11. package/dist/context.js +56 -0
  12. package/dist/cross-extension-rpc.d.ts +46 -0
  13. package/dist/cross-extension-rpc.js +76 -0
  14. package/dist/custom-agents.d.ts +14 -0
  15. package/dist/custom-agents.js +127 -0
  16. package/dist/default-agents.d.ts +12 -0
  17. package/dist/default-agents.js +489 -0
  18. package/dist/env.d.ts +6 -0
  19. package/dist/env.js +28 -0
  20. package/dist/group-join.d.ts +32 -0
  21. package/dist/group-join.js +116 -0
  22. package/dist/index.d.ts +13 -0
  23. package/dist/index.js +1863 -0
  24. package/dist/invocation-config.d.ts +22 -0
  25. package/dist/invocation-config.js +15 -0
  26. package/dist/memory.d.ts +49 -0
  27. package/dist/memory.js +151 -0
  28. package/dist/model-config-loader.d.ts +58 -0
  29. package/dist/model-config-loader.js +157 -0
  30. package/dist/model-resolver.d.ts +19 -0
  31. package/dist/model-resolver.js +62 -0
  32. package/dist/output-file.d.ts +24 -0
  33. package/dist/output-file.js +86 -0
  34. package/dist/prompts.d.ts +29 -0
  35. package/dist/prompts.js +65 -0
  36. package/dist/schedule-store.d.ts +38 -0
  37. package/dist/schedule-store.js +155 -0
  38. package/dist/schedule.d.ts +109 -0
  39. package/dist/schedule.js +338 -0
  40. package/dist/settings.d.ts +66 -0
  41. package/dist/settings.js +130 -0
  42. package/dist/skill-loader.d.ts +24 -0
  43. package/dist/skill-loader.js +93 -0
  44. package/dist/types.d.ts +164 -0
  45. package/dist/types.js +8 -0
  46. package/dist/ui/agent-widget.d.ts +134 -0
  47. package/dist/ui/agent-widget.js +451 -0
  48. package/dist/ui/conversation-viewer.d.ts +35 -0
  49. package/dist/ui/conversation-viewer.js +252 -0
  50. package/dist/ui/schedule-menu.d.ts +16 -0
  51. package/dist/ui/schedule-menu.js +95 -0
  52. package/dist/usage.d.ts +50 -0
  53. package/dist/usage.js +49 -0
  54. package/dist/worktree.d.ts +36 -0
  55. package/dist/worktree.js +139 -0
  56. package/install.sh +77 -0
  57. package/lspec-model-config.example.json +17 -0
  58. package/package.json +50 -0
  59. package/src/agent-manager.ts +483 -0
  60. package/src/agent-runner.ts +486 -0
  61. package/src/agent-types.ts +188 -0
  62. package/src/context.ts +58 -0
  63. package/src/cross-extension-rpc.ts +122 -0
  64. package/src/custom-agents.ts +136 -0
  65. package/src/default-agents.ts +501 -0
  66. package/src/env.ts +33 -0
  67. package/src/group-join.ts +141 -0
  68. package/src/index.ts +2032 -0
  69. package/src/invocation-config.ts +40 -0
  70. package/src/memory.ts +165 -0
  71. package/src/model-config-loader.ts +193 -0
  72. package/src/model-resolver.ts +81 -0
  73. package/src/output-file.ts +96 -0
  74. package/src/prompts.ts +91 -0
  75. package/src/schedule-store.ts +153 -0
  76. package/src/schedule.ts +365 -0
  77. package/src/settings.ts +186 -0
  78. package/src/skill-loader.ts +102 -0
  79. package/src/types.ts +179 -0
  80. package/src/ui/agent-widget.ts +533 -0
  81. package/src/ui/conversation-viewer.ts +261 -0
  82. package/src/ui/schedule-menu.ts +104 -0
  83. package/src/usage.ts +60 -0
  84. package/src/worktree.ts +162 -0
  85. package/uninstall.sh +55 -0
  86. package/update.sh +64 -0
package/install.sh ADDED
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env bash
2
+ # lspec-subagents — Instalador
3
+ # Uso: curl -fsSL https://raw.githubusercontent.com/by-lua/lspec-subagents/main/install.sh | bash
4
+ # Alternativa npm: curl -fsSL https://raw.githubusercontent.com/by-lua/lspec-subagents/main/install.sh | bash -s npm
5
+ # Requer: git, pi (PI.dev)
6
+
7
+ set -uo pipefail
8
+
9
+ GREEN='\033[0;32m'
10
+ BLUE='\033[0;34m'
11
+ RED='\033[0;31m'
12
+ YELLOW='\033[0;33m'
13
+ NC='\033[0m'
14
+
15
+ REPO="https://github.com/by-lua/lspec-subagents.git"
16
+ PI_AGENTS_DIR="$HOME/.pi/agents"
17
+ PI_AGENT_DIR="$HOME/.pi/agent"
18
+
19
+ echo ""
20
+ echo -e "${BLUE}╔════════════════════════════════╗${NC}"
21
+ echo -e "${BLUE}║ lspec-subagents — Instalador ║${NC}"
22
+ echo -e "${BLUE}╚════════════════════════════════╝${NC}"
23
+ echo ""
24
+
25
+ if ! command -v pi &>/dev/null; then
26
+ echo -e "${RED}✗ PI não encontrado. Instale em https://pi.dev${NC}"
27
+ exit 1
28
+ fi
29
+
30
+ # ── Passo 0: Remover extensões conflitantes ──
31
+ echo -e "${BLUE}→ Removendo extensões conflitantes...${NC}"
32
+ pi remove "npm:@tintinweb/pi-subagents" 2>/dev/null && echo -e " ${YELLOW}⊘${NC} Removido npm:@tintinweb/pi-subagents (conflito)"
33
+ pi remove "git:github.com/by-lua/lspec-subagents" 2>/dev/null
34
+ pi remove "npm:@by-lua/lspec-subagents" 2>/dev/null
35
+
36
+ # ── Passo 1: Instalar extensão via npm ──
37
+ echo -e "${BLUE}→ Instalando @by-lua/lspec-subagents via npm...${NC}"
38
+ pi install "npm:@by-lua/lspec-subagents" 2>/dev/null
39
+ echo -e " ${GREEN}✓${NC} Extensão instalada (9 agentes L-Spec + /agents)"
40
+
41
+ # ── Passo 2: Clonar e copiar .md de agentes ──
42
+ echo -e "${BLUE}→ Copiando agent .md files...${NC}"
43
+ REPO_DIR="$(mktemp -d)"
44
+ git clone --depth 1 "$REPO" "$REPO_DIR" 2>/dev/null || {
45
+ echo -e "${RED}✗ Erro ao clonar. Git instalado?${NC}"; rm -rf "$REPO_DIR"; exit 1; }
46
+
47
+ mkdir -p "$PI_AGENTS_DIR" "$PI_AGENT_DIR"
48
+
49
+ agent_count=0
50
+ for agent_file in "$REPO_DIR"/.pi/agents/*.md; do
51
+ [[ -f "$agent_file" ]] || continue
52
+ agent_name=$(basename "$agent_file")
53
+ cp "$agent_file" "$PI_AGENTS_DIR/$agent_name"
54
+ echo -e " ${GREEN}✓${NC} agents/$agent_name"
55
+ ((agent_count++))
56
+ done
57
+
58
+ # Copiar config de modelos (não sobrescreve se já existe)
59
+ if [[ -f "$REPO_DIR/lspec-model-config.example.json" ]]; then
60
+ if [[ ! -f "$PI_AGENT_DIR/lspec-model-config.json" ]]; then
61
+ cp "$REPO_DIR/lspec-model-config.example.json" "$PI_AGENT_DIR/lspec-model-config.json"
62
+ echo -e " ${GREEN}✓${NC} lspec-model-config.json (criado com defaults)"
63
+ else
64
+ echo -e " ${BLUE}⊘${NC} lspec-model-config.json (já existe, mantido)"
65
+ fi
66
+ fi
67
+
68
+ echo ""
69
+ echo -e "${GREEN}✓ lspec-subagents instalado!${NC} ($agent_count .md agents | extensão @by-lua/lspec-subagents)"
70
+ echo ""
71
+ echo "Agentes: orchestrator | explorer | librarian | oracle | designer | fixer | observer | council | councillor"
72
+ echo "Extensão: pi install npm:@by-lua/lspec-subagents"
73
+ echo "Config: ~/.pi/agent/lspec-model-config.json"
74
+ echo "Atualizar: curl -fsSL https://raw.githubusercontent.com/by-lua/lspec-subagents/main/update.sh | bash"
75
+ echo "Desinstalar: curl -fsSL https://raw.githubusercontent.com/by-lua/lspec-subagents/main/uninstall.sh | bash"
76
+ echo ""
77
+ rm -rf "$REPO_DIR"
@@ -0,0 +1,17 @@
1
+ {
2
+ "_note": "L-Spec Model Config — centralized model assignment for all subagents.",
3
+ "_docs": "Place this file at .pi/lspec-model-config.json (project) or ~/.pi/agent/lspec-model-config.json (global).",
4
+ "_override_order": "project > global > embedded defaults",
5
+ "_usage": "Each entry maps an agent role to a model string. Format: 'provider/modelId' or just 'modelId'. Mix and match providers freely.",
6
+ "agents": {
7
+ "orchestrator": "claude-sonnet-4",
8
+ "explorer": "gpt-4o-mini",
9
+ "librarian": "claude-sonnet-4",
10
+ "oracle": "claude-opus-4",
11
+ "designer": "claude-sonnet-4",
12
+ "fixer": "codex",
13
+ "observer": "gpt-4o-mini",
14
+ "council": "claude-opus-4",
15
+ "councillor": "grok-2"
16
+ }
17
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@by-lua/lspec-subagents",
3
+ "version": "1.0.1",
4
+ "description": "L-Spec Subagents \u2014 9 specialized agents for PI.dev with centralized model config (inspired by oh-my-opencode-slim). Forked from @tintinweb/pi-subagents.",
5
+ "author": "Lua <noelia.assis@by-lua.com> (https://github.com/by-lua)",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/by-lua/lspec-subagents.git"
10
+ },
11
+ "homepage": "https://github.com/by-lua/lspec-subagents#readme",
12
+ "keywords": [
13
+ "pi-package",
14
+ "pi",
15
+ "pi-extension",
16
+ "subagent",
17
+ "agent",
18
+ "autonomous",
19
+ "lspec",
20
+ "sdd"
21
+ ],
22
+ "peerDependencies": {
23
+ "@mariozechner/pi-ai": ">=0.70.5",
24
+ "@mariozechner/pi-coding-agent": ">=0.70.5",
25
+ "@mariozechner/pi-tui": ">=0.70.5"
26
+ },
27
+ "dependencies": {
28
+ "@sinclair/typebox": "^0.34.49",
29
+ "croner": "^10.0.1",
30
+ "nanoid": "^5.0.0"
31
+ },
32
+ "scripts": {
33
+ "build": "tsc",
34
+ "test": "vitest run",
35
+ "typecheck": "tsc --noEmit",
36
+ "lint": "biome check src/ test/"
37
+ },
38
+ "devDependencies": {
39
+ "@biomejs/biome": "^2.4.14",
40
+ "@types/node": "^25.5.0",
41
+ "typescript": "^6.0.0",
42
+ "vitest": "^4.0.18"
43
+ },
44
+ "pi": {
45
+ "extensions": [
46
+ "./dist/index.js"
47
+ ],
48
+ "image": "https://raw.githubusercontent.com/lua/lspec-subagents/main/media/screenshot.png"
49
+ }
50
+ }
@@ -0,0 +1,483 @@
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 "@mariozechner/pi-ai";
11
+ import type { AgentSession, ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
12
+ import { resumeAgent, runAgent, type ToolActivity } from "./agent-runner.js";
13
+ import type { AgentInvocation, AgentRecord, IsolationMode, SubagentType, ThinkingLevel } from "./types.js";
14
+ import { addUsage } from "./usage.js";
15
+ import { cleanupWorktree, createWorktree, pruneWorktrees, } from "./worktree.js";
16
+
17
+ export type OnAgentComplete = (record: AgentRecord) => void;
18
+ export type OnAgentStart = (record: AgentRecord) => void;
19
+ export type OnAgentCompact = (record: AgentRecord, info: CompactionInfo) => void;
20
+ export type CompactionInfo = { reason: "manual" | "threshold" | "overflow"; tokensBefore: number };
21
+
22
+ /** Default max concurrent background agents. */
23
+ const DEFAULT_MAX_CONCURRENT = 4;
24
+
25
+ interface SpawnArgs {
26
+ pi: ExtensionAPI;
27
+ ctx: ExtensionContext;
28
+ type: SubagentType;
29
+ prompt: string;
30
+ options: SpawnOptions;
31
+ }
32
+
33
+ interface SpawnOptions {
34
+ description: string;
35
+ model?: Model<any>;
36
+ maxTurns?: number;
37
+ isolated?: boolean;
38
+ inheritContext?: boolean;
39
+ thinkingLevel?: ThinkingLevel;
40
+ isBackground?: boolean;
41
+ /**
42
+ * Skip the maxConcurrent queue check for this spawn — start immediately even
43
+ * if the configured concurrency limit would otherwise queue it. Used by the
44
+ * scheduler so a fired job can't be deferred past its trigger window.
45
+ */
46
+ bypassQueue?: boolean;
47
+ /** Isolation mode — "worktree" creates a temp git worktree for the agent. */
48
+ isolation?: IsolationMode;
49
+ /** Resolved invocation snapshot captured for UI display. */
50
+ invocation?: AgentInvocation;
51
+ /** Parent abort signal — when aborted, the subagent is also stopped. */
52
+ signal?: AbortSignal;
53
+ /** Called on tool start/end with activity info (for streaming progress to UI). */
54
+ onToolActivity?: (activity: ToolActivity) => void;
55
+ /** Called on streaming text deltas from the assistant response. */
56
+ onTextDelta?: (delta: string, fullText: string) => void;
57
+ /** Called when the agent session is created (for accessing session stats). */
58
+ onSessionCreated?: (session: AgentSession) => void;
59
+ /** Called at the end of each agentic turn with the cumulative count. */
60
+ onTurnEnd?: (turnCount: number) => void;
61
+ /** Called once per assistant message_end with that message's usage delta. */
62
+ onAssistantUsage?: (usage: { input: number; output: number; cacheWrite: number }) => void;
63
+ /** Called when the session successfully compacts. */
64
+ onCompaction?: (info: CompactionInfo) => void;
65
+ }
66
+
67
+ export class AgentManager {
68
+ private agents = new Map<string, AgentRecord>();
69
+ private cleanupInterval: ReturnType<typeof setInterval>;
70
+ private onComplete?: OnAgentComplete;
71
+ private onStart?: OnAgentStart;
72
+ private onCompact?: OnAgentCompact;
73
+ private maxConcurrent: number;
74
+
75
+ /** Queue of background agents waiting to start. */
76
+ private queue: { id: string; args: SpawnArgs }[] = [];
77
+ /** Number of currently running background agents. */
78
+ private runningBackground = 0;
79
+
80
+ constructor(
81
+ onComplete?: OnAgentComplete,
82
+ maxConcurrent = DEFAULT_MAX_CONCURRENT,
83
+ onStart?: OnAgentStart,
84
+ onCompact?: OnAgentCompact,
85
+ ) {
86
+ this.onComplete = onComplete;
87
+ this.onStart = onStart;
88
+ this.onCompact = onCompact;
89
+ this.maxConcurrent = maxConcurrent;
90
+ // Cleanup completed agents after 10 minutes (but keep sessions for resume)
91
+ this.cleanupInterval = setInterval(() => this.cleanup(), 60_000);
92
+ this.cleanupInterval.unref();
93
+ }
94
+
95
+ /** Update the max concurrent background agents limit. */
96
+ setMaxConcurrent(n: number) {
97
+ this.maxConcurrent = Math.max(1, n);
98
+ // Start queued agents if the new limit allows
99
+ this.drainQueue();
100
+ }
101
+
102
+ getMaxConcurrent(): number {
103
+ return this.maxConcurrent;
104
+ }
105
+
106
+ /**
107
+ * Spawn an agent and return its ID immediately (for background use).
108
+ * If the concurrency limit is reached, the agent is queued.
109
+ */
110
+ spawn(
111
+ pi: ExtensionAPI,
112
+ ctx: ExtensionContext,
113
+ type: SubagentType,
114
+ prompt: string,
115
+ options: SpawnOptions,
116
+ ): string {
117
+ const id = randomUUID().slice(0, 17);
118
+ const abortController = new AbortController();
119
+ const record: AgentRecord = {
120
+ id,
121
+ type,
122
+ description: options.description,
123
+ status: options.isBackground ? "queued" : "running",
124
+ toolUses: 0,
125
+ startedAt: Date.now(),
126
+ abortController,
127
+ lifetimeUsage: { input: 0, output: 0, cacheWrite: 0 },
128
+ compactionCount: 0,
129
+ invocation: options.invocation,
130
+ };
131
+ this.agents.set(id, record);
132
+
133
+ const args: SpawnArgs = { pi, ctx, type, prompt, options };
134
+
135
+ if (options.isBackground && !options.bypassQueue && this.runningBackground >= this.maxConcurrent) {
136
+ // Queue it — will be started when a running agent completes
137
+ this.queue.push({ id, args });
138
+ return id;
139
+ }
140
+
141
+ // startAgent can throw (e.g. strict worktree-isolation failure) — clean
142
+ // up the record so callers don't see an orphan in `listAgents()`.
143
+ try {
144
+ this.startAgent(id, record, args);
145
+ } catch (err) {
146
+ this.agents.delete(id);
147
+ throw err;
148
+ }
149
+ return id;
150
+ }
151
+
152
+ /** Actually start an agent (called immediately or from queue drain). */
153
+ private startAgent(id: string, record: AgentRecord, { pi, ctx, type, prompt, options }: SpawnArgs) {
154
+ // Worktree isolation: try to create a temporary git worktree. Strict —
155
+ // fail loud if not possible (no silent fallback to main tree). Done
156
+ // BEFORE state mutation so a throw doesn't leave the record half-running.
157
+ let worktreeCwd: string | undefined;
158
+ if (options.isolation === "worktree") {
159
+ const wt = createWorktree(ctx.cwd, id);
160
+ if (!wt) {
161
+ throw new Error(
162
+ 'Cannot run with isolation: "worktree" — not a git repo, no commits yet, or `git worktree add` failed. ' +
163
+ 'Initialize git and commit at least once, or omit `isolation`.',
164
+ );
165
+ }
166
+ record.worktree = wt;
167
+ worktreeCwd = wt.path;
168
+ }
169
+
170
+ record.status = "running";
171
+ record.startedAt = Date.now();
172
+ if (options.isBackground) this.runningBackground++;
173
+ this.onStart?.(record);
174
+
175
+ // Wire parent abort signal to stop the subagent when the parent is interrupted
176
+ let detachParentSignal: (() => void) | undefined;
177
+ if (options.signal) {
178
+ const onParentAbort = () => this.abort(id);
179
+ options.signal.addEventListener("abort", onParentAbort, { once: true });
180
+ detachParentSignal = () => options.signal!.removeEventListener("abort", onParentAbort);
181
+ }
182
+ const detach = () => { detachParentSignal?.(); detachParentSignal = undefined; };
183
+
184
+ const promise = runAgent(ctx, type, prompt, {
185
+ pi,
186
+ agentId: id,
187
+ model: options.model,
188
+ maxTurns: options.maxTurns,
189
+ isolated: options.isolated,
190
+ inheritContext: options.inheritContext,
191
+ thinkingLevel: options.thinkingLevel,
192
+ cwd: worktreeCwd,
193
+ signal: record.abortController!.signal,
194
+ onToolActivity: (activity) => {
195
+ if (activity.type === "end") record.toolUses++;
196
+ options.onToolActivity?.(activity);
197
+ },
198
+ onTurnEnd: options.onTurnEnd,
199
+ onTextDelta: options.onTextDelta,
200
+ onAssistantUsage: (usage) => {
201
+ addUsage(record.lifetimeUsage, usage);
202
+ options.onAssistantUsage?.(usage);
203
+ },
204
+ onCompaction: (info) => {
205
+ record.compactionCount++;
206
+ this.onCompact?.(record, info);
207
+ options.onCompaction?.(info);
208
+ },
209
+ onSessionCreated: (session) => {
210
+ record.session = session;
211
+ // Flush any steers that arrived before the session was ready
212
+ if (record.pendingSteers?.length) {
213
+ for (const msg of record.pendingSteers) {
214
+ session.steer(msg).catch(() => {});
215
+ }
216
+ record.pendingSteers = undefined;
217
+ }
218
+ options.onSessionCreated?.(session);
219
+ },
220
+ })
221
+ .then(({ responseText, session, aborted, steered }) => {
222
+ // Don't overwrite status if externally stopped via abort()
223
+ if (record.status !== "stopped") {
224
+ record.status = aborted ? "aborted" : steered ? "steered" : "completed";
225
+ }
226
+ record.result = responseText;
227
+ record.session = session;
228
+ record.completedAt ??= Date.now();
229
+
230
+ detach();
231
+
232
+ // Final flush of streaming output file
233
+ if (record.outputCleanup) {
234
+ try { record.outputCleanup(); } catch { /* ignore */ }
235
+ record.outputCleanup = undefined;
236
+ }
237
+
238
+ // Clean up worktree if used
239
+ if (record.worktree) {
240
+ const wtResult = cleanupWorktree(ctx.cwd, record.worktree, options.description);
241
+ record.worktreeResult = wtResult;
242
+ if (wtResult.hasChanges && wtResult.branch) {
243
+ record.result = (record.result ?? "") +
244
+ `\n\n---\nChanges saved to branch \`${wtResult.branch}\`. Merge with: \`git merge ${wtResult.branch}\``;
245
+ }
246
+ }
247
+
248
+ if (options.isBackground) {
249
+ this.runningBackground--;
250
+ try { this.onComplete?.(record); } catch { /* ignore completion side-effect errors */ }
251
+ this.drainQueue();
252
+ }
253
+ return responseText;
254
+ })
255
+ .catch((err) => {
256
+ // Don't overwrite status if externally stopped via abort()
257
+ if (record.status !== "stopped") {
258
+ record.status = "error";
259
+ }
260
+ record.error = err instanceof Error ? err.message : String(err);
261
+ record.completedAt ??= Date.now();
262
+
263
+ detach();
264
+
265
+ // Final flush of streaming output file on error
266
+ if (record.outputCleanup) {
267
+ try { record.outputCleanup(); } catch { /* ignore */ }
268
+ record.outputCleanup = undefined;
269
+ }
270
+
271
+ // Best-effort worktree cleanup on error
272
+ if (record.worktree) {
273
+ try {
274
+ const wtResult = cleanupWorktree(ctx.cwd, record.worktree, options.description);
275
+ record.worktreeResult = wtResult;
276
+ } catch { /* ignore cleanup errors */ }
277
+ }
278
+
279
+ if (options.isBackground) {
280
+ this.runningBackground--;
281
+ this.onComplete?.(record);
282
+ this.drainQueue();
283
+ }
284
+ return "";
285
+ });
286
+
287
+ record.promise = promise;
288
+ }
289
+
290
+ /** Start queued agents up to the concurrency limit. */
291
+ private drainQueue() {
292
+ while (this.queue.length > 0 && this.runningBackground < this.maxConcurrent) {
293
+ const next = this.queue.shift()!;
294
+ const record = this.agents.get(next.id);
295
+ if (!record || record.status !== "queued") continue;
296
+ try {
297
+ this.startAgent(next.id, record, next.args);
298
+ } catch (err) {
299
+ // Late failure (e.g. strict worktree-isolation) — surface on the record
300
+ // so the user/agent can see it via /agents, then keep draining.
301
+ record.status = "error";
302
+ record.error = err instanceof Error ? err.message : String(err);
303
+ record.completedAt = Date.now();
304
+ this.onComplete?.(record);
305
+ }
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Spawn an agent and wait for completion (foreground use).
311
+ * Foreground agents bypass the concurrency queue.
312
+ */
313
+ async spawnAndWait(
314
+ pi: ExtensionAPI,
315
+ ctx: ExtensionContext,
316
+ type: SubagentType,
317
+ prompt: string,
318
+ options: Omit<SpawnOptions, "isBackground">,
319
+ ): Promise<AgentRecord> {
320
+ const id = this.spawn(pi, ctx, type, prompt, { ...options, isBackground: false });
321
+ const record = this.agents.get(id)!;
322
+ await record.promise;
323
+ return record;
324
+ }
325
+
326
+ /**
327
+ * Resume an existing agent session with a new prompt.
328
+ */
329
+ async resume(
330
+ id: string,
331
+ prompt: string,
332
+ signal?: AbortSignal,
333
+ ): Promise<AgentRecord | undefined> {
334
+ const record = this.agents.get(id);
335
+ if (!record?.session) return undefined;
336
+
337
+ record.status = "running";
338
+ record.startedAt = Date.now();
339
+ record.completedAt = undefined;
340
+ record.result = undefined;
341
+ record.error = undefined;
342
+
343
+ try {
344
+ const responseText = await resumeAgent(record.session, prompt, {
345
+ onToolActivity: (activity) => {
346
+ if (activity.type === "end") record.toolUses++;
347
+ },
348
+ onAssistantUsage: (usage) => {
349
+ addUsage(record.lifetimeUsage, usage);
350
+ },
351
+ onCompaction: (info) => {
352
+ record.compactionCount++;
353
+ this.onCompact?.(record, info);
354
+ },
355
+ signal,
356
+ });
357
+ record.status = "completed";
358
+ record.result = responseText;
359
+ record.completedAt = Date.now();
360
+ } catch (err) {
361
+ record.status = "error";
362
+ record.error = err instanceof Error ? err.message : String(err);
363
+ record.completedAt = Date.now();
364
+ }
365
+
366
+ return record;
367
+ }
368
+
369
+ getRecord(id: string): AgentRecord | undefined {
370
+ return this.agents.get(id);
371
+ }
372
+
373
+ listAgents(): AgentRecord[] {
374
+ return [...this.agents.values()].sort(
375
+ (a, b) => b.startedAt - a.startedAt,
376
+ );
377
+ }
378
+
379
+ abort(id: string): boolean {
380
+ const record = this.agents.get(id);
381
+ if (!record) return false;
382
+
383
+ // Remove from queue if queued
384
+ if (record.status === "queued") {
385
+ this.queue = this.queue.filter(q => q.id !== id);
386
+ record.status = "stopped";
387
+ record.completedAt = Date.now();
388
+ return true;
389
+ }
390
+
391
+ if (record.status !== "running") return false;
392
+ record.abortController?.abort();
393
+ record.status = "stopped";
394
+ record.completedAt = Date.now();
395
+ return true;
396
+ }
397
+
398
+ /** Dispose a record's session and remove it from the map. */
399
+ private removeRecord(id: string, record: AgentRecord): void {
400
+ record.session?.dispose?.();
401
+ record.session = undefined;
402
+ this.agents.delete(id);
403
+ }
404
+
405
+ private cleanup() {
406
+ const cutoff = Date.now() - 10 * 60_000;
407
+ for (const [id, record] of this.agents) {
408
+ if (record.status === "running" || record.status === "queued") continue;
409
+ if ((record.completedAt ?? 0) >= cutoff) continue;
410
+ this.removeRecord(id, record);
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Remove all completed/stopped/errored records immediately.
416
+ * Called on session start/switch so tasks from a prior session don't persist.
417
+ */
418
+ clearCompleted(): void {
419
+ for (const [id, record] of this.agents) {
420
+ if (record.status === "running" || record.status === "queued") continue;
421
+ this.removeRecord(id, record);
422
+ }
423
+ }
424
+
425
+ /** Whether any agents are still running or queued. */
426
+ hasRunning(): boolean {
427
+ return [...this.agents.values()].some(
428
+ r => r.status === "running" || r.status === "queued",
429
+ );
430
+ }
431
+
432
+ /** Abort all running and queued agents immediately. */
433
+ abortAll(): number {
434
+ let count = 0;
435
+ // Clear queued agents first
436
+ for (const queued of this.queue) {
437
+ const record = this.agents.get(queued.id);
438
+ if (record) {
439
+ record.status = "stopped";
440
+ record.completedAt = Date.now();
441
+ count++;
442
+ }
443
+ }
444
+ this.queue = [];
445
+ // Abort running agents
446
+ for (const record of this.agents.values()) {
447
+ if (record.status === "running") {
448
+ record.abortController?.abort();
449
+ record.status = "stopped";
450
+ record.completedAt = Date.now();
451
+ count++;
452
+ }
453
+ }
454
+ return count;
455
+ }
456
+
457
+ /** Wait for all running and queued agents to complete (including queued ones). */
458
+ async waitForAll(): Promise<void> {
459
+ // Loop because drainQueue respects the concurrency limit — as running
460
+ // agents finish they start queued ones, which need awaiting too.
461
+ while (true) {
462
+ this.drainQueue();
463
+ const pending = [...this.agents.values()]
464
+ .filter(r => r.status === "running" || r.status === "queued")
465
+ .map(r => r.promise)
466
+ .filter(Boolean);
467
+ if (pending.length === 0) break;
468
+ await Promise.allSettled(pending);
469
+ }
470
+ }
471
+
472
+ dispose() {
473
+ clearInterval(this.cleanupInterval);
474
+ // Clear queue
475
+ this.queue = [];
476
+ for (const record of this.agents.values()) {
477
+ record.session?.dispose();
478
+ }
479
+ this.agents.clear();
480
+ // Prune any orphaned git worktrees (crash recovery)
481
+ try { pruneWorktrees(process.cwd()); } catch { /* ignore */ }
482
+ }
483
+ }