@ferris1225/pi-subagents 4.3.34 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +32 -359
  2. package/README.md +130 -557
  3. package/index.ts +4 -2
  4. package/package.json +1 -1
  5. package/skills/workflow/SKILL.md +46 -29
  6. package/src/configuration/config.ts +4 -4
  7. package/src/configuration/setup.ts +88 -229
  8. package/src/configuration/ui.ts +107 -129
  9. package/src/delegation/builtin-agents.ts +9 -9
  10. package/src/delegation/dispatch.ts +9 -6
  11. package/src/delegation/prompt.ts +7 -8
  12. package/src/execution/cli-run.ts +364 -0
  13. package/src/execution/process-tree.ts +1 -1
  14. package/src/execution/{rpc-control.ts → run-control.ts} +15 -33
  15. package/src/execution/spawn.ts +33 -185
  16. package/src/isolation/temp-hygiene.ts +2 -3
  17. package/src/lifecycle/cancellation.ts +36 -0
  18. package/src/lifecycle/completion.ts +1 -1
  19. package/src/lifecycle/dispatch-core.ts +0 -1
  20. package/src/lifecycle/durable.ts +1 -1
  21. package/src/lifecycle/runtime.ts +42 -29
  22. package/src/lifecycle/stop.ts +175 -0
  23. package/src/lifecycle/thread-lifecycle.ts +11 -14
  24. package/src/lifecycle/thread-restore.ts +3 -3
  25. package/src/lifecycle/tools.ts +18 -173
  26. package/src/presentation/format.ts +2 -5
  27. package/src/presentation/monitor.ts +16 -1
  28. package/src/presentation/widget.ts +140 -175
  29. package/src/workflow/engine.ts +68 -34
  30. package/src/workflow/files.ts +10 -32
  31. package/src/workflow/plan.ts +61 -13
  32. package/src/workflow/state.ts +4 -3
  33. package/src/workflow/tool.ts +23 -12
  34. package/workflows/code-review.md +12 -7
  35. package/workflows/migration.md +14 -26
  36. package/workflows/research.md +6 -5
  37. package/src/execution/rpc-run.ts +0 -889
