pi-subagents 0.19.0 → 0.19.2

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
@@ -4,7 +4,7 @@
4
4
 
5
5
  # pi-subagents
6
6
 
7
- Pi extension for delegating tasks to subagents with chains, parallel execution, TUI clarification, and async support.
7
+ `pi-subagents` lets Pi delegate work to focused child agents. Use it for code review, scouting, implementation, parallel audits, saved workflows, background jobs, and anything else that benefits from a second or third set of model eyes.
8
8
 
9
9
  https://github.com/user-attachments/assets/702554ec-faaf-4635-80aa-fb5d6e292fd1
10
10
 
@@ -14,379 +14,513 @@ https://github.com/user-attachments/assets/702554ec-faaf-4635-80aa-fb5d6e292fd1
14
14
  pi install npm:pi-subagents
15
15
  ```
16
16
 
17
- If you use [pi-prompt-template-model](https://github.com/nicobailon/pi-prompt-template-model), you can wrap subagent delegation in a slash command:
17
+ That is the only required step. You can add optional pieces later.
18
18
 
19
- ```markdown
20
- ---
21
- description: Take a screenshot
22
- model: claude-sonnet-4-20250514
23
- subagent: browser-screenshoter
24
- cwd: /tmp/screenshots
25
- ---
26
- Use url in the prompt to take screenshot: $@
27
- ```
19
+ ## Try this first
28
20
 
29
- Then `/take-screenshot https://example.com` switches to Sonnet, delegates to the `browser-screenshoter` agent with `/tmp/screenshots` as the working directory, and restores your model when done. Runtime overrides like `--cwd=<path>` and `--subagent=<name>` work too.
21
+ You do not need to create agents, write config, or learn slash commands. After installing, ask Pi for delegation in plain language:
30
22
 
31
- pi-prompt-template-model is entirely optional — pi-subagents works standalone through the `subagent` tool and slash commands. If you want reusable prompt-template workflows on top of subagents, including `/chain-prompts` and compare-style prompts like `pi-prompt-template-model`'s `/best-of-n` example, install [pi-prompt-template-model](https://github.com/nicobailon/pi-prompt-template-model) separately and copy any example prompts you want from its `examples/` directory into `~/.pi/agent/prompts/`.
23
+ ```text
24
+ Use reviewer to review this diff.
25
+ ```
32
26
 
33
- ## Agents
27
+ ```text
28
+ Ask oracle for a second opinion on my current plan.
29
+ ```
34
30
 
35
- Agents are markdown files with YAML frontmatter that define specialized subagent configurations.
31
+ ```text
32
+ Use scout to understand this code based on our discussion then ask me clarification questions.
33
+ ```
36
34
 
37
- **Agent file locations:**
35
+ ```text
36
+ Run parallel reviewers: one for correctness, one for tests, and one for unnecessary complexity.
37
+ ```
38
38
 
39
- | Scope | Path | Priority |
40
- |-------|------|----------|
41
- | Builtin | `~/.pi/agent/extensions/subagent/agents/` | Lowest |
42
- | User | `~/.pi/agent/agents/{name}.md` | Medium |
43
- | Project | `.pi/agents/{name}.md` (searches up directory tree) | Highest |
39
+ That is enough to start.
44
40
 
45
- Project discovery also reads legacy `.agents/{name}.md` files. If both `.agents/` and `.pi/agents/` contain a project agent with the same parsed `name`, `.pi/agents/` wins and the agent manager still writes to `.pi/agents/`.
41
+ ## What happens
46
42
 
47
- Use `agentScope` parameter to control discovery: `"user"`, `"project"`, or `"both"` (default; project takes priority).
43
+ Pi is the parent session. A subagent is a focused child Pi session with its own job.
48
44
 
49
- **Builtin agents:** The extension ships with ready-to-use agents `scout`, `planner`, `worker`, `reviewer`, `context-builder`, `researcher`, `delegate`, `oracle`, and `oracle-executor`. They load at lowest priority so any user or project agent with the same name overrides them.
45
+ When you ask for a subagent, Pi starts the child, gives it the task, and brings the result back. Foreground runs stream in the conversation. Background runs keep working and can be checked later.
50
46
 
51
- - `oracle` is a high-context advisory reviewer on `openai-codex/gpt-5.5`. It critiques direction, surfaces hidden risks, and proposes a concrete execution prompt, but it does not edit files directly.
52
- - `oracle-executor` is a high-context implementation escalator on `openai-codex/gpt-5.5`. It is intended to run only after the main agent explicitly approves a course of action.
47
+ Installing the extension does not start an automatic reviewer in the background. It gives Pi a delegation tool. If you want every implementation reviewed, say that in your prompt or put it in your project instructions:
53
48
 
54
- You can also override selected builtin fields without copying the whole agent. Builtin overrides are stored in settings under `subagents.agentOverrides`:
49
+ ```text
50
+ When you finish implementing, run a reviewer subagent before summarizing.
51
+ ```
55
52
 
56
- - User scope: `~/.pi/agent/settings.json`
57
- - Project scope: `.pi/settings.json`
53
+ ## Good first prompts
58
54
 
59
- Supported builtin override fields are `model`, `fallbackModels`, `thinking`, `systemPromptMode`, `inheritProjectContext`, `inheritSkills`, `disabled`, `skills`, `tools`, and `systemPrompt`. Project overrides beat user overrides.
55
+ These cover most day-to-day use:
60
56
 
61
- **Overriding builtin defaults:**
57
+ ```text
58
+ Ask oracle for a second opinion on my current plan. Challenge assumptions and tell me what I might be missing.
59
+ ```
62
60
 
63
- All builtin agents inherit project instruction files (`AGENTS.md`, `CLAUDE.md`, etc.) by default. To make a builtin agent run without those project instructions:
61
+ ```text
62
+ Use oracle to help solve this hard bug. Have it inspect the code and propose the best next move before we edit anything.
63
+ ```
64
64
 
65
- **Via settings file** — add to `~/.pi/agent/settings.json` (user scope) or `.pi/settings.json` (project scope):
66
- ```json
67
- {
68
- "subagents": {
69
- "agentOverrides": {
70
- "reviewer": {
71
- "inheritProjectContext": false
72
- }
73
- }
74
- }
75
- }
65
+ ```text
66
+ Run parallel reviewers on this diff. I want one focused on correctness, one on tests, and one on unnecessary complexity.
67
+ ```
68
+
69
+ ```text
70
+ Implement this plan with oracle-executor. Afterward, run parallel reviewers, summarize their feedback, and apply the fixes that make sense.
76
71
  ```
77
72
 
78
- **Via `/agents` UI** — press `e` on any builtin agent (like `reviewer`), then toggle `inheritProjectContext` to `false` and save. This creates an override that you can edit or remove later without modifying the builtin definition itself.
73
+ ```text
74
+ Use scout to understand the auth flow, then have planner turn that into an implementation plan.
75
+ ```
79
76
 
80
- Set `disabled: true` inside an agent override to hide one builtin from runtime discovery while still keeping it visible in `/agents` so you can re-enable it later. For bulk control, set `subagents.disableBuiltins: true` in `settings.json`; project scope beats user scope, and an explicit same-scope override can opt one builtin back in with `disabled: false` or any other override fields.
77
+ Those are ordinary Pi requests. Pi decides whether to call `subagent`, which agent to use, and whether a chain or parallel run makes sense.
81
78
 
82
- Overridden builtins show badges like `[builtin+user]` or `[builtin+project]`. Disabled builtins show `off` badges in the manager so they are easy to spot and re-enable.
79
+ ## Common workflows
83
80
 
84
- > **Note:** The `researcher` agent uses `web_search`, `fetch_content`, and `get_search_content` tools which require the [pi-web-access](https://github.com/nicobailon/pi-web-access) extension. Install it with `pi install npm:pi-web-access`.
81
+ | Want | Ask naturally |
82
+ |------|---------------|
83
+ | Get a second opinion | “Ask oracle to review this plan and challenge assumptions.” |
84
+ | Solve a hard problem | “Use oracle to investigate this bug before we edit.” |
85
+ | Review a diff | “Use reviewer to review this diff.” |
86
+ | Run parallel reviewers | “Run reviewers for correctness, tests, and cleanup.” |
87
+ | Implement then review | “Implement this, then review it.” |
88
+ | Execute a plan carefully | “Use oracle-executor to implement this plan, then run reviewers and apply the feedback.” |
89
+ | Scout before planning | “Use scout to inspect the auth flow before planning.” |
90
+ | Run in the background | “Run this in the background.” |
91
+ | Browse agents | “Show me the available subagents.” |
92
+ | Use a saved workflow | “Run the review chain on this branch.” |
93
+ | See running work | “Show subagent status.” |
94
+ | Check setup | “Check whether subagents are configured correctly.” |
85
95
 
86
- ### Prompt Assembly Philosophy
96
+ The extension ships with builtin agents you can use immediately.
87
97
 
88
- Subagents are designed to be **narrow and intentional**. Custom subagents default to seeing only what you explicitly give them — not Pi's entire base prompt, not your repo's `AGENTS.md`, and not the parent's discovered skills.
98
+ ## Builtin agents in plain English
89
99
 
90
- This prevents subtle bugs where a "simple" code review agent starts making decisions based on project architecture rules it shouldn't know about, or a focused research agent gets distracted by tool descriptions meant for the orchestrator.
100
+ | Agent | Use it when you want... |
101
+ |-------|--------------------------|
102
+ | `scout` | Fast local codebase recon: relevant files, entry points, data flow, risks, and where another agent should start. |
103
+ | `researcher` | Web/docs research with sources: official docs, specs, benchmarks, recent changes, and a concise research brief. |
104
+ | `planner` | A concrete implementation plan from existing context. It should read and plan, not edit code. |
105
+ | `worker` | General implementation work. It reads context or a plan, edits files, and runs validation when it can. |
106
+ | `reviewer` | Code review and small fixes. It checks the implementation against the task/plan, tests, edge cases, and simplicity. |
107
+ | `context-builder` | A stronger setup pass before planning: gathers code context and writes handoff material such as `context.md` and `meta-prompt.md`. |
108
+ | `oracle` | A second opinion before acting. It challenges assumptions, catches drift, and recommends the safest next move without editing. |
109
+ | `oracle-executor` | Careful implementation after a direction has been approved. It is the “go do the approved thing” agent. |
110
+ | `delegate` | A lightweight general delegate when you want a child agent that behaves close to the parent session. |
91
111
 
92
- Use inheritance flags to selectively add back context when you actually want it:
93
- - **`inheritProjectContext: true`** — Keep Pi's inherited project-instructions block from project-level files like `AGENTS.md` and `CLAUDE.md`
94
- - **`inheritSkills: true`** — Let the child use Pi's discovered skills catalog
95
- - **`systemPromptMode: append`** — Add the agent's prompt to Pi's base instead of replacing it
112
+ A simple rule of thumb: use `scout` before you understand the code, `researcher` before you trust external facts, `planner` before a bigger change, `worker` to implement, `reviewer` to check, and `oracle` when the decision itself feels risky.
96
113
 
97
- Builtin agents ship a little differently: they all inherit project instruction files by default so they follow repo-specific rules out of the box. `delegate` is still the exception for `systemPromptMode` — it stays on `append` because its job is orchestration within the parent workflow, not isolated task execution.
114
+ ## Changing a builtin agent's model
98
115
 
99
- **Agent frontmatter:**
116
+ You do not need to copy builtin agent files just to change their model.
100
117
 
101
- ```yaml
102
- ---
103
- name: scout
104
- description: Fast codebase recon
105
- tools: read, grep, find, ls, bash, mcp:chrome-devtools # mcp: requires pi-mcp-adapter
106
- extensions: # absent=all, empty=none, csv=allowlist
107
- model: claude-haiku-4-5
108
- fallbackModels: openai/gpt-5-mini, anthropic/claude-sonnet-4 # optional ordered fallbacks
109
- thinking: high # off, minimal, low, medium, high, xhigh
110
- systemPromptMode: replace # replace by default, except builtin delegate
111
- inheritProjectContext: false # custom agents default false; builtins opt into true
112
- inheritSkills: false # strip Pi's discovered skills section
113
- skill: safe-bash, chrome-devtools # comma-separated skills to inject
114
- output: context.md # writes to {chain_dir}/context.md
115
- defaultReads: context.md # comma-separated files to read
116
- defaultProgress: true # maintain progress.md
117
- interactive: true # (parsed but not enforced in v1)
118
- maxSubagentDepth: 1 # tighten nested delegation for this agent's children
119
- ---
118
+ For one run, put the override in the command:
120
119
 
121
- Your system prompt goes here (the markdown body after frontmatter).
120
+ ```text
121
+ /run reviewer[model=anthropic/claude-sonnet-4] "Review this diff"
122
122
  ```
123
123
 
124
- The `thinking` field sets a default extended thinking level for the agent. At runtime it's appended as a `:level` suffix to the model string (e.g., `claude-sonnet-4-5:high`). If the model already has a thinking suffix (from a chain-clarify override), the agent's default is not double-applied.
124
+ For a persistent override, use `/agents`:
125
125
 
126
- `fallbackModels` is an optional ordered list of backup models to try when the primary model fails with a provider/model-style error such as quota, auth, timeout, or provider/model unavailable. In markdown frontmatter, declare it as a comma-separated string. In management `config` objects, you can pass either a comma-separated string or a string array.
126
+ ```text
127
+ /agents
128
+ ```
127
129
 
