@herbertgao/pi-extensions 2026.11.9 → 2026.11.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +6 -6
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +12 -0
  5. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +8 -6
  6. package/node_modules/@herbertgao/pi-cc-extensions/README.md +8 -6
  7. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/config.ts +12 -0
  8. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +36 -13
  9. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/compact-thinking.ts +4 -8
  10. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/context.ts +7 -2
  11. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/footer.ts +115 -6
  12. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +47 -15
  13. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/startup-header.ts +3 -18
  14. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +34 -10
  15. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/default-mode.ts +6 -1
  16. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +30 -17
  17. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/mouse/scroll.ts +4 -21
  18. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/grouping.ts +63 -7
  19. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/names.ts +3 -13
  20. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/tool-io.ts +0 -5
  21. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/transcript-mode.ts +34 -7
  22. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/ansi-text.ts +43 -4
  23. package/node_modules/@herbertgao/pi-cc-extensions/extensions/utils/keybindings.ts +75 -0
  24. package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
  25. package/node_modules/@herbertgao/pi-impeccable/CHANGELOG.md +6 -0
  26. package/node_modules/@herbertgao/pi-impeccable/README.md +2 -2
  27. package/node_modules/@herbertgao/pi-impeccable/package.json +4 -4
  28. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/SKILL.md +3 -1
  29. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/adapt.md +1 -1
  30. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.md +12 -1
  31. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/audit.native.md +4 -0
  32. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/critique.md +5 -5
  33. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/documenter.md +1 -1
  34. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/degraded/finish-reviewer.md +1 -1
  35. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/distill.md +1 -1
  36. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/document.md +3 -1
  37. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/foundations.md +44 -0
  38. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live-setup.md +1 -1
  39. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/live.md +26 -12
  40. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/new-work.md +10 -9
  41. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/onboard.md +7 -6
  42. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/overdrive.md +2 -2
  43. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/quieter.md +1 -1
  44. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/reference/visualize.md +1 -1
  45. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/VERSION +1 -1
  46. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/engine-checksums.txt +5 -5
  47. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/impeccable +69 -16
  48. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/impeccable.cmd +55 -7
  49. package/node_modules/@herbertgao/pi-impeccable/skills/impeccable/scripts/live-browser.js +34 -4
  50. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +12 -0
  51. package/node_modules/@herbertgao/pi-subagents/README.md +53 -26
  52. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +12 -12
  53. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  54. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +84 -8
  55. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +51 -32
  56. package/node_modules/@herbertgao/pi-subagents/src/default-agents.ts +7 -0
  57. package/node_modules/@herbertgao/pi-subagents/src/index.ts +369 -879
  58. package/node_modules/@herbertgao/pi-subagents/src/nested-tools.ts +4 -1
  59. package/node_modules/@herbertgao/pi-subagents/src/prompts.ts +13 -0
  60. package/node_modules/@herbertgao/pi-subagents/src/schedule-store.ts +18 -13
  61. package/node_modules/@herbertgao/pi-subagents/src/schedule.ts +25 -5
  62. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +225 -61
  63. package/node_modules/@herbertgao/pi-subagents/src/types.ts +27 -0
  64. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-tree.ts +47 -0
  65. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +16 -5
  66. package/node_modules/@herbertgao/pi-subagents/src/ui/agents-menu.ts +705 -0
  67. package/node_modules/@herbertgao/pi-subagents/src/ui/fleet-list.ts +211 -47
  68. package/node_modules/@herbertgao/pi-subagents/src/ui/settings-menu.ts +361 -0
  69. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +1 -1
  70. package/node_modules/pi-commandcode-provider/CHANGELOG.md +11 -1
  71. package/node_modules/pi-commandcode-provider/index.ts +2 -1
  72. package/node_modules/pi-commandcode-provider/package.json +5 -4
  73. package/node_modules/pi-commandcode-provider/src/pricing.ts +8 -1
  74. package/node_modules/pi-commandcode-provider/src/responses-compat.ts +137 -0
  75. package/package.json +5 -5
@@ -17,7 +17,7 @@ https://github.com/user-attachments/assets/8685261b-9338-4fea-8dfe-1c590d5df543
17
17
  - **Conversation viewer** — select any agent in `/agents` to open a live-scrolling overlay of its full conversation (auto-follows new content, scroll up to pause). In pi's fullscreen mode it is a borderless, full-terminal observer with mouse support. Steer a running agent inline by pressing `Enter` to open a composer, typing, then `Enter` to send (`Esc` or an empty submit returns) — the message appears as a user message and redirects the agent after its current tool. Press `b` on a running foreground `Agent` call to hand that run to the background (see [Sending a foreground agent to the background](#sending-a-foreground-agent-to-the-background)). Stop a still-running agent by pressing `x` (then `x` again to confirm) — steer and stop both work for background agents too. Tool calls render the way they do in pi's own transcript, through the renderers registered in the agent's session: a bash call shows its command and output, `read` its line numbers, `edit` its diff, an extension tool its own renderer, and a tool without one falls back to its arguments plus a bounded output preview. `ctrl+o` (or whatever `app.tools.expand` is bound to) unfolds elided tool output. Assistant text renders as Markdown; `m` cycles that between off, assistant-only and everything (see [Viewer markdown](#persistent-settings))
18
18
  - **Custom agent types** — define agents in `.pi/agents/<name>.md` or `.agents/agents/<name>.md` (project) or globally, with YAML frontmatter: custom system prompts, model selection, thinking levels, tool restrictions, and Claude Code-compatible colored name badges
