@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/README.md ADDED
@@ -0,0 +1,123 @@
1
+ # lspec-subagents
2
+
3
+ > **9 specialized sub-agents for PI.dev** — extensão standalone com modelo centralizado de configuração (inspirado no oh-my-opencode-slim). Fork do `@tintinweb/pi-subagents`.
4
+
5
+ 9 agentes especializados para o fluxo L-Spec (Lua Spec-Driven Development). Os 3 agentes padrão do original (general-purpose, Explore, Plan) foram **completamente removidos** — só os 9 L-Spec existem no código.
6
+
7
+ ## Agentes
8
+
9
+ - **orchestrator** — Coordenador central do fluxo L-Spec (`claude-sonnet-4`)
10
+ - **explorer** — Navegação rápida no codebase, read-only (`gpt-4o-mini`)
11
+ - **librarian** — Pesquisa de docs externas e APIs (`claude-sonnet-4`)
12
+ - **oracle** — Arquiteto sênior, code review, read-only (`claude-opus-4`)
13
+ - **designer** — UI/UX specialist (`claude-sonnet-4`)
14
+ - **fixer** — Implementador rápido de tarefas definidas (`claude-sonnet-4`)
15
+ - **observer** — Análise visual (imagens, PDFs, screenshots) (`gpt-4o-mini`, vision-capable)
16
+ - **council** — Consenso multi-modelo (spawna councillors) (`claude-opus-4`)
17
+ - **councillor** — Membro individual do conselho (`gpt-4o-mini`)
18
+
19
+ ## Configuração Centralizada de Modelos
20
+
21
+ Modelos são **placeholders** (`{{model:orchestrator}}`) resolvidos em runtime via JSON.
22
+
23
+ ### Como configurar
24
+
25
+ Crie `lspec-model-config.json` em:
26
+ - **Global**: `~/.pi/agent/lspec-model-config.json`
27
+ - **Projeto**: `.pi/lspec-model-config.json` (sobrescreve o global)
28
+
29
+ ```json
30
+ {
31
+ "agents": {
32
+ "orchestrator": "claude-sonnet-4",
33
+ "explorer": "gpt-4o-mini",
34
+ "librarian": "claude-sonnet-4",
35
+ "oracle": "claude-opus-4",
36
+ "designer": "claude-sonnet-4",
37
+ "fixer": "claude-sonnet-4",
38
+ "observer": "gpt-4o-mini",
39
+ "council": "claude-opus-4",
40
+ "councillor": "gpt-4o-mini"
41
+ }
42
+ }
43
+ ```
44
+
45
+ Pode usar qualquer modelo disponível no seu provedor. O observer precisa de um modelo com **visão**.
46
+
47
+ ### Ordem de resolução
48
+
49
+ 1. Projeto (`.pi/lspec-model-config.json`) — **maior prioridade**
50
+ 2. Global (`~/.pi/agent/lspec-model-config.json`)
51
+ 3. Defaults embutidos (claude-sonnet-4, gpt-4o-mini, claude-opus-4)
52
+
53
+ ## Instalação
54
+
55
+ ```bash
56
+ curl -fsSL https://raw.githubusercontent.com/by-lua/lspec-subagents/main/install.sh | bash
57
+ ```
58
+
59
+ O instalador faz 2 passos:
60
+ 1. `pi install git:github.com/by-lua/lspec-subagents` — instala a extensão standalone
61
+ 2. Copia os 9 agent `.md` files pra `~/.pi/agents/` + cria `lspec-model-config.json` (se não existir)
62
+
63
+ Requer: `git`, `pi` (PI.dev).
64
+
65
+ ### Dependências Opcionais (Recomendadas)
66
+
67
+ Os agentes usam estas ferramentas PI quando disponíveis:
68
+
69
+ ```bash
70
+ pi install npm:pi-cymbal # Code navigation (explorer, oracle, fixer, orchestrator)
71
+ pi install npm:@davehardy20/pi-lsp-tools # LSP-powered code tools (explorer, fixer, oracle)
72
+ pi install npm:pi-mermaid # Mermaid diagrams (orchestrator, designer)
73
+ ```
74
+
75
+ Cada agente usa as ferramentas disponíveis com fallback para grep/read se o pacote não estiver instalado.
76
+
77
+ ### Atualizar
78
+
79
+ ```bash
80
+ curl -fsSL https://raw.githubusercontent.com/by-lua/lspec-subagents/main/update.sh | bash
81
+ ```
82
+
83
+ ### Desinstalar
84
+
85
+ ```bash
86
+ curl -fsSL https://raw.githubusercontent.com/by-lua/lspec-subagents/main/uninstall.sh | bash
87
+ ```
88
+
89
+ Remove extensão + 9 agent .md files. Preserva `lspec-model-config.json`.
90
+
91
+ ### Instalação manual
92
+
93
+ ```bash
94
+ pi install git:github.com/by-lua/lspec-subagents # extensão standalone
95
+ git clone --depth 1 https://github.com/by-lua/lspec-subagents.git /tmp/lspec-sub
96
+ cp /tmp/lspec-sub/.pi/agents/*.md ~/.pi/agents/ # .md overrides
97
+ cp /tmp/lspec-sub/lspec-model-config.example.json ~/.pi/agent/lspec-model-config.json
98
+ rm -rf /tmp/lspec-sub
99
+ ```
100
+
101
+ ## Como usar
102
+
103
+ No PI, use o tool `Agent` com o tipo do agente:
104
+
105
+ ```
106
+ Agent(agent_type="explorer", prompt="Find all React components in src/")
107
+ Agent(agent_type="orchestrator", prompt="Run L-Spec Discovery for the auth feature")
108
+ ```
109
+
110
+ Ou customize agentes `.md` em `.pi/agents/` para sobrescrever os defaults.
111
+
112
+ ## Diferenças do pi-subagents original
113
+
114
+ - ✅ **9 agentes L-Spec** embutidos no código (não override por .md)
115
+ - ✅ **Zero agentes padrão** — general-purpose/Explore/Plan removidos do source
116
+ - ✅ **Placeholders de modelo** (`{{model:orchestrator}}`)
117
+ - ✅ **Config JSON centralizada** (projeto + global + defaults)
118
+ - ✅ **Fallback** mudou de `general-purpose` pra `orchestrator`
119
+ - ✅ **Extensão standalone** — não depende do pacote npm @tintinweb
120
+
121
+ ## Licença
122
+
123
+ MIT — fork de `@tintinweb/pi-subagents` (MIT).
@@ -0,0 +1,108 @@
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
+ import type { Model } from "@mariozechner/pi-ai";
9
+ import type { AgentSession, ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
10
+ import { type ToolActivity } from "./agent-runner.js";
11
+ import type { AgentInvocation, AgentRecord, IsolationMode, SubagentType, ThinkingLevel } from "./types.js";
12
+ export type OnAgentComplete = (record: AgentRecord) => void;
13
+ export type OnAgentStart = (record: AgentRecord) => void;
14
+ export type OnAgentCompact = (record: AgentRecord, info: CompactionInfo) => void;
15
+ export type CompactionInfo = {
16
+ reason: "manual" | "threshold" | "overflow";
17
+ tokensBefore: number;
18
+ };
19
+ interface SpawnOptions {
20
+ description: string;
21
+ model?: Model<any>;
22
+ maxTurns?: number;
23
+ isolated?: boolean;
24
+ inheritContext?: boolean;
25
+ thinkingLevel?: ThinkingLevel;
26
+ isBackground?: boolean;
27
+ /**
28
+ * Skip the maxConcurrent queue check for this spawn — start immediately even
29
+ * if the configured concurrency limit would otherwise queue it. Used by the
30
+ * scheduler so a fired job can't be deferred past its trigger window.
31
+ */
32
+ bypassQueue?: boolean;
33
+ /** Isolation mode — "worktree" creates a temp git worktree for the agent. */
34
+ isolation?: IsolationMode;
35
+ /** Resolved invocation snapshot captured for UI display. */
36
+ invocation?: AgentInvocation;
37
+ /** Parent abort signal — when aborted, the subagent is also stopped. */
38
+ signal?: AbortSignal;
39
+ /** Called on tool start/end with activity info (for streaming progress to UI). */
40
+ onToolActivity?: (activity: ToolActivity) => void;
41
+ /** Called on streaming text deltas from the assistant response. */
42
+ onTextDelta?: (delta: string, fullText: string) => void;
43
+ /** Called when the agent session is created (for accessing session stats). */
44
+ onSessionCreated?: (session: AgentSession) => void;
45
+ /** Called at the end of each agentic turn with the cumulative count. */
46
+ onTurnEnd?: (turnCount: number) => void;
47
+ /** Called once per assistant message_end with that message's usage delta. */
48
+ onAssistantUsage?: (usage: {
49
+ input: number;
50
+ output: number;
51
+ cacheWrite: number;
52
+ }) => void;
53
+ /** Called when the session successfully compacts. */
54
+ onCompaction?: (info: CompactionInfo) => void;
55
+ }
56
+ export declare class AgentManager {
57
+ private agents;
58
+ private cleanupInterval;
59
+ private onComplete?;
60
+ private onStart?;
61
+ private onCompact?;
62
+ private maxConcurrent;
63
+ /** Queue of background agents waiting to start. */
64
+ private queue;
65
+ /** Number of currently running background agents. */
66
+ private runningBackground;
67
+ constructor(onComplete?: OnAgentComplete, maxConcurrent?: number, onStart?: OnAgentStart, onCompact?: OnAgentCompact);
68
+ /** Update the max concurrent background agents limit. */
69
+ setMaxConcurrent(n: number): void;
70
+ getMaxConcurrent(): number;
71
+ /**
72
+ * Spawn an agent and return its ID immediately (for background use).
73
+ * If the concurrency limit is reached, the agent is queued.
74
+ */
75
+ spawn(pi: ExtensionAPI, ctx: ExtensionContext, type: SubagentType, prompt: string, options: SpawnOptions): string;
76
+ /** Actually start an agent (called immediately or from queue drain). */
77
+ private startAgent;
78
+ /** Start queued agents up to the concurrency limit. */
79
+ private drainQueue;
80
+ /**
81
+ * Spawn an agent and wait for completion (foreground use).
82
+ * Foreground agents bypass the concurrency queue.
83
+ */
84
+ spawnAndWait(pi: ExtensionAPI, ctx: ExtensionContext, type: SubagentType, prompt: string, options: Omit<SpawnOptions, "isBackground">): Promise<AgentRecord>;
85
+ /**
86
+ * Resume an existing agent session with a new prompt.
87
+ */
88
+ resume(id: string, prompt: string, signal?: AbortSignal): Promise<AgentRecord | undefined>;
89
+ getRecord(id: string): AgentRecord | undefined;
90
+ listAgents(): AgentRecord[];
91
+ abort(id: string): boolean;
92
+ /** Dispose a record's session and remove it from the map. */
93
+ private removeRecord;
94
+ private cleanup;
95
+ /**
96
+ * Remove all completed/stopped/errored records immediately.
97
+ * Called on session start/switch so tasks from a prior session don't persist.
98
+ */
99
+ clearCompleted(): void;
100
+ /** Whether any agents are still running or queued. */
101
+ hasRunning(): boolean;
102
+ /** Abort all running and queued agents immediately. */
103
+ abortAll(): number;
104
+ /** Wait for all running and queued agents to complete (including queued ones). */
105
+ waitForAll(): Promise<void>;
106
+ dispose(): void;
107
+ }
108
+ export {};
@@ -0,0 +1,391 @@
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
+ import { randomUUID } from "node:crypto";
9
+ import { resumeAgent, runAgent } from "./agent-runner.js";
10
+ import { addUsage } from "./usage.js";
11
+ import { cleanupWorktree, createWorktree, pruneWorktrees, } from "./worktree.js";
12
+ /** Default max concurrent background agents. */
13
+ const DEFAULT_MAX_CONCURRENT = 4;
14
+ export class AgentManager {
15
+ agents = new Map();
16
+ cleanupInterval;
17
+ onComplete;
18
+ onStart;
19
+ onCompact;
20
+ maxConcurrent;
21
+ /** Queue of background agents waiting to start. */
22
+ queue = [];
23
+ /** Number of currently running background agents. */
24
+ runningBackground = 0;
25
+ constructor(onComplete, maxConcurrent = DEFAULT_MAX_CONCURRENT, onStart, onCompact) {
26
+ this.onComplete = onComplete;
27
+ this.onStart = onStart;
28
+ this.onCompact = onCompact;
29
+ this.maxConcurrent = maxConcurrent;
30
+ // Cleanup completed agents after 10 minutes (but keep sessions for resume)
31
+ this.cleanupInterval = setInterval(() => this.cleanup(), 60_000);
32
+ this.cleanupInterval.unref();
33
+ }
34
+ /** Update the max concurrent background agents limit. */
35
+ setMaxConcurrent(n) {
36
+ this.maxConcurrent = Math.max(1, n);
37
+ // Start queued agents if the new limit allows
38
+ this.drainQueue();
39
+ }
40
+ getMaxConcurrent() {
41
+ return this.maxConcurrent;
42
+ }
43
+ /**
44
+ * Spawn an agent and return its ID immediately (for background use).
45
+ * If the concurrency limit is reached, the agent is queued.
46
+ */
47
+ spawn(pi, ctx, type, prompt, options) {
48
+ const id = randomUUID().slice(0, 17);
49
+ const abortController = new AbortController();
50
+ const record = {
51
+ id,
52
+ type,
53
+ description: options.description,
54
+ status: options.isBackground ? "queued" : "running",
55
+ toolUses: 0,
56
+ startedAt: Date.now(),
57
+ abortController,
58
+ lifetimeUsage: { input: 0, output: 0, cacheWrite: 0 },
59
+ compactionCount: 0,
60
+ invocation: options.invocation,
61
+ };
62
+ this.agents.set(id, record);
63
+ const args = { pi, ctx, type, prompt, options };
64
+ if (options.isBackground && !options.bypassQueue && this.runningBackground >= this.maxConcurrent) {
65
+ // Queue it — will be started when a running agent completes
66
+ this.queue.push({ id, args });
67
+ return id;
68
+ }
69
+ // startAgent can throw (e.g. strict worktree-isolation failure) — clean
70
+ // up the record so callers don't see an orphan in `listAgents()`.
71
+ try {
72
+ this.startAgent(id, record, args);
73
+ }
74
+ catch (err) {
75
+ this.agents.delete(id);
76
+ throw err;
77
+ }
78
+ return id;
79
+ }
80
+ /** Actually start an agent (called immediately or from queue drain). */
81
+ startAgent(id, record, { pi, ctx, type, prompt, options }) {
82
+ // Worktree isolation: try to create a temporary git worktree. Strict —
83
+ // fail loud if not possible (no silent fallback to main tree). Done
84
+ // BEFORE state mutation so a throw doesn't leave the record half-running.
85
+ let worktreeCwd;
86
+ if (options.isolation === "worktree") {
87
+ const wt = createWorktree(ctx.cwd, id);
88
+ if (!wt) {
89
+ throw new Error('Cannot run with isolation: "worktree" — not a git repo, no commits yet, or `git worktree add` failed. ' +
90
+ 'Initialize git and commit at least once, or omit `isolation`.');
91
+ }
92
+ record.worktree = wt;
93
+ worktreeCwd = wt.path;
94
+ }
95
+ record.status = "running";
96
+ record.startedAt = Date.now();
97
+ if (options.isBackground)
98
+ this.runningBackground++;
99
+ this.onStart?.(record);
100
+ // Wire parent abort signal to stop the subagent when the parent is interrupted
101
+ let detachParentSignal;
102
+ if (options.signal) {
103
+ const onParentAbort = () => this.abort(id);
104
+ options.signal.addEventListener("abort", onParentAbort, { once: true });
105
+ detachParentSignal = () => options.signal.removeEventListener("abort", onParentAbort);
106
+ }
107
+ const detach = () => { detachParentSignal?.(); detachParentSignal = undefined; };
108
+ const promise = runAgent(ctx, type, prompt, {
109
+ pi,
110
+ agentId: id,
111
+ model: options.model,
112
+ maxTurns: options.maxTurns,
113
+ isolated: options.isolated,
114
+ inheritContext: options.inheritContext,
115
+ thinkingLevel: options.thinkingLevel,
116
+ cwd: worktreeCwd,
117
+ signal: record.abortController.signal,
118
+ onToolActivity: (activity) => {
119
+ if (activity.type === "end")
120
+ record.toolUses++;
121
+ options.onToolActivity?.(activity);
122
+ },
123
+ onTurnEnd: options.onTurnEnd,
124
+ onTextDelta: options.onTextDelta,
125
+ onAssistantUsage: (usage) => {
126
+ addUsage(record.lifetimeUsage, usage);
127
+ options.onAssistantUsage?.(usage);
128
+ },
129
+ onCompaction: (info) => {
130
+ record.compactionCount++;
131
+ this.onCompact?.(record, info);
132
+ options.onCompaction?.(info);
133
+ },
134
+ onSessionCreated: (session) => {
135
+ record.session = session;
136
+ // Flush any steers that arrived before the session was ready
137
+ if (record.pendingSteers?.length) {
138
+ for (const msg of record.pendingSteers) {
139
+ session.steer(msg).catch(() => { });
140
+ }
141
+ record.pendingSteers = undefined;
142
+ }
143
+ options.onSessionCreated?.(session);
144
+ },
145
+ })
146
+ .then(({ responseText, session, aborted, steered }) => {
147
+ // Don't overwrite status if externally stopped via abort()
148
+ if (record.status !== "stopped") {
149
+ record.status = aborted ? "aborted" : steered ? "steered" : "completed";
150
+ }
151
+ record.result = responseText;
152
+ record.session = session;
153
+ record.completedAt ??= Date.now();
154
+ detach();
155
+ // Final flush of streaming output file
156
+ if (record.outputCleanup) {
157
+ try {
158
+ record.outputCleanup();
159
+ }
160
+ catch { /* ignore */ }
161
+ record.outputCleanup = undefined;
162
+ }
163
+ // Clean up worktree if used
164
+ if (record.worktree) {
165
+ const wtResult = cleanupWorktree(ctx.cwd, record.worktree, options.description);
166
+ record.worktreeResult = wtResult;
167
+ if (wtResult.hasChanges && wtResult.branch) {
168
+ record.result = (record.result ?? "") +
169
+ `\n\n---\nChanges saved to branch \`${wtResult.branch}\`. Merge with: \`git merge ${wtResult.branch}\``;
170
+ }
171
+ }
172
+ if (options.isBackground) {
173
+ this.runningBackground--;
174
+ try {
175
+ this.onComplete?.(record);
176
+ }
177
+ catch { /* ignore completion side-effect errors */ }
178
+ this.drainQueue();
179
+ }
180
+ return responseText;
181
+ })
182
+ .catch((err) => {
183
+ // Don't overwrite status if externally stopped via abort()
184
+ if (record.status !== "stopped") {
185
+ record.status = "error";
186
+ }
187
+ record.error = err instanceof Error ? err.message : String(err);
188
+ record.completedAt ??= Date.now();
189
+ detach();
190
+ // Final flush of streaming output file on error
191
+ if (record.outputCleanup) {
192
+ try {
193
+ record.outputCleanup();
194
+ }
195
+ catch { /* ignore */ }
196
+ record.outputCleanup = undefined;
197
+ }
198
+ // Best-effort worktree cleanup on error
199
+ if (record.worktree) {
200
+ try {
201
+ const wtResult = cleanupWorktree(ctx.cwd, record.worktree, options.description);
202
+ record.worktreeResult = wtResult;
203
+ }
204
+ catch { /* ignore cleanup errors */ }
205
+ }
206
+ if (options.isBackground) {
207
+ this.runningBackground--;
208
+ this.onComplete?.(record);
209
+ this.drainQueue();
210
+ }
211
+ return "";
212
+ });
213
+ record.promise = promise;
214
+ }
215
+ /** Start queued agents up to the concurrency limit. */
216
+ drainQueue() {
217
+ while (this.queue.length > 0 && this.runningBackground < this.maxConcurrent) {
218
+ const next = this.queue.shift();
219
+ const record = this.agents.get(next.id);
220
+ if (!record || record.status !== "queued")
221
+ continue;
222
+ try {
223
+ this.startAgent(next.id, record, next.args);
224
+ }
225
+ catch (err) {
226
+ // Late failure (e.g. strict worktree-isolation) — surface on the record
227
+ // so the user/agent can see it via /agents, then keep draining.
228
+ record.status = "error";
229
+ record.error = err instanceof Error ? err.message : String(err);
230
+ record.completedAt = Date.now();
231
+ this.onComplete?.(record);
232
+ }
233
+ }
234
+ }
235
+ /**
236
+ * Spawn an agent and wait for completion (foreground use).
237
+ * Foreground agents bypass the concurrency queue.
238
+ */
239
+ async spawnAndWait(pi, ctx, type, prompt, options) {
240
+ const id = this.spawn(pi, ctx, type, prompt, { ...options, isBackground: false });
241
+ const record = this.agents.get(id);
242
+ await record.promise;
243
+ return record;
244
+ }
245
+ /**
246
+ * Resume an existing agent session with a new prompt.
247
+ */
248
+ async resume(id, prompt, signal) {
249
+ const record = this.agents.get(id);
250
+ if (!record?.session)
251
+ return undefined;
252
+ record.status = "running";
253
+ record.startedAt = Date.now();
254
+ record.completedAt = undefined;
255
+ record.result = undefined;
256
+ record.error = undefined;
257
+ try {
258
+ const responseText = await resumeAgent(record.session, prompt, {
259
+ onToolActivity: (activity) => {
260
+ if (activity.type === "end")
261
+ record.toolUses++;
262
+ },
263
+ onAssistantUsage: (usage) => {
264
+ addUsage(record.lifetimeUsage, usage);
265
+ },
266
+ onCompaction: (info) => {
267
+ record.compactionCount++;
268
+ this.onCompact?.(record, info);
269
+ },
270
+ signal,
271
+ });
272
+ record.status = "completed";
273
+ record.result = responseText;
274
+ record.completedAt = Date.now();
275
+ }
276
+ catch (err) {
277
+ record.status = "error";
278
+ record.error = err instanceof Error ? err.message : String(err);
279
+ record.completedAt = Date.now();
280
+ }
281
+ return record;
282
+ }
283
+ getRecord(id) {
284
+ return this.agents.get(id);
285
+ }
286
+ listAgents() {
287
+ return [...this.agents.values()].sort((a, b) => b.startedAt - a.startedAt);
288
+ }
289
+ abort(id) {
290
+ const record = this.agents.get(id);
291
+ if (!record)
292
+ return false;
293
+ // Remove from queue if queued
294
+ if (record.status === "queued") {
295
+ this.queue = this.queue.filter(q => q.id !== id);
296
+ record.status = "stopped";
297
+ record.completedAt = Date.now();
298
+ return true;
299
+ }
300
+ if (record.status !== "running")
301
+ return false;
302
+ record.abortController?.abort();
303
+ record.status = "stopped";
304
+ record.completedAt = Date.now();
305
+ return true;
306
+ }
307
+ /** Dispose a record's session and remove it from the map. */
308
+ removeRecord(id, record) {
309
+ record.session?.dispose?.();
310
+ record.session = undefined;
311
+ this.agents.delete(id);
312
+ }
313
+ cleanup() {
314
+ const cutoff = Date.now() - 10 * 60_000;
315
+ for (const [id, record] of this.agents) {
316
+ if (record.status === "running" || record.status === "queued")
317
+ continue;
318
+ if ((record.completedAt ?? 0) >= cutoff)
319
+ continue;
320
+ this.removeRecord(id, record);
321
+ }
322
+ }
323
+ /**
324
+ * Remove all completed/stopped/errored records immediately.
325
+ * Called on session start/switch so tasks from a prior session don't persist.
326
+ */
327
+ clearCompleted() {
328
+ for (const [id, record] of this.agents) {
329
+ if (record.status === "running" || record.status === "queued")
330
+ continue;
331
+ this.removeRecord(id, record);
332
+ }
333
+ }
334
+ /** Whether any agents are still running or queued. */
335
+ hasRunning() {
336
+ return [...this.agents.values()].some(r => r.status === "running" || r.status === "queued");
337
+ }
338
+ /** Abort all running and queued agents immediately. */
339
+ abortAll() {
340
+ let count = 0;
341
+ // Clear queued agents first
342
+ for (const queued of this.queue) {
343
+ const record = this.agents.get(queued.id);
344
+ if (record) {
345
+ record.status = "stopped";
346
+ record.completedAt = Date.now();
347
+ count++;
348
+ }
349
+ }
350
+ this.queue = [];
351
+ // Abort running agents
352
+ for (const record of this.agents.values()) {
353
+ if (record.status === "running") {
354
+ record.abortController?.abort();
355
+ record.status = "stopped";
356
+ record.completedAt = Date.now();
357
+ count++;
358
+ }
359
+ }
360
+ return count;
361
+ }
362
+ /** Wait for all running and queued agents to complete (including queued ones). */
363
+ async waitForAll() {
364
+ // Loop because drainQueue respects the concurrency limit — as running
365
+ // agents finish they start queued ones, which need awaiting too.
366
+ while (true) {
367
+ this.drainQueue();
368
+ const pending = [...this.agents.values()]
369
+ .filter(r => r.status === "running" || r.status === "queued")
370
+ .map(r => r.promise)
371
+ .filter(Boolean);
372
+ if (pending.length === 0)
373
+ break;
374
+ await Promise.allSettled(pending);
375
+ }
376
+ }
377
+ dispose() {
378
+ clearInterval(this.cleanupInterval);
379
+ // Clear queue
380
+ this.queue = [];
381
+ for (const record of this.agents.values()) {
382
+ record.session?.dispose();
383
+ }
384
+ this.agents.clear();
385
+ // Prune any orphaned git worktrees (crash recovery)
386
+ try {
387
+ pruneWorktrees(process.cwd());
388
+ }
389
+ catch { /* ignore */ }
390
+ }
391
+ }