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