128
- `systemPromptMode` How the agent markdown body is passed to Pi:
129
- - **`replace`** (default) — The agent's markdown body becomes the system prompt. Clean slate, no Pi base prompt baggage.
130
- - **`append`** — The agent's prompt is appended to Pi's normal base prompt. Use this when you want Pi's full capabilities plus your extra instructions.
130
+ Choose the builtin agent, press `e`, change the model or other fields, then save a user or project override. User overrides apply everywhere. Project overrides apply only in that repo and win over user overrides.
131
131
 
132
- `inheritProjectContext` Whether the child keeps Pi's inherited project-instructions block, built from project-level instruction files like `AGENTS.md` and `CLAUDE.md`:
133
- - **`false`** (default) — Strip those inherited project-level instructions from the child's final system prompt. This does not remove repo access, cwd, tools, or the task itself; it only removes those inherited instructions.
134
- - **`true`** — Keep those inherited project-level instructions. Use for specialists that should follow project-specific constraints and conventions.
132
+ You can also edit settings directly:
135
133
 
136
- `inheritSkills` — Whether the child keeps Pi's discovered skills section:
137
- - **`false`** (default) — Skills catalog is stripped. Good for focused agents that shouldn't browse unrelated skills.
138
- - **`true`** — Child sees the full skills list. Use for general-purpose assistants that might need varied tools.
134
+ ```json
135
+ {
136
+ "subagents": {
137
+ "agentOverrides": {
138
+ "reviewer": {
139
+ "model": "anthropic/claude-sonnet-4",
140
+ "thinking": "high",
141
+ "fallbackModels": ["openai/gpt-5-mini"]
142
+ }
143
+ }
144
+ }
145
+ }
146
+ ```
139
147
 
140
- The `skills` field still works independently it injects specific skills directly into the agent prompt regardless of `inheritSkills`.
148
+ Use `~/.pi/agent/settings.json` for a user override or `.pi/settings.json` for a project override. The same `agentOverrides` block can change `tools`, `skills`, inherited context, prompt text, or disable a builtin. If you want a totally different agent, create a user or project agent with the same name; for normal tweaks, prefer overrides.
141
149
 
142
- **Common Recipes**
150
+ ## Where running subagents show up
143
151
 
144
- | Goal | `systemPromptMode` | `inheritProjectContext` | `inheritSkills` |
145
- |------|-------------------|------------------------|-----------------|
146
- | Fully isolated specialist (custom-agent default) | `replace` | `false` | `false` |
147
- | Specialist that should follow project instruction files | `replace` | `true` | `false` |
148
- | Pi-plus-extensions | `append` | `true` | `true` |
152
+ Foreground runs stream progress in the conversation while they run.
149
153
 
150
- - **Security auditor**: Fully isolated so it objectively checks for vulnerabilities without being biased by project conventions.
151
- - **Architecture planner**: Repo-aware so it respects `AGENTS.md` constraints when making design decisions.
152
- - **Generic helper**: Append mode with full inheritance so it behaves like a slightly-customized Pi.
154
+ Background runs keep working after control returns to you. They show completion notifications and can be inspected with:
153
155
 
154
- Fallback resolution follows the same conservative model lookup as normal execution. Explicit `provider/model` values are used as-is. Bare model IDs first prefer the current session provider when that provider actually exposes the model, then fall back to a unique registry match. If a bare ID is still ambiguous, it stays bare.
156
+ ```text
157
+ /subagents-status
158
+ ```
155
159
 
156
- Fallback is only used for provider/model availability failures. Ordinary task failures such as bad `bash` commands, missing files, or other tool/runtime errors do not trigger a model hop.
160
+ You can also ask naturally:
157
161
 
158
- **Tool selection semantics**
162
+ ```text
163
+ Show me the current subagent status.
164
+ ```
159
165
 
160
- The `tools` field controls builtin-tool allowlisting and a couple of related extension behaviors:
166
+ If something feels misconfigured, run:
161
167
 
162
- - `tools` **omitted** → `pi-subagents` does not pass `--tools`, so the child gets Pi's normal default builtin tools.
163
- - `tools` **present** → listed builtin tool names become an explicit allowlist passed via `--tools`.
164
- - `mcp:...` entries are split out of `tools` and forwarded as direct MCP tool selections.
165
- - Path-like entries in `tools` (extension paths or file paths ending in `.ts` / `.js`) are treated as tool-extension paths, not builtin tool names.
168
+ ```text
169
+ /subagents-doctor
170
+ ```
166
171
 
167
- This means:
172
+ or ask:
168
173
 
169
- - `tools` omitted + `extensions` omitted → child gets Pi's normal builtin tools and normal extension set.
170
- - `tools: mcp:chrome-devtools` child still gets Pi's default builtin tools, plus direct MCP tools from `chrome-devtools`.
171
- - `tools: read, bash, mcp:chrome-devtools` → child is restricted to `read` and `bash` for builtin tools, plus direct MCP tools from `chrome-devtools`.
174
+ ```text
175
+ Check whether subagents and intercom are set up correctly.
176
+ ```
172
177
 
173
- **Extension sandboxing**
178
+ ## Optional shortcuts
174
179
 
175
- Use `extensions` in frontmatter to control which extensions a subagent can access:
180
+ The package includes reusable prompt templates for common workflows. You do not need them, but they are handy when you want the same shape every time:
176
181
 
177
- ```yaml
178
- # Field absent: all extensions load (default behavior)
182
+ | Prompt | Use it for |
183
+ |--------|------------|
184
+ | `/parallel-review` | Launch fresh-context reviewers with distinct angles, then synthesize what to fix. |
185
+ | `/parallel-research` | Combine `researcher` and `scout` for external evidence, local code context, and practical tradeoffs. |
186
+ | `/gather-context-and-clarify` | Scout/research first, then ask the user the clarification questions that matter. |
187
+ | `/oracle-executor` | Send an explicitly approved implementation task to `oracle-executor` with inherited context. |
179
188
 
180
- # Empty field: no extensions
181
- extensions:
189
+ ## Optional pi-intercom companion
182
190
 
183
- # Allowlist specific extensions
184
- extensions: /abs/path/to/ext-a.ts, /abs/path/to/ext-b.ts
191
+ `pi-subagents` works without `pi-intercom`. Install `pi-intercom` only if you want child agents to talk back to the parent Pi session while they are running.
192
+
193
+ ```bash
194
+ pi install npm:pi-intercom
185
195
  ```
186
196
 
187
- Semantics:
188
- - `extensions` absent → all extensions load
189
- - `extensions:` empty → `--no-extensions`
190
- - `extensions: a,b` → `--no-extensions --extension a --extension b`
197
+ Most users do not call `intercom` directly. After `pi-intercom` is installed, `pi-subagents` can automatically give child agents a private coordination channel back to the parent session.
191
198
 
192
- When `extensions` is present, it takes precedence over extension paths implied by `tools` entries.
199
+ Use it for work where the child might need a decision instead of guessing:
193
200
 
194
- **MCP Tools (optional)**
201
+ ```text
202
+ Run this implementation in the background. If the worker gets blocked or needs a product decision, have it ask me through intercom.
203
+ ```
195
204
 
196
- If you have the [pi-mcp-adapter](https://github.com/nicobailon/pi-mcp-adapter) extension installed, subagents can use MCP server tools directly. Without that extension, everything below is ignored — MCP integration is entirely optional.
205
+ ```text
206
+ Ask oracle to review this plan. If it sees a decision I need to make, have it ask me instead of assuming.
207
+ ```
197
208
 
198
- Add `mcp:` prefixed entries to the `tools` field in agent frontmatter:
209
+ The child can use two kinds of messages:
199
210
 
200
- ```yaml
201
- # All tools from a server
202
- tools: read, bash, mcp:chrome-devtools
211
+ - `ask`: the child needs a decision or clarification from the parent session
212
+ - `send`: the child sends a short update when blocked or explicitly asked for progress
203
213
 
204
- # Specific tools from a server
205
- tools: read, bash, mcp:github/search_repositories, mcp:github/get_file_contents
206
- ```
214
+ Routine completion does not go through intercom. The normal subagent result still comes back through `pi-subagents`.
207
215
 
208
- | Syntax | Effect |
209
- |--------|--------|
210
- | `mcp:server-name` | All tools from that MCP server |
211
- | `mcp:server-name/tool_name` | One specific tool |
216
+ If a child appears stalled, needs-attention notices can show up in the parent session with useful next actions, such as checking `/subagents-status`, interrupting the run, or nudging the child.
212
217
 
213
- The `mcp:` items are additive — they don't affect which builtins the agent gets. `tools: mcp:chrome-devtools` (with no regular tools listed) gives the agent all default builtins plus chrome-devtools tools. To restrict builtins, list them explicitly: `tools: read, bash, mcp:chrome-devtools`.
218
+ If messages do not show up, run:
219
+
220
+ ```text
221
+ /subagents-doctor
222
+ ```
214
223
 
215
- Subagents only get direct MCP tools when `mcp:` items are explicitly listed. Even if your `mcp.json` has `directTools: true` globally, a subagent without `mcp:` in its frontmatter won't get any direct tools — keeping it lean. The `mcp` proxy tool is still available for discovery if needed.
224
+ For normal use, you do not need to configure anything. Advanced users can tune the bridge with `intercomBridge` in the configuration section below.
216
225
 
217
- > **First-run caveat:** The MCP adapter caches tool metadata at startup. The first time you connect to a new MCP server, that cache is empty, so tools are only available through the generic `mcp` proxy. After that first session, restart pi and direct tools become available.
226
+ At this point, you know enough to use the plugin. The rest of this README is reference material for exact command syntax, custom agents, saved chains, worktrees, and configuration.
218
227
 
219
- **Resolution priority:** step override > agent frontmatter > disabled
228
+ ## Direct commands
220
229
 
221
- ## Quick Commands
230
+ Skip this section until you want exact syntax.
222
231
 
223
232
  | Command | Description |
224
233
  |---------|-------------|
225
- | `/run <agent> [task]` | Run a single agent; omit the task for self-contained agents |
226
- | `/chain agent1 "task1" -> agent2 "task2"` | Run agents in sequence with per-step tasks |
227
- | `/parallel agent1 "task1" -> agent2 "task2"` | Run agents in parallel with per-step tasks |
228
- | `/subagents-status` | Open the async status overlay for active and recent runs |
234
+ | `/run <agent> [task]` | Run one agent; omit the task for self-contained agents |
235
+ | `/chain agent1 "task1" -> agent2 "task2"` | Run agents in sequence |
236
+ | `/parallel agent1 "task1" -> agent2 "task2"` | Run agents in parallel |
237
+ | `/run-chain <chainName> -- <task>` | Launch a saved `.chain.md` workflow |
229
238
  | `/agents` | Open the Agents Manager overlay |
239
+ | `/subagents-status` | Open the active/recent run overlay |
240
+ | `/subagents-doctor` | Show read-only setup diagnostics |
230
241
 
231
- All commands validate agent names locally and tab-complete them, then route through the tool framework for full live progress rendering. Results are sent to the conversation for the LLM to discuss.
242
+ Commands validate agent names locally, support tab completion, and still send results back into the conversation.
232
243
 
233
- ### Per-Step Tasks
244
+ ### Per-step tasks
234
245
 
235
- Use `->` to separate steps and give each step its own task with quotes or `--`:
246
+ Use `->` to separate steps and give each step its own task:
236
247
 
237
- ```
238
- /chain scout "scan the codebase" -> planner "create implementation plan"
248
+ ```text
249
+ /chain scout "scan the codebase" -> planner "create an implementation plan"
239
250
  /parallel scanner "find security issues" -> reviewer "check code style"
240
251
  ```
241
252
 
242
- Both double and single quotes work. The `--` delimiter also works: `/chain scout -- scan code -> planner -- analyze auth`.
253
+ Both double and single quotes work. You can also use `--` as a delimiter:
243
254
 
244
- Steps without a task inherit behavior from the execution mode: chain steps get `{previous}` (output from the prior step), parallel steps get the first available task as a fallback.
245
-
246
- ```
247
- /chain scout "analyze auth" -> planner -> implementer
248
- # scout: "analyze auth", planner: gets scout's output, implementer: gets planner's output
255
+ ```text
256
+ /chain scout -- scan code -> planner -- analyze auth
249
257
  ```
250
258
 
251
- **Shared task (no `->`):** Space-separated agents with a single `--` task:
259
+ Steps without a task inherit behavior from the execution mode. Chain steps get `{previous}`, the prior step’s output. Parallel steps use the first available task as a fallback.
252
260
 
261
+ ```text
262
+ /chain scout "analyze auth" -> planner -> worker
263
+ # scout gets "analyze auth"; planner gets scout output; worker gets planner output
253
264
  ```
265
+
266
+ For a shared task, list agents and place one `--` before the task:
267
+
268
+ ```text
254
269
  /chain scout planner -- analyze the auth system
255
270
  /parallel scout reviewer -- check for security issues