package/README.md CHANGED
@@ -1,619 +1,192 @@
1
1
  # pi-subagents
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/@ferris1225/pi-subagents?color=blue)](https://www.npmjs.com/package/@ferris1225/pi-subagents)
4
- [![downloads](https://img.shields.io/npm/dm/@ferris1225/pi-subagents)](https://www.npmjs.com/package/@ferris1225/pi-subagents)
5
- [![license](https://img.shields.io/npm/l/@ferris1225/pi-subagents)](./LICENSE)
6
- ![platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey)
7
- ![pi](https://img.shields.io/badge/pi-extension-orange)
8
-
9
- On-demand delegation for [pi](https://github.com/earendil-works/pi): a lightweight
10
- reader and an implementer, durable threads, and Git worktree isolation. Main
11
- delegates whenever the work has independent parts or a bounded job can be briefed
12
- self-contained — parallel phases usually beat a serialized main.
13
-
14
- ## What's new
15
-
16
- **4.3.34** — a workflow that would reuse a phase this session already owns (a
17
- settled run, or an interrupted one retained from an earlier session) is now
18
- rejected before any node starts, naming each owning run and the way out; the
19
- per-run duplicate message says the same for a parked owner instead of asking you
20
- to "let it finish".
21
-
22
- **4.3.33** — dependency graphs for multi-phase work. `subagent_workflow` declares
23
- nodes with `dependsOn`, validates the graph before any child starts, dispatches
24
- each node as its prerequisites settle, and reports the whole graph once. Saved
25
- definitions live in `.pi/workflows/` or `~/.pi/agent/workflows/`, three templates
26
- ship with the package, and a `workflow` skill carries the authoring guidance.
27
- `subagent_status` and `subagent_stop` accept a graph id.
28
-
29
- **4.3.32** — codemode-aware, tool-agnostic role policy and a minimal config.
30
- `scout` keeps every active tool the host proves read-only and can never keep a
31
- tool that reaches other tools, such as `codemode`, while `artisan` inherits the
32
- session's live surface, codemode included, so a code-mode host works unchanged.
33
- The two roles ship as code, are always enabled, and custom `agent.md` discovery
34
- is gone; `/subagents-setup` now only picks a model and thinking level per role,
35
- and the config file keeps just `agentModels` and `agentThinkingLevels`. The
36
- delegation contract defaults to delegating independent or self-contained work.
37
-
38
- See [CHANGELOG.md](./CHANGELOG.md) for earlier releases; every published version
39
- is preserved as a GitHub Release.
40
-
41
- ## Contents
42
-
43
- - [Why](#why)
44
- - [Install](#install)
45
- - [The team](#the-team)
46
- - [Dispatching work](#dispatching-work)
47
- - [Workflows](#workflows)
48
- - [Parallel edits](#parallel-edits)
49
- - [Runs: status and stop](#runs-status-and-stop)
50
- - [Live status and results](#live-status-and-results)
51
- - [Models, thinking, and tools](#models-thinking-and-tools)
52
- - [Configuration](#configuration)
53
- - [Evaluate delegation](#evaluate-delegation)
54
- - [Storage and cleanup](#storage-and-cleanup)
55
- - [Development](#development)
56
- - [Release](#release)
57
-
58
- ## Why
59
-
60
- Delegation is supposed to remove coordination work. Most sub-agent launchers stop
61
- at "spawn a child with a prompt" and leave the hard parts — when to delegate, how
62
- wide to fan out, what happens when a model dies, how results come
63
- back — with you. This extension owns them:
64
-
65
- - Main delegates whenever the work has independent parts or a bounded job can be
66
- briefed self-contained — parallel phases usually beat a serialized main, and
67
- broad or unfamiliar lookups go to a child instead of the same searches run
68
- serially.
69
- `scout` covers read-only code, documentation, and web
70
- lookup only — it has no shell, so work that needs execution stays in main;
71
- `artisan` covers one substantial change. A small edit already understood in
72
- the current context stays in main, and a free process slot is not a reason
73
- to invent another phase. Briefs define the outcome, done condition, useful
74
- context, and boundaries.
75
- - A stable `phaseId` owns a logical phase in one resolved working directory even if
76
- its task wording changes. IDs are 1–80 ASCII letters, numbers, or `._:-`, starting
77
- with a letter or number, so lease output stays single-line. Exact normalized task+cwd
78
- remains the backward-compatible fallback for old calls.
79
- - Runs are one-shot. Use `subagent_status` to inspect them and `subagent_stop` to
80
- cancel them; main handles unfinished work instead of continuing a failed child.
81
- - Background completions and stop results arrive at the next parent model boundary;
82
- `wait: true` returns the same result in-turn instead. A run uses exactly one route.
83
- - Parallel writers use detached Git worktrees without touching your index.
84
- Worktree setup obeys the bounded queue; final integration releases its process slot.
85
- - Interrupted work retains artifacts for manual recovery after reload or crash.
86
- Within a run, a configured child-model failure can still hand off to the main model.
87
- - Failure notifications include available reasons, and status answers live
88
- progress with an activity trail and keeps terminal facts and retained
89
- recovery paths queryable for the current parent session.
3
+ Sub-agents for [Pi](https://github.com/earendil-works/pi): research, implementation,
4
+ dependency workflows, and Git worktree isolation.
90
5
 
91
6
  ## Install
92
7
 
93
- Requires **pi >= 1.0.0** and **Node.js >= 22.19.0**.
8
+ Requires **Pi >= 1.0.0** and **Node.js >= 22.19.0**.
94
9
 
95
10
  ```bash
96
11
  pi install npm:@ferris1225/pi-subagents
97
12
  ```
98
13
 
99
- Pi's extension list shows `@ferris1225/pi-subagents` without an internal source-path suffix.
14
+ Run `/subagents-setup` for a grouped role settings panel. Edit **Model** and
15
+ **Thinking** independently; **Reset role** restores that role's defaults. Each
16
+ selection saves immediately, Esc returns without applying a picker selection,
17
+ and the panel keeps your focus. Model pickers support search, paste, and paging.
100
18
 
101
- A fresh install writes a default config at session start — both roles enabled,
102
- both following the main model — and announces `/subagents-setup` once; the file
103
- itself is the marker, so later sessions stay silent. Run `/subagents-setup` to
104
- pick a model and thinking level per role — that is the entire configuration
105
- surface. Then ask for work:
19
+ Both roles follow the main model by default; thinking defaults to `low` for scout
20
+ and `high` for artisan. The panel distinguishes defaults from overrides and
21
+ shows the effective level when model capabilities clamp a preference. Changing
22
+ a model preserves the thinking preference. Settings live in
23
+ `~/.pi/agent/pi-subagents.json` as `agentModels` and `agentThinkingLevels`.
106
24
 
107
- ```text
108
- Map how authentication works, fix the refresh race, and run the tests.
109
- ```
110
-
111
- The main agent prefers scout for the unfamiliar part and artisan for the change.
112
- You can also call the tools directly when you want exact control.
113
-
114
- ## The team
25
+ ## Agents
115
26
 
116
- | Agent | Access | Owns |
117
- | --------- | --------- | ---- |
118
- | `scout` | Read-only | Searching code and documentation, and looking up external facts on the web. Returns citations as retrieval leads. No shell — it cannot run commands, tests, or builds. |
119
- | `artisan` | Full | One substantial implementation, fix, refactor, test, or docs change, including the checks that change needs. |
27
+ | Agent | Use for | Access |
28
+ | --- | --- | --- |
29
+ | `scout` | Code, documentation, and web research with citations | Read-only tools; no commands or edits |
30
+ | `artisan` | Implementation with tests, or reviews and validation that need commands | Parent's tool surface, including codemode |
120
31
 
121
- Role prompts state the outcome, the priority of the brief, and the hard boundary.
122
- Scout stays read-only. Artisan implements the authorized change through affected
123
- tests, docs, and local cleanup, and reports a disproved premise or a scope/approval
124
- blocker with evidence. Handoffs lead with the outcome and report checks as
125
- `command → result`.
32
+ Children receive a self-contained brief and project instructions, but no parent
33
+ conversation. They cannot delegate or release. Main owns planning, integration,
34
+ and the final result. Keep a fix and its regression tests with one owner.
126
35
 
127
- The catalog is fixed: `scout` and `artisan` are always enabled, and there are no
128
- custom role files. Two roles do not require two children on every task.
36
+ ## Delegate
129
37
 
130
- Every child is a leaf pi process with its own context window and no memory of your
131
- conversation. It still loads normal Pi context, including applicable project
132
- instructions; its role prompt is appended rather than replacing that context.
133
- The brief supplies the outcome and done condition, relevant paths/symbols, known
134
- facts and available citations, boundaries, and needed output. Children cannot
135
- obtain interactive clarification, so they resolve routine details and report
136
- material assumptions or blockers.
38
+ Pi chooses delegation from the task structure; no special request is required.
39
+ Small, familiar, or tightly coupled work stays in main. A child earns its cost
40
+ when substantial bounded work benefits from parallel progress, isolating noisy
41
+ research, or an independent check. Free process slots are not a team-size target.
137
42
 
138
- Children run the official `pi --mode rpc` server, using Pi's exported command/response
139
- types and its own session persistence. There is no separate subagent protocol. The
140
- host transport remains local.
43
+ Use one owner per deliverable, including its regression tests. Brief the child
44
+ with the outcome, done condition, relevant paths, established evidence, write
45
+ boundaries, required checks, and a compact expected result. Scout retrieves
46
+ sources; artisan can execute commands. This policy applies the context-isolation,
47
+ focused-role, and coordination-cost guidance in the official
48
+ [Codex subagents](https://developers.openai.com/codex/subagents) and
49
+ [Claude Code subagents](https://code.claude.com/docs/en/sub-agents) docs to Pi's
50
+ one-shot leaf runs.
141
51
 
142
- ## Dispatching work
52
+ Ask Pi to delegate explicitly, or call the tools directly:
143
53
 
144
54
  ```ts
145
- // One task
146
55
  subagent({
147
- phaseId: "cache-invalidation-fix",
148
56
  agent: "artisan",
149
- task: "Fix the cache invalidation bug in src/cache, add regression tests, run the checks.",
150
- scope: {
151
- paths: ["src/cache"],
152
- symbols: [{ path: "test/cache.test.ts", name: "invalidates stale entries" }],
153
- },
57
+ phaseId: "cache-fix",
58
+ task: "Fix cache invalidation in src/cache, add regression tests, and run the checks.",
59
+ scope: { paths: ["src/cache", "test/cache.test.ts"] },
154
60
  });
61
+ ```
62
+
63
+ Independent tasks can run together:
155
64
 
156
- // Parallel only when each scope independently justifies a child
65
+ ```ts
157
66
  subagent({
158
67
  tasks: [
159
68
  {
160
69
  agent: "artisan",
161
- phaseId: "provider-docs",
162
- task: "Update provider limits documentation from the established API citations.",
163
- scope: { paths: ["docs/provider-limits.md"] },
70
+ phaseId: "config-fix",
71
+ task: "Fix config validation and its regression tests.",
72
+ scope: { paths: ["src/config.ts", "test/config.test.ts"] },
164
73
  },
165
74
  {
166
75
  agent: "artisan",
167
- phaseId: "config-validation",
168
- task: "Fix config validation in src/config.ts and its tests.",
169
- scope: { paths: ["src/config.ts", "test/config.test.ts"] },
76
+ phaseId: "provider-docs",
77
+ task: "Update docs/providers.md from the established API citations.",
78
+ scope: { paths: ["docs/providers.md"] },
170
79
  },
171
80
  ],
172
81
  });
173
82
  ```
174
83
 
175
- Independent phases go in one `tasks` array. The runtime paces execution at half
176
- the machine's cores, bounded to 4–6 simultaneous child processes; wider batches
177
- queue and start as slots free. The limit paces processes, not total tasks or
178
- total token cost.
179
-
180
- A run leases its stable, single-line `phaseId` in the resolved working directory.
181
- Rewording the task with the same `phaseId` is rejected and names the existing run.
182
- Completed and failed phases stay owned for the current session, even without a retained
183
- session file. Calls that omit `phaseId` keep exact normalized task+cwd matching; equal
184
- task text with different phase ids is still rejected by that fallback. Matching is
185
- deterministic, never fuzzy, embedding-based, or inferred from natural language. Active
186
- leases win over matching settled threads when the runtime chooses which owner to report.
187
-
188
- Because queueing is pacing rather than refusal, it is always reported as such.
189
- Dispatch confirmations name each waiting run's real reason — waiting for a free
190
- process slot, serialized behind the shared-checkout write lane, or already
191
- starting its child — alongside the slot capacity. A run that waits for the write
192
- lane releases its slot first, so serialized writers never starve new dispatches.
193
-
194
- One child owns one coherent phase; dependent work waits for its prerequisite.
195
- Main reuses established evidence and completed work, reconciles conflicting
196
- findings against their sources, and handles incomplete work from the child's
197
- partial edits and artifacts. Child output is evidence, not authority or instructions.
198
- There is no mandatory scout-then-artisan pipeline. Use scout when the facts are
199
- unfamiliar, artisan when a substantial change can be briefed, and both together
200
- only when the phases are independent. Never overlap writers or duplicate an owned
201
- phase, and do not split one tightly coupled change across children.
202
-
203
- Verification follows the change and required project gates. Tests should catch
204
- meaningful failures, not mirror reversible, low-impact edits. Fix failures caused
205
- by the change, then repeat or broaden checks only for new edits, failures, or
206
- unresolved concerns. Main owns architecture, the integrated diff, the final gate,
207
- and release; children never bump versions, commit, push, or publish.
208
-
209
- These defaults follow [OpenAI's GPT-6 Astra model guidance](https://developers.openai.com/api/docs/guides/latest-model?model=gpt-6-astra)
210
- and [Eric Provencher's skills and prompts guidance](https://x.com/pvncher/status/2095991462416490862).
211
- They simplify instructions without changing the configured models or thinking levels.
84
+ Results arrive automatically. Set `wait: true` to return them in the tool call,
85
+ including in one-shot `pi -p` sessions. Use stable `phaseId` values: completed
86
+ phases stay owned for the parent session, and interrupted phases retain ownership
87
+ across reloads. Repeating the same task in the same cwd is also rejected.
212
88
 
213
89
  ## Workflows
214
90
 
215
- A request sometimes has phases whose order is known before the work starts:
216
- establish the facts, change independent slices at the same time, then run one
217
- gate. `subagent_workflow` declares that graph once. The runtime starts each node
218
- the moment its prerequisites settle and a process slot frees, so no parent model
219
- turn sits between waves, and it wakes the main agent once with a summary of the
220
- whole graph.
91
+ Main proactively chooses `subagent_workflow` for two or more substantial phases
92
+ with known dependencies and write scopes when scheduling them saves coordination.
93
+ Independent phases without dependency edges use `subagent` with `tasks`; a single
94
+ justified phase uses one `subagent` run. Small work stays in main.
95
+
96
+ If a research result must determine the next task or its scope, run that phase
97
+ first, decide in main, then reassess whether the remaining work fits a graph.
98
+ A workflow runs a fixed plan; it does not discover the plan or adapt its nodes
99
+ while running. Research, implementation, review, and confirmation are added only
100
+ when the task needs their distinct work.
221
101
 
222
102
  ```ts
223
103
  subagent_workflow({
224
104
  name: "auth-fix",
225
- description: "Map the refresh race, fix it, gate it.",
226
105
  nodes: [
227
- { id: "map", agent: "scout", task: "Map the refresh race in src/auth. Cite path:line." },
228
- { id: "fix", agent: "artisan", task: "Fix it. Evidence:\n{{map}}", dependsOn: ["map"],
229
- scope: { paths: ["src/auth"] } },
230
- { id: "tests", agent: "artisan", task: "Add regression tests. Evidence:\n{{map}}",
231
- dependsOn: ["map"], scope: { paths: ["test/auth.test.ts"] } },
232
- { id: "gate", agent: "artisan", task: "Run the checks.\nFix:\n{{fix}}\nTests:\n{{tests}}",
233
- dependsOn: ["fix", "tests"] },
106
+ {
107
+ id: "fix",
108
+ agent: "artisan",
109
+ task: "Fix the refresh race in src/auth and add regression tests. Run the relevant checks.",
110
+ scope: { paths: ["src/auth", "test/auth.test.ts"] },
111
+ },
112
+ {
113
+ id: "review",
114
+ agent: "artisan",
115
+ isolation: "shared",
116
+ dependsOn: ["fix"],
117
+ task: "Try to disprove this fix: inspect callers and edge cases, then run focused checks. Do not edit files.\n{{fix}}",
118
+ },
234
119
  ],
235
120
  });
236
121
  ```
237
122
 
238
- - `{{id}}` interpolates that node's final answer into a dependent's brief;
239
- `{{id.status}}`, `{{id.runId}}`, and `{{id.error}}` interpolate facts. A
240
- placeholder may only name a node the current one waits for, directly or through
241
- its chain; anything else is rejected at compile time.
242
- - The graph is validated before the first child starts: unique ids, existing
243
- dependencies, no cycles, resolvable placeholders, and no declared writer-scope
244
- overlap between nodes that no dependency orders.
245
- - Nodes are ordinary one-shot runs: same admission, isolation, durable
246
- checkpoints, and usage accounting as a `subagent` call. A node's result is
247
- registered only after its worktree is integrated, so a dependent reads what its
248
- prerequisite actually left behind.
249
- - Failure is contained by the graph. A failed node blocks only its dependents,
250
- independent branches keep running, and the summary names completed, failed, and
251
- never-ran nodes with the reason. Nodes never retry: main finishes incomplete work
252
- from the retained evidence.
253
- - A workflow reports once. Node completions are quiet, and the single summary
254
- carries each node's answer (clipped, with a full-report file when anything was
255
- cut) plus a per-model tally.
256
- - Write-capable nodes in a graph default to a detached worktree, which needs a
257
- committed `HEAD`; pass `"isolation": "shared"` on a node to keep it in your
258
- checkout and serialize it on the repository write lane.
259
-
260
- Saved definitions run by name and can be reviewed before they run:
261
-
262
- - Project: `.pi/workflows/<name>.json` or `.pi/workflows/<name>.md` (trusted projects only)
263
- - User: `~/.pi/agent/workflows/`
264
- - Shipped: the `code-review`, `research`, and `migration` templates in this package
265
- - Precedence: project > user > built-in, where the same `name` wins
123
+ `dependsOn` starts a node after its prerequisites complete and integrate.
124
+ `{{id}}` inserts an upstream answer; `.status`, `.runId`, and `.error` expose its
125
+ facts. Long answers include a full-result file. A failed node blocks its
126
+ dependents; independent branches continue. The graph delivers one summary.
266
127
 
267
- ```ts
268
- subagent_workflow({ workflow: "code-review" });
269
- subagent_workflow({ file: ".pi/workflows/code-review.md" });
270
- ```
128
+ Reviews seek counterexamples and try to disprove findings. Add independent
129
+ confirmation and synthesis when risk warrants them; combine stages for small tasks.
271
130
 
272
- A Markdown definition carries prose plus one `json` fenced block holding the plan
273
- object or a bare node array. The package also ships a `workflow` skill
274
- (`skills/workflow/SKILL.md`) with the authoring guidance: when a graph is worth
275
- its cost, how to slice phases, how to write briefs, and the anti-patterns.
276
-
277
- Derived phase ids are `<workflow-slug>.<node-id>`, and a phase stays owned after it
278
- settles and across reloads — an interrupted run keeps its claim until it is retired.
279
- A graph that reuses one is rejected before any node starts, naming each owning run;
280
- retire the owner with `subagent_stop({ id })`, or give those nodes different ids or
281
- `phaseId`s, or run the graph under a different name.
282
-
283
- `subagent_status({ workflow: id })` reports nodes and their wait reasons;
284
- `subagent_stop({ workflow: id })` stops a graph without starting its idle
285
- dependents. An unfinished graph keeps its shape on disk, so the next session's
286
- start notice and `subagent_status` report which nodes completed and which were
287
- still running.
288
-
289
- ## Parallel edits
290
-
291
- `scope` is declarative admission metadata for expected writes, not access control. `paths`
292
- contains exact file or directory paths; `symbols` contains exact `{ path, name }` claims.
293
- Paths resolve from each task's caller-facing cwd and use case-insensitive comparison on
294
- Windows. Wildcard `*` and `?` inputs are rejected; other punctuation is treated literally,
295
- so paths such as `app/[id]/page.tsx` are valid exact claims. A path claim overlaps the same
296
- path, an ancestor/descendant path, or a symbol under that path; identical path+symbol
297
- claims overlap, while two different symbols in the same file may run together.
298
-
299
- Fresh dispatches check declared writer scope against active, interrupted, or settling
300
- writer leases before allocating a run. Scope
301
- comparison uses normalized absolute claims rather than requiring equal caller cwd, so a
302
- repo-root claim still conflicts with the same path claimed from a nested cwd. Settled
303
- threads do not block a later phase solely because it edits the same scope.
304
-
305
- Before allocating any run in a parallel call, the runtime also rejects deterministic phase
306
- duplicates within the batch or against existing active/retained threads, then compares
307
- declared writer scopes across the whole batch. A definite conflict rejects the whole batch
308
- with zero starts. Parallel calls without `scope` remain valid, but their tool result and
309
- launch receipt say `independence not verified`; that means the contract lacked enough
310
- metadata, not that overlap was proved safe. Single calls never make a batch-independence
311
- claim. The existing shared-checkout writer lane remains the final serialization boundary.
312
-
313
- - Single tasks use your checkout. Parallel write-capable agents (`artisan`)
314
- default to a detached Git worktree, so parallel writers run at
315
- the same time. Worktree mode needs a committed `HEAD`. Read-only roles such as
316
- scout stay on the shared checkout, and an explicit `isolation: worktree` for a
317
- read-only role is rejected.
318
-
319
- > **Security boundary:** worktree isolation isolates Git changes only; it is not a sandbox.
320
- Child tools, network access, and environment access retain the Pi process's privileges.
321
- Third-party Pi packages execute as trusted code and must be reviewed accordingly.
322
-
323
- - An isolated run's tracked, deleted, untracked, and binary changes integrate
324
- back exactly once, after the child settles. Nothing is staged and your index is
325
- untouched.
326
- - Integration is a three-way merge, so parallel workers that touched disjoint
327
- files or regions land cleanly even when earlier patches moved the checkout
328
- underneath them. A genuine overlap leaves conflict markers in the checkout and
329
- keeps the worktree and patch for you to resolve.
330
- - Shared-checkout writers serialize through
331
- one repository lane, so two of them never race. A run waiting there is reported
332
- as a lane wait, not as slot queueing, and its process slot is already released.
333
- - Setup and integration failures keep the useful patch and worktree, and record
334
- where they are in `~/.pi/agent/ferris-pi-subagents/pi-subagents-recovery.json`.
335
- Later session starts in that same project repeat the notice until you remove
336
- the artifacts. A different project's pi window does not show or retry them.
337
- When the changes had already been applied and only the cleanup failed, the next
338
- session start in that project removes the retained copy itself and clears the notice.
339
-
340
- ## Runs: status and stop
341
-
342
- Every dispatch returns a stable `#id`. Runs are one-shot: there is no
343
- `subagent_control`, `steer`, `park`, or `resume` interface. Main takes over failed
344
- or incomplete work using the child's partial edits and artifacts. A different
345
- deliverable needs a new phase and brief, not a recycled thread.
346
-
347
- | Tool | What it does |
348
- | ---- | ------------ |
349
- | `subagent_workflow` | Run a dependency graph: declare `nodes` with `dependsOn` (or name a saved definition), get a launch receipt, and receive one summary when the graph settles. |
350
- | `subagent_status` | Read-only progress check. Omit `id` to list this parent session's runs, or pass an exact numeric `id` to inspect one. Omit `workflow` to include graphs, or pass a graph id. |
351
- | `subagent_stop` | Destructively cancel/retire a run by id/prefix, a whole graph with `workflow: id`, or all active runs with `all: true`. Delivers partial output and finalizes isolated changes. |
131
+ Saved definitions use JSON or Markdown with a `json` fenced block:
352
132
 
353
133
  ```ts
354
- subagent_status({});
355
- subagent_status({ id: 7 });
356
- subagent_stop({ id: "7" });
357
- ```
358
-
359
- Status reads runtime state without starting, stopping, continuing, or waiting for a
360
- child to finish. The model-facing answer is the progress view: state, elapsed time,
361
- and an activity trail of what the run has been doing (for example
362
- `activity: read src/config.ts · grep "cacheKey" · thinking`), plus failure
363
- diagnostics and any actionable paths (a truncated run's full-result file, retained
364
- worktree/patch artifacts). States distinguish `queued`, `running`, `interrupting`,
365
- `settling` (Git finalization), `completed`, `failed`, `stopped`, and `interrupted`
366
- (recovered unfinished work). Queued runs report their actual wait reason. Settled
367
- runs remain queryable in the current parent session even after their transient
368
- widget rows disappear.
369
-
370
- The tool returns these facts in Pi's structured `details.runs` field. An individual
371
- run's failure does not make a successful status lookup a tool error; an unknown `id`
372
- does. This is runtime-authored data, not a requirement for children to generate
373
- strict JSON. Agent-written reports remain evidence to verify.
374
-
375
- A background dispatch returns a launch receipt, then its completion arrives at
376
- the next safe parent boundary — after current tool calls and before the next model
377
- call. `wait: true` instead holds the dispatch until its new runs settle, which is
378
- useful for one-shot `pi -p` sessions or an immediate dependency. Each run has one
379
- delivery route; aborting the waiting parent turn transfers delivery to the
380
- background path. Use status for on-demand inspection, not a polling or sleep loop.
381
-
382
- Stop drops messages still queued inside Pi, performs a bounded RPC abort, and
383
- terminates the child process tree. It retires the session; it never starts another
384
- attempt. Worktree integration failures keep their recovery artifacts.
385
-
386
- Interrupted work retains a durable record and any session/worktree artifacts for
387
- manual recovery after reload or crash. Missing session files no longer discard
388
- isolated edits. Restore for this checkout runs at session start; lookup tools,
389
- prompt injection, and fresh dispatch wait for that pass so an existing id cannot
390
- be reported missing or reused. A sibling window in another project leaves those
391
- records untouched. Missing recorded worktrees surface as failures without
392
- discarding the remaining recovery evidence.
393
-
394
- Invalid durable records are dropped without following or deleting their targets.
395
- Recovery-owned worktrees and patches stay protected from startup sweeps and
396
- project-root retention. Completed/failed runs drop their durable thread record;
397
- after reload, inspect their delivered result instead of expecting them in the
398
- current-session status list.
399
-
400
- ## Live status and results
401
-
402
- The TUI widget renders one line per active run in fixed identity columns —
403
- status icon, right-aligned `#id`, padded agent name, then the task label — with
404
- the live activity dimmed after `↳` on its own line and the rest of the telemetry
405
- inline after ` · `: the worktree badge, wait state, token flow in pi's footer
406
- vocabulary (`↑` input, `↓` output, `R`/`W` cache read/write), cost, full
407
- `provider/model`, current effective `think:<level>`, and seconds-precision elapsed:
408
-
409
- ```text
410
- ● #12 artisan src/cache.ts · worktree:a91f3c · ↑5.2k ↓41.0k R210.0k W6.1k $1.9400 · think:high · 12m06s
411
- ↳ edit src/auth.ts
412
- ● #15 scout src/models.ts · ↑1.2k ↓8.4k R31.0k W1.1k $0.0900 · openai/gpt-5-mini · think:low · 3m07s
413
- ↳ grep fallback
414
- ○ #23 artisan src/config.ts · repo lane
415
- ○ #24 artisan tests/config.test.ts · queued · 5m02s
416
- ```
417
-
418
- Telemetry drops leftmost-first when a row runs out of width (badge, wait state,
419
- usage, model, thinking) while elapsed survives every width. Queued rows state
420
- what they actually wait for — `queued` for a free process slot, `repo lane`
421
- for shared-checkout write serialization, or `starting`. The widget is
422
- capped at ten lines: extra runs collapse into a `… +N more` marker.
423
-
424
- Completions resume the main agent on their own, with a compact block of at most 40
425
- lines by default. Longer output (or lines wider than 200 characters) is not inlined
426
- at all: the notice states the true size and points at the unchanged Markdown artifact
427
- holding the full output, and main is told to read that file. The content therefore
428
- enters the main context exactly once, never first as a truncated copy the model
429
- cannot trust and then again as the file read. Roles write result-only handoffs —
430
- outcome, paths, verification, unresolved blockers — and the main agent is told to
431
- add its conclusion rather than restate what you already read. A failed run adds its
432
- failed-tool diagnostics.
433
-
434
- Delivery is held while a context compaction is in flight and released once it
435
- settles — on failure and abort too — so a result a child spent minutes producing
436
- is never swallowed by the summary that replaces the history.
437
-
438
- A `wait: true` dispatch streams its progress onto the tool card while it waits.
439
- Each child reports its usage per run — with its full `provider/model` ref — when it
440
- settles, and a parallel group's totals are grouped per model, never summed across
441
- them:
442
-
443
- ```text
444
- Totals: 3 runs · zhipu/glm-4.7: ↓300 $0.0500 · anthropic/claude-sonnet-4: ↓4.0k $1.5000
445
- ```
446
-
447
- A background dispatch returns before its children finish; their usage arrives
448
- with the completion message instead.
449
-
450
- ## Models, thinking, and tools
451
-
452
- Each agent runs on the current main model or one picked in `/subagents-setup`,
453
- which labels vision and text-only models. If a selected model is missing,
454
- rate-limited, or fails at the provider level, the **same retained
455
- session** continues on the main model, so finished searches, reads, and edits
456
- survive. Ordinary task failures do not trigger a handoff.
457
-
458
- Thinking is a **role default** — scout `low`, artisan `high` — clamped to what
459
- the effective model supports. The `/subagents-setup` thinking picker lists only
460
- the levels that model supports and marks the role
461
- default; selecting it clears the stored override. There is no
462
- Auto choice and no per-dispatch `thinking` flag. Precedence: your setup override > the
463
- role default, then the model clamp. There is no separate vision mode — assign
464
- a multimodal model and name the image paths in the task.
465
-
466
- Every dispatch, startup retry, and model fallback snapshots the parent's live
467
- tools, and all `subagent*` tools are removed so children remain leaves. A broad
468
- role inherits that snapshot — including `codemode` when the session runs it — so
469
- a code-mode parent produces code-mode children under the same `codemode.mode`.
470
- An explicit resolved list that names no MCP tool also excludes MCP tools it does
471
- not name.
472
-
473
- Neither role names extension, MCP, or vendor tools. `scout` is a hard
474
- read-only boundary that is derived from the live catalog: it keeps every active
475
- tool the host proves read-only — `annotations.readOnlyHint` for extension and
476
- MCP tools, plus pi's own `read`, `grep`, `find`, and `ls` — and never a shell, a
477
- mutation tool, or a tool that reaches other tools, so `codemode` and
478
- `tool_search` cannot reach a writer through it. A retrieval extension or an MCP
479
- search server therefore works for scout without being named anywhere, and without
480
- reconfiguring the server: a read-only tool the session reaches only through
481
- `codemode` or `tool_search` — pi's default for MCP servers — is handed to scout
482
- directly, which is the same capability without giving scout a way to reach a
483
- writer. Every other MCP tool stays excluded from that child. Tools with no
484
- read-only annotation, whether they are declared by another role or by an active
485
- extension, are conservatively treated as write-capable when isolation is chosen.
486
- An empty resolved snapshot starts the child with `--no-tools`.
487
-
488
- For external research scout prefers official documentation, specifications, release
489
- notes, and first-party repositories; it fetches decisive pages rather than citing
490
- search snippets, records material dates/versions, and marks uncertainty.
491
-
492
- ## Configuration
493
-
494
- `scout` and `artisan` are always enabled; the only settings are a model and a
495
- thinking level per role. `/subagents-setup` opens a menu with one row per role —
496
- its summary, current model, and current thinking level — plus a "Both roles"
497
- walk that asks each role's model and then its thinking level. `Esc` moves back,
498
- and the model picker supports fuzzy search. To start over, delete
499
- `~/.pi/agent/pi-subagents.json` and run `/subagents-setup`; the next session
500
- writes the defaults again. Settings live in `~/.pi/agent/pi-subagents.json`
501
- (following `PI_CODING_AGENT_DIR`):
502
-
503
- ```json
504
- {
505
- "agentModels": { "scout": "anthropic/claude-haiku-4-5" },
506
- "agentThinkingLevels": { "artisan": "high" }
507
- }
134
+ subagent_workflow({ workflow: "code-review" });
135
+ subagent_workflow({ file: ".pi/workflows/code-review.md" });
508
136
  ```
509
137
 
510
- | Field | Meaning |
511
- | --------------------- | ------- |
512
- | `agentModels` | Optional model per role as `provider/model-id`; missing means the current main model. |
513
- | `agentThinkingLevels` | Optional thinking override per role; missing means the role default (`scout` low, `artisan` high). |
514
-
515
- Everything else is a fixed constant: result deliveries keep 40 lines before the
516
- on-disk artifact takes over, process capacity is automatic, and a child silent
517
- for 30 minutes is terminated. Obsolete keys left by older config files are
518
- dropped when the canonical shape is persisted, and invalid values fall back to
519
- defaults.
520
-
521
- The delegation directive is installed as a `<subagents>` prompt section. Active
522
- leases go in `<subagent_leases>`. Pi 1.0 appends a section delta only when that
523
- text changes, so idle turns keep the cached system prefix. Hosts without a
524
- section map still receive the same contract appended to the system prompt.
525
-
526
- At session start, model overrides that pi no longer reports are removed with a
527
- one-time notice. If pi's own session compaction fails mid-thread, a notice surfaces
528
- the error and automatic retry instead of failing quietly.
529
-
530
- ## Evaluate delegation
531
-
532
- Choose delegation settings from your workload. The extension records execution
533
- facts, but its tests do not establish a quality or cost advantage over solo Pi.
534
-
535
- 1. Select representative tasks: a localized fix with a known cause, unfamiliar
536
- code exploration, independently verifiable module changes, and a tightly
537
- coupled debugging task. Define acceptance checks before running them.
538
- 2. Use fresh sessions and separate clean checkouts at the same starting commit.
539
- Keep task prompts, models, thinking levels, tools, and project instructions
540
- fixed. Keep results from earlier attempts out of later prompts; alternate
541
- execution order and repeat each comparison several times.
542
- 3. Compare a session where main delegates freely against one where you instruct
543
- it to work solo (or uninstall the extension). Record actual child counts and
544
- roles as well — a delegation-prone main may still finish some tasks alone.
545
- 4. Measure final acceptance and regressions, elapsed time through integration,
546
- and rework. Record main plus every child's token usage and cost, retaining
547
- model identities and including failed attempts, review, integration, and
548
- retries. A child's successful exit or quick first patch is not final success.
549
- 5. Compare quality under matched total-cost budgets and matched wall-clock
550
- limits as separate experiments. Include failed or unfinished runs. The idle
551
- timeout only detects a silent child; enforce experiment-wide budgets in your
552
- evaluation process.
553
-
554
- The [BOAD coding study](https://arxiv.org/html/2512.23631v2) found a useful small
555
- expert set but declining results when adding more roles; its role-count result
556
- does not prescribe a concurrency limit. A broader
557
- [2026 agent-system study](https://www.nature.com/articles/s42256-026-01268-y)
558
- also found that coordination outcomes depend on the task and single-agent
559
- baseline. These motivate measuring your own workflow, not a universal team size.
560
-
561
- ## Storage and cleanup
562
-
563
- Everything lives under your pi agent directory, grouped per project. Nothing
564
- long-lived is written to the OS temp directory, and every class of file has a rule
565
- that removes it, so this directory does not grow without bound:
566
-
567
- | Path | Holds | Removed |
568
- | ------------------------------------------ | ---------------------------------------------------- | ---------------------------------------------------------------- |
569
- | `pi-subagents.json` | Your configuration | Never — it is yours |
570
- | `ferris-pi-subagents/pi-subagents-recovery.json` | Worktree integration and cleanup failures | When the retained patch or worktree it points at is gone |
571
- | `ferris-pi-subagents/<project>/pi-subagents-threads.json` | One record per interrupted thread | When the thread settles, or after 30 days |
572
- | `ferris-pi-subagents/<project>/sessions/` | Child sessions for in-run fallback and manual recovery | When the owning session ends and no recovery record claims them |
573
- | `ferris-pi-subagents/<project>/worktrees/` | Isolated checkouts for parallel writers | On integration, or when no thread/recovery record claims them |
574
- | `ferris-pi-subagents/<project>/results/` | Full text of truncated results | After 7 days, or beyond 50 per project |
575
- | `ferris-pi-subagents/<project>/pi-subagents-workflows.json` | Shape and node state of unfinished workflow graphs | When the graph settles, or after 30 days |
576
- | `ferris-pi-subagents/<project>/tmp/` | Child prompt copies and the no-retry policy shim | When its owning process exits |
577
- | `ferris-pi-subagents/<project>/` | All of the above for one checkout | After 3 idle days unless a thread/recovery record claims it |
578
-
579
- Cleanup runs at session start and is deliberately conservative. A directory goes
580
- away only when the process that created it is gone and no valid manifest record still
581
- claims it, so a live sibling pi instance never loses state and interrupted or recovery-owned
582
- work outlives its own process by design. Thread and recovery references always beat an
583
- age rule. Restore and recovery notices themselves are scoped to the current checkout:
584
- opening pi in another project does not restore, announce, or stop the first project's runs.
138
+ Definitions load from `.pi/workflows/`, `~/.pi/agent/workflows/`, and the shipped
139
+ [templates](./workflows), in that order of precedence. Project definitions and
140
+ explicit file paths require project trust. Customize template questions, targets,
141
+ and scopes before running them.
142
+
143
+ See the [workflow skill](./skills/workflow/SKILL.md) for graph authoring details.
144
+
145
+ ## Status, cancellation, and recovery
146
+
147
+ | Tool | Use |
148
+ | --- | --- |
149
+ | `subagent_status({ id: 12 })` | Inspect a run's progress, result, and recovery paths |
150
+ | `subagent_status({ workflow: 3 })` | Inspect graph nodes and dependencies |
151
+ | `subagent_stop({ id: "12" })` | Stop a run and retire its retained session |
152
+ | `subagent_stop({ workflow: 3 })` | Stop a graph and finalize its active nodes |
153
+ | `subagent_stop({ all: true })` | Stop all active runs and graphs |
154
+
155
+ The widget is a compact task board capped at 10 lines: a status overview,
156
+ workflow progress groups, and task rows with status and elapsed time at the right.
157
+ Activity, model, thinking, token usage, and worktree state use secondary lines as
158
+ space permits. Task identities take priority over detail; failed and blocked
159
+ work takes priority over ordinary activity. Completed nodes collapse into graph
160
+ progress, and overflow reports hidden tasks. Queue reasons distinguish process
161
+ capacity, the repository write lane, and startup. Execution uses 4–6 process
162
+ slots; wider batches queue automatically.
163
+
164
+ Single writers use the shared checkout. Parallel writers and workflow writers
165
+ default to detached worktrees, which require a committed `HEAD`. Set
166
+ `isolation: "shared"` to use the checkout's serialized write lane. Declare exact
167
+ write paths or symbols in `scope` to detect conflicts. Worktrees isolate Git
168
+ changes, not tool permissions. Integration leaves your index untouched; failures
169
+ retain recovery artifacts.
170
+
171
+ Cancelling the parent run or navigating the conversation tree stops unfinished
172
+ work without completion wake-ups. New/resume/fork/reload ends old children and retains interrupted work
173
+ for manual recovery. Runs do not resume automatically; main finishes incomplete
174
+ work from partial changes and artifacts.
175
+
176
+ Children use Pi's native `--mode json` CLI, retries, and session persistence.
177
+ A settled provider failure can hand off once to the main model in the same
178
+ session. State and full-result files live under
179
+ `~/.pi/agent/ferris-pi-subagents/`, grouped by project. `PI_CODING_AGENT_DIR`
180
+ overrides the agent directory.
585
181
 
586
182
  ## Development
587
183
 
588
184
  ```bash
589
- npm install
185
+ npm ci
590
186
  npm run check
591
187
  ```
592
188
 
593
- `npm run check` is `tsc --noEmit` plus the unit tests (`npm test`). There are
594
- no bundled runtime dependencies; pi and TypeBox are peers. The source is
595
- grouped by responsibility under `src/`: configuration, delegation, execution, isolation,
596
- lifecycle, and presentation.
597
-
598
- `npm test` runs the TypeScript sources on Node's built-in type stripping from
599
- Node 22.19 up, including Node 26, which removed `--experimental-transform-types`;
600
- the source therefore avoids parameter properties and other transform-only
601
- syntax. Pi and TypeBox are peers, and the extension imports only pi's public SDK
602
- surface, so nothing is bundled.
603
-
604
- ## Changelog
605
-
606
- See [CHANGELOG.md](./CHANGELOG.md) for the latest release notes. Every
607
- published version is preserved as a GitHub Release; older entries are trimmed
608
- from the file.
609
-
610
- ## Release
611
-
612
- Pushing to `main` publishes `@ferris1225/pi-subagents` when `package.json`
613
- carries a version npm does not have yet, then opens a matching GitHub Release.
614
- Do not `npm publish` from a laptop. The workflow is
615
- `.github/workflows/publish.yml` (npm trusted publisher or `NPM_TOKEN`).
616
-
617
- ## License
189
+ Pushing an unpublished package version to `main` triggers
190
+ [publishing and a GitHub Release](./.github/workflows/publish.yml).
618
191
 
619
- MIT
192
+ [Changelog](./CHANGELOG.md) · [MIT license](./LICENSE)