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