256
271
  ```
257
272
 
258
- ### Inline Per-Step Config
273
+ ### Inline per-step config
259
274
 
260
- Append `[key=value,...]` to any agent name to override its defaults:
275
+ Append `[key=value,...]` to an agent name to override defaults for that step:
261
276
 
262
- ```
277
+ ```text
263
278
  /chain scout[output=context.md] "scan code" -> planner[reads=context.md] "analyze auth"
264
279
  /run scout[model=anthropic/claude-sonnet-4] summarize this codebase
265
- /parallel scanner[model=anthropic/claude-sonnet-4] "find issues" -> reviewer[skills=code-review+security] "check style"
280
+ /parallel reviewer[skills=code-review+security] "review backend" -> reviewer[model=openai/gpt-5-mini] "review frontend"
266
281
  ```
267
282
 
268
283
  | Key | Example | Description |
269
284
  |-----|---------|-------------|
270
- | `output` | `output=context.md` | Write results to file (relative to chain dir for `/chain`/`/parallel`; for `/run`, absolute paths are used as-is and relative paths resolve against cwd) |
271
- | `reads` | `reads=a.md+b.md` | Read files before executing (`+` separates multiple) |
272
- | `model` | `model=anthropic/claude-sonnet-4` | Override model for this step |
273
- | `skills` | `skills=planning+review` | Override skills (`+` separates multiple) |
274
- | `progress` | `progress` | Enable progress tracking |
285
+ | `output` | `output=context.md` | Write results to a file. For `/chain` and `/parallel`, relative paths live under the chain directory; for `/run`, relative paths resolve against cwd. |
286
+ | `reads` | `reads=a.md+b.md` | Read files before executing. `+` separates multiple paths. |
287
+ | `model` | `model=anthropic/claude-sonnet-4` | Override model for this step. |
288
+ | `skills` | `skills=planning+review` | Override injected skills. `+` separates multiple skills. |
289
+ | `progress` | `progress` | Enable progress tracking. |
275
290
 
276
- Set `output=false`, `reads=false`, or `skills=false` to explicitly disable.
291
+ Set `output=false`, `reads=false`, or `skills=false` to disable that behavior explicitly.
277
292
 
278
- ### Background Execution
293
+ ### Background and forked runs
279
294
 
280
- Add `--bg` at the end of any slash command to run in the background:
295
+ Add `--bg` to run in the background:
281
296
 
282
- ```
283
- /run scout "full security audit of the codebase" --bg
284
- /chain scout "analyze auth system" -> planner "design refactor plan" -> worker --bg
285
- /parallel scout "scan frontend" -> scout "scan backend" -> scout "scan infra" --bg
297
+ ```text
298
+ /run scout "audit the codebase" --bg
299
+ /chain scout "analyze auth" -> planner "design refactor" -> worker --bg
300
+ /parallel scout "scan frontend" -> scout "scan backend" --bg
286
301
  ```
287
302
 
288
- Without `--bg`, the run is foreground: the tool call stays active and streams progress until completion. With `--bg`, the run is launched asynchronously: control returns immediately, and completion arrives later via notification. In both cases subagents run as separate processes. Check status with `subagent({ action: "status", id })`, or open the `/subagents-status` slash command for a read-only overlay listing active runs and recent completions.
303
+ Add `--fork` to start each child from a real branched session created from the parent’s current leaf:
289
304
 
290
- ### Forked Context Execution
291
-
292
- Add `--fork` at the end of `/run`, `/chain`, or `/parallel` to run with `context: "fork"`:
293
-
294
- ```
305
+ ```text
295
306
  /run reviewer "review this diff" --fork
296
307
  /chain scout "analyze this branch" -> planner "plan next steps" --fork
297
308
  /parallel scout "audit frontend" -> reviewer "audit backend" --fork
298
309
  ```
299
310
 
300
- You can combine `--fork` and `--bg` in any order:
311
+ You can combine them in either order:
301
312
 
302
- ```
313
+ ```text
303
314
  /run reviewer "review this diff" --fork --bg
304
315
  /run reviewer "review this diff" --bg --fork
305
316
  ```
306
317
 
307
- For the oracle pair, the intended default control loop is:
318
+ The `oracle` and `oracle-executor` builtins are designed for an explicit decision loop. A typical pattern is to ask `oracle` for diagnosis and a recommended execution prompt, then only run `oracle-executor` after the main agent approves that direction.
319
+
320
+ ## Clarify and launch UI
321
+
322
+ Chains open a clarify UI by default so you can preview and edit the workflow before it runs. Single and parallel tool calls can opt into the same flow with `clarify: true`; slash commands and `/agents` use their own launch screens.
323
+
324
+ Common clarify keys:
325
+
326
+ - `Enter` runs in the foreground, or in the background if background is toggled on
327
+ - `Esc` cancels or backs out
328
+ - `↑↓` moves between steps or tasks
329
+ - `e` edits the task/template
330
+ - `m` selects a model
331
+ - `t` selects thinking level
332
+ - `s` selects skills
333
+ - `b` toggles background execution
334
+ - `w` edits output/write behavior where supported
335
+ - `r` edits reads where supported
336
+ - `p` toggles progress tracking where supported
337
+ - `S` saves current overrides to the agent frontmatter
338
+ - `W` saves a chain configuration to `.chain.md`
339
+
340
+ Picker screens use `↑↓`, `Enter`, `Esc`, and type-to-filter. The full-screen editor supports word wrapping, paste, `Esc` to save, and `Ctrl+C` to discard.
341
+
342
+ ## Agents Manager
343
+
344
+ Press `Ctrl+Shift+A` or type `/agents` to open the Agents Manager. It is the easiest way to browse, inspect, edit, create, and launch agents and chains.
345
+
346
+ Use it when you want to see what agents exist, adjust a builtin override, build a parallel run without writing slash syntax, or save a chain for later.
347
+
348
+ The main screens are:
349
+
350
+ | Screen | What it does |
351
+ |--------|--------------|
352
+ | List | Browse agents and chains with search, filters, scope badges, and selection. |
353
+ | Detail | View resolved prompt, frontmatter fields, run history, and builtin override path. |
354
+ | Edit | Edit models, thinking level, prompt mode, inheritance flags, skills, and prompt text. |
355
+ | Chain Detail | Inspect saved chain steps. |
356
+ | Parallel Builder | Build parallel slots, including repeated agents and per-slot task overrides. |
357
+ | Task Input | Enter the shared task and launch with fork/background/worktree toggles where supported. |
358
+ | New Agent | Create from templates such as Scout, Planner, Implementer, Code Reviewer, Blank Agent, or Blank Chain. |
359
+
360
+ Useful keys:
361
+
362
+ - type to search the list
363
+ - `Enter` opens detail screens
364
+ - `Alt+N` creates an agent or chain from a template
365
+ - `Ctrl+R` launches selected agents as a run or chain
366
+ - `Ctrl+P` opens the parallel builder
367
+ - `Tab` selects agents in the list or toggles skip-clarify in task input
368
+ - `Ctrl+A` adds a slot in the parallel builder
369
+ - `e` edits an agent or builtin override
370
+ - `Ctrl+S` saves an override; `r` resets the focused override field; `D` removes the override
371
+ - `Ctrl+K` clones the current item
372
+ - `Ctrl+D` or `Del` deletes the current item or removes a parallel slot
373
+ - `Esc` backs out of the current screen
374
+
375
+ ## Agents and chains
308
376
 
309
- 1. main agent invokes `oracle` with forked context
310
- 2. `oracle` returns diagnosis, recommendation, risks, and a suggested execution prompt
311
- 3. main agent decides whether to accept that direction
312
- 4. only then does main agent invoke `oracle-executor`
377
+ Agents are markdown files with YAML frontmatter and a system prompt body. They define the specialist that will run in the child Pi process.
378
+
379
+ Agent locations, lowest to highest priority:
380
+
381
+ | Scope | Path |
382
+ |-------|------|
383
+ | Builtin | `~/.pi/agent/extensions/subagent/agents/` |
384
+ | User | `~/.pi/agent/agents/{name}.md` |
385
+ | Project | `.pi/agents/{name}.md` |
386
+
387
+ Project discovery also reads legacy `.agents/{name}.md` files. If both `.agents/` and `.pi/agents/` define the same project agent, `.pi/agents/` wins. Use `agentScope: "user" | "project" | "both"` to control discovery; `both` is the default and project definitions win name collisions.
388
+
389
+ Builtin agents load at the lowest priority, so a user or project agent with the same name overrides them. `oracle` is an advisory reviewer that critiques direction and proposes an execution prompt without editing files. `oracle-executor` is an implementation escalator intended to run only after the main agent approves a course of action.
390
+
391
+ The `researcher` builtin uses `web_search`, `fetch_content`, and `get_search_content`; those require [pi-web-access](https://github.com/nicobailon/pi-web-access):
392
+
393
+ ```bash
394
+ pi install npm:pi-web-access
395
+ ```
396
+
397
+ ### Builtin overrides
398
+
399
+ You can override selected builtin fields without copying the whole agent. Overrides live in settings:
400
+
401
+ - User: `~/.pi/agent/settings.json`
402
+ - Project: `.pi/settings.json`
313
403
 
314
404
  Example:
315
405
 
316
- ```text
317
- /run oracle "Review my current direction, challenge assumptions, and propose the best next move." --fork
318
- /run oracle-executor "Implement the approved approach: ..." --fork
406
+ ```json
407
+ {
408
+ "subagents": {
409
+ "agentOverrides": {
410
+ "reviewer": {
411
+ "inheritProjectContext": false
412
+ }
413
+ }
414
+ }
415
+ }
319
416
  ```
320
417
 
321
- This keeps decision authority in the main thread while still giving you a stronger review/escalation path.
418
+ Supported override fields are `model`, `fallbackModels`, `thinking`, `systemPromptMode`, `inheritProjectContext`, `inheritSkills`, `disabled`, `skills`, `tools`, and `systemPrompt`. Project overrides beat user overrides.
322
419
 
