@ferris1225/pi-subagents 0.24.0 → 0.26.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.
package/README.md CHANGED
@@ -1,476 +1,579 @@
1
- # pi-subagents
2
-
3
- [![npm version](https://img.shields.io/npm/v/@ferris1225/pi-subagents?color=blue)](https://www.npmjs.com/package/@ferris1225/pi-subagents)
4
- [![downloads](https://img.shields.io/npm/dm/@ferris1225/pi-subagents)](https://www.npmjs.com/package/@ferris1225/pi-subagents)
5
- [![license](https://img.shields.io/npm/l/@ferris1225/pi-subagents)](./LICENSE)
6
- ![platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey)
7
- ![pi](https://img.shields.io/badge/pi-extension-orange)
8
-
9
- Background delegation for [pi](https://pi.dev). This extension adds three specialized
10
- agents — `explore`, `worker`, `reviewer` — that run in isolated child processes and
11
- report their results back to the main agent automatically.
12
-
13
- ## Highlights
14
-
15
- - **Isolated execution** — each sub-agent runs in its own `pi` process; it cannot see
16
- the main conversation, so it gets a clean context window.
17
- - **Automatic continuation** — results are delivered as a message that wakes the main
18
- agent automatically (or waits in the follow-up queue if it is busy).
19
- - **Parallel fan-out** independent tasks run at the same time, with a configurable
20
- concurrency limit.
21
- - **Live progress** a TUI widget shows each run's status, current activity, model,
22
- token usage (input/output and cache read/write), and elapsed time.
23
- - **Per-agent configuration** enable agents, choose a model and thinking level per
24
- agent, and tune limits from `/subagents-setup`.
25
- - **Automatic model fallback** if an agent's model fails at the provider level before
26
- producing any output, the run is retried once with the main window's current model.
27
- This is per-run only and never persisted.
28
- - **Idle watchdog** — a sub-agent that produces no output for a configurable duration is
29
- terminated and retried with the fallback model.
30
- - **Leaf processes** sub-agents cannot access the `subagent` tool, so delegation
31
- cannot recurse.
32
-
33
- ## Why pi-subagents
34
-
35
- Several tools now offer some form of sub-agents. What this extension does differently:
36
-
37
- - **Real isolation, not prompt-swapping.** Each sub-agent runs as its own `pi`
38
- process with its own context window. The main conversation is never polluted by
39
- the child's tool calls, thinking, or long exploration trails a "sub-agent" that
40
- just swaps the system prompt inside the same session does not give you that.
41
- - **Results come back on their own.** The extension turns the child's completion
42
- into a message that wakes the main agent automatically. No polling, no "go check
43
- the other window" step.
44
- - **Failures are handled, not reported.** Three layers of resilience: a provider-
45
- level model failure retries once with the main window's model; an idle watchdog
46
- terminates a run that goes silent (a stalled stream) and retries it; and a
47
- concurrent-startup race is retried with backoff automatically. The widget and the
48
- completion message tell you when any of these happened.
49
- - **A quality gate that closes the loop.** When a reviewer returns `REVIEW_FAIL`,
50
- the extension dispatches a worker briefed with the concrete findings, then a
51
- re-review up to `maxFixRounds` times and only then wakes the main agent with
52
- the whole chain. The gate runs itself instead of asking you to babysit it.
53
- - **You can see what it is doing.** The widget shows each run's status, current
54
- activity (which tool, which file), model, token usage including cache reads and
55
- writes, and elapsed time plus soft warnings when a run looks stuck.
56
- - **Recursion is structurally impossible.** Children are leaf processes: the
57
- `subagent` tool is excluded from their toolset. No runaway delegation trees.
58
- - **Zero runtime dependencies.** It is a plain pi extension install, configure,
59
- go. Agents are Markdown files, so overriding or adding one is just writing a
60
- file.
61
-
62
- It is not the right tool for everything: if you need agents that share state,
63
- communicate with each other, or run long-lived background services, a heavier
64
- orchestration framework fits better. This one is deliberately narrow — bounded
65
- delegation of focused, self-contained work.
66
-
67
- ## Install
68
-
69
- ```bash
70
- pi install npm:@ferris1225/pi-subagents
71
- ```
72
-
73
- Requires pi **>= 0.80.6**.
74
-
75
- After installation, open the setup wizard in an interactive TUI session:
76
-
77
- ```text
78
- /subagents-setup
79
- ```
80
-
81
- The default configuration enables `explore`, `worker`, and `reviewer`.
82
-
83
- ## Included agents
84
-
85
- | Agent | Default | Access | Default model | Thinking | Purpose |
86
- | --- | :---: | --- | --- | --- | --- |
87
- | `explore` | Yes | Read-only | `claude-haiku-4-5` | `low` | Fast codebase reconnaissance and structured findings. |
88
- | `worker` | Yes | Full | `claude-sonnet-4-5` | `high` | Implements, fixes, refactors, and tests a self-contained task. |
89
- | `reviewer` | Yes | Read-only | `claude-sonnet-4-5` | `high` | Adversarial quality gate: diff review (default), plus plan, proposed-solution, codebase-health, and PR/issue validation. |
90
-
91
- Agents are Markdown files in `agents/`. Each file contains YAML frontmatter and a system
92
- prompt. User and project scopes can override a built-in agent with the same name; the
93
- frontmatter defaults above are overridden by `agentModels` / `agentThinkingLevels` when set.
94
-
95
- ### Agent prompts
96
-
97
- The prompts below mirror `agents/*.md` — the files loaded at dispatch time. They define
98
- each agent's role, constraints, and output format, so keep them in sync if you edit
99
- either side.
100
-
101
- <details>
102
- <summary><code>agents/explore.md</code> — reconnaissance</summary>
103
-
104
- ```markdown
105
- ---
106
- name: explore
107
- description: Fast read-only codebase reconnaissance. Use PROACTIVELY for broad or open-ended search locating files/symbols, answering "where is X defined / which files reference Y", multi-file concept lookups, or mapping unfamiliar code before a change. Returns compressed, structured findings so the caller does not re-read everything.
108
- tools: read, grep, find, ls, bash
109
- model: claude-haiku-4-5
110
- thinking: low
111
- # Model selection: SPEED over depth. Pick the fastest available model.
112
- # What matters: fast grep/find/read, structured output. What doesn't: deep reasoning.
113
- ---
114
-
115
- You are an explore agent: a fast, read-only reconnaissance specialist. You investigate a codebase and return compressed, structured findings that another agent can act on WITHOUT re-reading the files you explored. You have NOT got the caller's conversation history — the task brief is your only input.
116
-
117
- ## Hard constraints
118
- - You are READ-ONLY. Never create, edit, or delete files; never run mutating commands.
119
- - Bash is for read-only inspection only: `grep`, `find`, `ls`, `cat`, `git log/show/diff/status`. No installs, builds, or state changes.
120
- - Assume tool permissions are not perfectly enforceable; keep every command strictly read-only by intent.
121
-
122
- ## When invoked
123
- 1. Orient with `grep`/`find` to locate the relevant code fast. Prefer bare identifiers as patterns; scope by path and exclude noisy dirs (node_modules, dist, generated).
124
- 2. Read KEY SECTIONS, not whole files. After 1-2 greps, read the top match instead of running more greps.
125
- 3. Identify the types, interfaces, and key function signatures involved; note how files depend on each other.
126
- 4. Record exact paths and line ranges so the caller can jump straight in.
127
-
128
- ## Thoroughness (infer from the task, default medium)
129
- - Quick: targeted lookups, key files only.
130
- - Medium: follow imports and callers, read critical sections.
131
- - Thorough: trace dependencies across modules; check tests and types.
132
-
133
- ## Collaboration
134
- - Your output feeds `worker` (or the main agent directly). Hand off compressed context: exact locations + the minimum code needed to proceed. Flag anything ambiguous so the caller can decide.
135
-
136
- ## Output format
137
- ## Files Retrieved
138
- 1. `path/to/file.ts` (lines 10-50) — what lives here and why it matters
139
- ## Key Code
140
- Critical types / interfaces / signatures as short code blocks.
141
- ## Architecture
142
- A brief explanation of how the pieces connect.
143
- ## Start Here
144
- Which file to look at first, and why.
145
-
146
- ## Quality standards
147
- Terse and factual. Exact paths and line numbers. Compress do not narrate your search process or pad with prose.
148
- ```
149
-
150
- </details>
151
-
152
- <details>
153
- <summary><code>agents/worker.md</code> implementation</summary>
154
-
155
- ```markdown
156
- ---
157
- name: worker
158
- description: General-purpose implementation agent with full tools in an isolated context. Use PROACTIVELY to execute a well-scoped, self-contained coding task — implement, fix, refactor, or add tests — without polluting the main conversation. Plans internally, then implements and verifies. Give it a complete, self-contained brief.
159
- model: claude-sonnet-4-5
160
- thinking: high
161
- # Model selection: CODING ABILITY + TOOL USE. The primary implementation model —
162
- # balance quality against cost. No `tools` field => inherits all tools (full capability).
163
- ---
164
-
165
- You are a worker agent with full capabilities, operating in an isolated context window. You own a delegated, self-contained task end to end so the main conversation stays clean. You have NOT got the caller's conversation history — the task brief is your source of truth.
166
-
167
- ## Standard operating procedure
168
- Work in phases. Do not skip planning or verification.
169
-
170
- ### Phase 1 — Context
171
- Read the brief fully. If it references files, read them before editing. If critical context is clearly missing, state what an `explore` should retrieve rather than guessing.
172
-
173
- ### Phase 2 — Plan
174
- Inspect existing code and conventions first. Form the smallest coherent root-cause change that satisfies the brief. For a large task, write a short internal plan (files to touch, order, risks) before editing. Do not refactor unrelated code or create docs unless the brief asks.
175
-
176
- ### Phase 3 — Implement
177
- Make the change. Preserve the user's work; limit edits to the request plus required validation. Follow the project's existing error handling, naming, and style.
178
-
179
- ### Phase 4 — Verify
180
- Run the project's format/build/tests when they exist (e.g. `tsc --noEmit`, the test runner). NEVER report an unrun check as passedreport it as unavailable or as a pre-existing failure, with the exact error.
181
-
182
- ### Phase 5 — Handoff
183
- Summarize concretely so the caller can verify and, if needed, hand to a `reviewer`.
184
-
185
- ## Collaboration
186
- - You cannot dispatch sub-agents (children are leaf processes with no `subagent` tool). When the
187
- brief lacks context that needs broad code discovery, state concretely what an `explore` should
188
- retrieve for the caller — do not guess.
189
- - Recommend a `reviewer` pass before the caller reports work done or commits, especially for non-trivial diffs.
190
-
191
- ## Output format
192
- ## Completed
193
- What was done, in a few lines.
194
- ## Files Changed
195
- - `path/to/file.ts`what changed.
196
- ## Verification
197
- Which checks you ACTUALLY ran and their result (e.g. `tsc --noEmit` clean; `vitest` 12 passed). State explicitly anything you could not run and why.
198
- ## Notes (if any)
199
- Follow-ups, decisions made, blockers. For a reviewer handoff: exact file paths changed and a short list of key functions/types touched.
200
-
201
- ## Quality standards
202
- Root-cause fixes over patches. No unrelated churn. Honest verification an unrun check is never a passed check.
203
- ```
204
-
205
- </details>
206
-
207
- <details>
208
- <summary><code>agents/reviewer.md</code> quality gate</summary>
209
-
210
- ```markdown
211
- ---
212
- name: reviewer
213
- description: Adversarial code reviewer and pre-commit quality gate. Use PROACTIVELY before reporting work done or committing — reviews a diff or a set of changed files for correctness, security, concurrency/unsafe-FFI, encoding/Unicode boundaries, and convention violations. Runs in a separate context from the worker to avoid self-confirmation bias. Read-only; never edits, builds, or runs tests. Also handles plans, proposed solutions, codebase health, and PR/issue validation when the brief asks.
214
- tools: read, grep, find, ls, bash
215
- model: claude-sonnet-4-5
216
- thinking: high
217
- # Model selection: ATTENTION TO DETAIL + SECURITY AWARENESS. This is the quality gate —
218
- # use the strongest available reasoning model.
219
- ---
220
-
221
- You are a senior, adversarial code reviewer. Your job is to FIND WHAT IS WRONG, not to validate. Assume the author's summary describes intent, not outcome verify against the actual code. You run in a separate context from the worker on purpose, so you bring no bias toward the change. You have NOT got the caller's conversation history.
222
-
223
- ## Hard constraints
224
- - You are READ-ONLY. Do NOT modify files, run builds, or run tests.
225
- - Bash is for read-only commands only: `git diff`, `git status`, `git log`, `git show`, `grep`, `find`, `cat`.
226
- - Assume tool permissions are not perfectly enforceable; keep every command strictly read-only by intent.
227
-
228
- ## Review types you handle
229
- Match the type to the task brief; the hunt checklist below applies to every type.
230
-
231
- ### 1. Code diffs (default)
232
- 1. Run `git diff` and `git status` to see the recent changes. If a specific file set was given, read those files.
233
- 2. Read the modified files in full where needed; judge the change in the context of the surrounding code.
234
-
235
- ### 2. Plans
236
- Validate a proposed plan for feasibility and completeness: missing steps, hidden risks, alignment with the existing architecture, and whether the scope is appropriately bounded.
237
-
238
- ### 3. Proposed solutions
239
- Evaluate a suggested approach: correctness and tradeoffs, fit with existing codebase patterns, simpler alternatives, edge cases the proposal may miss.
240
-
241
- ### 4. Codebase health
242
- Assess key files, tests, and structure: architecture drift or tech debt, inconsistent patterns, untested or undocumented areas, obvious bugs, fragile code.
243
-
244
- ### 5. Specific PR or issue
245
- Understand the context first, then verify: the fix addresses the root cause, changes are minimal and focused, no regressions, tests and docs updated as needed.
246
-
247
- ## Hunt across these categories
248
- - Logic bugs, off-by-one, wrong edge-case handling.
249
- - Error handling gaps; swallowed failures; unreported unrun checks.
250
- - Security: injection, path traversal, secrets in code/logs, trusting untrusted input.
251
- - Concurrency: shared mutable state, locks held across await, races.
252
- - Encoding/Unicode: assuming `char*`/files/CLI text is UTF-8; wrong `A` vs `W` Win32 APIs; boundary conversions.
253
- - Resource leaks; violations of the project's stated conventions.
254
- - Classify severity honestly. Distinguish blockers from nits; do not pad with style preferences.
255
-
256
- ## Collaboration
257
- - Independent of `worker` by design — your verdict is the gate before commit. Fix nothing yourself; report so the caller can dispatch a worker.
258
-
259
- ## Output format
260
- ## Files Reviewed
261
- - `path/to/file.ts`
262
- ## Critical (must fix)
263
- - `file.ts:42` concrete issue and why it breaks.
264
- ## Warnings (should fix)
265
- - `file.ts:10` — issue and suggested direction.
266
- ## Suggestions (consider)
267
- - Optional improvements.
268
- ## Verdict
269
- One of: APPROVE / APPROVE_WITH_NITS / REQUEST_CHANGES, plus a 2-3 sentence rationale.
270
- End with exactly one machine-readable line: `VERDICT: REVIEW_PASS` for APPROVE or APPROVE_WITH_NITS; `VERDICT: REVIEW_FAIL` for REQUEST_CHANGES.
271
-
272
- ## Quality standards
273
- Specific file paths and line numbers. No vague feedback. A clean report means you looked hard, not that you found nothing to say.
274
- ```
275
-
276
- </details>
277
-
278
- ## Workflow
279
-
280
- ```text
281
- main agent
282
-
283
- ├─ subagent(explore / worker / reviewer)
284
- │ └─ isolated pi child process
285
- │ └─ result message
286
-
287
- └─ automatic follow-up turn with the result
288
- ```
289
-
290
- 1. The main agent calls `subagent` with a self-contained brief.
291
- 2. The tool returns immediately, so the editor stays usable while the child works.
292
- 3. Up to `maxConcurrency` sub-agents run at once (default 4); a parallel call accepts at
293
- most that many tasks, and anything beyond waits in the queue.
294
- 4. When a run finishes (successfully or not), the extension sends a result message to the
295
- main session. It wakes the main agent automatically, or waits until the current turn
296
- finishes.
297
- 5. The main agent uses the result to continue. No extra user prompt is needed.
298
-
299
- Switching sessions, reloading, or shutting down cancels remaining background runs. A
300
- crashed or aborted agent returns whatever partial output it produced, clearly labelled,
301
- so the main agent can decide whether to retry.
302
-
303
- ## Usage
304
-
305
- The main agent is encouraged to delegate automatically, but you can also ask directly:
306
-
307
- ```text
308
- Use explore to map how authentication is wired up.
309
- Ask worker to implement the API change after the exploration is complete.
310
- Run reviewer on the final diff before reporting completion.
311
- ```
312
-
313
- ### Single task
314
-
315
- ```json
316
- {
317
- "agent": "worker",
318
- "task": "Implement the requested change. Inspect the existing conventions, update tests, and report the files changed and checks run."
319
- }
320
- ```
321
-
322
- Optional `cwd` selects the working directory for that child.
323
-
324
- ### Parallel tasks
325
-
326
- Use parallel mode only for independent work:
327
-
328
- ```json
329
- {
330
- "tasks": [
331
- { "agent": "explore", "task": "Map the API layer and its tests." },
332
- { "agent": "explore", "task": "Map the database layer and its tests." }
333
- ]
334
- }
335
- ```
336
-
337
- Start dependent work only after the relevant result has been delivered.
338
-
339
- ## Configuration
340
-
341
- Configuration is stored at `~/.pi/agent/pi-subagents.json`. The location follows
342
- `PI_CODING_AGENT_DIR` when set.
343
-
344
- The `/subagents-setup` wizard drives the main fields interactively: for each agent, picking
345
- a model is immediately followed by picking that agent's thinking strength (or inheriting the
346
- agent's default its frontmatter `thinking`, else the global default). The global
347
- `thinkingLevel` is set first and applies as the final fallback. `notifyOnReviewPass` and
348
- `maxResultLines` are edited directly in `pi-subagents.json`.
349
-
350
- When the config already exists, re-running `/subagents-setup` opens a menu whose
351
- **Configure an agent (model + thinking)** entry lets you pick one agent and set just its
352
- model and thinking strength — so changing a single agent no longer walks every enabled
353
- agent. After one agent's model + strength picks, the wizard returns to the agent picker
354
- so several agents can be configured in one pass; Esc at any step ends the pass and keeps
355
- every agent already configured. **Change default thinking strength** sets only the global
356
- fallback. The rest of the menu toggles injection, scope, concurrency, fix rounds, and
357
- idle timeout; **Full re-setup** re-runs the whole first-time wizard.
358
-
359
- ```json
360
- {
361
- "enabledAgents": ["explore", "worker", "reviewer"],
362
- "agentModels": {
363
- "explore": "anthropic/claude-haiku-4-5"
364
- },
365
- "agentThinkingLevels": {
366
- "explore": "low",
367
- "worker": "high"
368
- },
369
- "thinkingLevel": "high",
370
- "notifyOnReviewPass": false,
371
- "maxResultLines": 80,
372
- "proactiveInjection": true,
373
- "agentScope": "user",
374
- "maxConcurrency": 4,
375
- "maxFixRounds": 2,
376
- "idleTimeoutSec": 90
377
- }
378
- ```
379
-
380
- | Field | Description |
381
- | --- | --- |
382
- | `enabledAgents` | Agent names exposed to discovery and prompt injection. An empty array disables all agents. |
383
- | `agentModels` | Optional `provider/model-id` override per agent. |
384
- | `agentThinkingLevels` | Optional thinking level per agent; agents without an entry use the agent's frontmatter `thinking`, then `thinkingLevel`. |
385
- | `thinkingLevel` | Default thinking level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` (default `high`). |
386
- | `notifyOnReviewPass` | When `true`, a passing reviewer result is delivered without waking the main agent (default `false`). |
387
- | `maxResultLines` | Max lines of a sub-agent result carried in the completion message (default `80`). Longer results are truncated; the full text is written to a temp file whose path is included in the message. |
388
- | `proactiveInjection` | Whether to add the delegation directive to the main system prompt. |
389
- | `agentScope` | `user`, `project`, or `both`; controls which user/project agent directories are discovered. |
390
- | `maxConcurrency` | Max sub-agent processes running at once (1–16, default 4), and the max tasks one parallel `subagent` call accepts. Extra work waits in the queue. |
391
- | `maxFixRounds` | Auto-fix rounds when a reviewer returns `REVIEW_FAIL`: the extension dispatches a `worker` (briefed with the review's findings) then a `reviewer` re-review, repeating up to this many times before waking the main agent with the full chain. `0` disables it (the main agent handles fixes itself). Default 2. |
392
- | `idleTimeoutSec` | Idle timeout in seconds: a sub-agent that produces no output for this long is terminated and retried with the fallback model (if one is available). `0` disables the idle watchdog. Default 90. A long but active run is never interrupted. |
393
-
394
- ### Configuration migration
395
-
396
- The config file migrates itself on load — no manual steps after an upgrade:
397
-
398
- - **Schema upgrades** — a config written by an older version (missing newer keys or
399
- holding invalid values) is normalized and saved back with the new fields filled in.
400
- - **Removed agents** agents no longer shipped are stripped from `enabledAgents`,
401
- `agentModels`, and `agentThinkingLevels` automatically.
402
- - **Merged limits** — the pre-0.13 `maxParallelTasks` key is folded into `maxConcurrency`
403
- (the larger of the two wins) and dropped on the next save.
404
- - **Removed keys** — `maxSubagentDepth` (0.14) is dropped on load: sub-agent children are
405
- always leaf processes. To disable delegation entirely, use `"enabledAgents": []`.
406
- - **New fields** — `idleTimeoutSec` (0.16) is filled in on load with its default (90)
407
- when missing from an older config.
408
-
409
- Model selection uses this precedence:
410
-
411
- ```text
412
- configured agent model → current main-session model → agent frontmatter model
413
- ```
414
-
415
- Unavailable configured models are replaced with a usable current-session model when
416
- possible, and the repaired configuration is saved.
417
-
418
- At runtime, if an agent's model fails at the provider level before producing any output
419
- (bad model id, auth, thinking level, quota, ...), the run is retried **once** with the
420
- main window's current model. This degradation is per-run only and never persisted; it
421
- does not apply to task-level failures (the model worked, the task failed) or aborts.
422
- Idle timeouts count as model-level failures and do trigger the fallback, since a stalled
423
- stream is usually a provider-side issue. Results carry a `model fell back from …` note
424
- when it happened.
425
-
426
- If the model is unavailable or broken and the fallback retry also fails (or no fallback
427
- model is available), the task is **handed back to the main window**: the completion
428
- message tells the main agent to execute the task itself with its own tools. A background
429
- task that crashes with an exception is also surfaced — the user gets a `✗ dispatch
430
- failed` notification and the failure is delivered to the main agent, which can
431
- re-dispatch it.
432
-
433
- Thinking strength uses this precedence: `agentThinkingLevels` entry agent frontmatter `thinking` `thinkingLevel` default.
434
-
435
- ## Agent discovery and overrides
436
-
437
- - Built-in agents are shipped with the package.
438
- - User agents live in `~/.pi/agent/agents/`.
439
- - Project agents live in the nearest `.pi/agents/` directory.
440
- - For duplicate names, project overrides user and user overrides built-in.
441
-
442
- Use a matching Markdown filename and `name` field to replace a built-in agent. Keep the
443
- task brief explicit: include the goal, relevant paths, constraints, and expected handoff.
444
-
445
- Optional frontmatter fields: `model` (default model reference) and `thinking` (default
446
- thinking strength). Both are overridden by `agentModels` / `agentThinkingLevels` in
447
- `pi-subagents.json` when set.
448
-
449
- ## Development
450
-
451
- ```bash
452
- npm install
453
- npm run check
454
- npm test
455
- ```
456
-
457
- The package has no runtime dependencies beyond pi peer dependencies.
458
-
459
- ## Acknowledgments
460
-
461
- - The official [pi subagent example](https://github.com/earendil-works/pi)
462
- (`examples/extensions/subagent`) the child-process dispatch and
463
- event-stream handling build on it.
464
- - [tintinweb/pi-subagents](https://github.com/tintinweb/pi-subagents) the
465
- live widget (two lines per run: header + quiet gray activity row) and
466
- parallel fan-out follow its design.
467
- - The sub-agent pattern itself, popularized by
468
- [Claude Code](https://github.com/anthropics/claude-code): role-specialized
469
- agents that receive self-contained briefs.
470
-
471
- The agent prompts and extension code are written independently for this
472
- project; the projects above served as design references.
473
-
474
- ## License
475
-
476
- MIT
1
+ # pi-subagents
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@ferris1225/pi-subagents?color=blue)](https://www.npmjs.com/package/@ferris1225/pi-subagents)
4
+ [![downloads](https://img.shields.io/npm/dm/@ferris1225/pi-subagents)](https://www.npmjs.com/package/@ferris1225/pi-subagents)
5
+ [![license](https://img.shields.io/npm/l/@ferris1225/pi-subagents)](./LICENSE)
6
+ ![platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey)
7
+ ![pi](https://img.shields.io/badge/pi-extension-orange)
8
+
9
+ Background delegation for [pi](https://pi.dev). This extension adds three specialized
10
+ agents — `explore`, `worker`, `reviewer` — that run in isolated child processes and
11
+ report their results back to the main agent automatically.
12
+
13
+ ## Highlights
14
+
15
+ - **Isolated execution** — each sub-agent runs in its own `pi` process; it cannot see
16
+ the main conversation, so it gets a clean context window.
17
+ - **Automatic continuation** — results are delivered as a message that wakes the main
18
+ agent automatically: injected as soon as the current tool call finishes (even
19
+ mid-turn), or starting a new turn when idle. No polling, no "go check" step.
20
+ - **Sub-agent toolbelt** — three companion tools that replace the classic
21
+ sleep/poll anti-pattern: `subagent_wait` blocks in-tool and returns the result,
22
+ `subagent_status` inspects active and finished runs, and `subagent_stop` cancels
23
+ a run (delivering its partial output as an aborted result).
24
+ - **Honest completions** a run that exited cleanly but whose tool calls failed
25
+ (e.g. a broken build) is reported as `completed with N failed tool call(s)`
26
+ with the errors attached, so a rosy final text can never hide a failure.
27
+ - **Parallel fan-out** — independent tasks run at the same time, with a configurable
28
+ concurrency limit.
29
+ - **Live progress** a TUI widget shows each run's status, current activity, model,
30
+ token usage (input/output and cache read/write), and elapsed time.
31
+ - **Per-agent configuration** — enable agents, choose a model and thinking level per
32
+ agent, and tune limits from `/subagents-setup`.
33
+ - **Automatic model fallback** — if an agent's model fails at the provider level before
34
+ producing any output, the SAME model is retried up to five times (bounded backoff) for
35
+ transient errors (503/429/timeout/network/...); if it still fails, the run is retried
36
+ once with the main window's current model. Terminal errors (quota exhausted, billing,
37
+ an invalid API key) skip both and are handed straight back to the main agent. The
38
+ fallback is per-run only and never persisted.
39
+ - **Idle watchdog** a sub-agent that produces no output for a configurable duration is
40
+ terminated and retried with the fallback model.
41
+ - **Leaf processes** sub-agents cannot access the `subagent` tool, so delegation
42
+ cannot recurse.
43
+
44
+ ## Why pi-subagents
45
+
46
+ Several tools now offer some form of sub-agents. What this extension does differently:
47
+
48
+ - **Real isolation, not prompt-swapping.** Each sub-agent runs as its own `pi`
49
+ process with its own context window. The main conversation is never polluted by
50
+ the child's tool calls, thinking, or long exploration trails a "sub-agent" that
51
+ just swaps the system prompt inside the same session does not give you that.
52
+ - **Results come back on their own.** The extension turns the child's completion
53
+ into a message that wakes the main agent automatically delivered even
54
+ mid-turn, right after the current tool call. No polling, no "go check
55
+ the other window" step, and **no `sleep`**: if the model must keep the turn it
56
+ calls `subagent_wait` (event-driven, returns the actual result) instead of
57
+ sleeping or polling.
58
+ - **Failures are handled, not reported.** Three layers of resilience: a provider-
59
+ level model failure first retries the same model up to five times on a transient
60
+ provider error, then retries once with the main window's model; terminal errors
61
+ (quota/auth) short-circuit straight to the main agent; an idle watchdog terminates
62
+ a run that goes silent (a stalled stream) and retries it; and a concurrent-startup
63
+ race is retried with backoff automatically. The widget and the completion message
64
+ tell you when any of these happened.
65
+ - **A quality gate that closes the loop.** When a reviewer returns `REVIEW_FAIL`,
66
+ the extension dispatches a worker briefed with the concrete findings, then a
67
+ re-review — up to `maxFixRounds` times — and only then wakes the main agent with
68
+ the whole chain. The gate runs itself instead of asking you to babysit it.
69
+ - **Honest results.** A sub-agent can end its turn with "still working" while its
70
+ last build actually failed. The completion message surfaces the failed tool
71
+ calls from the run's final attempt (`completed with N failed tool call(s)`) with
72
+ the error lines attached, so the main agent never trusts a cheerful summary
73
+ over reality. (A model-fallback retry runs the work fresh, so only the final
74
+ attempt's tool calls are counted — never stale errors from an abandoned one.)
75
+ - **You can see what it is doing.** The widget shows each run's status, current
76
+ activity (which tool, which file), model, token usage including cache reads and
77
+ writes, and elapsed time — plus soft warnings when a run looks stuck.
78
+ - **Recursion is structurally impossible.** Children are leaf processes: the
79
+ `subagent` tool is excluded from their toolset. No runaway delegation trees.
80
+ - **Zero runtime dependencies.** It is a plain pi extension — install, configure,
81
+ go. Agents are Markdown files, so overriding or adding one is just writing a
82
+ file.
83
+
84
+ It is not the right tool for everything: if you need agents that share state,
85
+ communicate with each other, or run long-lived background services, a heavier
86
+ orchestration framework fits better. This one is deliberately narrow bounded
87
+ delegation of focused, self-contained work.
88
+
89
+ ## Install
90
+
91
+ ```bash
92
+ pi install npm:@ferris1225/pi-subagents
93
+ ```
94
+
95
+ Requires pi **>= 0.80.6**.
96
+
97
+ After installation, open the setup wizard in an interactive TUI session:
98
+
99
+ ```text
100
+ /subagents-setup
101
+ ```
102
+
103
+ The default configuration enables `explore`, `worker`, and `reviewer`.
104
+
105
+ ## Included agents
106
+
107
+ | Agent | Default | Access | Default model | Thinking | Purpose |
108
+ | --- | :---: | --- | --- | --- | --- |
109
+ | `explore` | Yes | Read-only | `claude-haiku-4-5` | `low` | Fast codebase reconnaissance and structured findings. |
110
+ | `worker` | Yes | Full | `claude-sonnet-4-5` | `high` | Implements, fixes, refactors, and tests a self-contained task. |
111
+ | `reviewer` | Yes | Read-only | `claude-sonnet-4-5` | `high` | Adversarial quality gate: diff review (default), plus plan, proposed-solution, codebase-health, and PR/issue validation. |
112
+
113
+ Agents are Markdown files in `agents/`. Each file contains YAML frontmatter and a system
114
+ prompt. User and project scopes can override a built-in agent with the same name; the
115
+ frontmatter defaults above are overridden by `agentModels` / `agentThinkingLevels` when set.
116
+
117
+ ### Agent prompts
118
+
119
+ The prompts below mirror `agents/*.md` the files loaded at dispatch time. They define
120
+ each agent's role, constraints, and output format, so keep them in sync if you edit
121
+ either side.
122
+
123
+ <details>
124
+ <summary><code>agents/explore.md</code> reconnaissance</summary>
125
+
126
+ ```markdown
127
+ ---
128
+ name: explore
129
+ description: Fast read-only codebase reconnaissance. Use PROACTIVELY for broad or open-ended search — locating files/symbols, answering "where is X defined / which files reference Y", multi-file concept lookups, or mapping unfamiliar code before a change. Returns compressed, structured findings so the caller does not re-read everything.
130
+ tools: read, grep, find, ls, bash
131
+ model: claude-haiku-4-5
132
+ thinking: low
133
+ # Model selection: SPEED over depth. Pick the fastest available model.
134
+ # What matters: fast grep/find/read, structured output. What doesn't: deep reasoning.
135
+ ---
136
+
137
+ You are an explore agent: a fast, read-only reconnaissance specialist. You investigate a codebase and return compressed, structured findings that another agent can act on WITHOUT re-reading the files you explored. You have NOT got the caller's conversation history — the task brief is your only input.
138
+
139
+ ## Hard constraints
140
+ - You are READ-ONLY. Never create, edit, or delete files; never run mutating commands.
141
+ - Bash is for read-only inspection only: `grep`, `find`, `ls`, `cat`, `git log/show/diff/status`. No installs, builds, or state changes.
142
+ - Assume tool permissions are not perfectly enforceable; keep every command strictly read-only by intent.
143
+
144
+ ## When invoked
145
+ 1. Orient with `grep`/`find` to locate the relevant code fast. Prefer bare identifiers as patterns; scope by path and exclude noisy dirs (node_modules, dist, generated).
146
+ 2. Read KEY SECTIONS, not whole files. After 1-2 greps, read the top match instead of running more greps.
147
+ 3. Identify the types, interfaces, and key function signatures involved; note how files depend on each other.
148
+ 4. Record exact paths and line ranges so the caller can jump straight in.
149
+
150
+ ## Thoroughness (infer from the task, default medium)
151
+ - Quick: targeted lookups, key files only.
152
+ - Medium: follow imports and callers, read critical sections.
153
+ - Thorough: trace dependencies across modules; check tests and types.
154
+
155
+ ## Collaboration
156
+ - Your output feeds `worker` (or the main agent directly). Hand off compressed context: exact locations + the minimum code needed to proceed. Flag anything ambiguous so the caller can decide.
157
+
158
+ ## Output format
159
+ ## Files Retrieved
160
+ 1. `path/to/file.ts` (lines 10-50) — what lives here and why it matters
161
+ ## Key Code
162
+ Critical types / interfaces / signatures as short code blocks.
163
+ ## Architecture
164
+ A brief explanation of how the pieces connect.
165
+ ## Start Here
166
+ Which file to look at first, and why.
167
+
168
+ ## Quality standards
169
+ Terse and factual. Exact paths and line numbers. Compress — do not narrate your search process or pad with prose.
170
+ ```
171
+
172
+ </details>
173
+
174
+ <details>
175
+ <summary><code>agents/worker.md</code> — implementation</summary>
176
+
177
+ ```markdown
178
+ ---
179
+ name: worker
180
+ description: General-purpose implementation agent with full tools in an isolated context. Use PROACTIVELY to execute a well-scoped, self-contained coding taskimplement, fix, refactor, or add tests without polluting the main conversation. Plans internally, then implements and verifies. Give it a complete, self-contained brief.
181
+ model: claude-sonnet-4-5
182
+ thinking: high
183
+ # Model selection: CODING ABILITY + TOOL USE. The primary implementation model
184
+ # balance quality against cost. No `tools` field => inherits all tools (full capability).
185
+ ---
186
+
187
+ You are a worker agent with full capabilities, operating in an isolated context window. You own a delegated, self-contained task end to end so the main conversation stays clean. You have NOT got the caller's conversation history — the task brief is your source of truth.
188
+
189
+ ## Standard operating procedure
190
+ Work in phases. Do not skip planning or verification.
191
+
192
+ ### Phase 1 — Context
193
+ Read the brief fully. If it references files, read them before editing. If critical context is clearly missing, state what an `explore` should retrieve rather than guessing.
194
+
195
+ ### Phase 2 Plan
196
+ Inspect existing code and conventions first. Form the smallest coherent root-cause change that satisfies the brief. For a large task, write a short internal plan (files to touch, order, risks) before editing. Do not refactor unrelated code or create docs unless the brief asks.
197
+
198
+ ### Phase 3 — Implement
199
+ Make the change. Preserve the user's work; limit edits to the request plus required validation. Follow the project's existing error handling, naming, and style.
200
+
201
+ ### Phase 4 — Verify
202
+ Run the project's format/build/tests when they exist (e.g. `tsc --noEmit`, the test runner). NEVER report an unrun check as passed — report it as unavailable or as a pre-existing failure, with the exact error.
203
+
204
+ ### Phase 5 — Handoff
205
+ Summarize concretely so the caller can verify and, if needed, hand to a `reviewer`.
206
+
207
+ ## Collaboration
208
+ - You cannot dispatch sub-agents (children are leaf processes with no `subagent` tool). When the
209
+ brief lacks context that needs broad code discovery, state concretely what an `explore` should
210
+ retrieve for the caller — do not guess.
211
+ - Recommend a `reviewer` pass before the caller reports work done or commits, especially for non-trivial diffs.
212
+
213
+ ## Output format
214
+ ## Completed
215
+ What was done, in a few lines.
216
+ ## Files Changed
217
+ - `path/to/file.ts` what changed.
218
+ ## Verification
219
+ Which checks you ACTUALLY ran and their result (e.g. `tsc --noEmit` clean; `vitest` 12 passed). State explicitly anything you could not run and why.
220
+ ## Notes (if any)
221
+ Follow-ups, decisions made, blockers. For a reviewer handoff: exact file paths changed and a short list of key functions/types touched.
222
+
223
+ ## Quality standards
224
+ Root-cause fixes over patches. No unrelated churn. Honest verification an unrun check is never a passed check.
225
+ ```
226
+
227
+ </details>
228
+
229
+ <details>
230
+ <summary><code>agents/reviewer.md</code> — quality gate</summary>
231
+
232
+ ```markdown
233
+ ---
234
+ name: reviewer
235
+ description: Adversarial code reviewer and pre-commit quality gate. Use PROACTIVELY before reporting work done or committing — reviews a diff or a set of changed files for correctness, security, concurrency/unsafe-FFI, encoding/Unicode boundaries, and convention violations. Runs in a separate context from the worker to avoid self-confirmation bias. Read-only; never edits, builds, or runs tests. Also handles plans, proposed solutions, codebase health, and PR/issue validation when the brief asks.
236
+ tools: read, grep, find, ls, bash
237
+ model: claude-sonnet-4-5
238
+ thinking: high
239
+ # Model selection: ATTENTION TO DETAIL + SECURITY AWARENESS. This is the quality gate
240
+ # use the strongest available reasoning model.
241
+ ---
242
+
243
+ You are a senior, adversarial code reviewer. Your job is to FIND WHAT IS WRONG, not to validate. Assume the author's summary describes intent, not outcome — verify against the actual code. You run in a separate context from the worker on purpose, so you bring no bias toward the change. You have NOT got the caller's conversation history.
244
+
245
+ ## Hard constraints
246
+ - You are READ-ONLY. Do NOT modify files, run builds, or run tests.
247
+ - Bash is for read-only commands only: `git diff`, `git status`, `git log`, `git show`, `grep`, `find`, `cat`.
248
+ - Assume tool permissions are not perfectly enforceable; keep every command strictly read-only by intent.
249
+
250
+ ## Review types you handle
251
+ Match the type to the task brief; the hunt checklist below applies to every type.
252
+
253
+ ### 1. Code diffs (default)
254
+ 1. Run `git diff` and `git status` to see the recent changes. If a specific file set was given, read those files.
255
+ 2. Read the modified files in full where needed; judge the change in the context of the surrounding code.
256
+
257
+ ### 2. Plans
258
+ Validate a proposed plan for feasibility and completeness: missing steps, hidden risks, alignment with the existing architecture, and whether the scope is appropriately bounded.
259
+
260
+ ### 3. Proposed solutions
261
+ Evaluate a suggested approach: correctness and tradeoffs, fit with existing codebase patterns, simpler alternatives, edge cases the proposal may miss.
262
+
263
+ ### 4. Codebase health
264
+ Assess key files, tests, and structure: architecture drift or tech debt, inconsistent patterns, untested or undocumented areas, obvious bugs, fragile code.
265
+
266
+ ### 5. Specific PR or issue
267
+ Understand the context first, then verify: the fix addresses the root cause, changes are minimal and focused, no regressions, tests and docs updated as needed.
268
+
269
+ ## Hunt across these categories
270
+ - Logic bugs, off-by-one, wrong edge-case handling.
271
+ - Error handling gaps; swallowed failures; unreported unrun checks.
272
+ - Security: injection, path traversal, secrets in code/logs, trusting untrusted input.
273
+ - Concurrency: shared mutable state, locks held across await, races.
274
+ - Encoding/Unicode: assuming `char*`/files/CLI text is UTF-8; wrong `A` vs `W` Win32 APIs; boundary conversions.
275
+ - Resource leaks; violations of the project's stated conventions.
276
+ - Classify severity honestly. Distinguish blockers from nits; do not pad with style preferences.
277
+
278
+ ## Collaboration
279
+ - Independent of `worker` by design — your verdict is the gate before commit. Fix nothing yourself; report so the caller can dispatch a worker.
280
+
281
+ ## Output format
282
+ ## Files Reviewed
283
+ - `path/to/file.ts`
284
+ ## Critical (must fix)
285
+ - `file.ts:42` — concrete issue and why it breaks.
286
+ ## Warnings (should fix)
287
+ - `file.ts:10` issue and suggested direction.
288
+ ## Suggestions (consider)
289
+ - Optional improvements.
290
+ ## Verdict
291
+ One of: APPROVE / APPROVE_WITH_NITS / REQUEST_CHANGES, plus a 2-3 sentence rationale.
292
+ End with exactly one machine-readable line: `VERDICT: REVIEW_PASS` for APPROVE or APPROVE_WITH_NITS; `VERDICT: REVIEW_FAIL` for REQUEST_CHANGES.
293
+
294
+ ## Quality standards
295
+ Specific file paths and line numbers. No vague feedback. A clean report means you looked hard, not that you found nothing to say.
296
+ ```
297
+
298
+ </details>
299
+
300
+ ## Workflow
301
+
302
+ ```text
303
+ main agent
304
+
305
+ ├─ subagent(explore / worker / reviewer)
306
+ │ └─ isolated pi child process
307
+ │ └─ result message
308
+
309
+ └─ automatic follow-up turn with the result
310
+ ```
311
+
312
+ 1. The main agent calls `subagent` with a self-contained brief.
313
+ 2. The tool returns immediately, so the editor stays usable while the child works.
314
+ 3. Up to `maxConcurrency` sub-agents run at once (default 4); a parallel call accepts at
315
+ most that many tasks, and anything beyond waits in the queue.
316
+ 4. When a run finishes (successfully or not), the extension sends a result message to the
317
+ main session. The result is delivered as soon as the current tool call finishes — even
318
+ mid-turn or starts a new turn when the agent is idle. A run that ended with failed
319
+ tool calls (e.g. a broken build) is reported as such, never as a plain success.
320
+ 5. The main agent uses the result to continue. No extra user prompt is needed.
321
+
322
+ ### Waiting, inspecting, and stopping runs
323
+
324
+ The extension registers three companion tools so the main agent never has to
325
+ `sleep`/poll for a background run:
326
+
327
+ - `subagent_wait` — blocks inside the tool call (event-driven, wakes on the run's
328
+ completion) and **returns the actual result in-turn**. Use it only when the current
329
+ turn must receive the result (sequential dependent steps); otherwise end the turn
330
+ and the completion message wakes you.
331
+ - `subagent_status` lists active runs (id, agent, model, usage, elapsed, activity)
332
+ and finished results; pass an id to read a finished run's full result.
333
+ - `subagent_stop` — cancels an active run (or `all: true`); the child is terminated
334
+ and an aborted result with its partial output is delivered, so the main agent
335
+ always knows the run did not complete.
336
+
337
+ Switching sessions, reloading, or shutting down cancels remaining background runs. A
338
+ crashed or aborted agent returns whatever partial output it produced, clearly labelled,
339
+ so the main agent can decide whether to retry.
340
+
341
+ ## Usage
342
+
343
+ The main agent is encouraged to delegate automatically, but you can also ask directly:
344
+
345
+ ```text
346
+ Use explore to map how authentication is wired up.
347
+ Ask worker to implement the API change after the exploration is complete.
348
+ Run reviewer on the final diff before reporting completion.
349
+ ```
350
+
351
+ ### Single task
352
+
353
+ ```json
354
+ {
355
+ "agent": "worker",
356
+ "task": "Implement the requested change. Inspect the existing conventions, update tests, and report the files changed and checks run."
357
+ }
358
+ ```
359
+
360
+ Optional `cwd` selects the working directory for that child.
361
+
362
+ ### Parallel tasks
363
+
364
+ Use parallel mode only for independent work:
365
+
366
+ ```json
367
+ {
368
+ "tasks": [
369
+ { "agent": "explore", "task": "Map the API layer and its tests." },
370
+ { "agent": "explore", "task": "Map the database layer and its tests." }
371
+ ]
372
+ }
373
+ ```
374
+
375
+ Start dependent work only after the relevant result has been delivered.
376
+
377
+ ### Waiting for a result in-turn
378
+
379
+ When the next step depends on a run's result and the turn must not end, use
380
+ `subagent_wait` instead of sleeping or polling. It blocks inside the tool call
381
+ (event-driven) and returns the actual result:
382
+
383
+ ```json
384
+ {
385
+ "id": "3"
386
+ }
387
+ ```
388
+
389
+ Pass `timeoutMs` to bound the wait; on timeout it reports the still-running runs
390
+ and the model re-invokes it or ends the turn (the completion message then wakes it).
391
+
392
+ ### Inspecting runs
393
+
394
+ `subagent_status` returns an overview of active and finished runs with their ids:
395
+
396
+ ```json
397
+ {}
398
+ ```
399
+
400
+ Pass a run id to read that run's full result:
401
+
402
+ ```json
403
+ {
404
+ "id": "3"
405
+ }
406
+ ```
407
+
408
+ ### Stopping a run
409
+
410
+ `subagent_stop` cancels a run that is obsolete, stuck, or superseded — the child is
411
+ terminated and an aborted result (with partial output) is delivered:
412
+
413
+ ```json
414
+ {
415
+ "id": "3"
416
+ }
417
+ ```
418
+
419
+ Or stop everything with `{ "all": true }`.
420
+
421
+ ## Configuration
422
+
423
+ Configuration is stored at `~/.pi/agent/pi-subagents.json`. The location follows
424
+ `PI_CODING_AGENT_DIR` when set.
425
+
426
+ The `/subagents-setup` wizard drives the main fields interactively: for each agent, picking
427
+ a model is immediately followed by picking that agent's thinking strength (or inheriting the
428
+ agent's default its frontmatter `thinking`, else the global default). The global
429
+ `thinkingLevel` is set first and applies as the final fallback. `notifyOnReviewPass` and
430
+ `maxResultLines` are edited directly in `pi-subagents.json`.
431
+
432
+ When the config already exists, re-running `/subagents-setup` opens a menu whose
433
+ **Configure an agent (model + thinking)** entry lets you pick one agent and set just its
434
+ model and thinking strength — so changing a single agent no longer walks every enabled
435
+ agent. After one agent's model + strength picks, the wizard returns to the agent picker
436
+ so several agents can be configured in one pass; Esc at any step ends the pass and keeps
437
+ every agent already configured. **Change default thinking strength** sets only the global
438
+ fallback. The rest of the menu toggles injection, scope, concurrency, fix rounds, and
439
+ idle timeout; **Full re-setup** re-runs the whole first-time wizard.
440
+
441
+ ```json
442
+ {
443
+ "enabledAgents": ["explore", "worker", "reviewer"],
444
+ "agentModels": {
445
+ "explore": "anthropic/claude-haiku-4-5"
446
+ },
447
+ "agentThinkingLevels": {
448
+ "explore": "low",
449
+ "worker": "high"
450
+ },
451
+ "thinkingLevel": "high",
452
+ "notifyOnReviewPass": false,
453
+ "maxResultLines": 80,
454
+ "proactiveInjection": true,
455
+ "agentScope": "user",
456
+ "maxConcurrency": 4,
457
+ "maxFixRounds": 2,
458
+ "idleTimeoutSec": 90
459
+ }
460
+ ```
461
+
462
+ | Field | Description |
463
+ | --- | --- |
464
+ | `enabledAgents` | Agent names exposed to discovery and prompt injection. An empty array disables all agents. |
465
+ | `agentModels` | Optional `provider/model-id` override per agent. |
466
+ | `agentThinkingLevels` | Optional thinking level per agent; agents without an entry use the agent's frontmatter `thinking`, then `thinkingLevel`. |
467
+ | `thinkingLevel` | Default thinking level: `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max` (default `high`). |
468
+ | `notifyOnReviewPass` | When `true`, a passing reviewer result is delivered without waking the main agent (default `false`). |
469
+ | `maxResultLines` | Max lines of a sub-agent result carried in the completion message (default `80`). Longer results are truncated; the full text is written to a temp file whose path is included in the message. |
470
+ | `proactiveInjection` | Whether to add the delegation directive to the main system prompt. |
471
+ | `agentScope` | `user`, `project`, or `both`; controls which user/project agent directories are discovered. |
472
+ | `maxConcurrency` | Max sub-agent processes running at once (1–16, default 4), and the max tasks one parallel `subagent` call accepts. Extra work waits in the queue. |
473
+ | `maxFixRounds` | Auto-fix rounds when a reviewer returns `REVIEW_FAIL`: the extension dispatches a `worker` (briefed with the review's findings) then a `reviewer` re-review, repeating up to this many times before waking the main agent with the full chain. `0` disables it (the main agent handles fixes itself). Default 2. |
474
+ | `idleTimeoutSec` | Idle timeout in seconds: a sub-agent whose stdout goes silent for this long is terminated and retried (same model first, then the main-window fallback, like any transient provider failure). `0` disables the idle watchdog. Default 90. A long but active run is never interrupted. |
475
+
476
+ ### Configuration migration
477
+
478
+ The config file migrates itself on load — no manual steps after an upgrade:
479
+
480
+ - **Schema upgrades** — a config written by an older version (missing newer keys or
481
+ holding invalid values) is normalized and saved back with the new fields filled in.
482
+ - **Removed agents** — agents no longer shipped are stripped from `enabledAgents`,
483
+ `agentModels`, and `agentThinkingLevels` automatically.
484
+ - **Merged limits** — the pre-0.13 `maxParallelTasks` key is folded into `maxConcurrency`
485
+ (the larger of the two wins) and dropped on the next save.
486
+ - **Removed keys** — `maxSubagentDepth` (0.14) is dropped on load: sub-agent children are
487
+ always leaf processes. To disable delegation entirely, use `"enabledAgents": []`.
488
+ - **New fields** — `idleTimeoutSec` (0.16) is filled in on load with its default (90)
489
+ when missing from an older config.
490
+
491
+ Model selection uses this precedence:
492
+
493
+ ```text
494
+ configured agent model → current main-session model → agent frontmatter model
495
+ ```
496
+
497
+ Unavailable configured models are replaced with a usable current-session model when
498
+ possible, and the repaired configuration is saved.
499
+
500
+ At runtime, if an agent's model fails at the provider level before producing any output
501
+ (bad model id, auth, thinking level, quota, ...), the run is retried **once** with the
502
+ main window's current model. This degradation is per-run only and never persisted; it
503
+ does not apply to task-level failures (the model worked, the task failed) or aborts.
504
+ Idle timeouts count as model-level failures and do trigger the fallback, since a stalled
505
+ stream is usually a provider-side issue. Results carry a `model fell back from …` note
506
+ when it happened.
507
+
508
+ If the model is unavailable or broken and the fallback retry also fails (or no fallback
509
+ model is available), the task is **handed back to the main window**: the completion
510
+ message tells the main agent to execute the task itself with its own tools. A background
511
+ task that crashes with an exception is also surfaced — the user gets a `✗ dispatch
512
+ failed` notification and the failure is delivered to the main agent, which can
513
+ re-dispatch it.
514
+
515
+ Thinking strength uses this precedence: `agentThinkingLevels` entry → agent frontmatter `thinking` → `thinkingLevel` default.
516
+
517
+ ## Agent discovery and overrides
518
+
519
+ - Built-in agents are shipped with the package.
520
+ - User agents live in `~/.pi/agent/agents/`.
521
+ - Project agents live in the nearest `.pi/agents/` directory.
522
+ - For duplicate names, project overrides user and user overrides built-in.
523
+
524
+ Use a matching Markdown filename and `name` field to replace a built-in agent. Keep the
525
+ task brief explicit: include the goal, relevant paths, constraints, and expected handoff.
526
+
527
+ Optional frontmatter fields: `model` (default model reference) and `thinking` (default
528
+ thinking strength). Both are overridden by `agentModels` / `agentThinkingLevels` in
529
+ `pi-subagents.json` when set.
530
+
531
+ ## Development
532
+
533
+ ```bash
534
+ npm install
535
+ npm run check
536
+ npm test
537
+ ```
538
+
539
+ The package has no runtime dependencies beyond pi peer dependencies.
540
+
541
+ ## Acknowledgments
542
+
543
+ - The official [pi subagent example](https://github.com/earendil-works/pi)
544
+ (`examples/extensions/subagent`) — the child-process dispatch and
545
+ event-stream handling build on it.
546
+ - [tintinweb/pi-subagents](https://github.com/tintinweb/pi-subagents) — the
547
+ live widget (two lines per run: header + quiet gray activity row) and
548
+ parallel fan-out follow its design.
549
+ - [nicobailon/pi-subagents](https://github.com/nicobailon/pi-subagents) — the
550
+ result-delivery design is learned from it: prompt **steer** delivery (a
551
+ completion is injected right after the current tool call instead of waiting
552
+ for the turn to end), a blocking `subagent_wait` tool that returns the result
553
+ in-turn, status inspection and stop/interrupt management, and the rule that
554
+ an agent should never `sleep`/poll for a background run. Its status-file and
555
+ workflow-script orchestration (JS chains, checkpoints, scheduling, missions)
556
+ are deliberately out of scope here: this extension stays a focused 3-agent
557
+ delegation tool with a configuration wizard instead of a full orchestrator.
558
+ - The sub-agent pattern itself, popularized by
559
+ [Claude Code](https://github.com/anthropics/claude-code): role-specialized
560
+ agents that receive self-contained briefs.
561
+
562
+ The agent prompts and extension code are written independently for this
563
+ project; the projects above served as design references.
564
+
565
+ ### What stays ours
566
+
567
+ - **Exactly three focused agents** (`explore` / `worker` / `reviewer`) with
568
+ hand-tuned prompts, not a generic orchestration surface.
569
+ - **`/subagents-setup` wizard** — per-agent model + thinking selection,
570
+ concurrency, fix rounds, idle watchdog, scope, injection — with config
571
+ migration and unavailable-model repair, all interactive.
572
+ - **The auto-fix loop** — a `REVIEW_FAIL` reviewer automatically drives
573
+ worker → re-review rounds before waking anyone.
574
+ - **Zero runtime dependencies**: agents are plain Markdown files; override or
575
+ add one by writing a file.
576
+
577
+ ## License
578
+
579
+ MIT