19
19
  - **Package-shipped agents** — a pi package can declare its own subagents (and workflow scripts) with `"pi": { "subagents": { "agents": ["./agents"] } }` in its `package.json`, so `pi install` is the whole setup: no copying files into `.pi/agents/` on every machine or container start. Only packages pi has actually installed are read (never `node_modules`), package definitions rank below every agent you wrote, and `/agents` shows them read-only with Eject and Disable. Narrow or switch it off with `packageAgents` / `packageWorkflows`. **[Full guide](https://github.com/HerbertGao/pi-extensions/blob/master/packages/pi-subagents/docs/packages.md)**
20
- - **Nested subagents** — opt-in, default-off delegation: a custom agent that sets `allowed_subagents` gets its own ownership-scoped `Agent`, `get_subagent_result`, and `steer_subagent` tools, depth-capped from the main session (default 2). It can control only its own children, they are stopped when it finishes, and their transcripts and token spend roll up to it. The allowlist is a privilege boundary — a child runs with its own tools, so pick it as carefully as `tools:` itself
20
+ - **Nested subagents** — the built-in `general-purpose` agent can delegate to subagents of its own, as in Claude Code; `Explore` and `Plan` cannot, and a custom agent opts in by setting `allowed_subagents`. A delegating agent gets its own ownership-scoped `Agent`, `get_subagent_result`, and `steer_subagent` tools, depth-capped from the main session (default 2). It can control only its own children, they are stopped when it finishes, and their transcripts and token spend roll up to it. The allowlist is a privilege boundary — a child runs with its own tools, so pick it as carefully as `tools:` itself
21
21
  - **Agent mentions** — subagents are first-class: type `@explore also check the RPC path` at the prompt and it goes to that agent instead of the main model, without a word of it entering the chat. One syntax covers the whole lifecycle — message it while it runs, resume it once it has finished, reopen its session from disk long after that, or start it if it never ran. Mentioning an agent that isn't running spawns it through an off-screen clone of the conversation, so it gets Claude Code's context-written prompt and a real `Agent` tool call without a word of it reaching the chat; `direct` mode starts it here from your text instead, with no model call at all. The orchestrator can `name` an agent so you address it as `@auth-audit`, and handles work in `steer_subagent`/`get_subagent_result` too. `@` completes live agents, resumable ones, and startable types alongside pi's file completion; `@main` forces text back to the main model. Toggle via `/agents → Settings → Agent mentions`
22
22
  - **Scripted workflows** — a `SubagentWorkflow` tool that runs a deterministic JavaScript script orchestrating many subagents: `agent()`, `parallel()`, `pipeline()`, `phase()`, `log()` and `args`, with a pure-literal `meta` block declaring the phases. `pipeline()` has no barrier between stages, so one item can be in a later stage while another is still in the first — unlike `parallel()`, which idles every fast agent until the slowest finishes. Runs in the background with a live card, inspectable via `/agents → Workflows` or by selecting the run in FleetView. `agent()` also takes `gate: "npm test"` to verify a child by running a command (inside its worktree, when isolated) rather than asking another model, and `resume: "<label>"` to continue a child instead of re-paying its context. Scripts run in a `node:vm` sandbox on a worker thread where `Date.now()`, `Math.random()` and `eval` throw. On by default, but it stands down for company: if another extension already provides a `Workflow` or `SubagentWorkflow` tool, this one warns and disables itself for the session rather than offering the model two orchestrators. Pin it either way with `"workflowsEnabled"` in `subagents.json` or `/agents → Settings → Workflows`. A script written for Claude Code's `Workflow` tool runs here unchanged: same globals, `schema` returns a validated object exactly as it does there, `budget` is present and always reports no token target (pi has no such directive) so its `budget.total`-guarded patterns still take the branch they were written for, and nested `workflow()` composes saved workflows one level deep. **[Full guide](https://github.com/HerbertGao/pi-extensions/blob/master/packages/pi-subagents/docs/workflows.md)**
23
23
  - **Mid-run steering** — inject messages into running agents to redirect their work without restarting
@@ -147,12 +147,15 @@ While subagents are running, a Claude Code-style navigable list renders **below*
147
147
 
148
148
  ● main
149
149
  ○ workflow audit-src 12/40 agents · 32s · ↓ 26.4k tokens
150
- ○ general-purpose Sleep then report 1 11s · ↓ 13.1k tokens
151
- ○ general-purpose Sleep then report 2 11s · ↓ 13.1k tokens
150
+ ❯ ○ general-purpose Review the auth module 41s · ↓ 13.1k tokens
151
+ ├ ○ Explore Find session handling 28s · ↓ 22.7k tokens
152
+ └ ○ Explore Find token refresh 27s · ↓ 19.4k tokens
152
153
  ↓ 3 more
153
154
  ```
154
155
 
155
- Running [workflows](#subagentworkflow) appear as a single `workflow` row above the agents, carrying their agent counts in place of a description. `Enter` on one opens the same two-pane inspector `/agents → Workflows` does, rather than a conversation overlay. A run's own agents are _not_ listed separately — they belong to the run, which reports for them, so they are filtered out of the fleet list, the above-editor widget, the `/agents` menus and `@handle` resolution exactly as nested children are. They are also outside the `maxConcurrent` pool: the run has its own concurrency cap, and routing a fan-out through the session pool as well would let one workflow starve everything else. The agents are ordered earliest-launched first, and only agents you can actually open are shown (pending/queued agents with no session yet appear once they start). At an **empty prompt**, press `↓` (or `←`) to move focus from the prompt into the list — the selected row is marked `●`, the rest `○`. The selected row renders in the theme's primary text color rather than the muted/dim treatment of the others; an agent with a configured `color` shows its badge there too, bolded. `↑`/`↓` move the selection, `Enter` opens the selected agent's live conversation overlay (it auto-updates as the agent works), and `Esc` (or `↑` above `main`) returns to the prompt. Selecting `main` returns to the normal view. Inside the overlay, press `Enter` to steer the running agent — type a message and `Enter` to send it (`Esc` or an empty submit returns), and it redirects the agent the same way the `steer_subagent` tool does. On a running foreground `Agent` call, press `b` to hand that run to the background; the hint only shows where the handoff is available. A viewer stays open when its agent finishes so you can read the final output, and finished agents linger in the list for a few seconds before dropping out. Typing anything at a non-empty prompt behaves normally — the list only captures arrow keys when the prompt is empty. Disable it entirely via `/agents → Settings → Fleet view`.
156
+ Subagents spawned by a subagent (nested delegation) are listed indented under their parent with `├`/`└`, and can be opened, steered and stopped like any other row. Each row's tokens and cost are that agent's own; a parent's figure excludes its children, which have rows of their own. Outside FleetView a parent still reports the rolled-up total, since nested children appear nowhere else.
157
+
158
+ Running [workflows](#subagentworkflow) appear as a single `workflow` row above the agents, carrying their agent counts in place of a description. `Enter` on one opens the same two-pane inspector `/agents → Workflows` does, rather than a conversation overlay. A run's own agents are _not_ listed separately — they belong to the run, which reports for them, so they are filtered out of the fleet list, the above-editor widget, the `/agents` menus and `@handle` resolution (nested children are filtered from all of those but the fleet list). They are also outside the `maxConcurrent` pool: the run has its own concurrency cap, and routing a fan-out through the session pool as well would let one workflow starve everything else. The agents are ordered earliest-launched first, and only agents you can actually open are shown (pending/queued agents with no session yet appear once they start). At an **empty prompt**, press `↓` (or `←`) to move focus from the prompt into the list — the selected row is marked with the `❯` cursor. `●` marks the view in front (`main`, or the agent whose overlay is open), `○` the rest. The selected row renders in the theme's primary text color rather than the muted/dim treatment of the others; an agent with a configured `color` shows its badge there too, bolded. `↑`/`↓` move the selection, `Enter` opens the selected agent's live conversation overlay (it auto-updates as the agent works), and `Esc` (or `↑` above `main`) returns to the prompt. Selecting `main` returns to the normal view. Inside the overlay, press `Enter` to steer the running agent — type a message and `Enter` to send it (`Esc` or an empty submit returns), and it redirects the agent the same way the `steer_subagent` tool does. On a running foreground `Agent` call, press `b` to hand that run to the background; the hint only shows where the handoff is available. A viewer stays open when its agent finishes so you can read the final output, and finished agents linger in the list for a few seconds before dropping out. Typing anything at a non-empty prompt behaves normally — the list only captures arrow keys when the prompt is empty. In fullscreen mode the mouse works too: hovering a row moves the `❯` cursor to it, and clicking a row opens it as `Enter` would (under tmux or screen, pi tracks clicks but not hover; regular mode has no mouse). Disable it entirely via `/agents → Settings → Fleet view`.
156
159
 
157
160
  ### Fullscreen conversation observer
158
161
 
@@ -239,7 +242,7 @@ The grammar mirrors Claude Code's, and is deliberately narrow so nothing gets sw
239
242
  | `@src/index.ts summarize this` | the main model, with pi's normal file attachment |
240
243
  | `@nosuchagent hello` | the main model, verbatim — no agent, no type, no interception |
241
244
 
242
- While an agent is live its handle addresses _it_, so `@explore` never starts a second Explore alongside a running one — use the `Agent` tool for deliberate parallelism. `@<agent-id>` works too. `main` is reserved and can never be an agent's handle (a type slugging to it gets `main-2`); handles are capped at 64 characters. A handle written as typed always wins over the `@agent-` form, so an agent genuinely called `agent-explore` stays reachable. [Nested subagents](#nested-subagents) are not addressable — they are hidden from every top-level surface and only their owner may steer them, so a handle that would name one starts a fresh top-level agent instead of reaching through that boundary. Suggestions list live agents first, then resumable ones, then startable types — and then pi's own file rows, in the same popup: `@` stays the file picker it always was, and the handles are added to it rather than replacing it. Disable the whole thing via `/agents → Settings → Agent mentions`.
245
+ While an agent is live its handle addresses _it_, so `@explore` never starts a second Explore alongside a running one — use the `Agent` tool for deliberate parallelism. `@<agent-id>` works too. `main` is reserved and can never be an agent's handle (a type slugging to it gets `main-2`); handles are capped at 64 characters. A handle written as typed always wins over the `@agent-` form, so an agent genuinely called `agent-explore` stays reachable. [Nested subagents](#nested-subagents) are not addressable — they are hidden from every top-level surface but [FleetView](#fleetview) and only their owner may steer them through tools, so a handle that would name one starts a fresh top-level agent instead of reaching through that boundary. Suggestions list live agents first, then resumable ones, then startable types — and then pi's own file rows, in the same popup: `@` stays the file picker it always was, and the handles are added to it rather than replacing it. Disable the whole thing via `/agents → Settings → Agent mentions`.
243
246
 
244
247
  A `direct`-mode start takes the non-tool spawn path shared with the scheduler and cross-extension RPC, so — like those — it writes no `.output` transcript. That is the trade for skipping the model call: a `model`-mode start goes through the real `Agent` tool and keeps everything. Live tool activity and the turn counter are _not_ part of that trade — a direct start renders them like any other agent. A mention-_resumed_ agent goes through the full resume wiring and keeps both in either mode.
245
248
 
@@ -275,7 +278,7 @@ Group completions render each agent as a separate block. The LLM receives struct
275
278
  | `Explore` | read, bash, grep, find, ls | inherit | `replace` (standalone) | Fast codebase exploration (read-only) |
276
279
  | `Plan` | read, bash, grep, find, ls | inherit | `replace` (standalone) | Software architect for implementation planning (read-only) |
277
280
 
278
- The `general-purpose` agent is a **parent twin** — it receives the parent's system prompt plus a sub-agent context bridge, so it follows the same rules the parent does. The parent's skill list, cwd and extension sections are left out: the subagent's own session adds them for itself, so its skills follow its `skills` setting. Explore and Plan use standalone prompts tailored to their read-only roles.
281
+ The `general-purpose` agent is a **parent twin** — it receives the parent's system prompt plus a sub-agent context bridge, so it follows the same rules the parent does. The parent's skill list, cwd and extension sections are left out: the subagent's own session adds them for itself, so its skills follow its `skills` setting. When it can [delegate](#nested-subagents), it also gets Claude Code's closing line telling it not to hand its whole assignment to a single child. Explore and Plan use standalone prompts tailored to their read-only roles.
279
282
 
280
283
  Default agents can be **ejected** (`/agents` → select agent → Eject) to export them as `.md` files for customization, **overridden** by creating a `.md` file with the same name (e.g. `.pi/agents/general-purpose.md`), or **disabled** per-project with `enabled: false` frontmatter. To run Explore on a cheaper model, eject it and add `model:` (e.g. `model: anthropic/claude-haiku-4-5`); a pinned model resolves through any provider with a key, not just the session's.
281
284
 
@@ -364,7 +367,7 @@ Frontmatter is authoritative. If an agent file sets `model`, `thinking`, `max_tu
364
367
 
365
368
  ### Nested subagents
366
369
 
367
- Nested delegation is default-off. Set `allowed_subagents` only on a non-isolated custom agent that owns a real fan-out responsibility:
370
+ The built-in `general-purpose` agent delegates out of the box, matching Claude Code: it already has every tool, so a child can do nothing it could not. It does not delegate as a [workflow](#subagentworkflow) `agent()`, where the script does the fanning out — Claude Code's workflow agents have no `Agent` tool either. `Explore` and `Plan` never delegate. For custom agents nesting is default-off — set `allowed_subagents` only on a non-isolated custom agent that owns a real fan-out responsibility:
368
371
 
369
372
  ```yaml
370
373
  ---
@@ -376,11 +379,19 @@ allowed_subagents: support-file-finder, support-callsite-tracer # or `all`
376
379
 
377
380
  **The allowlist is a privilege boundary, not just a routing hint.** A child runs with _its own_ `tools:`, `extensions:`, and `isolated:` — the parent's restrictions are not inherited — so delegation grants the parent the union of what the listed agents can do. The read-only agent above can write and run commands through any listed agent that can, and `all` reaches every enabled agent including `general-purpose`. Choose the list as carefully as you would choose `tools:` itself; that is the main reason this is default-off.
378
381
 
379
- `allowed_subagents` is runtime-enforced. A comma-separated list restricts nesting to those types; `all` (or `"*"` / `true`, matching how `extensions:` and `skills:` take booleans) allows any enabled agent; omitted, empty, `none`, or `false` means no nested tools are injected at all. Unknown, disabled, and out-of-list types are rejected rather than falling back — regardless of the project's [fallback agent](#persistent-settings) setting, so a configured fallback can never hand a nested caller an agent outside its allowlist — and a nested `model:` is validated against [Model Scope](#model-scope) exactly like a top-level spawn. Result, resume, and steering operations are ownership-scoped, so a parent can control only its own children. Nested records remain internal to that parent and do not appear in top-level tools, lifecycle events, or agent UI — so when a parent finishes, is stopped, or ends a resumed turn, its nested children are stopped with it. They do write their own `.output` transcript (subject to the same `output_transcript` gate), filed under the root session's directory alongside their ancestors', so a nested run can still be inspected after the fact. Their token usage is folded into every ancestor's totals up to the top-level agent (lifecycle events, completion notifications, `/agents`), so nested spend stays attributable at any depth even though the children themselves stay hidden. A nested result that ends `stopped`, `aborted`, or `steered` is labelled as partial, the same guarantee top-level results carry.
382
+ `allowed_subagents` is runtime-enforced. A comma-separated list restricts nesting to those types; `all` (or `"*"` / `true`, matching how `extensions:` and `skills:` take booleans) allows any enabled agent; omitted, empty, `none`, or `false` means no nested tools are injected at all. Unknown, disabled, and out-of-list types are rejected rather than falling back — regardless of the project's [fallback agent](#persistent-settings) setting, so a configured fallback can never hand a nested caller an agent outside its allowlist — and a nested `model:` is validated against [Model Scope](#model-scope) exactly like a top-level spawn. Result, resume, and steering operations are ownership-scoped, so a parent can control only its own children. Nested records remain internal to that parent and do not appear in top-level tools, lifecycle events, or agent UI other than [FleetView](#fleetview) (which lists them under their parent with their own usage) and `/agents → Running agents` — so when a parent finishes, is stopped, or ends a resumed turn, its nested children are stopped with it. They do write their own `.output` transcript (subject to the same `output_transcript` gate), filed under the root session's directory alongside their ancestors', so a nested run can still be inspected after the fact. Their token usage is folded into every ancestor's totals up to the top-level agent (lifecycle events, completion notifications, `/agents`), so nested spend stays attributable at any depth on surfaces where the children themselves stay hidden. A nested result that ends `stopped`, `aborted`, or `steered` is labelled as partial, the same guarantee top-level results carry.
383
+
384
+ `maxSubagentDepth` (default `2`) is the deepest level an agent may run at, counted from the main session (0). An agent can spawn only while its own depth is below it:
385
+
386
+ | `maxSubagentDepth` | Main → subagent (1) | Subagent → child (2) | Child → grandchild (3) |
387
+ | --------------------------- | ------------------- | -------------------- | ---------------------- |
388
+ | `0` or `1` | yes | no | no |
389
+ | `2` (default) | yes | yes | no |
390
+ | `3` (Claude Code's default) | yes | yes | yes |
380
391
 
381
- The hard cap is depth 2 by default: main session (0) → subagent (1) → nested child (2). Change it project-wide with `maxSubagentDepth` in `subagents.json` (or `/agents → Settings → Nested depth`); `0` or `1` turns nesting off everywhere. An agent already at the cap gets no nested tools at all — not even `get_subagent_result`, since it can never own a child. A child must independently set `allowed_subagents` to delegate again; isolated agents never receive nested tools.
392
+ **`0` or `1` turns nested subagents off everywhere, even for agents that set `allowed_subagents`** (including the built-in `general-purpose`). No agent gets nested tools or the re-delegation line, so no prompt carries any nesting text; top-level spawns from the main session are unaffected. Set it in `subagents.json` or `/agents → Settings → Nested depth`. An agent already at the cap gets no nested tools at all — not even `get_subagent_result`, since it can never own a child. A child delegates again only if its own agent allows it (`general-purpose` does); isolated agents never receive nested tools.
382
393
 
383
- Nested children occupy no concurrency slot, in either pool — their parent already holds one, and queueing them behind it would deadlock a parent waiting on its own child. The depth cap bounds how _deep_ nesting goes, not how _wide_: a parent's only limit on concurrent children is that each spawn costs it a turn. Pair `allowed_subagents` with a `max_turns` on that agent if you want a hard ceiling on its fan-out.
394
+ Nested children occupy no slot in either queueing pool — their parent already holds one, and queueing them behind it would deadlock a parent waiting on its own child. They do count toward the [nested limit](#concurrency) `maxConcurrentNested` (default `10`), which bounds how _wide_ nesting goes: a nested spawn over it is refused, not queued, and the parent gets a tool error telling it to do the work itself. The depth cap bounds how _deep_.
384
395
 
385
396
  Because a subagent session never activates this extension (that is what keeps a child from building a second agent manager, and it is why nested tools are injected directly instead), a subagent also gets none of the extension's other surfaces: no `/agents` command, no cross-extension RPC handlers, no `subagents:ready` event.
386
397
 
@@ -557,7 +568,7 @@ Check status and retrieve results from a background agent.
557
568
 
558
569
  Cancelling a `wait: true` call (for example, with `Esc`) stops only the wait. The background agent keeps running, and its completion notification still arrives normally.
559
570
 
560
- A finished agent's result stays retrievable after its in-memory record is cleaned up (about ten minutes after it finishes) or lost to a reload: the final record is saved in the session as a `subagents:record` entry, and `get_subagent_result` answers from it by id or by handle, without the stats or the conversation (`verbose`).
571
+ A finished agent's result stays retrievable after its in-memory record is cleaned up (about ten minutes after it finishes) or lost to a reload: the final record is saved in the session as a `subagents:record` entry, and `get_subagent_result` answers from it by id or by handle, without the stats or the conversation (`verbose`). That answer states when the run finished and how long ago, since the entry lasts as long as the session and a days-old result would otherwise read as current.
561
572
 
562
573
  ### `steer_subagent`
563
574
 
@@ -617,10 +628,10 @@ The `/agents` command opens an interactive menu:
617
628
  Running agents (2) — 1 running, 1 done ← only shown when agents exist
618
629
  Agent types (6) ← unified list: defaults + custom
619
630
  Create new agent ← manual wizard or AI-generated
620
- Settings ← max concurrency (background + foreground), max turns, grace turns, join mode
631
+ Settings ← max concurrency (background, foreground, nested), nested depth, max turns, grace turns, join mode
621
632
  ```
622
633
 
623
- - **Running agents** — select one to open its live conversation viewer. While it's still running, press `Enter` to open the steering composer, then `Enter` again to send a message that redirects the agent (same mechanism as the `steer_subagent` tool; `Esc` or an empty submit returns). On a live foreground run, press `b` to hand the same session and in-flight work to the background without stopping or restarting it — the blocked `Agent` call returns the agent ID and the run notifies on completion like any background agent. Press `x` (then `x` again to confirm) to stop/abort it — including **background** agents, which a global Esc can't unambiguously target (Esc still stops a blocking foreground `Agent` call, but no longer reaches one that has been handed off — `x` here does). A stopped agent reports its partial output flagged as incomplete, not as a completion. `m` cycles how much of the transcript renders as Markdown — see [Viewer markdown](#persistent-settings).
634
+ - **Running agents** — select one to open its live conversation viewer. Nested subagents are listed indented under their parent (`├`/`└`), as in [FleetView](#fleetview), and stay here after they finish. While it's still running, press `Enter` to open the steering composer, then `Enter` again to send a message that redirects the agent (same mechanism as the `steer_subagent` tool; `Esc` or an empty submit returns). On a live foreground run, press `b` to hand the same session and in-flight work to the background without stopping or restarting it — the blocked `Agent` call returns the agent ID and the run notifies on completion like any background agent. Press `x` (then `x` again to confirm) to stop/abort it — including **background** agents, which a global Esc can't unambiguously target (Esc still stops a blocking foreground `Agent` call, but no longer reaches one that has been handed off — `x` here does). A stopped agent reports its partial output flagged as incomplete, not as a completion. `m` cycles how much of the transcript renders as Markdown — see [Viewer markdown](#persistent-settings).
624
635
  - **Agent types** — unified list with source indicators: `•` (project), `◦` (global), `▪` ([package](docs/packages.md)), `✕` (disabled), explained by a legend naming only the badges actually on screen. Each row shows the agent's model, and the highlighted agent's full description appears below the list — prefixed with the declaring package's name for a `▪` agent, since the badge alone doesn't say _which_ package. The model column flags `(unavailable, fallback: inherit)` when a configured model can't be resolved (it would silently inherit the parent model), and shows `(→ provider/id)` when it resolves to a different provider or version than configured. Select an agent to manage it:
625
636
  - **Default agents** (no override): Eject (export as `.md`), Disable
626
637
  - **Default agents** (ejected/overridden): Edit, Disable, Reset to default, Delete
@@ -629,7 +640,7 @@ Settings ← max concurrency (background + fo
629
640
  - **Eject** — writes the embedded default config as a `.md` file to project or personal location, so you can customize it
630
641
  - **Disable/Enable** — toggle agent availability. Disabled agents stay visible in the list (marked `✕`) and can be re-enabled
631
642
  - **Create new agent** — choose project/personal location, then manual wizard (step-by-step prompts for name, tools, model, thinking, system prompt) or AI-generated (describe what the agent should do and a sub-agent writes the `.md` file). Any name is allowed, including default agent names (overrides them)
632
- - **Settings** — configure max concurrency (background and foreground), default max turns, grace turns, and join mode at runtime
643
+ - **Settings** — configure max concurrency (background, foreground and nested), nested depth, default max turns, grace turns, and join mode at runtime
633
644
 
634
645
  ## Graceful Max Turns
635
646
 
@@ -650,7 +661,7 @@ A resumed agent gets a fresh budget: `max_turns` is counted from the resume prom
650
661
 
651
662
  ## Concurrency
652
663
 
653
- There are two independent pools.
664
+ Each running agent falls under exactly one limit: top-level agents under one of two queueing pools, nested children under a nested limit, and a workflow's agents under the run's own cap.
654
665
 
655
666
  **Background** (`maxConcurrent`, default 10). Excess agents are automatically queued and start as running agents complete. The widget shows queued agents as a collapsed count. Since agents run in the background by default, nearly every spawn takes a slot; the limit was raised from 4 so that ordinary parallel fan-outs don't queue.
656
667
 
@@ -660,7 +671,11 @@ The two are deliberately **not** one limit. A foreground agent blocks the parent
660
671
 
661
672
  The foreground pool does not cover `resume`: a foreground resume reopens an existing session and never reaches the spawn path, so several blocking resumes in one message can still run at once. A _background_ resume does take a background slot and queues behind them like any other background agent.
662
673
 
663
- Nested children and a [workflow](#subagentworkflow)'s agents are outside the pool entirely. A nested child would deadlock behind a parent waiting on it; a workflow already bounds its own fan-out at `max(1, min(16, cpus - 2))`, and counting its agents twice would let one run fill the session's pool and starve everything else.
674
+ **Nested** (`maxConcurrentNested`, default `10`, `0` = unlimited). It counts running [nested children](#nested-subagents) across the session, including the children of workflow agents. A nested spawn over it is refused, not queued: the nested `Agent` call returns an error telling the parent to do the work itself. Queueing would deadlock a child behind a parent that waits on it. Top-level agents neither count nor are refused. A nested `resume` counts while it runs but is never refused, as in Claude Code.
675
+
676
+ Claude Code instead has one limit, `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS` (default `20`), which counts every subagent and refuses top-level spawns too. Here top-level spawns queue, and the default 10 background plus 10 nested gives the same 20 at full load. Set all three limits to bound the total.
677
+
678
+ A [workflow](#subagentworkflow)'s agents are outside all three: a workflow already bounds its own fan-out at `max(1, min(16, cpus - 2))`, and counting its agents twice would let one run fill the session's pool and starve everything else.
664
679
 
665
680
  Sending a foreground agent to the background moves its slot: it gives up the foreground slot (so a queued blocking `Agent` call can start) and takes a background one. If the background pool is already full it runs above capacity rather than being suspended, and queued background work waits until the count drops back under the limit.
666
681
 
@@ -704,14 +719,22 @@ When on, each subagent spawn's effective model is validated against pi's own `en
704
719
 
705
720
  ## Persistent Settings
706
721
 
707
- Runtime tuning values set via `/agents` → Settings (max concurrency, max foreground concurrency, default max turns, grace turns, nested depth, fallback agent, default join mode, scheduling on/off, scope models on/off, disable defaults on/off, strict agent files on/off, package agents on/off, package workflows on/off, agent mentions on/off, output transcript on/off, tool description full/compact/custom, widget all/background/off, usage reporting on/off, cost display on/off, model display on/off, viewer markdown off/assistant/all) persist across pi restarts. Two files, merged on load:
722
+ Runtime tuning values set via `/agents` → Settings (max background concurrency, max foreground concurrency, max nested concurrency, nested depth, default max turns, grace turns, fallback agent, default join mode, scheduling on/off, scope models on/off, disable defaults on/off, strict agent files on/off, package agents on/off, package workflows on/off, agent mentions on/off, output transcript on/off, tool description full/compact/custom, widget all/background/off, usage reporting on/off, cost display on/off, model display on/off, viewer markdown off/assistant/all) persist across pi restarts. Two files, merged on load:
723
+
724
+ - **Global:** `~/.pi/agent/subagents.json` — your machine-wide defaults.
725
+ - **Project:** `<cwd>/.pi/subagents.json` — per-project overrides.
726
+
727
+ `/agents` → Settings writes to the scope named in its header: Project when the project already has a `subagents.json`, Global otherwise. Tab switches it. Choosing Project in a repo without the file creates it on your first change; without that choice the menu never creates one. The list always shows the effective (merged) values, and saving to Global a setting the project file also sets warns that the project value still wins.
728
+
729
+ A save writes only the setting you changed into that file; every other key in it, including ones another pi session saved, is left as it was.
730
+
731
+ Rows are ordered by category: limits, dispatch, features, agent files, display. The filter sits above the first row: typing filters the rows by label from anywhere in the list, ↓ or Enter from the filter moves onto the first row without changing it, ↑ from the first row returns to the filter, and Esc clears it before it closes the menu. The list fits the terminal and scrolls when it has more rows than room.
708
732
 
709
- - **Global:** `~/.pi/agent/subagents.json` — your machine-wide defaults. Edit by hand; the `/agents` menu never writes here.
710
- - **Project:** `<cwd>/.pi/subagents.json` — per-project overrides. Written by `/agents` → Settings.
733
+ A row whose value comes from a settings file is tagged with that file (`project` or `global`, in a column after the labels); an untagged row is at its built-in default. With the cursor on a tagged row, Delete (or Backspace) removes that setting from the tagged file, so the row shows what the next start would load: the other file's value if it sets one, otherwise the built-in default. With the cursor in the filter, those keys edit the filter instead. Enter on a number row opens an input under the list, with the accepted range: Enter saves, Esc returns to the list, and a value outside the range is refused. The ranges match what loading accepts, so a value the menu saves survives a restart.
711
734
 
712
- **Precedence:** project overrides global on any field present in both. Missing fields fall back to the hardcoded defaults (max concurrency `10`, max foreground concurrency `0` = unlimited, default max turns unlimited, grace turns `5`, nested depth `2`, join mode `smart`, defaults enabled).
735
+ **Precedence:** project overrides global on any field present in both. Missing fields fall back to the hardcoded defaults (max background concurrency `10`, max foreground concurrency `0` = unlimited, max nested concurrency `10`, default max turns unlimited, grace turns `5`, nested depth `2`, join mode `smart`, defaults enabled).
713
736
 
714
- **Nested depth** (`maxSubagentDepth`, default `2`): the hard ceiling on [nested delegation](#nested-subagents), counted from the main session (main = 0, its subagents = 1). `0` or `1` disables nesting project-wide regardless of any agent's `allowed_subagents`. Read when a subagent session is built, so a change applies to agents started after it.
737
+ **Nested depth** (`maxSubagentDepth`, default `2`): the hard ceiling on [nested delegation](#nested-subagents), counted from the main session (main = 0, its subagents = 1). `0` or `1` disables nested subagents entirely, even for agents that set `allowed_subagents` — see the [depth table](#nested-subagents). Read when a subagent session is built, so a change applies to agents started after it.
715
738
 
716
739
  **Fallback agent** (`fallbackSubagent`, default `general-purpose`): the agent used when a caller-supplied `subagent_type` doesn't resolve to exactly one enabled agent — unknown, disabled, or ambiguous because two agents differ only by case. Name any enabled agent to route those calls there instead, or set `none` for **strict**, fail-closed dispatch: the call is refused with an error listing the available types, and nothing spawns. Strict mode matters most for background and scheduled calls, which would otherwise start executing a substituted agent before the caller learns anything. Also settable from `/agents → Settings → Fallback agent`. The boolean `false` is accepted as a spelling of `none`, because it would otherwise be dropped as the wrong type and silently leave the permissive default in place. Every other value is read as an agent name, so a mistaken `off` fails loudly at dispatch rather than meaning one thing in the settings file and another in the resolver. A fallback agent that is itself unknown or disabled is a misconfiguration and is reported rather than quietly replaced. Note the default is unchanged and stays permissive by design: with `disableDefaultAgents` and no `general-purpose` of your own, an unresolvable type still resolves to a built-in config carrying _all_ tools — set `none` (or name one of your own agents) to close that.
717
740
 
@@ -748,13 +771,14 @@ The `~` marks it as pi's estimate rather than a billed figure. **A cost is shown
748
771
 
749
772
  Independent of `reportUsage`: this one is what you read, that one is what your session counts. Toggle via `/agents → Settings → Show cost`; applied live.
750
773
 
751
- **Show model** (`showModel`, default `false`): whether the widget's running rows name the model driving each agent and the thinking level it is running at:
774
+ **Show model** (`showModel`, default `false`): whether the widget's running rows and the fleet view rows name the model driving each agent and the thinking level it is running at:
752
775
 
753
776
  ```text
754
- ├─ ⠹ Explore inspect code · sonnet 4.6 · thinking: high · ↻3 · 8.2k token · 4.1s
777
+ ├─ ⠹ Explore inspect code · sonnet 4.6 · high · ↻3 · 8.2k token · 4.1s widget
778
+ ○ Explore inspect code · sonnet 4.6 · high 4s · ↓ 8.2k tokens fleet view
755
779
  ```
756
780
 
757
- Off by default because the row already carries the description, turns, tool uses, tokens and elapsed time, and every character it gains is one the description loses on a narrow terminal. The other surfaces show the pair either way: the `Agent` tool result names the model beside its tags, and the conversation viewer's `↳` row spells out the canonical `provider/model-id`.
781
+ Off by default because the row already carries the description, turns, tool uses, tokens and elapsed time, and every character it gains is one the description loses on a narrow terminal. On a fleet row the pair follows the description, so a narrow terminal cuts it before the agent's name or stats. The other surfaces show the pair either way: the `Agent` tool result names the model beside its tags, and the conversation viewer's `↳` row spells out the canonical `provider/model-id`.
758
782
 
759
783
  Both places report what the run _actually_ used, read back from the child session once pi has resolved its defaults and clamped the level to what the model supports — not what the call asked for. Where those differ, the request is kept beside the effective value rather than dropped, whether pi clamped it or an agent file's frontmatter outranked it:
760
784
 
@@ -815,7 +839,7 @@ EOF
815
839
 
816
840
  Every project now starts with concurrency 16 and grace 10, without ever touching the menu. Individual projects can still override via `/agents` → Settings.
817
841
 
818
- **Failure behavior:** missing file is silent; malformed JSON logs a `[pi-subagents] Ignoring malformed settings at …` warning to stderr; invalid/out-of-range field values are dropped per-field; write failures downgrade the `/agents` toast to a warning with `(session only; failed to persist)`.
842
+ **Failure behavior:** missing file is silent; malformed JSON logs a `[pi-subagents] Ignoring malformed settings at …` warning to stderr; invalid/out-of-range field values are dropped per-field; a successful save's `/agents` toast ends with `(saved to global settings)` or `(saved to project settings)`; write failures — including a target file that is malformed or not a JSON object, which is left untouched — downgrade it to a warning with `(session only; failed to persist)`.
819
843
 
820
844
  ## Events
821
845
 
@@ -901,7 +925,7 @@ pi.events.emit("subagents:rpc:spawn", {
901
925
  })
902
926
  ```
903
927
 
904
- `options` is the manager's spawn-option object, not the `Agent` tool's parameter schema — the background flag is `isBackground`, and the tool's snake_case `run_in_background` is forwarded verbatim and ignored. Every RPC spawn returns its id immediately and runs detached either way; `isBackground: true` is what makes the agent occupy one of the `maxConcurrent` slots (and queue behind them when they are full). It does not affect `subagents:created`, which is never emitted for an RPC spawn at all — the first event you see for one is `subagents:started`. Leaving it unset starts the agent immediately regardless of the limit. `maxConcurrentForeground` never applies here whatever `isBackground` says: it bounds only spawns a caller is blocking on inline, and every RPC spawn is detached. A top-level RPC spawn renders in the widget and FleetView while it runs, with the same live tool activity and turn counter an `Agent`-tool spawn gets — only an explicit `isBackground: false` is dropped by the widget's default `background` mode, the way a foreground `Agent` call is. Nested spawns stay hidden from both.
928
+ `options` is the manager's spawn-option object, not the `Agent` tool's parameter schema — the background flag is `isBackground`, and the tool's snake_case `run_in_background` is forwarded verbatim and ignored. Every RPC spawn returns its id immediately and runs detached either way; `isBackground: true` is what makes the agent occupy one of the `maxConcurrent` slots (and queue behind them when they are full). It does not affect `subagents:created`, which is never emitted for an RPC spawn at all — the first event you see for one is `subagents:started`. Leaving it unset starts the agent immediately regardless of the limit. `maxConcurrentForeground` never applies here whatever `isBackground` says: it bounds only spawns a caller is blocking on inline, and every RPC spawn is detached. A top-level RPC spawn renders in the widget and FleetView while it runs, with the same live tool activity and turn counter an `Agent`-tool spawn gets — only an explicit `isBackground: false` is dropped by the widget's default `background` mode, the way a foreground `Agent` call is. Nested spawns stay hidden from the widget; FleetView lists them under their parent.
905
929
 
906
930
  `options.model` accepts either a `Model` object (e.g. `ctx.model`) or a `"provider/modelId"` string — strings are resolved against `ctx.modelRegistry` at the RPC boundary, so cross-extension callers can forward serializable values without losing auth context. Resolution is fuzzy, so a bare `"sonnet"` can land on a provider you never named: with [Model Scope](#model-scope) on, an override that resolves outside `enabledModels` is refused with an error envelope listing the allowed models, exactly as a caller-supplied `Agent({ model })` is. `null` means unset — the agent inherits, same as omitting the field.
907
931
 
@@ -1118,10 +1142,13 @@ src/
1118
1142
  ui/
1119
1143
  agent-widget.ts # Persistent widget: spinners, activity, status icons, theming
1120
1144
  fleet-list.ts # FleetView: navigable agent list below the editor
1145
+ agent-tree.ts # Nested agents laid out under their parent (FleetView, /agents)
1121
1146
  conversation-viewer.ts # Live conversation overlay for viewing agent sessions
1122
1147
  viewer-keys.ts # Viewer scroll, expand and jump keys, resolved through user keybindings
1123
1148
  agent-mention.ts # `@` roster (running, resumable, and startable agents) + popup rows
1149
+ agents-menu.ts # /agents root menu, running agents, agent types and detail, create wizards
1124
1150
  schedule-menu.ts # /agents → Scheduled jobs submenu
1151
+ settings-menu.ts # /agents → Settings page: filter, focus, number editor, terminal-sized list
1125
1152
  select-item.ts # Collision-safe ctx.ui.select wrapper (numbered rows)
1126
1153
  workflow-card.ts # Inline workflow card (tool result and session entry)
1127
1154
  workflow-dialog.ts # /agents → Workflows two-pane inspector
@@ -263,17 +263,17 @@ Spawns one subagent and resolves to its final text — or, with `schema`, to a v
263
263
 
264
264
  **Returns `null` if the agent failed terminally _or_ if you skipped it from the inspector**, indistinguishably. Filter with `.filter(Boolean)` when a `null` would break a later stage, and be careful with in-script retry loops: retrying on `null` will re-run something you deliberately skipped.
265
265
 
266
- | Option | Type | Notes |
267
- | ----------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
268
- | `label` | string | Display name in the progress tree. Also the handle `resume` addresses |
269
- | `phase` | string | Put this agent in a named group, overriding the ambient `phase()`. **Use it inside `pipeline`/`parallel` stages**, where the ambient phase races |
270
- | `agentType` | string | Which agent definition to use. Defaults to `general-purpose`; built-ins are `general-purpose`, `Explore`, `Plan`, plus your custom agents |
271
- | `model` | string | `provider/modelId`, or fuzzy like `haiku` |
272
- | `effort` | string | `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. Omitted, the agent definition's own `thinking` decides, then the parent's |
273
- | `isolation` | `"worktree"` | Run in a throwaway git worktree. Only when agents write files in parallel and would collide — it costs setup time and disk per agent. Only this option decides, as in Claude Code — an agent file's `isolation:` does not apply to workflow children |
274
- | `gate` | string | A shell command run after the agent finishes; a non-zero exit fails the agent and its output becomes the error |
275
- | `resume` | string | Continue the child that ran under that label instead of starting fresh |
276
- | `schema` | object | A JSON Schema with an object root. Resolves to the validated object instead of text |
266
+ | Option | Type | Notes |
267
+ | ----------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
268
+ | `label` | string | Display name in the progress tree. Also the handle `resume` addresses |
269
+ | `phase` | string | Put this agent in a named group, overriding the ambient `phase()`. **Use it inside `pipeline`/`parallel` stages**, where the ambient phase races |
270
+ | `agentType` | string | Which agent definition to use. Defaults to `general-purpose`; built-ins are `general-purpose`, `Explore`, `Plan`, plus your custom agents. The built-in `general-purpose` gets no nested `Agent` tool here; a custom agent with `allowed_subagents` keeps its own |
271
+ | `model` | string | `provider/modelId`, or fuzzy like `haiku` |
272
+ | `effort` | string | `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. Omitted, the agent definition's own `thinking` decides, then the parent's |
273
+ | `isolation` | `"worktree"` | Run in a throwaway git worktree. Only when agents write files in parallel and would collide — it costs setup time and disk per agent. Only this option decides, as in Claude Code — an agent file's `isolation:` does not apply to workflow children |
274
+ | `gate` | string | A shell command run after the agent finishes; a non-zero exit fails the agent and its output becomes the error |
275
+ | `resume` | string | Continue the child that ran under that label instead of starting fresh |
276
+ | `schema` | object | A JSON Schema with an object root. Resolves to the validated object instead of text |
277
277
 
278
278
  Any other key is rejected **by name** at the call. Note that this checks option _keys_, not option _values_ — an `agentType` that names no known agent falls back to `general-purpose` silently.
279
279
 
@@ -341,7 +341,7 @@ These are three different things and are easy to conflate: 1000 is a budget for
341
341
 
342
342
  Above 25 scheduled agents, or 1.5M tokens actual or projected, the card adds `⚠ Large workflow · /agents → Workflows to stop`.
343
343
 
344
- A run's concurrency limit is its own, independent of the session's `maxConcurrent` and `maxConcurrentForeground` pools — its agents do not enter either.
344
+ A run's concurrency limit is its own, independent of the session's `maxConcurrent` and `maxConcurrentForeground` pools — its agents do not enter either, and do not count toward `maxConcurrentNested`. Nested children that a workflow agent spawns through `allowed_subagents` do count, and are refused over that limit.
345
345
 
346
346
  ### Settings and the CLI flag
347
347
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herbertgao/pi-subagents",
3
- "version": "0.23.2-local.1",
3
+ "version": "0.25.0-local.1",
4
4
  "description": "Claude Code-style autonomous subagents and workflow orchestration for Pi, with HerbertGao-maintained UI extensions.",
5
5
  "keywords": [
6
6
  "agent",
@@ -69,10 +69,10 @@
69
69
  },
70
70
  "x-upstream": {
71
71
  "package": "@tintinweb/pi-subagents",
72
- "version": "0.23.2",
73
- "reviewedVersion": "0.23.2",
72
+ "version": "0.25.0",
73
+ "reviewedVersion": "0.25.0",
74
74
  "repository": "https://github.com/tintinweb/pi-subagents",
75
- "commit": "a35acfb3b699e49f579f494473c38c87592f6c8e",
75
+ "commit": "b8efc069f05efe50b58a4b74140116c1c9a9dcc1",
76
76
  "trackVersion": true
77
77
  }
78
78
  }
@@ -12,6 +12,9 @@
12
12
  * session of work it could have done itself. Excess agents in either pool are
13
13
  * queued and auto-started as slots free up. Nested children take no slot in
14
14
  * either — see `occupiesPoolSlot` / `occupiesForegroundSlot`.
15
+ *
16
+ * Nested children are bounded by `maxConcurrentNested` instead, which refuses
17
+ * rather than queues — see `spawn`.
15
18
  */
16
19
 
17
20
  import { randomUUID } from "node:crypto"
@@ -64,7 +67,8 @@ export type OnAgentCompact = (record: AgentRecord, info: CompactionInfo) => void
64
67
  * double-booked into ancestors (see `nested-tools.ts`) so a hidden child's spend
65
68
  * shows up on the record a human can see, which makes those records useless as
66
69
  * a basis for anything that must not count a message twice — parent-session
67
- * accounting above all.
70
+ * accounting above all. (`AgentRecord.ownUsage` is the per-record figure that
71
+ * is not double-booked.)
68
72
  */
69
73
  export type OnAgentUsage = (record: AgentRecord, usage: LifetimeUsage) => void
70
74
  export type CompactionInfo = {
@@ -96,6 +100,13 @@ const DEFAULT_MAX_CONCURRENT = 10
96
100
  */
97
101
  const DEFAULT_MAX_CONCURRENT_FOREGROUND = 0
98
102
 
103
+ /**
104
+ * Default cap on running nested children. Added to a full background pool
105
+ * (`DEFAULT_MAX_CONCURRENT`) it gives 20, Claude Code's default for
106
+ * `CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS`.
107
+ */
108
+ const DEFAULT_MAX_CONCURRENT_NESTED = 10
109
+
99
110
  /**
100
111
  * How many evicted agents stay addressable by name. Only a bound on memory —
101
112
  * a session that spawns hundreds of agents shouldn't retain every one — and
@@ -145,9 +156,7 @@ function assertValidSpawnCwd(
145
156
  * Nested children don't: their parent already holds a slot, so counting (and
146
157
  * therefore queueing) them would deadlock a parent that waits on its own child.
147
158
  *
148
- * Note this bounds nothing horizontally — the depth cap limits how DEEP nesting
149
- * goes, not how WIDE. A parent's only limit on concurrent children is that each
150
- * spawn costs it a turn, which is unbounded when max turns is unlimited.
159
+ * How WIDE nesting goes is bounded by `maxConcurrentNested` — see `spawn`.
151
160
  */
152
161
  function occupiesPoolSlot(
153
162
  record: Pick<AgentRecord, "isBackground" | "parentAgentId" | "workflowId">,
@@ -159,10 +168,12 @@ function occupiesPoolSlot(
159
168
  * Whether a record is one of the session's own agents, rather than something
160
169
  * another agent or a workflow owns.
161
170
  *
162
- * The single definition behind every user-facing surface — the fleet list, the
163
- * widget, the `/agents` menus, `@handle` resolution, and the completion events
164
- * and session entries. An owned child reports through its owner, so surfacing
165
- * it separately would double-count the same work in the places a person reads.
171
+ * The single definition behind the user-facing surfaces — the widget, `@handle`
172
+ * resolution, and the completion events and session entries. An owned child
173
+ * reports through its owner, so surfacing it separately would double-count the
174
+ * same work in the places a person reads. FleetView and `/agents → Running
175
+ * agents` are the exceptions: they list Agent-tool children under their parent
176
+ * (`agentTree`), with no rolled-up figures to double-count.
166
177
  */
167
178
  export function isTopLevelAgent(
168
179
  record: Pick<AgentRecord, "parentAgentId" | "workflowId">,
@@ -443,6 +454,7 @@ export class AgentManager {
443
454
  private onSteered?: OnAgentSteered
444
455
  private maxConcurrent: number
445
456
  private maxConcurrentForeground = DEFAULT_MAX_CONCURRENT_FOREGROUND
457
+ private maxConcurrentNested = DEFAULT_MAX_CONCURRENT_NESTED
446
458
  /** Base repos worktrees were created from — so dispose() can prune them all,
447
459
  * not just the parent repo (caller-supplied cwd can target other repos). */
448
460
  private worktreeRepos = new Set<string>()
@@ -534,6 +546,34 @@ export class AgentManager {
534
546
  return this.maxConcurrentForeground
535
547
  }
536
548
 
549
+ /** Update the cap on running nested children, over which nested spawns are refused. 0 = unlimited. */
550
+ setMaxConcurrentNested(n: number) {
551
+ // Nothing queues on this cap, so a change has nothing to drain.
552
+ this.maxConcurrentNested = Math.max(0, n)
553
+ }
554
+
555
+ getMaxConcurrentNested(): number {
556
+ return this.maxConcurrentNested
557
+ }
558
+
559
+ /**
560
+ * Running nested children outside workflows — what `maxConcurrentNested`
561
+ * caps. Read from the records rather than kept as a counter, so no start or
562
+ * settle path can leak a slot.
563
+ */
564
+ private runningNestedCount(): number {
565
+ let n = 0
566
+ for (const record of this.agents.values()) {
567
+ if (
568
+ record.status === "running" &&
569
+ record.parentAgentId !== undefined &&
570
+ record.workflowId === undefined
571
+ )
572
+ n++
573
+ }
574
+ return n
575
+ }
576
+
537
577
  /**
538
578
  * Which pool a spawn is charged to, or undefined for one that is charged to
539
579
  * neither (nested children, detached non-background spawns).
@@ -581,6 +621,25 @@ export class AgentManager {
581
621
  // can fix and retry; the RPC layer converts throws into error envelopes.
582
622
  assertValidSpawnCwd(options.cwd)
583
623
 
624
+ // Nested fan-out is capped by refusing, not queueing: a nested child cannot
625
+ // queue — its parent waits on it while holding a slot — so refusing is the
626
+ // only bound that cannot deadlock. The parent is told to do the work itself,
627
+ // as Claude Code tells it over CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS. Only
628
+ // nested children count; top-level agents have their pools, and a
629
+ // workflow's agents the run's own cap.
630
+ if (
631
+ options.parentAgentId !== undefined &&
632
+ options.workflowId === undefined &&
633
+ this.maxConcurrentNested > 0 &&
634
+ this.runningNestedCount() >= this.maxConcurrentNested
635
+ ) {
636
+ throw new Error(
637
+ `Concurrent nested subagent limit reached. You can run ${this.maxConcurrentNested} nested subagents at once. Do not retry. ` +
638
+ "Complete this task directly with your tools, or if the user wants more, " +
639
+ "ask them to raise maxConcurrentNested in /agents → Settings.",
640
+ )
641
+ }
642
+
584
643
  // A reclaimed id must not be live: the record would replace the one in the
585
644
  // map, orphaning its run beyond the reach of stop and `abortAll()`.
586
645
  // Callers reopen only what they found evicted; this keeps that true.
@@ -622,6 +681,7 @@ export class AgentManager {
622
681
  startedAt: Date.now(),
623
682
  abortController,
624
683
  lifetimeUsage: { input: 0, output: 0, cacheWrite: 0, cost: 0 },
684
+ ownUsage: { input: 0, output: 0, cacheWrite: 0, cost: 0 },
625
685
  compactionCount: 0,
626
686
  // Raw tri-state (not coerced to a boolean): true = background, false =
627
687
  // foreground (has an inline tool-result surface), undefined = caller never
@@ -952,6 +1012,7 @@ export class AgentManager {
952
1012
  onTextDelta: options.onTextDelta,
953
1013
  onAssistantUsage: (usage) => {
954
1014
  addUsage(record.lifetimeUsage, usage)
1015
+ addUsage(record.ownUsage, usage)
955
1016
  this.onUsage?.(record, usage)
956
1017
  options.onAssistantUsage?.(usage)
957
1018
  },
@@ -1446,6 +1507,7 @@ export class AgentManager {
1446
1507
  },
1447
1508
  onAssistantUsage: (usage) => {
1448
1509
  addUsage(record.lifetimeUsage, usage)
1510
+ addUsage(record.ownUsage, usage)
1449
1511
  this.onUsage?.(record, usage)
1450
1512
  options?.onAssistantUsage?.(usage)
1451
1513
  },
@@ -1587,6 +1649,7 @@ export class AgentManager {
1587
1649
  },
1588
1650
  onAssistantUsage: (usage) => {
1589
1651
  addUsage(record.lifetimeUsage, usage)
1652
+ addUsage(record.ownUsage, usage)
1590
1653
  this.onUsage?.(record, usage)
1591
1654
  options.onAssistantUsage?.(usage)
1592
1655
  },
@@ -1831,6 +1894,8 @@ export class AgentManager {
1831
1894
  * Called on session start/switch so tasks from a prior session don't persist.
1832
1895
  * Pass skipUnconsumed=true to preserve records the LLM hasn't read yet
1833
1896
  * (resultConsumed=false). The cleanup timer only evicts consumed results.
1897
+ * A nested child is spared only while its parent stays: the parent is its
1898
+ * only reader, and nothing marks it consumed when the parent collects it.
1834
1899
  */
1835
1900
  clearCompleted(skipUnconsumed = false): void {
1836
1901
  for (const [id, record] of this.agents) {
@@ -1838,6 +1903,17 @@ export class AgentManager {
1838
1903
  if (skipUnconsumed && !record.resultConsumed) continue
1839
1904
  this.removeRecord(id, record)
1840
1905
  }
1906
+ // One pass reaches grandchildren too: the map is in spawn order, so a
1907
+ // parent is visited, and removed, before its children.
1908
+ for (const [id, record] of this.agents) {
1909
+ if (record.status === "running" || record.status === "queued") continue
1910
+ if (
1911
+ record.parentAgentId === undefined ||
1912
+ this.agents.has(record.parentAgentId)
1913
+ )
1914
+ continue
1915
+ this.removeRecord(id, record)
1916
+ }
1841
1917
  // Unconditional: both callers are session boundaries (`session_start` and
1842
1918
  // `session_before_switch`), and `skipUnconsumed` only spares records whose
1843
1919
  // results the LLM has yet to read — it does not make the sweep partial in
@@ -1005,6 +1005,57 @@ export async function runAgent(
1005
1005
  }
1006
1006
  }
1007
1007
 
1008
+ const disallowedSet = agentConfig?.disallowedTools
1009
+ ? new Set(agentConfig.disallowedTools)
1010
+ : undefined
1011
+
1012
+ // Nested delegation tools (opt-in, ownership-scoped). Empty unless the agent
1013
+ // set `allowed_subagents` and a nestedRuntime was provided — and never when
1014
+ // isolated. Their names collide with EXCLUDED_TOOL_NAMES by design, so the
1015
+ // scoping below re-admits them explicitly (registry deny + active-set narrow).
1016
+ // Decided before the prompt is built, which says so when the agent delegates.
1017
+ const effectiveMaxDepth =
1018
+ options.nestedRuntime?.maxSubagentDepth ?? getMaxSubagentDepth()
1019
+ // At (or past) the cap this agent can never spawn, so it can never own a child
1020
+ // to fetch from or steer either — inject nothing rather than three tools whose
1021
+ // every call is an error. This is also what makes `maxSubagentDepth` 0/1 mean
1022
+ // "nesting off" instead of "nesting always fails".
1023
+ const nestedRuntime =
1024
+ options.nestedRuntime && options.nestedRuntime.depth < effectiveMaxDepth
1025
+ ? options.nestedRuntime
1026
+ : undefined
1027
+ // A workflow agent running the built-in general-purpose (what an untyped
1028
+ // agent() gets) does not delegate: Claude Code's `workflow-subagent` drops the
1029
+ // Agent tool, and the workflow script is what fans out. A custom agent's own
1030
+ // `allowed_subagents` still applies.
1031
+ const builtinInWorkflow =
1032
+ options.workflow === true && agentConfig?.isDefault === true
1033
+ const nestedTools =
1034
+ agentConfig?.allowedSubagents &&
1035
+ nestedRuntime &&
1036
+ !isolated &&
1037
+ !builtinInWorkflow
1038
+ ? createNestedSubagentTools({
1039
+ manager: nestedRuntime.manager,
1040
+ pi: options.pi,
1041
+ parentAgentId: nestedRuntime.parentAgentId,
1042
+ depth: nestedRuntime.depth,
1043
+ maxSubagentDepth: effectiveMaxDepth,
1044
+ allowedSubagents: agentConfig.allowedSubagents,
1045
+ configCwd,
1046
+ })
1047
+ : []
1048
+ const nestedToolNames = new Set(nestedTools.map((tool) => tool.name))
1049
+ // Only where the built-in general-purpose can actually spawn — not in a
1050
+ // workflow, at the depth cap, isolated, or with `Agent` disallowed.
1051
+ if (
1052
+ agentConfig?.isDefault &&
1053
+ nestedToolNames.has("Agent") &&
1054
+ !disallowedSet?.has("Agent")
1055
+ ) {
1056
+ extras.delegationGuideline = true
1057
+ }
1058
+
1008
1059
  // Build system prompt from agent config
1009
1060
  let systemPrompt: string
1010
1061
  if (agentConfig) {
@@ -1267,38 +1318,6 @@ export async function runAgent(
1267
1318
  const thinkingLevel =
1268
1319
  options.thinkingLevel ?? agentConfig?.thinking ?? ctx.thinkingLevel
1269
1320
 
1270
- const disallowedSet = agentConfig?.disallowedTools
1271
- ? new Set(agentConfig.disallowedTools)
1272
- : undefined
1273
-
1274
- // Nested delegation tools (opt-in, ownership-scoped). Empty unless the agent
1275
- // set `allowed_subagents` and a nestedRuntime was provided — and never when
1276
- // isolated. Their names collide with EXCLUDED_TOOL_NAMES by design, so the
1277
- // scoping below re-admits them explicitly (registry deny + active-set narrow).
1278
- const effectiveMaxDepth =
1279
- options.nestedRuntime?.maxSubagentDepth ?? getMaxSubagentDepth()
1280
- // At (or past) the cap this agent can never spawn, so it can never own a child
1281
- // to fetch from or steer either — inject nothing rather than three tools whose
1282
- // every call is an error. This is also what makes `maxSubagentDepth` 0/1 mean
1283
- // "nesting off" instead of "nesting always fails".
1284
- const nestedRuntime =
1285
- options.nestedRuntime && options.nestedRuntime.depth < effectiveMaxDepth
1286
- ? options.nestedRuntime
1287
- : undefined
1288
- const nestedTools =
1289
- agentConfig?.allowedSubagents && nestedRuntime && !isolated
1290
- ? createNestedSubagentTools({
1291
- manager: nestedRuntime.manager,
1292
- pi: options.pi,
1293
- parentAgentId: nestedRuntime.parentAgentId,
1294
- depth: nestedRuntime.depth,
1295
- maxSubagentDepth: effectiveMaxDepth,
1296
- allowedSubagents: agentConfig.allowedSubagents,
1297
- configCwd,
1298
- })
1299
- : []
1300
- const nestedToolNames = new Set(nestedTools.map((tool) => tool.name))
1301
-
1302
1321
  // The `agent({ schema })` contract: this child reports its answer by calling
1303
1322
  // StructuredOutput, and `structuredJson` below is what the caller reads. The
1304
1323
  // schema was already compiled by whoever asked for it, so a bad one failed