323
- ## Agents Manager
420
+ You can also manage builtin overrides from `/agents`. On a builtin detail screen, press `e`, choose user or project scope if needed, and save the fields you want to override.
421
+
422
+ Set `disabled: true` to hide a builtin from runtime discovery while keeping it visible in `/agents`. For bulk control, set `subagents.disableBuiltins: true` in settings. Overridden builtins show badges like `[builtin+user]` or `[builtin+project]`; disabled builtins show `off` badges in the manager.
423
+
424
+ ### Prompt assembly
425
+
426
+ Subagents are designed to be narrow by default. Custom agents start with a clean system prompt and only the context you intentionally give them. They do not automatically inherit Pi’s whole base prompt, project instruction files, or discovered skills catalog.
427
+
428
+ Use these fields when an agent should see more:
429
+
430
+ | Field | Effect |
431
+ |-------|--------|
432
+ | `systemPromptMode: append` | Append the agent prompt to Pi’s normal base prompt. |
433
+ | `inheritProjectContext: true` | Keep inherited project instructions from files like `AGENTS.md` and `CLAUDE.md`. |
434
+ | `inheritSkills: true` | Let the child see Pi’s discovered skills catalog. |
435
+
436
+ Builtin agents opt into project instruction inheritance by default so they follow repo-specific rules out of the box. `delegate` also uses append mode because its job is orchestration inside the parent workflow.
437
+
438
+ ### Agent frontmatter
439
+
440
+ A typical agent looks like this:
441
+
442
+ ```yaml
443
+ ---
444
+ name: scout
445
+ description: Fast codebase recon
446
+ tools: read, grep, find, ls, bash, mcp:chrome-devtools
447
+ extensions:
448
+ model: claude-haiku-4-5
449
+ fallbackModels: openai/gpt-5-mini, anthropic/claude-sonnet-4
450
+ thinking: high
451
+ systemPromptMode: replace
452
+ inheritProjectContext: false
453
+ inheritSkills: false
454
+ skills: safe-bash, chrome-devtools
455
+ output: context.md
456
+ defaultReads: context.md
457
+ defaultProgress: true
458
+ interactive: true
459
+ maxSubagentDepth: 1
460
+ ---
324
461
 
325
- Press **Ctrl+Shift+A** or type `/agents` to open the Agents Manager overlay — a TUI for browsing, viewing, editing, creating, and launching agents and chains.
326
-
327
- **Screens:**
328
-
329
- | Screen | Description |
330
- |--------|-------------|
331
- | List | Browse all agents and chains with search/filter, scope badges, chain badges |
332
- | Detail | View resolved prompt, frontmatter fields, recent run history, and active builtin override path |
333
- | Edit | Edit fields with specialized pickers and toggles (model, thinking, prompt mode, inherited context, inherited skills, prompt editor) |
334
- | Chain Detail | View chain steps with flow visualization and dependency map |
335
- | Parallel Builder | Build parallel execution slots, add same agent multiple times, per-slot task overrides |
336
- | Task Input | Enter task and launch with optional skip-clarify toggle |
337
- | New Agent | Create from templates (Blank, Scout, Planner, Implementer, Code Reviewer, Blank Chain) |
338
-
339
- **List screen keybindings:**
340
- - `↑↓` navigate agents/chains
341
- - `Enter` view detail
342
- - Type any character search/filter
343
- - `Tab` toggle selection (agents only)
344
- - `Alt+N` new agent from template
345
- - `Ctrl+K` clone current item
346
- - `Ctrl+D` or `Del` — delete current item
347
- - `Ctrl+R` run selected (1 agent: launch, 2+: sequential chain)
348
- - `Ctrl+P` — open parallel builder (from selection or cursor agent)
349
- - `Esc` clear query, then selection, then close overlay
350
-
351
- On a builtin detail screen, `e` opens the builtin override flow instead of cloning the whole agent. If no override exists yet, the manager asks whether to store it in user or project settings first.
352
-
353
- **Parallel builder keybindings:**
354
- - `↑↓` navigate slots
355
- - `Ctrl+A` add agent (opens search picker)
356
- - `Del` or `Ctrl+D` — remove slot
357
- - `Enter` edit per-slot task override
358
- - `Ctrl+R` — continue to task input (requires 2+ slots)
359
- - `Esc` back to list
360
-
361
- **Task input keybindings:**
362
- - `Enter` launch (or quick run if skip-clarify is on)
363
- - `Tab` — toggle skip-clarify (defaults to on for all manager launches)
364
- - `Esc` back
365
-
366
- **Builtin override edit keybindings:**
367
- - `Ctrl+S` — save override
368
- - `r` — reset the focused field back to the builtin value
369
- - `D` — remove the entire override
370
- - `Esc` — back
371
-
372
- **Multi-select workflow:** Select agents with `Tab`, then press `Ctrl+R` for a sequential chain or `Ctrl+P` to open the parallel builder. The parallel builder lets you add the same agent multiple times, set per-slot task overrides, and launch N agents in parallel. Slots without a custom task use the shared task entered on the next screen.
373
-
374
- ## Chain Files
375
-
376
- Chains are `.chain.md` files stored alongside agent files. They define reusable multi-step pipelines.
377
-
378
- **Chain file locations:**
462
+ Your system prompt goes here.
463
+ ```
464
+
465
+ Important fields:
466
+
467
+ | Field | Notes |
468
+ |-------|-------|
469
+ | `tools` | Builtin tool allowlist. `mcp:` entries select direct MCP tools when `pi-mcp-adapter` is installed. |
470
+ | `extensions` | Omitted means normal extensions; empty means no extensions; comma-separated values allowlist specific extensions. |
471
+ | `model` | Default model. Bare ids prefer the current provider when possible, then unique registry matches. |
472
+ | `fallbackModels` | Ordered backup models for provider/model failures such as quota, auth, timeout, or unavailable model. Ordinary task failures do not trigger fallback. |
473
+ | `thinking` | Appended as a `:level` suffix at runtime unless a suffix is already present. |
474
+ | `systemPromptMode` | `replace` by default; `append` keeps Pi’s base prompt. |
475
+ | `inheritProjectContext` | Keeps or strips inherited project instruction blocks. |
476
+ | `inheritSkills` | Keeps or strips Pi’s discovered skills catalog. |
477
+ | `skills` | Injects specific skills directly, regardless of `inheritSkills`. |
478
+ | `output` | Default single-agent output file. |
479
+ | `defaultReads` | Files to read before running in chain/parallel behavior. |
480
+ | `defaultProgress` | Maintain `progress.md`. |
481
+ | `interactive` | Parsed for compatibility but not enforced in v1. |
482
+ | `maxSubagentDepth` | Tightens nested delegation for this agent’s children. |
483
+
484
+ ### Tool and extension selection
485
+
486
+ If `tools` is omitted, `pi-subagents` does not pass `--tools`, so the child gets Pi’s normal builtin tools. If `tools` is present, regular tool names become an explicit allowlist. `mcp:` entries are split out and forwarded as direct MCP selections. Path-like `tools` entries, such as extension paths or `.ts`/`.js` files, are treated as tool-extension paths rather than builtin tool names.
487
+
488
+ Examples:
489
+
490
+ - `tools` omitted and `extensions` omitted: normal builtins and normal extensions.
491
+ - `tools: mcp:chrome-devtools`: normal builtins plus direct Chrome DevTools MCP tools.
492
+ - `tools: read, bash, mcp:chrome-devtools`: only `read` and `bash` as builtins, plus direct Chrome DevTools MCP tools.
493
+
494
+ Direct MCP tools require [pi-mcp-adapter](https://github.com/nicobailon/pi-mcp-adapter). Subagents only receive direct MCP tools when `mcp:` entries are listed in their frontmatter; global `directTools: true` in `mcp.json` is not enough by itself. The generic `mcp` proxy tool can still be used for discovery when available. The adapter caches tool metadata at startup, so after connecting a new MCP server for the first time, restart Pi before relying on direct tools.
495
+
496
+ `extensions` controls child extension loading:
497
+
498
+ ```yaml
499
+ # Omitted: all normal extensions load
500
+
501
+ # Empty: no extensions
502
+ extensions:
503
+
504
+ # Allowlist
505
+ extensions: /abs/path/to/ext-a.ts, /abs/path/to/ext-b.ts
506
+ ```
507
+
508
+ When `extensions` is present, it takes precedence over extension paths implied by `tools` entries.
509
+
510
+ ## Chain files
511
+
512
+ Chains are reusable `.chain.md` workflows stored next to agent files.
379
513
 
380
514
  | Scope | Path |
381
515
  |-------|------|
382
516
  | User | `~/.pi/agent/agents/{name}.chain.md` |
383
517
  | Project | `.pi/agents/{name}.chain.md` |
384
518
 
385
- Project chain discovery also reads legacy `.agents/{name}.chain.md` files. If both locations define the same parsed chain `name`, `.pi/agents/` wins and manager writes stay in `.pi/agents/`.
519
+ Project discovery also reads legacy `.agents/{name}.chain.md` files. If both locations define the same parsed chain name, `.pi/agents/` wins.
386
520
 
387
- **Format:**
521
+ Example:
388
522
 
389
- ```markdown
523
+ ```md
390
524
  ---
391
525
  name: scout-planner
392
526
  description: Gather context then plan implementation
@@ -405,275 +539,128 @@ progress: true
405
539
  Create an implementation plan based on {previous}
406
540
  ```
407
541
 
408
- Each `## agent-name` section defines a step. Config lines (`output`, `reads`, `model`, `skills`, `progress`) go immediately after the header. A blank line separates config from the task text. Chains support the same three-state semantics as tool params: omitted (inherit from agent), value (override), `false` (disable).
542
+ Each `## agent-name` section is a step. Config lines such as `output`, `reads`, `model`, `skills`, and `progress` go immediately after the header. A blank line separates config from task text.
409
543
 
410
- Chains can be created from the Agents Manager template picker ("Blank Chain"), or saved from the chain-clarify TUI during execution.
544
+ Chains support three-state behavior: omitted inherits from the agent, a value overrides, and `false` disables.
411
545
 
412
- ## Features (beyond base)
546
+ Create chains from the Agents Manager template picker, save them from the chain-clarify TUI, or write them by hand. Run them with natural language, `/agents`, or:
413
547
 
414
- - **Slash Commands**: `/run`, `/chain`, `/parallel` with tab-completion and live progress
415
- - **Agents Manager Overlay**: Browse, view, edit, create, delete, and launch agents/chains from a TUI (`Ctrl+Shift+A`)
416
- - **Management Actions**: LLM can list, inspect, create, update, and delete agent/chain definitions via `action` field
417
- - **Chain Files**: Reusable `.chain.md` files with per-step config, saveable from the clarify TUI
418
- - **Multi-select & Parallel**: Select agents in the overlay, launch as chain or parallel
419
- - **Run History**: Per-agent JSONL recording of task, exit code, duration; shown on detail screen
420
- - **Thinking Level**: First-class `thinking` frontmatter field with picker UI and runtime suffix application
421
- - **Agent Templates**: Create agents from presets (Scout, Planner, Implementer, Code Reviewer, Blank Chain)
422
- - **Skill Injection**: Agents declare skills in frontmatter; skills get injected into system prompts
423
- - **Parallel-in-Chain**: Fan-out/fan-in patterns with `{ parallel: [...] }` steps within chains
424
- - **Worktree Isolation**: `worktree: true` gives each parallel agent its own git worktree, preventing filesystem conflicts during concurrent execution
425
- - **Chain Clarification TUI**: Interactive preview/edit of chain templates and behaviors before execution
426
- - **Agent Frontmatter Extensions**: Agents declare default chain behavior (`output`, `defaultReads`, `defaultProgress`, `skill`) plus optional recursion limits via `maxSubagentDepth`
427
- - **Chain Artifacts**: Shared directory at a user-scoped temp path like `<tmpdir>/pi-subagents-<scope>/chain-runs/{runId}/` for inter-step files
428
- - **Solo Agent Output**: Agents with `output` write to temp dir and return path to caller
429
- - **Live Progress Display**: Real-time visibility during sync execution showing current tool, recent output, tokens, and duration
430
- - **Output Truncation**: Configurable byte/line limits via `maxOutput`
431
- - **Debug Artifacts**: Input/output/JSONL/metadata files per task
432
- - **Session Logs**: JSONL session files with paths shown in output
433
- - **Async Status Files**: Durable `status.json`, `events.jsonl`, and markdown logs for async runs
434
- - **Async Widget**: Lightweight TUI widget shows background run progress
435
- - **Session-scoped Notifications**: Async completions only notify the originating session
548
+ ```text
549
+ /run-chain scout-planner -- refactor authentication
550
+ ```
436
551
 
437
- ## Modes
552
+ ## Chain variables
438
553
 
439
- | Mode | Async Support | Notes |
440
- |------|---------------|-------|
441
- | Single | Yes | `{ agent, task? }` - omit `task` for self-contained agents; agents with `output` write to temp dir |
442
- | Chain | Yes | `{ chain: [{agent, task}...] }` with `{task}`, `{previous}`, `{chain_dir}` variables |
443
- | Parallel | Yes | `{ tasks: [{agent, task}...] }` - via TUI toggle or converted to chain for async |
554
+ Task templates support:
444
555
 
445
- Execution context defaults to `context: "fresh"`, which starts each child run from a clean session. Set `context: "fork"` to start each child from a real branched session created from the parent's current leaf.
446
- When `intercomBridge` is enabled (default: `always`) and `pi-intercom` is installed/enabled, delegated children get runtime instructions for contacting the orchestrator session via `intercom({ action: "ask"|"send", ... })`.
556
+ | Variable | Description |
557
+ |----------|-------------|
558
+ | `{task}` | Original task from the first step. |
559
+ | `{previous}` | Output from the prior step, or aggregated output from a parallel step. |
560
+ | `{chain_dir}` | Path to the chain artifact directory. |
447
561
 
448
- > **Note:** Intercom bridging requires the [pi-intercom](https://github.com/nicobailon/pi-intercom) extension. Install it with `pi install npm:pi-intercom`.
562
+ Parallel outputs are aggregated with clear separators before being passed to the next step:
449
563
 
450
- All modes support foreground and background execution. Foreground is the default (the call waits and streams progress). For programmatic background launch, use `clarify: false, async: true`. For interactive background launch, use `clarify: true` and press `b` in the TUI before running. Chains with parallel steps (`{ parallel: [...] }`) run concurrently with configurable `concurrency` and `failFast` options.
564
+ ```text
565
+ === Parallel Task 1 (worker) ===
566
+ ...
451
567
 
452
- **Clarify TUI for single/parallel:**
568
+ === Parallel Task 2 (worker) ===
569
+ ...
570
+ ```
453
571
 
454
- Single and parallel modes also support the clarify TUI for previewing/editing parameters before execution. Unlike chains, they default to no TUI - use `clarify: true` to enable:
572
+ ## Skills
455
573
 
456
- ```typescript
457
- // Single agent with clarify TUI
458
- { agent: "scout", task: "Analyze the codebase", clarify: true }
574
+ Skills are `SKILL.md` files injected into an agent’s system prompt.
459
575
 
460
- // Parallel tasks with clarify TUI
461
- { tasks: [{agent: "scout", task: "Analyze frontend"}, ...], clarify: true }
462
- ```
576
+ Discovery uses project-first precedence:
463
577
 
464
- **Clarification TUI keybindings:**
465
-
466
- *Navigation mode:*
467
- - `Enter` - Run (foreground) or launch in background if `b` is toggled on
468
- - `Esc` - Cancel
469
- - `↑↓` - Navigate between steps/tasks (parallel, chain)
470
- - `e` - Edit task/template (all modes)
471
- - `m` - Select model (all modes)
472
- - `t` - Select thinking level (all modes)
473
- - `s` - Select skills (all modes)
474
- - `b` - Toggle background/async execution (all modes) — shows `[b]g:ON` when enabled
475
- - `w` - Edit writes/output file (single, chain only)
476
- - `r` - Edit reads list (chain only)
477
- - `p` - Toggle progress tracking (chain only)
478
- - `S` - Save current overrides to agent's frontmatter file (all modes)
479
- - `W` - Save chain configuration to a `.chain.md` file (chain only)
480
-
481
- *Model selector mode:*
482
- - `↑↓` - Navigate model list
483
- - `Enter` - Select model
484
- - `Esc` - Cancel (keep current model)
485
- - Type to filter (fuzzy search by model name or provider)
486
-
487
- *Thinking level selector mode:*
488
- - `↑↓` - Navigate level list
489
- - `Enter` - Select level
490
- - `Esc` - Cancel (keep current level)
491
-
492
- *Skill selector mode:*
493
- - `↑↓` - Navigate skill list
494
- - `Space` - Toggle skill selection
495
- - `Enter` - Confirm selection
496
- - `Esc` - Cancel (keep current skills)
497
- - Type to filter (fuzzy search by name or description)
498
-
499
- *Edit mode (full-screen editor with word wrapping):*
500
- - `Esc` - Save changes and exit
501
- - `Ctrl+C` - Discard changes and exit
502
- - `←→` - Move cursor left/right
503
- - `Alt+←→` - Move cursor by word
504
- - `↑↓` - Move cursor up/down by display line (auto-scrolls)
505
- - `Page Up/Down` or `Shift+↑↓` - Move cursor by viewport (12 lines)
506
- - `Home/End` - Start/end of current display line
507
- - `Ctrl+Home/End` - Start/end of text
508
- - `Alt+Backspace` - Delete word backward
509
- - Paste supported (multi-line in multi-line editors)
578
+ 1. `.pi/skills/{name}/SKILL.md`
579
+ 2. Project packages and project settings packages via `package.json -> pi.skills`
580
+ 3. Current task cwd package via `package.json -> pi.skills`
581
+ 4. `.pi/settings.json -> skills`
582
+ 5. `~/.pi/agent/skills/{name}/SKILL.md`
583
+ 6. User packages and user settings packages via `package.json -> pi.skills`
584
+ 7. `~/.pi/agent/settings.json -> skills`
510
585
 
511
- ## Skills
586
+ Use agent defaults, override them at runtime, or disable them:
512
587
 
513
- Skills are specialized instructions loaded from SKILL.md files and injected into the agent's system prompt.
514
-
515
- **Skill locations (project-first precedence):**
516
- - Project: `.pi/skills/{name}/SKILL.md`
517
- - Project packages: `.pi/npm/node_modules/*` via `package.json -> pi.skills`
518
- - Project settings packages: local package roots from `.pi/settings.json -> packages`, then `package.json -> pi.skills`
519
- - Current task cwd package: `<cwd>/package.json -> pi.skills`
520
- - Project settings: `.pi/settings.json -> skills`
521
- - User: `~/.pi/agent/skills/{name}/SKILL.md`
522
- - User packages: `~/.pi/agent/npm/node_modules/*` via `package.json -> pi.skills`
523
- - User settings packages: local package roots from `~/.pi/agent/settings.json -> packages`, then `package.json -> pi.skills`
524
- - User settings: `~/.pi/agent/settings.json -> skills`
525
-
526
- **Usage:**
527
- ```typescript
528
- // Agent with skills from frontmatter
529
- { agent: "scout", task: "..." } // uses agent's default skills
530
-
531
- // Override skills at runtime
588
+ ```ts
589
+ { agent: "scout", task: "..." }
532
590
  { agent: "scout", task: "...", skill: "tmux, safe-bash" }
533
-
534
- // Disable all skills (including agent defaults)
535
591
  { agent: "scout", task: "...", skill: false }
592
+ ```
536
593
 
537
- // Chain with chain-level skills (additive to agent skills)
538
- { chain: [...], skill: "code-review" }
594
+ For chains, `skill` at the top level is additive. A step-level `skill` overrides that step; `false` disables skills for that step.
539
595
 
540
- // Chain step with skill override
541
- { chain: [
542
- { agent: "scout", skill: "safe-bash" }, // only safe-bash
543
- { agent: "worker", skill: false } // no skills at all
544
- ]}
545
- ```
596
+ Injected skills use this shape:
546
597
 
547
- **Skill injection format:**
548
598
  ```xml
549
599
  <skill name="safe-bash">
550
600
  [skill content from SKILL.md, frontmatter stripped]
551
601
  </skill>
552
602
  ```
553
603
 
554
- **Missing skills:** If a skill cannot be found, execution continues with a warning shown in the result summary.
604
+ Missing skills do not fail execution. The result summary shows a warning.
605
+
606
+ ## Programmatic tool usage
555
607
 
556
- ## Usage
608
+ These are the parameters the LLM passes when it calls the `subagent` tool. Most users ask naturally or use slash commands instead.
557
609
 
558
- These are the parameters the **LLM agent** passes when it calls the `subagent` tool — not something you type directly. The agent decides to use these based on your conversation. For user-facing commands, see [Quick Commands](#quick-commands) above.
610
+ ### Execution examples
559
611
 
560
- **subagent tool parameters:**
561
- ```typescript
612
+ ```ts
562
613
  // Single agent
563
614
  { agent: "worker", task: "refactor auth" }
564
615
  { agent: "scout", task: "find todos", maxOutput: { lines: 1000 } }
565
- { agent: "scout", task: "investigate", output: false } // disable file output
616
+ { agent: "scout", task: "investigate", output: false }
566
617
 
567
- // Single agent from parent-session fork (real branched session at current leaf)
618
+ // Forked context
568
619
  { agent: "worker", task: "continue this thread", context: "fork" }
569
620
 
570
621
  // Parallel
571
- { tasks: [{ agent: "scout", task: "a" }, { agent: "scout", task: "b" }] }
572
-
573
- // Parallel with top-level concurrency override
574
- { tasks: [{ agent: "scout", task: "a" }, { agent: "reviewer", task: "b" }], concurrency: 2 }
575
-
576
- // Parallel with count shorthand (run the same task 3 times)
622
+ { tasks: [{ agent: "scout", task: "a" }, { agent: "reviewer", task: "b" }] }
577
623
  { tasks: [{ agent: "scout", task: "audit auth", count: 3 }] }
578
-
579
- // Parallel with forked context (each task gets its own isolated fork)
580
624
  { tasks: [{ agent: "scout", task: "audit frontend" }, { agent: "reviewer", task: "audit backend" }], context: "fork" }
581
625
 
582
- // Chain with TUI clarification (default)
626
+ // Chain
583
627
  { chain: [
584
628
  { agent: "scout", task: "Gather context for auth refactor" },
585
- { agent: "planner" }, // task defaults to {previous}
586
- { agent: "worker" }, // uses agent defaults for reads/progress
629
+ { agent: "planner" },
630
+ { agent: "worker" },
587
631
  { agent: "reviewer" }
588
632
  ]}
589
633
 
590
- // Chain with forked context (each step gets its own isolated fork of the same parent leaf)
591
- { chain: [
592
- { agent: "scout", task: "Analyze current branch decisions" },
593
- { agent: "planner", task: "Plan from {previous}" }
594
- ], context: "fork" }
595
-
596
- // Chain without TUI (enables async)
634
+ // Chain without TUI, suitable for background execution
597
635
  { chain: [...], clarify: false, async: true }
598
636
 
599
- // Chain with behavior overrides
637
+ // Chain with fan-out/fan-in
600
638
  { chain: [
601
- { agent: "scout", task: "find issues", output: false }, // text-only, no file
602
- { agent: "worker", progress: false } // disable progress tracking
603
- ]}
604
-
605
- // Chain with parallel step (fan-out/fan-in)
606
- { chain: [
607
- { agent: "scout", task: "Gather context for the codebase" },
639
+ { agent: "scout", task: "Gather context" },
608
640
  { parallel: [
609
- { agent: "worker", task: "Implement auth based on {previous}", count: 2 },
610
- { agent: "worker", task: "Implement API based on {previous}" }
611
- ]},
641
+ { agent: "worker", task: "Implement feature A from {previous}" },
642
+ { agent: "worker", task: "Implement feature B from {previous}" }
643
+ ], concurrency: 2, failFast: true },
612
644
  { agent: "reviewer", task: "Review all changes from {previous}" }
613
645
  ]}
614
646
 
615
- // Parallel step with options
616
- { chain: [
617
- { agent: "scout", task: "Find all modules" },
618
- { parallel: [
619
- { agent: "worker", task: "Refactor module A" },
620
- { agent: "worker", task: "Refactor module B" },
621
- { agent: "worker", task: "Refactor module C" }
622
- ], concurrency: 2, failFast: true } // limit concurrency, stop on first failure
623
- ]}
624
-
625
- // Worktree isolation — each parallel agent gets its own git worktree
647
+ // Worktree isolation
626
648
  { tasks: [
627
649
  { agent: "worker", task: "Implement auth" },
628
650
  { agent: "worker", task: "Implement API" }
629
651
  ], worktree: true }
630
-
631
- // Worktree isolation in a chain (fan-out with isolation, fan-in for review)
632
- { chain: [
633
- { agent: "scout", task: "Gather context" },
634
- { parallel: [
635
- { agent: "worker", task: "Implement feature A based on {previous}" },
636
- { agent: "worker", task: "Implement feature B based on {previous}" }
637
- ], worktree: true },
638
- { agent: "reviewer", task: "Review changes from {previous}" }
639
- ]}
640
-
641
- // Async chain with parallel step (runs in background)
642
- { chain: [
643
- { agent: "scout", task: "Gather context" },
644
- { parallel: [
645
- { agent: "worker", task: "Implement feature A based on {previous}" },
646
- { agent: "worker", task: "Implement feature B based on {previous}" }
647
- ]},
648
- { agent: "reviewer", task: "Review all changes from {previous}" }
649
- ], clarify: false, async: true }
650
- ```
651
-
652
- **Programmatic status:**
653
- ```typescript
654
- subagent({ action: "status" }) // active async runs only
655
- subagent({ action: "status", id: "a53ebe46" }) // inspect one run
656
- subagent({ action: "status", dir: "<tmpdir>/pi-subagents-<scope>/async-subagent-runs/a53ebe46-..." })
657
652
  ```
658
653
 
659
- **/subagents-status slash command:**
660
-
661
- Opens a small read-only overlay that shows active async runs plus recent completed, failed, and paused runs. It auto-refreshes every 2 seconds while open, keeps the current run selected when possible, and uses `↑↓` to select a run plus `Esc` to close.
662
-
663
- ## Management Actions
654
+ ### Management actions
664
655
 
665
- Agent definitions are not loaded into LLM context by default. Management actions let the LLM discover, inspect, create, and modify agent and chain definitions at runtime through the `subagent` tool — no manual file editing or restart required. Newly created agents are immediately usable in the same session. Set `action` and omit execution payloads (`task`, `chain`, `tasks`).
656
+ Agent definitions are not loaded into context by default. Management actions let the LLM discover, inspect, create, update, and delete agents and chains at runtime.
666
657
 
667
- ```typescript
668
- // Discover all agents and chains (management defaults to both scopes)
658
+ ```ts
669
659
  { action: "list" }
670
660
  { action: "list", agentScope: "project" }
671
-
672
- // Inspect one agent or chain (searches both scopes)
673
661
  { action: "get", agent: "scout" }
674
662
  { action: "get", chainName: "review-pipeline" }
675
663
 
676
- // Create agent
677
664
  { action: "create", config: {
678
665
  name: "Code Scout",
679
666
  description: "Scans codebases for patterns and issues",
@@ -685,7 +672,7 @@ Agent definitions are not loaded into LLM context by default. Management actions
685
672
  model: "anthropic/claude-sonnet-4",
686
673
  fallbackModels: ["openai/gpt-5-mini", "anthropic/claude-haiku-4-5"],
687
674
  tools: "read, bash, mcp:github/search_repositories",
688
- extensions: "", // empty = no extensions
675
+ extensions: "",
689
676
  skills: "parallel-scout",
690
677
  thinking: "high",
691
678
  output: "context.md",
@@ -693,7 +680,6 @@ Agent definitions are not loaded into LLM context by default. Management actions
693
680
  progress: true
694
681
  }}
695
682
 
696
- // Create chain (presence of steps creates .chain.md)
697
683
  { action: "create", config: {
698
684
  name: "review-pipeline",
699
685
  description: "Scout then review",
@@ -704,208 +690,107 @@ Agent definitions are not loaded into LLM context by default. Management actions
704
690
  ]
705
691
  }}
706
692
 
707
- // Update agent fields (merge semantics)
708
693
  { action: "update", agent: "scout", config: { model: "openai/gpt-4o" } }
709
- { action: "update", agent: "scout", config: { output: false, skills: "" } } // clear optional fields
710
- { action: "update", chainName: "review-pipeline", config: {
711
- steps: [
712
- { agent: "scout", task: "Scan {task}", output: "context.md" },
713
- { agent: "reviewer", task: "Improved review of {previous}", reads: ["context.md"] }
714
- ]
715
- }}
716
-
717
- // Delete definitions
694
+ { action: "update", chainName: "review-pipeline", config: { steps: [...] } }
718
695
  { action: "delete", agent: "scout" }
719
696
  { action: "delete", chainName: "review-pipeline" }
720
697
  ```
721
698
 
722
- Notes:
723
- - `create` uses `config.scope` (`"user"` or `"project"`), not `agentScope`.
724
- - `update`/`delete` use `agentScope` only for scope disambiguation when the same name exists in both scopes.
725
- - Agent config mapping: `reads -> defaultReads`, `progress -> defaultProgress`, `extensions` controls extension sandboxing, `maxSubagentDepth`, `fallbackModels`, `systemPromptMode`, `inheritProjectContext`, and `inheritSkills` map directly to agent frontmatter, and `tools` supports `mcp:` entries that map to direct MCP tools.
726
- - To clear any optional field, set it to `false` or `""` (e.g., `{ model: false }` or `{ skills: "" }`). Both work for all string-typed fields.
699
+ `create` uses `config.scope`, not `agentScope`. `update` and `delete` use `agentScope` only when the same name exists in multiple scopes. To clear optional string fields, set them to `false` or `""`.
727
700
 
728
- ## Parameters
701
+ ### Parameter reference
729
702
 
730
703
  | Param | Type | Default | Description |
731
704
  |-------|------|---------|-------------|
732
- | `agent` | string | - | Agent name (single mode) or target for management get/update/delete |
733
- | `task` | string | - | Task string (single mode) |
734
- | `action` | string | - | Management action: `list`, `get`, `create`, `update`, `delete` |
735
- | `chainName` | string | - | Chain name for management get/update/delete |
736
- | `config` | object | - | Agent or chain config for management create/update. Agent configs also accept `fallbackModels` (comma-separated string or string array), `systemPromptMode` (`append` or `replace`), `inheritProjectContext` (boolean), and `inheritSkills` (boolean). |
737
- | `output` | `string \| false` | agent default | Override output file for single agent (absolute path as-is, relative path resolved against cwd) |
738
- | `skill` | `string \| string[] \| false` | agent default | Override skills (comma-separated string, array, or false to disable) |
739
- | `model` | string | agent default | Override model for single agent |
740
- | `fallbackModels` | `string \| string[]` | agent default | Management/config-only field for ordered backup models. Markdown frontmatter uses a comma-separated string. |
741
- | `tasks` | `{agent, task, cwd?, count?, skill?}[]` | - | Parallel tasks. Foreground runs directly; background requests are converted to an equivalent chain. `count` repeats one task entry N times with the same settings. |
742
- | `concurrency` | number | `config.parallel.concurrency` or `4` | Top-level `tasks` mode only: max concurrent tasks. |
743
- | `worktree` | boolean | false | Create isolated git worktrees for each parallel task. Requires clean git state. Per-worktree diffs included in output. |
744
- | `chain` | ChainItem[] | - | Sequential steps with behavior overrides (see below) |
745
- | `context` | `"fresh" \| "fork"` | `fresh` | Execution context mode. `fork` uses a real branched session from the parent's current leaf for each child run |
746
- | `chainDir` | string | user-scoped temp dir like `<tmpdir>/pi-subagents-<scope>/chain-runs/` | Persistent directory for chain artifacts (default auto-cleaned after 24h) |
747
- | `clarify` | boolean | true (chains) | Show TUI to preview/edit chain; implies sync mode |
748
- | `agentScope` | `"user" \| "project" \| "both"` | `both` | Agent discovery scope (project wins on name collisions) |
749
- | `async` | boolean | false | Background execution (requires `clarify: false` for chains) |
750
- | `cwd` | string | - | Override working directory |
751
- | `maxOutput` | `{bytes?, lines?}` | 200KB, 5000 lines | Truncation limits for final output |
752
- | `artifacts` | boolean | true | Write debug artifacts |
753
- | `includeProgress` | boolean | false | Include full progress in result |
754
- | `share` | boolean | false | Upload session to GitHub Gist (see [Session Sharing](#session-sharing)) |
755
- | `sessionDir` | string | - | Override session log directory (takes precedence over `defaultSessionDir` and parent-session-derived path) |
756
-
757
- `context: "fork"` fails fast when the parent session is not persisted, the current leaf is missing, or a branched child session cannot be created. It never silently downgrades to `fresh`.
758
-
759
- **ChainItem** can be either a sequential step or a parallel step:
760
-
761
- *Sequential step fields:*
762
-
763
- | Field | Type | Default | Description |
764
- |-------|------|---------|-------------|
765
- | `agent` | string | required | Agent name |
766
- | `task` | string | `{task}` or `{previous}` | Task template (required for first step) |
767
- | `cwd` | string | - | Override working directory |
768
- | `output` | `string \| false` | agent default | Override output filename or disable |
769
- | `reads` | `string[] \| false` | agent default | Override files to read from chain dir |
770
- | `progress` | boolean | agent default | Override progress.md tracking |
771
- | `skill` | `string \| string[] \| false` | agent default | Override skills or disable all |
772
- | `model` | string | agent default | Override model for this step |
773
-
774
- Fallbacks are inherited from the selected agent for that step. There is no per-step `fallbackModels` override in v1.
775
-
776
- *Parallel step fields:*
777
-
778
- | Field | Type | Default | Description |
779
- |-------|------|---------|-------------|
780
- | `parallel` | ParallelTask[] | required | Array of tasks to run concurrently |
781
- | `concurrency` | number | 4 | Max concurrent tasks |
782
- | `failFast` | boolean | false | Stop remaining tasks on first failure |
783
- | `worktree` | boolean | false | Create isolated git worktrees for each parallel task |
784
-
785
- *ParallelTask fields:* (same as sequential step)
786
-
787
- | Field | Type | Default | Description |
788
- |-------|------|---------|-------------|
789
- | `agent` | string | required | Agent name |
790
- | `task` | string | `{previous}` | Task template |
791
- | `cwd` | string | - | Override working directory |
792
- | `count` | number | 1 | Repeat this parallel task N times with the same settings |
793
- | `output` | `string \| false` | agent default | Override output (namespaced to parallel-N/M-agent/) |
794
- | `reads` | `string[] \| false` | agent default | Override files to read |
795
- | `progress` | boolean | agent default | Override progress tracking |
796
- | `skill` | `string \| string[] \| false` | agent default | Override skills or disable all |
797
- | `model` | string | agent default | Override model for this task |
798
-
799
- Fallbacks are inherited from the selected agent for that task. There is no per-task `fallbackModels` override in v1.
800
-
801
- Status commands:
802
-
803
- | Command | Description |
804
- |------|-------------|
805
- | `subagent({ action: "status" })` | List active async runs |
806
- | `subagent({ action: "status", id })` | Inspect a foreground or async run by id or prefix |
705
+ | `agent` | string | - | Agent name for single mode, or target for management actions. |
706
+ | `task` | string | - | Task string for single mode. |
707
+ | `action` | string | - | `list`, `get`, `create`, `update`, `delete`, `status`, `interrupt`, or `doctor`. |
708
+ | `chainName` | string | - | Chain name for management actions. |
709
+ | `config` | object/string | - | Agent or chain config for create/update. |
710
+ | `output` | `string \| false` | agent default | Override single-agent output file. |
711
+ | `skill` | `string \| string[] \| false` | agent default | Override skills or disable all. |
712
+ | `model` | string | agent default | Override model. |
713
+ | `tasks` | array | - | Top-level parallel tasks. Supports `agent`, `task`, `cwd`, `count`, `output`, `reads`, `progress`, `skill`, and `model`. |
714
+ | `concurrency` | number | config or `4` | Top-level parallel concurrency. |
715
+ | `worktree` | boolean | false | Create isolated git worktrees for parallel tasks. |
716
+ | `chain` | array | - | Sequential and parallel chain steps. |
717
+ | `context` | `fresh \| fork` | `fresh` | `fork` creates real branched sessions from the parent leaf. |
718
+ | `chainDir` | string | temp chain dir | Persistent directory for chain artifacts. |
719
+ | `clarify` | boolean | true for chains | Show TUI preview/edit flow. |
720
+ | `agentScope` | `user \| project \| both` | `both` | Agent discovery scope. Project wins on collisions. |
721
+ | `async` | boolean | false | Background execution. Chains require `clarify: false`. |
722
+ | `cwd` | string | runtime cwd | Override working directory. |
723
+ | `maxOutput` | object | 200KB, 5000 lines | Final output truncation limits. |
724
+ | `artifacts` | boolean | true | Write debug artifacts. |
725
+ | `includeProgress` | boolean | false | Include full progress in result. |
726
+ | `share` | boolean | false | Upload session export to GitHub Gist. |
727
+ | `sessionDir` | string | derived | Override session log directory. |
728
+
729
+ `context: "fork"` fails fast when the parent session is not persisted, the current leaf is missing, or the branched child session cannot be created. It never silently downgrades to `fresh`.
730
+
731
+ Sequential and parallel chain tasks accept `agent`, `task`, `cwd`, `output`, `reads`, `progress`, `skill`, and `model`. Parallel tasks also accept `count`. Parallel step groups accept `parallel`, `concurrency`, `failFast`, and `worktree`.
732
+
733
+ Status and control actions:
734
+
735
+ ```ts
736
+ subagent({ action: "status" })
737
+ subagent({ action: "status", id: "<run-id>" })
738
+ subagent({ action: "interrupt", id: "<run-id>" })
739
+ subagent({ action: "doctor" })
740
+ ```
807
741
 
808
- ## Worktree Isolation
742
+ ## Worktree isolation
809
743
 
810
- When multiple agents run in parallel against the same repo, they can clobber each other's file changes. Pass `worktree: true` to give each parallel agent its own git worktree branched from HEAD.
744
+ Parallel agents can clobber each other if they edit the same checkout. `worktree: true` gives each parallel child its own git worktree branched from `HEAD`.
811
745
 
812
- ```typescript
813
- // Top-level parallel with worktree isolation
746
+ ```ts
814
747
  { tasks: [
815
748
  { agent: "worker", task: "Implement auth", count: 2 },
816
749
  { agent: "worker", task: "Implement API" }
817
750
  ], worktree: true }
818
751
 
819
- // Chain with worktree-isolated parallel step
820
752
  { chain: [
821
753
  { agent: "scout", task: "Gather context" },
822
754
  { parallel: [
823
- { agent: "worker", task: "Implement feature A based on {previous}" },
824
- { agent: "worker", task: "Implement feature B based on {previous}" }
755
+ { agent: "worker", task: "Implement feature A from {previous}" },
756
+ { agent: "worker", task: "Implement feature B from {previous}" }
825
757
  ], worktree: true },
826
758
  { agent: "reviewer", task: "Review all changes from {previous}" }
827
759
  ]}
828
760
  ```
829
761
 
830
- After the parallel step completes, per-agent diff stats are appended to the output (and become `{previous}` for the next chain step). Full patch files are written to disk. The caller or next step can decide what to keep.
831
-
832
- **Requirements:**
833
-
834
- - Must be inside a git repository
835
- - Working tree must be clean (no uncommitted changes) — commit or stash first
836
- - `node_modules/` is symlinked into each worktree to avoid reinstalling
837
- - Worktree runs use the shared parallel/step `cwd`. Task-level `cwd` overrides must be omitted or match that shared `cwd`; if you need different working directories, disable `worktree` or split the run.
838
- - If `worktreeSetupHook` is configured, it must return valid JSON and complete before timeout
839
-
840
- **What happens under the hood:**
841
-
842
- 1. `git worktree add` creates a temporary worktree per agent in `<tmpdir>/pi-worktree-*`
843
- 2. Optional `worktreeSetupHook` runs once per worktree (JSON in on stdin, JSON out on stdout)
844
- 3. Each agent runs in its worktree's cwd (preserving subdirectory context)
845
- 4. Before diff capture, declared synthetic helper paths (for example `.venv` or copied local config files) are removed
846
- 5. After execution, `git add -A && git diff --cached` captures all real changes (committed, modified, and new files)
847
- 6. Diff stats appear in the aggregated output; full `.patch` files are written to the artifacts directory
848
- 7. Worktrees and temp branches are cleaned up in a `finally` block
849
-
850
- If you use [pi-prompt-template-model](https://github.com/nicobailon/pi-prompt-template-model), worktree isolation is also available via `worktree: true` in chain template frontmatter or the `--worktree` CLI flag on `chain-prompts`. `pi-prompt-template-model` compare-style prompts can route through the same worktree machinery too; see the `pi-prompt-template-model` README and `examples/` directory for the installable prompt templates.
851
-
852
- ## Chain Variables
853
-
854
- Templates support three variables:
855
-
856
- | Variable | Description |
857
- |----------|-------------|
858
- | `{task}` | Original task from first step (use in subsequent steps) |
859
- | `{previous}` | Output from prior step (or aggregated outputs from parallel step) |
860
- | `{chain_dir}` | Path to chain artifacts directory |
861
-
862
- **Parallel output aggregation:** When a parallel step completes, all outputs are concatenated with clear separators:
863
-
864
- ```
865
- === Parallel Task 1 (worker) ===
866
- [output from first task]
762
+ Requirements:
867
763
 
868
- === Parallel Task 2 (worker) ===
869
- [output from second task]
870
- ```
764
+ - run inside a git repo
765
+ - working tree must be clean
766
+ - `node_modules/` is symlinked into each worktree when present
767
+ - task-level `cwd` overrides must be omitted or match the shared cwd
768
+ - configured `worktreeSetupHook` must return valid JSON before timeout
871
769
 
872
- This aggregated output becomes `{previous}` for the next step.
770
+ After a worktree parallel step completes, per-agent diff stats are appended to the output and full patch files are written to artifacts. Worktrees and temp branches are cleaned up in `finally` blocks.
873
771
 
874
- ## Extension Configuration
772
+ ## Configuration
875
773
 
876
774
  `pi-subagents` reads optional JSON config from `~/.pi/agent/extensions/subagent/config.json`.
877
775
 
878
776
  ### `asyncByDefault`
879
777
 
880
- `asyncByDefault` makes top-level subagent calls use background execution when the request does not explicitly set `async`.
881
-
882
778
  ```json
883
- {
884
- "asyncByDefault": true
885
- }
779
+ { "asyncByDefault": true }
886
780
  ```
887
781
 
888
- This only changes the default. Callers can still force foreground execution by setting `async: false` unless `forceTopLevelAsync` is also enabled.
782
+ Makes top-level calls use background execution when the request does not explicitly set `async`. Callers can still force foreground with `async: false` unless `forceTopLevelAsync` is enabled.
889
783
 
890
784
  ### `forceTopLevelAsync`
891
785
 
892
- `forceTopLevelAsync` forces depth-0 subagent execution into background mode. This is useful for automation setups that never want the top-level orchestrator to block on child runs.
893
-
894
786
  ```json
895
- {
896
- "forceTopLevelAsync": true
897
- }
787
+ { "forceTopLevelAsync": true }
898
788
  ```
899
789
 
900
- When enabled:
901
- - top-level single, parallel, and chain runs are forced to `async: true`
902
- - top-level clarify UI is bypassed by forcing `clarify: false`
903
- - nested subagent calls still follow their own inherited depth and async settings
790
+ Forces depth-0 single, parallel, and chain runs into background mode and bypasses clarify UI by forcing `clarify: false`. Nested calls keep their own inherited settings.
904
791
 
905
792
  ### `parallel`
906
793
 
907
- `parallel` controls top-level `tasks` mode defaults and limits.
908
-
909
794
  ```json
910
795
  {
911
796
  "parallel": {
@@ -915,135 +800,48 @@ When enabled:
915
800
  }
916
801
  ```
917
802
 
918
- Fields:
919
- - `maxTasks` defaults to `8` when unset or invalid
920
- - `concurrency` defaults to `4` when unset or invalid
921
-
922
- Per-call `concurrency` on the `subagent` tool takes precedence over `config.parallel.concurrency` for top-level `tasks` runs.
803
+ `maxTasks` defaults to `8`; `concurrency` defaults to `4`. Per-call `concurrency` takes precedence.
923
804
 
924
805
  ### `defaultSessionDir`
925
806
 
926
- `defaultSessionDir` sets the fallback directory used for session logs. Eg:
927
-
928
807
  ```json
929
- {
930
- "defaultSessionDir": "~/.pi/agent/sessions/subagent/"
931
- }
808
+ { "defaultSessionDir": "~/.pi/agent/sessions/subagent/" }
932
809
  ```
933
810
 
934
- Session root resolution follows this precedence:
935
- 1. `params.sessionDir` from the `subagent` tool call
936
- 2. `config.defaultSessionDir`
937
- 3. Derived from parent session (stored alongside parent session file)
938
-
939
- Sessions are always enabled — every subagent run gets a session directory for tracking.
811
+ Session directory precedence is: `params.sessionDir`, then `config.defaultSessionDir`, then a directory derived from the parent session. Sessions are always enabled.
940
812
 
941
813
  ### `maxSubagentDepth`
942
814
 
943
- `maxSubagentDepth` sets the default recursion limit for nested delegation when no inherited `PI_SUBAGENT_MAX_DEPTH` is already in effect. Eg:
944
-
945
815
  ```json
946
- {
947
- "maxSubagentDepth": 1
948
- }
816
+ { "maxSubagentDepth": 1 }
949
817
  ```
950
818
 
951
- Per-agent `maxSubagentDepth` can tighten that limit further for child runs, but it does not relax an already inherited stricter limit.
819
+ Controls nested delegation when no inherited `PI_SUBAGENT_MAX_DEPTH` is already in effect. Per-agent `maxSubagentDepth` can tighten the limit for that agent’s child runs, but cannot relax an inherited stricter limit.
952
820
 
953
821
  ### `intercomBridge`
954
822
 
955
- Controls whether subagents receive runtime intercom coordination instructions (and `intercom` is auto-added to their tool allowlist when needed).
956
-
957
823
  ```json
958
824
  {
959
- "intercomBridge": {
960
- "mode": "always",
961
- "instructionFile": "./intercom-bridge.md"
962
- }
825
+ "intercomBridge": {
826
+ "mode": "always",
827
+ "instructionFile": "./intercom-bridge.md"
828
+ }
963
829
  }
964
830
  ```
965
831
 
966
- Fields:
967
- - `"mode"` (default: `"always"`): inject bridge in both `fresh` and `fork`, only in `fork`, or disable it entirely
968
- - `"instructionFile"` (optional): path to a Markdown template that replaces the default injected subagent intercom instructions. Supports `{orchestratorTarget}` placeholder interpolation. Relative paths resolve from `~/.pi/agent/extensions/subagent/`.
969
-
970
- Example `instructionFile`:
971
-
972
- ```md
973
- Intercom orchestration channel:
974
-
975
- The inherited thread is reference-only. Do not continue that conversation or send questions, status updates, or completion handoffs to the orchestrator in normal assistant text.
976
-
977
- Use `intercom` only to coordinate with the orchestrator session `{orchestratorTarget}`.
978
-
979
- - Need a decision or you're blocked: `intercom({ action: "ask", to: "{orchestratorTarget}", message: "<question>" })`
980
- - Blocked or explicitly asked to send progress: `intercom({ action: "send", to: "{orchestratorTarget}", message: "UPDATE: <summary>" })`
981
-
982
- Do not send routine completion handoffs through intercom. If no coordination is needed, return a focused task result.
983
- ```
984
-
985
- Bridge activation also requires all of the following:
986
- - [pi-intercom](https://github.com/nicobailon/pi-intercom) is installed (`pi install npm:pi-intercom`)
987
- - `~/.pi/agent/intercom/config.json` is not set to `"enabled": false`
988
- - the current session can be targeted by intercom (existing `/name`, or the runtime-only fallback alias `subagent-chat-<id>` when unnamed)
989
- - if agent `extensions` is an explicit allowlist, it must include `pi-intercom`
990
-
991
- When an unnamed session falls back to `subagent-chat-<id>`, that alias is used only for the live intercom broker. It is not persisted as the Pi session title, so `pi --resume` can still show the transcript snippet.
992
-
993
- If you want a stronger prompt contract for forked chat-back runs without changing builtins, define a custom agent for it. Keeping that as an opt-in agent works better than teaching every delegated run to behave this way.
832
+ Controls whether subagents receive runtime intercom coordination instructions and whether `intercom` is auto-added to their tool allowlist when needed.
994
833
 
995
- Example agent:
996
-
997
- ```md
998
- ---
999
- name: fork-chatback
1000
- description: Forked worker that asks the orchestrator questions through intercom when needed
1001
- tools: read, bash, edit, write, intercom
1002
- systemPromptMode: replace
1003
- inheritProjectContext: true
1004
- inheritSkills: false
1005
- ---
1006
-
1007
- You are a delegated worker running from a fork of the orchestrator session.
1008
-
1009
- Treat the inherited conversation as reference-only context. Do not continue that conversation in normal assistant text.
1010
-
1011
- Your job is to do the task. If you need a decision, clarification, or unblock from the orchestrator, use `intercom` to ask the orchestrator session named in the runtime bridge instructions.
834
+ Fields:
1012
835
 
1013
- If you need to send a progress update or completion handoff upstream, use `intercom` to send it to that same orchestrator session.
836
+ - `mode`: default `always`; use `fork-only` to inject only for forked runs, or `off` to disable the bridge.
837
+ - `instructionFile`: optional Markdown template replacing the default bridge instructions. `{orchestratorTarget}` is interpolated. Relative paths resolve from `~/.pi/agent/extensions/subagent/`.
1014
838
 
1015
- If no upstream coordination is needed, just complete the work and return a focused task result.
1016
- ```
839
+ Bridge activation also requires `pi-intercom` to be installed and enabled, a targetable current session name or fallback alias, and `pi-intercom` in any explicit agent `extensions` allowlist.
1017
840
 
1018
- Pair that with task wording that makes the contract explicit, like "Work from the forked context below. If you need anything from me, ask through `intercom`. Otherwise complete the task and return the result."
841
+ The default injected guidance tells children to use intercom only for coordination: ask when blocked or needing a decision, send updates only when blocked or explicitly asked, and avoid routine completion handoffs.
1019
842
 
1020
843
  ### `worktreeSetupHook`
1021
844
 
1022
- `worktreeSetupHook` configures an optional setup hook for worktree-isolated parallel runs. The hook runs once per created worktree, after `git worktree add` succeeds and before the agent starts.
1023
-
1024
- ```json
1025
- {
1026
- "worktreeSetupHook": "./scripts/setup-worktree.mjs"
1027
- }
1028
- ```
1029
-
1030
- Path rules:
1031
- - Must be an absolute path or a repo-relative path
1032
- - Bare command names from `PATH` are rejected
1033
- - `~/...` is supported for home-directory hooks
1034
-
1035
- Hook I/O contract (JSON only):
1036
- - stdin: one JSON object with `repoRoot`, `worktreePath`, `agentCwd`, `branch`, `index`, `runId`, and `baseCommit`
1037
- - stdout: one JSON object, e.g. `{ "syntheticPaths": [".venv", ".env.local"] }`
1038
-
1039
- `syntheticPaths` must be relative to the worktree root. These paths are removed before diff capture so helper files/symlinks do not pollute generated patches.
1040
-
1041
- Tracked-file edits are never excluded. If the hook tries to mark tracked paths as synthetic, setup fails.
1042
-
1043
- ### `worktreeSetupHookTimeoutMs`
1044
-
1045
- Optional timeout (milliseconds) for each worktree hook invocation.
1046
-
1047
845
  ```json
1048
846
  {
1049
847
  "worktreeSetupHook": "./scripts/setup-worktree.mjs",
@@ -1051,183 +849,135 @@ Optional timeout (milliseconds) for each worktree hook invocation.
1051
849
  }
1052
850
  ```
1053
851
 
1054
- Default: `30000` ms.
852
+ The hook runs once per created worktree. Paths must be absolute, `~/...`, or repo-relative; bare command names are rejected.
1055
853
 
1056
- ## Chain Directory
1057
- Each chain run creates a user-scoped temp directory like `<tmpdir>/pi-subagents-<scope>/chain-runs/{runId}/` containing:
1058
- - `context.md` - Scout/context-builder output
1059
- - `plan.md` - Planner output
1060
- - `progress.md` - Worker/reviewer shared progress
1061
- - `parallel-{stepIndex}/` - Subdirectories for parallel step outputs
1062
- - `0-{agent}/output.md` - First parallel task output
1063
- - `1-{agent}/output.md` - Second parallel task output
1064
- - Additional files as written by agents
854
+ stdin is a JSON object with `repoRoot`, `worktreePath`, `agentCwd`, `branch`, `index`, `runId`, and `baseCommit`. stdout must be one JSON object, for example:
1065
855
 
1066
- Directories older than 24 hours are cleaned up on extension startup.
856
+ ```json
857
+ { "syntheticPaths": [".venv", ".env.local"] }
858
+ ```
1067
859
 
1068
- ## Artifacts
860
+ `syntheticPaths` must be relative to the worktree root. They are removed before diff capture so helper files do not pollute patches. Tracked files are never excluded; marking a tracked path as synthetic fails setup. Default timeout is `30000` ms.
1069
861
 
1070
- Location: `{sessionDir}/subagent-artifacts/` or a user-scoped temp directory like `<tmpdir>/pi-subagents-<scope>/artifacts/`
862
+ ## Files, logs, and observability
1071
863
 
1072
- Files per task:
1073
- - `{runId}_{agent}_input.md` - Task prompt
1074
- - `{runId}_{agent}_output.md` - Full output (untruncated)
1075
- - `{runId}_{agent}.jsonl` - Event stream (sync only)
1076
- - `{runId}_{agent}_meta.json` - Timing, usage, exit code, final model, attempted models, and per-attempt outcomes
864
+ Each chain run creates a user-scoped temp directory like:
1077
865
 
1078
- When fallback is used, metadata records both the ordered `attemptedModels` list and `modelAttempts` entries with success/failure, exit code, error, and usage per attempt.
866
+ ```text
867
+ <tmpdir>/pi-subagents-<scope>/chain-runs/{runId}/
868
+ ```
1079
869
 
1080
- ## Session Logs
870
+ It may contain files such as `context.md`, `plan.md`, `progress.md`, and `parallel-{stepIndex}/.../output.md`. Directories older than 24 hours are cleaned up on extension startup.
1081
871
 
1082
- Session files (JSONL) are stored under a per-run session directory. Directory selection follows the same precedence as session root resolution: explicit `sessionDir` > `config.defaultSessionDir` > parent-session-derived path. The session file path is shown in output.
872
+ Debug artifacts live under `{sessionDir}/subagent-artifacts/` or a user-scoped temp artifact directory. Per task you may see:
1083
873
 
1084
- When `context: "fork"` is used, each child run starts with `--session <branched-session-file>` produced from the parent's current leaf. This is a real session fork, not injected summary text. The fork preamble explicitly tells the child to treat the inherited conversation as reference-only context rather than a live thread to continue.
874
+ - `{runId}_{agent}_input.md`
875
+ - `{runId}_{agent}_output.md`
876
+ - `{runId}_{agent}.jsonl`
877
+ - `{runId}_{agent}_meta.json`
1085
878
 
1086
- ## Session Sharing
879
+ Metadata records timing, usage, exit code, final model, attempted models, and fallback attempt outcomes.
1087
880
 
1088
- When `share: true` is passed, the extension will:
881
+ Session files are stored under a per-run session directory. With `context: "fork"`, each child starts with `--session <branched-session-file>` produced from the parent’s current leaf. That is a real session fork, not an injected summary.
1089
882
 
1090
- 1. Export the full session (all tool calls, file contents, outputs) to an HTML file
1091
- 2. Upload it to a GitHub Gist using your `gh` CLI credentials
1092
- 3. Return a shareable URL (`https://shittycodingagent.ai/session/?<gistId>`)
883
+ Async completions notify only the originating session. The result watcher emits `subagent:async-complete`, and the extension consumes that event to render completion notifications.
1093
884
 
1094
- **This is disabled by default.** Session data may contain sensitive information like source code, file paths, environment variables, or credentials that appear in tool outputs.
885
+ Async runs write:
1095
886
 
1096
- To enable sharing for a specific run:
1097
- ```typescript
1098
- { agent: "scout", task: "...", share: true }
887
+ ```text
888
+ <tmpdir>/pi-subagents-<scope>/async-subagent-runs/<id>/
889
+ status.json
890
+ events.jsonl
891
+ output-<n>.log
892
+ subagent-log-<id>.md
1099
893
  ```
1100
894
 
1101
- Requirements:
1102
- - GitHub CLI (`gh`) must be installed and authenticated (`gh auth login`)
1103
- - Gists are created as "secret" (unlisted but accessible to anyone with the URL)
1104
-
1105
- ## Live progress (sync mode)
895
+ `status.json` powers the widget and `/subagents-status`. `events.jsonl` contains wrapper events plus child Pi JSON events annotated with run and step metadata. `output-<n>.log` is a live human-readable tail. Fallback information is persisted so background runs are debuggable after completion.
1106
896
 
1107
- During sync execution, the collapsed view shows real-time progress for single, chain, and parallel modes.
897
+ ## Live progress
1108
898
 
1109
- **Chains:**
1110
- - Header: `running chain 1/2 | 8 tools, 1.4k tok, 38s`
1111
- - Chain visualization with status: `done scout → running planner` (`done`, `running`, `pending`, `failed`)
1112
- - Current tool: `> read: packages/tui/src/...`
1113
- - Recent output lines (last 2-3 lines)
899
+ Foreground runs show compact live progress for single, chain, and parallel modes: current tool, recent output, token counts, duration, activity freshness, and current-tool duration.
1114
900
 
1115
- **Parallel:**
1116
- - Header: `... parallel 2/4 | 12 tools, 2.1k tok, 15s`
1117
- - Per-task step cards showing status icon, agent name, model, tool count, and duration
1118
- - Current tool and recent output for each running task
901
+ Press `Ctrl+O` to expand the full streaming view with complete output per step.
1119
902
 
1120
- While a foreground run is active, the compact view also hints when richer detail is available and shows lightweight live-state signals like activity freshness and current-tool duration.
903
+ Sequential chains show a flow line like `done scout running planner`. Chains with parallel steps show per-step cards instead.
1121
904
 
1122
- Press **Ctrl+O** to expand the full streaming view with complete output per step.
905
+ ## Session sharing
1123
906
 
1124
- > **Note:** Chain visualization (the `done scout running planner` line) is only shown for sequential chains. Chains with parallel steps show per-step cards instead.
907
+ Pass `share: true` to export a full session to HTML, upload it to a secret GitHub Gist through your `gh` credentials, and return a `https://shittycodingagent.ai/session/?<gistId>` URL.
1125
908
 
1126
- ## Nested subagent recursion guard
909
+ ```ts
910
+ { agent: "scout", task: "...", share: true }
911
+ ```
1127
912
 
1128
- Subagents can themselves call the `subagent` tool, which risks unbounded recursive spawning (slow, expensive, hard to observe). A depth guard prevents this.
913
+ This is disabled by default. Session data may contain source code, paths, environment variables, credentials, or other sensitive output. You need `gh` installed and authenticated.
1129
914
 
1130
- By default nesting is limited to **2 levels**: `main session → subagent → sub-subagent`. Any deeper `subagent` calls are blocked and return an error with guidance to the calling agent.
915
+ ## Recursion guard
1131
916
 
1132
- You can configure the limit in three places:
917
+ Subagents can call `subagent`, which can get expensive and hard to observe. A depth guard prevents unbounded nesting.
1133
918
 
1134
- 1. `PI_SUBAGENT_MAX_DEPTH` in the environment before starting `pi`
1135
- 2. `config.maxSubagentDepth` in `~/.pi/agent/extensions/subagent/config.json`
1136
- 3. `maxSubagentDepth` in an agent's frontmatter to tighten the limit for that agent's child runs
919
+ By default, nesting is limited to two levels: main session → subagent → sub-subagent. Deeper calls are blocked with guidance to complete the current task directly.
1137
920
 
1138
- Environment inherits downward and wins for the current process. Per-agent limits can tighten child delegation but do not relax an already inherited stricter limit.
921
+ Configure the limit with:
1139
922
 
1140
- Override the limit with `PI_SUBAGENT_MAX_DEPTH` **set before starting `pi`**:
923
+ 1. `PI_SUBAGENT_MAX_DEPTH` before starting Pi
924
+ 2. `config.maxSubagentDepth`
925
+ 3. `maxSubagentDepth` in agent frontmatter, which can only tighten the inherited limit
1141
926
 
1142
927
  ```bash
1143
- export PI_SUBAGENT_MAX_DEPTH=3 # allow one more level (use with caution)
1144
- export PI_SUBAGENT_MAX_DEPTH=1 # only allow direct subagents, no nesting
1145
- export PI_SUBAGENT_MAX_DEPTH=0 # disable the subagent tool entirely
928
+ export PI_SUBAGENT_MAX_DEPTH=3
929
+ export PI_SUBAGENT_MAX_DEPTH=1
930
+ export PI_SUBAGENT_MAX_DEPTH=0
1146
931
  ```
1147
932
 
1148
- `PI_SUBAGENT_DEPTH` is an internal variable propagated automatically to child processes -- don't set it manually.
933
+ `PI_SUBAGENT_DEPTH` is internal and propagated automatically. Do not set it manually.
1149
934
 
1150
- ## Async observability
935
+ ## Events
1151
936
 
1152
- Async runs write a dedicated observability folder:
937
+ Async events:
1153
938
 
1154
- ```
1155
- <tmpdir>/pi-subagents-<scope>/async-subagent-runs/<id>/
1156
- status.json
1157
- events.jsonl
1158
- output-<n>.log
1159
- subagent-log-<id>.md
1160
- ```
939
+ - `subagent:async-started`
940
+ - `subagent:async-complete`
1161
941
 
1162
- `status.json` is the source of truth for async progress and powers both the TUI widget and `/subagents-status`. Async status and result files are written atomically, so readers do not observe partial JSON during background updates.
942
+ The result watcher emits `subagent:async-complete`; `index.ts` registers the notification handler that consumes it. Control/attention events are surfaced as visible parent notices and persisted for async runs. With `pi-intercom`, needs-attention notices can also reach the orchestrator over intercom.
1163
943
 
1164
- `events.jsonl` is the live event stream. It includes high-level wrapper events plus child `pi` JSON events annotated with subagent metadata for the run and step they belong to. `output-<n>.log` is a live human-readable tail for the current step. `subagent-log-<id>.md` is written when the run completes.
944
+ ## Prompt-template integration
1165
945
 
1166
- When fallback is used in async/background mode, `status.json` and the final result JSON include the final selected model, ordered attempted models, and per-attempt outcomes so background runs are as debuggable as sync runs.
946
+ `pi-subagents` works standalone through natural language, the `subagent` tool, slash commands, and the packaged prompt shortcuts listed near the top of this README. If you use [pi-prompt-template-model](https://github.com/nicobailon/pi-prompt-template-model), you can also wrap subagent delegation in your own reusable prompt templates.
1167
947
 
1168
- For programmatic access:
948
+ Example:
1169
949
 
1170
- ```typescript
1171
- subagent({ action: "status" })
1172
- subagent({ action: "status", id: "<id>" })
1173
- subagent({ action: "status", dir: "<tmpdir>/pi-subagents-<scope>/async-subagent-runs/<id>" })
950
+ ```md
951
+ ---
952
+ description: Take a screenshot
953
+ model: claude-sonnet-4-20250514
954
+ subagent: browser-screenshoter
955
+ cwd: /tmp/screenshots
956
+ ---
957
+ Use url in the prompt to take screenshot: $@
1174
958
  ```
1175
959
 
1176
- For an interactive overview, run the `/subagents-status` slash command to open the overlay listing active runs and recent completed, failed, and paused runs. The overlay auto-refreshes every 2 seconds while it is open and focuses on summary/status information, including the current output/session paths when available.
960
+ Then `/take-screenshot https://example.com` switches to Sonnet, delegates to `browser-screenshoter` with `/tmp/screenshots` as cwd, and restores your model when done. Runtime overrides like `--cwd=<path>` and `--subagent=<name>` work too.
1177
961
 
1178
- ## Events
962
+ For more reusable workflows on top of subagents, including `/chain-prompts` and compare-style prompts such as `/best-of-n`, install `pi-prompt-template-model` separately and copy the examples you want into `~/.pi/agent/prompts/`.
1179
963
 
1180
- Async events:
1181
- - `subagent:async-started`
1182
- - `subagent:async-complete`
1183
-
1184
- The result watcher emits `subagent:async-complete`; `index.ts` registers the notification handler that consumes it.
964
+ ## Runtime files
1185
965
 
1186
- ## Files
966
+ The main runtime files are:
1187
967
 
1188
- ```
1189
- ├── index.ts # Main extension, tool registration, overlay dispatch
1190
- ├── agents.ts # Agent + chain discovery, frontmatter parsing
1191
- ├── skills.ts # Skill resolution, caching, and discovery
1192
- ├── settings.ts # Chain behavior resolution, templates, chain dir
1193
- ├── chain-clarify.ts # TUI for chain/single/parallel clarification
1194
- ├── chain-execution.ts # Chain orchestration (sequential + parallel)
1195
- ├── chain-serializer.ts # Parse/serialize .chain.md files
1196
- ├── async-execution.ts # Async/background execution support
1197
- ├── async-status.ts # Async run discovery, listing, and formatting
1198
- ├── execution.ts # Core runSync and sync fallback handling
1199
- ├── render.ts # TUI rendering (widget, tool result display)
1200
- ├── subagents-status.ts # Async status overlay component
1201
- ├── artifacts.ts # Artifact management
1202
- ├── formatters.ts # Output formatting utilities
1203
- ├── schemas.ts # TypeBox parameter schemas
1204
- ├── utils.ts # Shared utility functions (mapConcurrent, readStatus, etc.)
1205
- ├── types.ts # Shared types and constants
1206
- ├── model-fallback.ts # Fallback candidate resolution and retry classification
1207
- ├── subagent-runner.ts # Async runner (detached process)
1208
- ├── parallel-utils.ts # Parallel execution utilities for async runner
1209
- ├── worktree.ts # Git worktree isolation for parallel execution
1210
- ├── pi-spawn.ts # Cross-platform pi CLI spawning
1211
- ├── single-output.ts # Solo agent output file handling
1212
- ├── notify.ts # Async completion notifications
1213
- ├── completion-dedupe.ts # Completion deduplication for notifications
1214
- ├── file-coalescer.ts # Debounced file write coalescing
1215
- ├── jsonl-writer.ts # JSONL event stream writer
1216
- ├── agent-manager.ts # Overlay orchestrator, screen routing, CRUD
1217
- ├── agent-manager-list.ts # List screen (search, multi-select, progressive footer)
1218
- ├── agent-manager-detail.ts # Detail screen (resolved prompt, runs, fields)
1219
- ├── agent-manager-edit.ts # Edit screen (pickers, prompt editor)
1220
- ├── agent-manager-parallel.ts # Parallel builder screen (slot management, agent picker)
1221
- ├── agent-manager-chain-detail.ts # Chain detail screen (flow visualization)
1222
- ├── agent-management.ts # Management action handlers (list, get, create, update, delete)
1223
- ├── agent-serializer.ts # Serialize agents to markdown frontmatter
1224
- ├── agent-scope.ts # Agent scope resolution utilities
1225
- ├── agent-selection.ts # Agent selection state management
1226
- ├── agent-templates.ts # Agent/chain creation templates
1227
- ├── render-helpers.ts # Shared pad/row/header/footer helpers
1228
- ├── run-history.ts # Per-agent run recording (JSONL)
1229
- ├── test/unit/ # Fast unit tests for pure modules
1230
- ├── test/integration/ # Loader-based execution/integration tests
1231
- ├── test/support/ # Shared test loader, helpers, and mock pi harness
1232
- └── text-editor.ts # Shared text editor (word nav, paste)
1233
- ```
968
+ | File | Purpose |
969
+ |------|---------|
970
+ | `index.ts` | Extension registration, tool registration, message/render wiring. |
971
+ | `agents.ts` | Agent and chain discovery, frontmatter parsing. |
972
+ | `subagent-executor.ts` | Main execution routing for single, parallel, chain, management, status, interrupt, and doctor actions. |
973
+ | `execution.ts` | Core foreground `runSync` handling. |
974
+ | `subagent-runner.ts` | Detached async runner. |
975
+ | `async-execution.ts` | Background launch support. |
976
+ | `async-status.ts` / `subagents-status.ts` | Status discovery and overlay UI. |
977
+ | `chain-execution.ts` / `chain-serializer.ts` | Chain orchestration and `.chain.md` parsing. |
978
+ | `agent-manager*.ts` | Agents Manager screens and editing flows. |
979
+ | `settings.ts` | Chain behavior, instructions, and config helpers. |
980
+ | `worktree.ts` | Git worktree isolation. |
981
+ | `intercom-bridge.ts` | Runtime intercom bridge instructions and diagnostics. |
982
+ | `schemas.ts` / `types.ts` | Tool schemas, shared types, and event constants. |
983
+ | `test/unit/` / `test/integration/` | Unit and loader-based integration tests. |