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