pi-subagents 0.40.0 → 0.41.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 (119) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +246 -525
  3. package/agents/oracle.md +1 -0
  4. package/package.json +12 -4
  5. package/prompts/parallel-context-build.md +1 -1
  6. package/prompts/parallel-handoff-plan.md +1 -1
  7. package/prompts/review-loop.md +1 -1
  8. package/skills/pi-subagents/SKILL.md +6 -6
  9. package/skills/pi-subagents/references/constraints-and-recipes.md +19 -26
  10. package/skills/pi-subagents/references/execution-controls.md +98 -97
  11. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  12. package/skills/pi-subagents/references/prompting-and-roles.md +18 -27
  13. package/src/agents/agent-management.ts +155 -65
  14. package/src/agents/agent-serializer.ts +19 -0
  15. package/src/agents/agents.ts +154 -71
  16. package/src/agents/chain-serializer.ts +10 -7
  17. package/src/agents/frontmatter.ts +5 -3
  18. package/src/agents/identity.ts +1 -1
  19. package/src/agents/proactive-skills.ts +13 -10
  20. package/src/agents/skills.ts +23 -6
  21. package/src/api/control-channel.ts +4 -0
  22. package/src/api/delegation.ts +26 -194
  23. package/src/api/external-runs.ts +129 -0
  24. package/src/api/intercom-bridge.ts +3 -0
  25. package/src/api/pi-args.ts +5 -0
  26. package/src/api/preflight.ts +3 -3
  27. package/src/api/shared-types.ts +19 -0
  28. package/src/extension/config.ts +10 -0
  29. package/src/extension/control-notices.ts +5 -39
  30. package/src/extension/doctor.ts +10 -9
  31. package/src/extension/fanout-child.ts +7 -4
  32. package/src/extension/index.ts +232 -68
  33. package/src/extension/rpc.ts +18 -12
  34. package/src/extension/schemas.ts +48 -37
  35. package/src/extension/tool-description.ts +36 -86
  36. package/src/inspectors/herdr/actions.ts +229 -0
  37. package/src/inspectors/herdr/client.ts +130 -0
  38. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  39. package/src/inspectors/herdr/project-panes.ts +154 -0
  40. package/src/integrations/herdr-status.ts +330 -0
  41. package/src/intercom/intercom-bridge.ts +3 -2
  42. package/src/intercom/result-intercom.ts +5 -1
  43. package/src/missions/actions.ts +372 -0
  44. package/src/missions/lifecycle.ts +314 -0
  45. package/src/missions/store.ts +442 -0
  46. package/src/missions/types.ts +135 -0
  47. package/src/policy/authority.ts +46 -0
  48. package/src/profiles/profiles.ts +29 -3
  49. package/src/runs/background/async-execution.ts +98 -49
  50. package/src/runs/background/async-job-tracker.ts +10 -2
  51. package/src/runs/background/async-resume.ts +6 -6
  52. package/src/runs/background/async-status.ts +29 -1
  53. package/src/runs/background/auto-drain.ts +3 -3
  54. package/src/runs/background/chain-append.ts +3 -2
  55. package/src/runs/background/control-channel.ts +9 -7
  56. package/src/runs/background/fleet-view.ts +3 -4
  57. package/src/runs/background/notify.ts +2 -1
  58. package/src/runs/background/process-terminal.ts +5 -5
  59. package/src/runs/background/result-watcher.ts +13 -5
  60. package/src/runs/background/run-id-resolver.ts +3 -3
  61. package/src/runs/background/run-status.ts +35 -8
  62. package/src/runs/background/scheduled-runs.ts +602 -375
  63. package/src/runs/background/stale-run-reconciler.ts +3 -3
  64. package/src/runs/background/subagent-runner.ts +608 -445
  65. package/src/runs/background/subagent-wait.ts +50 -9
  66. package/src/runs/background/wait-subscriptions.ts +253 -0
  67. package/src/runs/background/wait-tool.ts +12 -4
  68. package/src/runs/foreground/async-steering-action.ts +3 -3
  69. package/src/runs/foreground/chain-clarify.ts +8 -4
  70. package/src/runs/foreground/chain-execution.ts +56 -30
  71. package/src/runs/foreground/execution.ts +15 -2
  72. package/src/runs/foreground/subagent-executor.ts +1023 -273
  73. package/src/runs/shared/acceptance.ts +28 -6
  74. package/src/runs/shared/child-protocol.ts +302 -22
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/external-cli-runner.ts +130 -0
  77. package/src/runs/shared/long-running-guard.ts +42 -1
  78. package/src/runs/shared/nested-events.ts +59 -5
  79. package/src/runs/shared/nested-render.ts +9 -4
  80. package/src/runs/shared/parallel-handoff.ts +86 -2
  81. package/src/runs/shared/parallel-utils.ts +11 -2
  82. package/src/runs/shared/permissions.ts +95 -0
  83. package/src/runs/shared/pi-args.ts +11 -1
  84. package/src/runs/shared/pi-spawn.ts +11 -1
  85. package/src/runs/shared/run-history.ts +1 -1
  86. package/src/runs/shared/subagent-prompt-runtime.ts +36 -5
  87. package/src/runs/shared/subagent-startup-retry.ts +5 -2
  88. package/src/runs/shared/turn-budget.ts +6 -6
  89. package/src/runs/shared/worktree.ts +122 -12
  90. package/src/shared/accessible-dir.ts +29 -7
  91. package/src/shared/artifacts.ts +18 -1
  92. package/src/shared/fork-context.ts +3 -2
  93. package/src/shared/launch-contract.ts +1 -0
  94. package/src/shared/settings.ts +10 -0
  95. package/src/shared/types.ts +156 -14
  96. package/src/shared/utils.ts +8 -6
  97. package/src/slash/delegation-adapters.ts +32 -194
  98. package/src/slash/delegation-request.ts +43 -126
  99. package/src/slash/prompt-template-bridge.ts +158 -205
  100. package/src/slash/prompt-workflows.ts +21 -57
  101. package/src/slash/slash-bridge.ts +14 -0
  102. package/src/slash/slash-commands.ts +31 -632
  103. package/src/slash/subagents-admin.ts +18 -14
  104. package/src/tui/fleet-status.ts +156 -21
  105. package/src/tui/fleet-transcript.ts +110 -5
  106. package/src/tui/fleet.ts +56 -24
  107. package/src/tui/render.ts +291 -109
  108. package/src/types/pi-runtime-compat.d.ts +14 -0
  109. package/src/watchdog/lsp-diagnostics.ts +12 -7
  110. package/src/watchdog/model-selection.ts +2 -2
  111. package/src/watchdog/permission-arbiter.ts +145 -0
  112. package/src/watchdog/register-child.ts +1 -1
  113. package/src/watchdog/register-main.ts +1 -1
  114. package/src/watchdog/review.ts +4 -1
  115. package/src/watchdog/runtime.ts +3 -2
  116. package/src/workflows/chat-progress.ts +140 -0
  117. package/src/workflows/scripted-workflow.ts +415 -0
  118. package/agents/advisor.md +0 -73
  119. package/src/extension/chain-validation.ts +0 -181
package/agents/oracle.md CHANGED
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  name: oracle
3
+ aliases: advisor
3
4
  description: High-context decision-consistency oracle that protects inherited state and prevents drift
4
5
  tools: read, grep, find, ls, bash, intercom
5
6
  thinking: high
package/package.json CHANGED
@@ -1,16 +1,21 @@
1
1
  {
2
2
  "name": "pi-subagents",
3
- "version": "0.40.0",
4
- "description": "Pi extension for delegating tasks to subagents with chains, parallel execution, and TUI clarification",
3
+ "version": "0.41.0",
4
+ "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
5
5
  "author": "Nico Bailon",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
8
  "exports": {
9
9
  ".": "./index.ts",
10
10
  "./background-work": "./src/api/background-work.ts",
11
+ "./external-runs": "./src/api/external-runs.ts",
11
12
  "./delegation": "./src/api/delegation.ts",
12
13
  "./capability-ceiling": "./src/api/capability-ceiling.ts",
13
- "./preflight": "./src/api/preflight.ts"
14
+ "./preflight": "./src/api/preflight.ts",
15
+ "./control-channel": "./src/api/control-channel.ts",
16
+ "./intercom-bridge": "./src/api/intercom-bridge.ts",
17
+ "./pi-args": "./src/api/pi-args.ts",
18
+ "./shared-types": "./src/api/shared-types.ts"
14
19
  },
15
20
  "repository": {
16
21
  "type": "git",
@@ -43,6 +48,7 @@
43
48
  "CHANGELOG.md"
44
49
  ],
45
50
  "scripts": {
51
+ "typecheck": "tsc --noEmit",
46
52
  "test": "npm run test:unit",
47
53
  "test:unit": "node --experimental-strip-types --test test/unit/*.test.ts",
48
54
  "test:integration": "node --experimental-strip-types --import ./test/support/register-loader.mjs --test test/integration/*.test.ts",
@@ -89,6 +95,8 @@
89
95
  "@earendil-works/pi-agent-core": "0.81.0",
90
96
  "@earendil-works/pi-ai": "0.81.0",
91
97
  "@earendil-works/pi-coding-agent": "0.81.0",
92
- "@earendil-works/pi-tui": "0.81.0"
98
+ "@earendil-works/pi-tui": "0.81.0",
99
+ "@types/node": "24.13.3",
100
+ "typescript": "5.9.3"
93
101
  }
94
102
  }
@@ -4,7 +4,7 @@ description: Parallel context builders for planning handoff
4
4
 
5
5
  Launch fresh-context `context-builder` subagents in parallel to build grounded handoff context for planning or implementation.
6
6
 
7
- Use the `subagent` tool in chain mode with a single parallel step, not top-level parallel tasks, so relative output files live under the temporary chain directory. Use `context: "fresh"` unless I explicitly ask for forked context. Give every parallel task a distinct `output` path, `label`, and `as` name, for example:
7
+ Use the `subagent` tool with `workflowScript` and `runs.all(...)`; assign each child a distinct absolute or durable output path. Use `context: "fresh"` unless I explicitly ask for forked context. Give every parallel task a distinct `output` path, `label`, and `as` name, for example:
8
8
 
9
9
  - `context-build/request-and-scope.md`
10
10
  - `context-build/codebase-and-patterns.md`
@@ -10,7 +10,7 @@ $@
10
10
 
11
11
  Use `context: "fresh"` unless I explicitly ask for forked context. First read or fetch any URLs, issue links, PRs, screenshots, plans, docs, or local files mentioned in the request. Treat them as primary scope, not optional context.
12
12
 
13
- Use the `subagent` tool in chain mode:
13
+ Use the `subagent` tool with `workflowScript`:
14
14
 
15
15
  1. First step: a parallel group.
16
16
  - `researcher`, when the request includes external references, APIs, libraries, docs, current best practices, or prompt-guidance research.
@@ -8,7 +8,7 @@ Use the `subagent` tool. Keep the parent session as the loop controller and fina
8
8
 
9
9
  Default to a maximum of 3 review rounds unless I specify a different cap. Count a review round each time fresh-context reviewers inspect the current diff after a worker pass. Stop early when reviewers find no blockers or fixes worth doing now.
10
10
 
11
- If the invocation includes an implementation request, first launch one async `worker` to implement the approved scope. If the current diff is already the target, start with review. The sequence can be launched up front as an async/background chain when the workflow is already clear, or continued as follow-up subagent runs after each async completion. For an initial chain, pass `async: true` so the main chat is unblocked; do not set `clarify: true` unless I explicitly want the foreground clarify UI. Use only one writer against the active worktree at a time unless I explicitly ask for isolated worktrees.
11
+ If the invocation includes an implementation request, first launch one async `worker` to implement the approved scope. If the current diff is already the target, start with review. The sequence can be launched up front with `workflowScript` when it is already clear, or continued as follow-up single-agent runs after each async completion. For an initial workflowScript, pass `async: true` so the main chat is unblocked; do not set `clarify: true` unless I explicitly want the foreground clarify UI. Use only one writer against the active worktree at a time unless I explicitly ask for isolated worktrees.
12
12
 
13
13
  As a conservative orchestration policy, do not set `turnBudget`, a hard `toolBudget`, or a tight `usageBudget` on implementation or fix workers. A default tool budget blocks read/search tools rather than mutation tools, and reported usage has no reservation model, so count or usage limits still do not measure delivery safety. Give each writer a narrow delivery slice and an outer elapsed deadline with enough margin. Before that deadline, request a checkpoint after the current tool returns with changed files, build/test state, remaining work, and commit or PR state. An elapsed timeout is not a mutation-safe boundary and must not be the checkpoint trigger.
14
14
 
@@ -1,8 +1,8 @@
1
1
  ---
2
2
  name: pi-subagents
3
3
  description: |
4
- Delegate work to builtin or custom subagents with single-agent, chain,
5
- parallel, async, forked-context, and intercom-coordinated workflows. Use
4
+ Delegate work to builtin or custom subagents with single-agent, parallel,
5
+ scripted, compatibility-chain, async, forked-context, and coordinated workflows. Use
6
6
  for advisory review, implementation handoffs, and multi-step tasks where a
7
7
  single agent should stay in control while other agents contribute context,
8
8
  planning, or execution.
@@ -12,7 +12,7 @@ description: |
12
12
 
13
13
  This skill is for the main parent orchestrator only. Do not inject or follow it inside spawned child subagents. The parent session owns delegation, orchestration, review fanout, and final fix-worker launches. Ordinary children should not run their own subagent workflows; the explicit exception is a delegated fanout child whose resolved builtin `tools` includes `subagent`, and that child may use `subagent` only for the fanout work the parent assigned.
14
14
 
15
- Use this skill when the parent orchestrator needs to launch a specialized subagent, compose multiple agents into a workflow, or create/edit agents and chains on demand.
15
+ Use this skill when the parent orchestrator needs one specialized child or composed orchestration. Use `{ agent, task }` for one isolated child with no sibling lane, monitor, dependency, or aggregation. Use `workflowScript` proactively for coordinated waves: sequence, parallelism, branching, retries, gate monitors, and aggregation. Scripted workflows start asynchronously by default; pass `async:false` only for a small foreground run. `workflowScript` is the only public multi-agent orchestration surface.
16
16
 
17
17
  ## How to use this router
18
18
 
@@ -21,7 +21,7 @@ Read the matching reference file before acting. Paths are relative to this `SKIL
21
21
  | Task | Read |
22
22
  | --- | --- |
23
23
  | Decide whether to delegate, choose agents, compare tool versus slash commands, apply prompt techniques, or understand builtin roles | `references/prompting-and-roles.md` |
24
- | Run single, parallel, chain, async, scheduled, forked, worktree, watchdog, clarify, oracle, or intercom-coordinated workflows | `references/execution-controls.md` |
24
+ | Run single, scripted, async, scheduled, mission-backed, forked, watchdog, clarify, oracle, or intercom-coordinated workflows | `references/execution-controls.md` |
25
25
  | List/create/update/delete/eject/disable agents or chains, edit agent files, use prompt-template integration, or expose extension RPC | `references/management-authoring-rpc.md` |
26
26
  | Check safety constraints, best practices, standard workflows, or error handling | `references/constraints-and-recipes.md` |
27
27
 
@@ -31,9 +31,9 @@ For broad or uncertain requests, read more than one reference. For complex work,
31
31
 
32
32
  - Keep the parent as orchestrator and final decision-maker.
33
33
  - Use one writer per cwd/worktree unless isolated worktrees are intentional.
34
- - For parallel fanout, compare child prompts before launch. Do not send clone prompts with only issue numbers, titles, or broad file globs swapped; each child needs a lane-specific task, source seam, prior evidence, and decision that remains distinct without the item number.
34
+ - For parallel fanout, compare child prompts before launch. Do not send clone prompts with only issue numbers, titles, or broad file globs swapped; each child needs a lane-specific task, source seam, prior evidence, and decision that remains distinct without the item number. Launch that fanout as one `workflowScript` with stable keys and aggregate output unless there is truly only one child.
35
35
  - Prefer fresh-context review/validation fanout, then synthesize and apply fixes in the parent.
36
- - Use async/background only when work can proceed independently; do not poll just to wait. For planned human gates in chains, use `{ checkpoint: "name", message?: "..." }` and approve or reject paused async checkpoints with `approve-checkpoint` / `reject-checkpoint`.
36
+ - Use async/background only when work can proceed independently; do not poll just to wait. For adaptive gates, branch in `workflowScript`. Approval controls remain available only for already-running durable legacy chains.
37
37
  - Preserve capability ceilings, including child tool restrictions and session-scoped allowed-agent restrictions.
38
38
  - Escalate unresolved product, architecture, or safety decisions upward instead of letting a child decide silently.
39
39
  - As a conservative orchestration policy, do not pass `turnBudget`, a hard `toolBudget`, or a tight `usageBudget` to mutation-capable workers. The default tool budget blocks read/search tools rather than mutation tools, and reported usage has no reservation model. If a worker is interrupted after a tool call starts, checkpoint after the current tool returns with changed files, build/test state, and commit or PR state.
@@ -17,14 +17,15 @@ This file is a detailed reference loaded from `skills/pi-subagents/SKILL.md`.
17
17
  ask wait state at a time.
18
18
  - **Keep conversational authority clear.** Advisory subagents should not silently
19
19
  become second decision-makers.
20
+ - **Respect the fixed authority policy.** `authorityPolicy` is a small `auto` / `confirm` / `forbid` map for supported operational actions. Worktree discard, destructive cleanup, and spawn-budget grants default to confirmation; stop, steer, and schedule creation remain automatic. Use `worktree.discard` with the durable `handoffPath`; confirm-required actions refuse safely without an interactive UI and retained paths include manual Git recovery commands.
20
21
 
21
- Runtime config can change orchestration behavior. `intercomBridge.resultDelivery: false` disables only external acknowledged grouped-result delivery when native parent notifications own completion; supervisor asks/progress stay active, and enabled transport failures are still reported. `asyncByDefault` and `forceTopLevelAsync` affect whether launches detach; `waitTool` can make direct `subagent_wait()` calls return immediately while headless auto-drain remains active, and its effective value is propagated to child runtimes; `globalConcurrencyLimit` bounds concurrent fanout, while a positive `maxSubagentSpawnsPerSession` optionally caps cumulative launches (`0` or unset is unlimited). Status and doctor report the budget; static work preflights declared capacity; only the settled root interactive parent can use `grant-spawn-budget` after native confirmation, with total grants bounded by the original cap. Compaction does not reset usage or grants; `singleRunOutputBaseDir` and `worktreeBaseDir` route outputs and worktrees; `completionBatch` groups async notifications. `artifactDir` is `project` (default), `session`, or `temp` and chooses where subagent artifacts are stored. Set `asyncWidget: false` to hide the above-editor background-run widget when a companion footer or dashboard owns that space (fleet inspector remains available). Per-run `artifacts: false` disables artifact capture for that launch. Async status and result artifacts are versioned with fields such as `lifecycleArtifactVersion`, `workflowGraph`, `steps`, `results`, `totalTokens`, `totalCost`, `turnCount`, `toolCount`, and nested `children`. Child protocol failures expose a structured `protocolError`; `protocol_output_limit` means a child emitted a JSONL line above the 4 MiB live-parser cap. Prefer these artifacts and `status` views over scraping terminal output.
22
+ Runtime config can change orchestration behavior. `intercomBridge.resultDelivery: false` disables only external acknowledged grouped-result delivery when native parent notifications own completion; supervisor asks/progress stay active, and enabled transport failures are still reported. `asyncByDefault` and `forceTopLevelAsync` affect whether launches detach; `waitTool` can make direct `subagent_wait()` calls return immediately while headless auto-drain remains active, and its effective value is propagated to child runtimes; `globalConcurrencyLimit` bounds concurrent fanout, while a positive `maxSubagentSpawnsPerSession` optionally caps cumulative launches (`0` or unset is unlimited). Status and doctor report the budget; static work preflights declared capacity; only the settled root interactive parent can use `grant-spawn-budget` after native confirmation, with total grants bounded by the original cap. Compaction does not reset usage or grants; `singleRunOutputBaseDir` and `worktreeBaseDir` route outputs and worktrees; `completionBatch` groups async notifications. `artifactDir` is `project` (default), `session`, or `temp` and chooses where subagent artifacts are stored. Set `asyncWidget: false` to hide the above-editor background-run widget when a companion footer or dashboard owns that space (fleet inspector remains available). Per-run `artifacts: false` disables artifact capture for that launch. Async status and result artifacts include `lifecycleArtifactVersion` and fields such as `workflowGraph`, `steps`, `results`, `totalTokens`, `totalCost`, `turnCount`, `toolCount`, and nested `children`. Child protocol failures expose a structured `protocolError`; `protocol_output_limit` means a child emitted a JSONL line above the 4 MiB live-parser cap. Prefer these artifacts and `status` views over scraping terminal output.
22
23
 
23
24
  ## Best Practices
24
25
 
25
26
  ### Prefer async orchestration
26
27
 
27
- Launch every subagent asynchronously by default. Use `async: true` for scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, chains, and parallel groups unless you intentionally need a foreground/blocking run. The parent should keep moving: inspect code while scouts run, prepare validation while a worker implements, do a local diff pass while reviewers review, and synthesize or verify while a fix worker applies accepted feedback. Async is the default orchestration posture; foreground runs are the explicit opt-out.
28
+ Launch every subagent asynchronously by default. Use `async: true` for scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, and scripted workflows unless you intentionally need a foreground/blocking run. When two or more child lanes, monitors, or dependent steps should move together, launch them as one `workflowScript` with stable keys instead of separate tool calls. Use direct single-child launches only for truly isolated work. The parent should keep moving: inspect code while scouts run, prepare validation while a worker implements, do a local diff pass while reviewers review, and synthesize or verify while a fix worker applies accepted feedback. Async is the default orchestration posture; foreground runs are the explicit opt-out.
28
29
 
29
30
  ### Use subagent_wait() to block until async runs finish
30
31
 
@@ -35,7 +36,7 @@ In an interactive chat, do not call `subagent_wait()` merely to wait after launc
35
36
  - `subagent_wait({ id: "..." })` — block on one async or remembered detached foreground run (id or prefix). Provider items are not selected through this parameter.
36
37
  - `subagent_wait({ timeoutMs })` — cap the block; active work keeps running if it elapses.
37
38
 
38
- Providers are discovered through the versioned `pi-subagents/background-work` registry and must return stable item IDs with exact owning session IDs. Child agents receive no provider automatically: keep `subagent_wait` in the child `tools` allowlist and load provider extensions through `extensions` or `subagentOnlyExtensions`.
39
+ Providers are discovered through the `pi-subagents/background-work` registry and must return stable item IDs with exact owning session IDs. Child agents receive no provider automatically: keep `subagent_wait` in the child `tools` allowlist and load provider extensions through `extensions` or `subagentOnlyExtensions`.
39
40
 
40
41
  For non-interactive fleet orchestration, `subagent_wait()` can keep N workers in flight: launch N, wait for the next completion, react to the result, launch a replacement if needed, then wait again. Use `subagent_wait({ all: true })` only when you intentionally want to drain the fleet to zero. If the turn ends first, headless `agent_end` auto-drain still waits for exact current-session work. In an interactive session, return to the user instead of holding the turn open just to await completion.
41
42
 
@@ -75,14 +76,12 @@ Use `/name` so intercom targeting stays stable.
75
76
 
76
77
  ### Recon → Plan → Implement
77
78
 
78
- ```typescript
79
- subagent({
80
- chain: [
81
- { agent: "scout", task: "Map the auth flow and summarize relevant files" },
82
- { agent: "planner", task: "Plan the migration from {previous}" },
83
- { agent: "worker", task: "Implement the approved plan from {previous}" }
84
- ]
85
- })
79
+ ```js
80
+ subagent({ workflowScript: `
81
+ const context = await runs.run("recon", { agent: "scout", task: "Inspect the codebase and identify the implementation seam" });
82
+ const plan = await runs.run("plan", { agent: "planner", task: "Plan from: " + context.output });
83
+ return (await runs.run("implement", { agent: "worker", task: "Implement this approved plan: " + plan.output })).output;
84
+ ` })
86
85
  ```
87
86
 
88
87
  ### Fable mode for complex work
@@ -111,7 +110,7 @@ When the user approves launching a subagent to carry out a plan or workflow, tre
111
110
  - `/parallel-review` maps to: launch fresh-context `reviewer` agents with distinct review angles; synthesize the feedback before applying anything.
112
111
  - `/review-loop` maps to: keep the parent in charge of worker → fresh reviewers → synthesized fix worker cycles until no fixes worth doing now remain, an unapproved decision appears, or the review-round cap is reached.
113
112
  - `/parallel-research` maps to: combine local `scout` context with external `researcher` evidence when current docs, ecosystem behavior, or API details matter.
114
- - `/parallel-context-build` maps to: run a chain-mode parallel group of `context-builder` agents with distinct temp output paths, then synthesize their context and meta-prompt sections.
113
+ - `/parallel-context-build` maps to: use `workflowScript` with `runs.all` for distinct `context-builder` lanes, then synthesize their context and meta-prompt sections.
115
114
  - `/parallel-handoff-plan` maps to: run external `researcher` plus local/strategy `context-builder` passes, then a synthesis `context-builder` that writes an implementation handoff plan and implementation-ready meta-prompt.
116
115
  - `/parallel-cleanup` maps to: use review-only cleanup passes after implementation, especially for simplicity, verbosity, and redundant tests.
117
116
 
@@ -194,22 +193,16 @@ For explicit review-loop requests, repeat worker → fresh-reviewer → synthesi
194
193
 
195
194
  ### Parallel non-conflicting analysis
196
195
 
197
- ```typescript
198
- subagent({
199
- tasks: [
200
- { agent: "scout", task: "Audit frontend auth flow" },
201
- { agent: "researcher", task: "Research current retry/backoff best practices" }
202
- ]
203
- })
204
- ```
205
-
206
- ### Saved chain
207
-
208
- ```text
209
- /run-chain review-chain -- review this branch
196
+ ```js
197
+ subagent({ workflowScript: `
198
+ return await runs.all([
199
+ { key: "frontend", agent: "scout", task: "Inspect the frontend" },
200
+ { key: "backend", agent: "scout", task: "Inspect the backend" }
201
+ ]);
202
+ ` })
210
203
  ```
211
204
 
212
- Use saved `.chain.md` or `.chain.json` workflows when the user wants a repeatable multi-agent flow without rewriting the chain each time. Prefer `.chain.json` for dynamic fanout or inline `outputSchema` objects; `.chain.md` remains the simple sequential/static authoring format.
205
+ Use distinct keys, prompts, and output paths. Do not launch parallel writers into the same checkout.
213
206
 
214
207
  ## Error Handling
215
208
 
@@ -9,11 +9,7 @@ Agent files can live in:
9
9
  - `.pi/agents/**/*.md` — canonical project scope
10
10
  - legacy `.agents/**/*.md` — still read for compatibility, but `.pi/agents/` wins on conflicts
11
11
 
12
- Chains live in:
13
- - `~/.pi/agent/chains/**/*.chain.md` and `~/.pi/agent/chains/**/*.chain.json` — user scope
14
- - `.pi/chains/**/*.chain.md` and `.pi/chains/**/*.chain.json` — project scope
15
-
16
- Discovery is recursive. `.chain.md` files do not define agents. Use `.chain.md` for simple saved chains and `.chain.json` for dynamic fanout or inline schema objects. Agents and chains can set optional frontmatter/package metadata; `name: scout` plus `package: code-analysis` registers as runtime name `code-analysis.scout` while serialization keeps `name` and `package` separate.
12
+ Saved chain files may still be discovered for management and existing durable run state, but they are not a public execution surface. Author new orchestration with `workflowScript`.
17
13
 
18
14
  Precedence is by parsed runtime name:
19
15
  1. project scope
@@ -24,6 +20,12 @@ Project settings resolve from the nearest parent directory containing `.pi` or `
24
20
 
25
21
  ## Running Subagents
26
22
 
23
+ ### External CLI profiles
24
+
25
+ An agent may set `runner.type: external-cli` with a non-empty `command`, optional string `args`, and `promptDelivery: stdin` (the default). The command runs with `shell: false`, inherits the resolved cwd and environment, and receives the combined agent instructions and task through stdin. It must already be installed; pi-subagents adds no CLI dependency.
26
+
27
+ External CLI profiles are async-only and one-shot. They support lifecycle artifacts, stdout/stderr logs, timeout, and stop. Full stdout and stderr are retained in their log files, while the final stdout response and stderr error kept in memory are each limited to their last 64 KiB. They do not support foreground/clarify, steer/resume/interrupt-as-pause, Pi models/tools/extensions/skills, tool or turn budgets, structured output, nested subagents, fallbacks, or sessions.
28
+
27
29
  ### Single agent
28
30
 
29
31
  ```typescript
@@ -52,74 +54,28 @@ Foreground results, async status, fleet, and widget surfaces label each child wi
52
54
  its resolved launch context as `[fresh]` or `[fork]`. Aggregate headers show
53
55
  `[mixed]` when a run uses both modes.
54
56
 
55
- ### Parallel execution
57
+ ### Scripted workflows
56
58
 
57
- ```typescript
58
- subagent({
59
- tasks: [
60
- { agent: "scout", task: "Explore the auth module" },
61
- { agent: "reviewer", task: "Review the API client" }
62
- ]
63
- })
64
- ```
65
-
66
- Top-level parallel tasks can override per-task behavior:
59
+ `workflowScript` is the sole public orchestration surface. Use `runs.run(key, { agent, task, ... })` for one child, `runs.all([...])` for parallel children, and ordinary JavaScript for sequence, branching, filtering, retries, and aggregation. Prefer a single scripted workflow whenever the parent is starting a coordinated wave, such as multiple reviews, review plus gate monitor, worker then monitor setup, or a fanout that the parent will consume together. Use a direct `{ agent, task }` call only for one isolated child with no sibling work or aggregate handoff.
67
60
 
68
- ```typescript
61
+ ```js
69
62
  subagent({
70
- tasks: [
71
- { agent: "scout", task: "Map auth", output: "auth-context.md", progress: true },
72
- { agent: "researcher", task: "Research OAuth best practices", output: "oauth-research.md" },
73
- { agent: "reviewer", task: "Review auth tests", model: "anthropic/claude-sonnet-4" }
74
- ],
75
- concurrency: 3
63
+ workflowScript: `
64
+ const scan = await runs.run("scan", { agent: "scout", task: "Map the target" });
65
+ const reviews = await runs.all([
66
+ { key: "correctness", agent: "reviewer", task: "Review correctness: " + scan.output },
67
+ { key: "tests", agent: "reviewer", task: "Review tests: " + scan.output }
68
+ ]);
69
+ return reviews.map(result => result.output);
70
+ `
76
71
  })
77
72
  ```
78
73
 
79
- Repeat one parallel task N times with the same settings via `count` (useful for identical scouts or review angles without hand-duplicating entries):
80
-
81
- ```typescript
82
- subagent({
83
- tasks: [
84
- { agent: "scout", task: "Map a distinct slice of the auth surface and return compressed context.", count: 3 }
85
- ],
86
- concurrency: 3,
87
- context: "fresh"
88
- })
89
- ```
90
-
91
- Avoid duplicate output paths in parallel tasks. Concurrent children should not write to the same file. For large saved outputs, set `outputMode: "file-only"` together with an `output` path. The parent result then contains only a compact reference like `Output saved to: /abs/report.md (48.2 KB, 2847 lines). Read this file if needed.` instead of the full saved content. Do not use `output: false` for this; `output: false` means no file output. In chains, relative `output` paths are chain-artifact paths under `{chain_dir}`, not project CWD paths; use an absolute `output` path or a persistent `chainDir` when a saved artifact must outlive the temp chain directory. Read-only children return the complete artifact in their final response and the runtime persists it, so missing write tools are not a supervisor blocker. Mutation-capable children still receive direct-write instructions. Failed runs and save errors still return inline details for debugging.
92
-
93
- ### Chain execution
94
-
95
- ```typescript
96
- subagent({
97
- chain: [
98
- { agent: "scout", task: "Map the auth flow and summarize key files" },
99
- { agent: "planner", task: "Create an implementation plan from {previous}" },
100
- { agent: "worker", task: "Implement the approved plan based on {previous}" }
101
- ]
102
- })
103
- ```
104
-
105
- Chain steps can use templated variables such as `{task}`, `{previous}`,
106
- `{chain_dir}`, and `{outputs.name}`. Use `as: "name"` on a successful step or
107
- parallel task to make that output available to later steps. Prefer named outputs
108
- when a later step needs one specific result; keep `{previous}` for simple linear
109
- handoffs or full fan-in summaries. Use `phase` and `label` for status readability.
110
- Use `outputSchema` when later steps need reliable structured data; the child must
111
- call `structured_output` with schema-valid JSON, or the step fails.
112
-
113
- Use `agentContract: { version: 1 }` when a caller needs generic result projections
114
- instead of acceptance or mutation effects rewriting execution success. V1 adds
115
- `execution`, `acceptance`, `review`, and `effects`; omitted acceptance means no
116
- acceptance request. Chain steps advance on execution by default under v1. Set
117
- `gateOn: "acceptance"` only when a rejected explicit acceptance report should stop
118
- the chain.
74
+ Scripts run in a timed worker with only `runs.run`, `runs.all`, `runs.status`, `runs.ref/refs`, `emit`, captured `console`, and standard JavaScript. Stable keys are required. Child launches follow ordinary single-agent execution controls. Give each child a distinct decision and output path when reports must outlive the workflow, then consume the aggregate workflow result before opening individual reports.
119
75
 
120
76
  ### Async/background
121
77
 
122
- Prefer async mode for every subagent launch. Set `async: true` no matter the task unless there is a specific reason to opt into a foreground/blocking run. This applies to scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, chains, and parallel groups. Keep the write path single-threaded even when the run is async.
78
+ Prefer async mode for every subagent launch. Set `async: true` no matter the task unless there is a specific reason to opt into a foreground/blocking run. This applies to scouts, researchers, workers, reviewers, validators, oracle checks, one-off delegates, and scripted workflows. Keep the write path single-threaded even when the run is async.
123
79
 
124
80
  Async does not mean parallel writes. Do not edit the same active worktree while an async worker is changing it. Parent-side overlap should be reading, validation prep, synthesis, command planning, or review of unaffected context unless the writer is isolated in a separate worktree.
125
81
 
@@ -127,7 +83,7 @@ Do not end your turn immediately after launching an async child if you promised
127
83
 
128
84
  In an interactive chat, normally return control when ready to yield and let Pi wake the session on completion; do not call `subagent_wait()` merely to wait. Override that default and call it when the current request is run-to-completion — for example, the user asked you to report results back before continuing or a skill cannot return before its background work finishes. Headless sessions auto-drain exact current-session work at `agent_end`; call `subagent_wait()` when this turn must receive results before it ends. Never substitute sleep or status-polling loops.
129
85
 
130
- `subagent_wait()` returns when the next initially active async run or registered provider item finishes or a subagent needs attention. Use `subagent_wait({ all: true })` for all work active at call time, `subagent_wait({ id: "..." })` for one async or remembered detached foreground run, and `subagent_wait({ timeoutMs })` to cap the block. If a foreground child detaches for supervisor coordination, reply first, then wait on its id; do not resume or launch a replacement while it remains detached. Headless sessions also auto-drain exact current-session work at `agent_end` as a final safeguard.
86
+ `subagent_wait()` returns when the next initially active async run or registered provider item finishes or a subagent needs attention. Use `subagent_wait({ all: true })` for all work active at call time, `subagent_wait({ id: "..." })` for one async or remembered detached foreground run, and `subagent_wait({ timeoutMs })` to cap the block. In a long-lived interactive parent session, use `subagent_wait({ id: "...", nonBlocking: true })` to resolve the prefix to one exact run, persist an armed subscription, return immediately, and wake later on completion, failure, attention, reconciliation failure, or timeout. Ordinary status lists armed subscriptions separately from active children. This differs from disabling `waitTool`, which returns immediately without arming a future wake. If a foreground child detaches for supervisor coordination, reply first, then wait on its id; do not resume or launch a replacement while it remains detached. Headless sessions also auto-drain exact current-session work at `agent_end` as a final safeguard.
131
87
 
132
88
  ```typescript
133
89
  subagent({
@@ -137,7 +93,7 @@ subagent({
137
93
  })
138
94
  ```
139
95
 
140
- File-only output mode also works for async single runs, top-level parallel task items, sequential chain steps, and chain parallel task items. In chains, `{previous}` receives the compact saved-file reference when the prior step used file-only mode. Relative chain output paths are resolved under `{chain_dir}`; pass a persistent `chainDir` or an absolute `output` path when a later human or process needs a stable path outside the temp chain run.
96
+ File-only output mode works for async single runs and workflowScript child launches. Use distinct absolute or durable output paths when later script steps need stable references.
141
97
 
142
98
  For review fanout where the parent continues a local audit:
143
99
 
@@ -151,18 +107,18 @@ const run = subagent({
151
107
  // Continue local inspection, then later call status with the returned id.
152
108
  ```
153
109
 
154
- While children run, the persistent FleetView and the collapsed foreground tool-result card show live per-child detail: resolved model and thinking level, `[fresh]`/`[fork]` context, tool/token/elapsed counters, and current activity. The collapsed running card also prints the configured expand-key hint ("Press … for live detail"); expanding it shows nested children, recent tools, and recent output. Model badges appear once the child's model resolves at first attempt start. `/subagents-fleet` opens the live fleet inspector, which also has per-child controls (`s` steer, `D` stop with confirmation).
110
+ While children run, the persistent FleetView and the collapsed foreground tool-result card show live per-child detail: resolved model and thinking level, `[fresh]`/`[fork]` context, tool/token/elapsed counters, and current activity. The collapsed running card also prints the configured expand-key hint ("Press … for live detail"); expanding it shows nested children, recent tools, and recent output. Model badges appear once the child's model resolves at first attempt start. `/subagents-fleet` opens the live fleet inspector, which also has per-child controls (`s` steer, `D` stop with confirmation). When optional Herdr 0.7.5+ is available, `H` opens a raw inspector dashboard for the selected active async child; this mirrors artifacts rather than attaching to the headless child. Use it for confusing or long-running active async work when the human wants a dedicated visual pane or FleetView is insufficient, not for routine headless runs.
155
111
 
156
112
  Inspect async runs with `subagent({ action: "status", id: "..." })` or `subagent({ action: "status" })` for active runs. Use `subagent({ action: "status", view: "fleet" })` when supervising several active foreground/background runs and `subagent({ action: "status", id: "...", view: "transcript", index: 0 })` when you need the latest child output without digging through artifacts. If a delegated fanout child launches nested runs, the parent status view shows them as a tree and you can target a nested run directly with its nested id.
157
113
 
158
- Stop a current-session top-level async run with `stop` (or `/subagents-stop`). Stopped runs finish as `stopped`/cancelled and are not resumable. For an active foreground single-subagent run, `/subagents-detach [run-id]` leaves the child running without terminating it and returns the eventual result through status/wait. Append one more step to the tail of a still-running async chain with `append-step` (`chain` must contain exactly one step). Use checkpoint steps for planned human gates; they pause without launching a child and are approved or rejected through current-session control actions:
114
+ Stop a current-session top-level async run with `stop` (or `/subagents-stop`). Stopped runs finish as `stopped`/cancelled and are not resumable. For an active foreground single-subagent run, `/subagents-detach [run-id]` leaves the child running without terminating it and returns the eventual result through status/wait. Append one more step to the tail of a still-running durable chain with `append-step` (`step` must contain exactly one step object). Use checkpoint steps for planned human gates; they pause without launching a child and are approved or rejected through current-session control actions:
159
115
 
160
116
  ```typescript
161
117
  subagent({ action: "stop", id: "run-id" })
162
118
  subagent({
163
119
  action: "append-step",
164
120
  id: "run-id",
165
- chain: [{ checkpoint: "review", message: "Approve the next implementation step?" }]
121
+ step: { checkpoint: "review", message: "Approve the next implementation step?" }
166
122
  })
167
123
  subagent({ action: "approve-checkpoint", id: "run-id" })
168
124
  subagent({ action: "reject-checkpoint", id: "run-id" })
@@ -195,26 +151,34 @@ Use diagnostics when setup or child startup looks wrong:
195
151
  subagent({ action: "doctor" })
196
152
  ```
197
153
 
198
- ### Scheduled subagent runs
154
+ ### External terminal work
199
155
 
200
- Scheduled runs defer a subagent launch until a future time. They are opt-in and require `{ "scheduledRuns": { "enabled": true } }` in `~/.pi/agent/extensions/subagent/config.json`. Only schedule explicit delayed runs the user asked for; do not schedule runs speculatively.
156
+ Use native `subagent` runs for unattended implementation, review, and gate work that needs managed isolation, durable artifacts, and process controls. Use `interactive_shell` for visible terminal work, alternate CLIs, trust prompts, and recovery.
201
157
 
202
- ```typescript
203
- // Launch a reviewer in 30 minutes
204
- subagent({ action: "schedule", agent: "reviewer", task: "Review the diff for correctness issues.", schedule: "+30m", scheduleName: "evening review" })
158
+ A cooperating terminal runtime can register read-only external records through `pi-subagents/external-runs`. Records include the source, session, state, optional report path, and completion reason. They are observations only: pi-subagents does not start, stop, steer, or otherwise own the foreign process. Run unattended raw terminal agents in an explicit isolated cwd or worktree; do not use a live project checkout as disposable review space.
205
159
 
206
- // Schedule a parallel fanout
207
- subagent({ action: "schedule", tasks: [{ agent: "scout", task: "Map the auth module" }, { agent: "scout", task: "Map the billing module" }], schedule: "+1h" })
160
+ ### Scheduled subagent runs
208
161
 
209
- // Inspect, list, and cancel
210
- subagent({ action: "schedule-list" })
211
- subagent({ action: "schedule-status", id: "ab12" })
212
- subagent({ action: "schedule-cancel", id: "ab12" })
213
- ```
162
+ Schedules are durable project records under `.pi-subagents/schedules/`. They are enabled by default; set `{ "scheduledRuns": { "enabled": false } }` in `~/.pi/agent/extensions/subagent/config.json` to disable them. Only schedule explicit work the user asked for.
214
163
 
215
- `schedule` accepts the same execution fields as a normal async run (`agent`/`tasks`/`chain`, `cwd`, `model`, `output`, `reads`, `progress`, `acceptance`, `timeoutMs` / `maxRuntimeMs`) plus `schedule` (a relative delay like `+10m`/`+2h`/`+1d` or a future ISO timestamp with a timezone such as `2030-01-01T09:00:00Z`) and an optional `scheduleName`. Scheduled runs always launch async with fresh context; `context: "fork"`, `async: false`, and `clarify: true` are rejected. Once the timer fires, the run becomes a normal tracked async run: it appears in the async widget, is inspectable with `subagent({ action: "status" })`, can be awaited with `subagent_wait()`, and delivers the normal completion notification.
164
+ ```typescript
165
+ // One-shot reviewer
166
+ subagent({ action: "schedule.create", id: "evening-review", name: "Evening review", at: "+30m", agent: "reviewer", task: "Review the diff." })
167
+
168
+ // Fixed recurring workflow
169
+ subagent({ action: "schedule.create", id: "backlog", every: "6h", catchUp: "latest", workflowScript: "..." })
170
+
171
+ subagent({ action: "schedule.list" })
172
+ subagent({ action: "schedule.show", id: "backlog" })
173
+ subagent({ action: "schedule.history", id: "backlog" })
174
+ subagent({ action: "schedule.pause", id: "backlog" })
175
+ subagent({ action: "schedule.resume", id: "backlog" })
176
+ subagent({ action: "schedule.run", id: "backlog" })
177
+ subagent({ action: "schedule.run-due" })
178
+ subagent({ action: "schedule.delete", id: "backlog" })
179
+ ```
216
180
 
217
- Schedules are persisted per session and restored after a Pi restart. A job whose scheduled time passed by more than `scheduledRuns.maxLatenessMs` (default 5 minutes) while Pi was unavailable is marked `missed` instead of firing late. `scheduledRuns.maxPending` (default 20) caps pending or running scheduled jobs per session.
181
+ `schedule.create` accepts exactly one target (`workflowScript`, or `agent` with optional `task`) and exactly one trigger (`at`, or a fixed `every` interval using `m`, `h`, `d`, or `w`). Runs always launch async with fresh context and no automatic mission; mission attachment is deferred from this first slice. `overlap` is currently `skip`; `catchUp` supports `latest` and `none`. `schedule.run-due` is the headless external-launcher seam. Calendar recurrence, cron, and the schedule inspector are deferred from this first safe slice. Definitions, bounded history, append-only events, and per-run receipts remain project-scoped across Pi sessions.
218
182
 
219
183
  Humans can use `/subagents-doctor` for the same read-only report. It checks runtime paths, discovery counts, async support, current session context, and intercom bridge state.
220
184
 
@@ -315,8 +279,40 @@ subagent({
315
279
  })
316
280
  ```
317
281
 
318
- Tool calls launch directly by default. Set `clarify: true` on single, parallel, or chain runs when you want the clarify UI. Clarify edits affect only the next run; use management actions, settings, or markdown files for persistent changes.
319
- For programmatic background launches, use `async: true`. `clarify: true` keeps the run foreground for the clarify UI.
282
+ Ordinary tool calls launch in the background by default. Set `async: false` when the current turn needs a foreground result, or `clarify: true` when you want the clarify UI; clarify always stays foreground. Clarify edits affect only the next run; use management actions, settings, or markdown files for persistent changes.
283
+
284
+ ## Missions and cross-project routing
285
+
286
+ Missions are the durable orchestration layer. Use this noun map:
287
+
288
+ - **Project/codebase** — where work happens.
289
+ - **Mission** — why delegated work exists and how to recover it later.
290
+ - **Run** — one actual subagent execution.
291
+ - **Receipt** — proof or a link for an external outcome, such as a PR, CI check, deployment, or release.
292
+
293
+ Ordinary launches with a task create a mission by default, so substantial delegated work has a persisted goal, status, run links, decisions, artifacts, and delivery receipts that survive compaction or a new parent chat. Automatic persistence failures leave the run intact and set `details.missionWarning`; explicit `missionId` or `mission` remains strict before launch. Human receipts end with a mission id/status line, while structured JSON text remains untouched and `details.missionId` is authoritative. Pass `missionId` to attach an existing mission, use `mission: { title, goal?, labels? }` to control the auto-created record, pass `mission: false` for intentionally ephemeral work, or set `missions.enabled: false` to opt out globally.
294
+
295
+ Use `mission.update` while work runs to record decisions, artifacts, labels, summaries, or delivery receipts. A receipt records a pull request, CI, deployment, or release link with a concise status; it does not authorize or automate merge, CI polling, or deployment. Record open product, architecture, or safety decisions there and escalate them upward; do not let a child decide silently. Use `mission.attach-run` only for runs launched outside the normal mission-backed path, and use `mission.close` with a terminal status and concise summary when the mission is done.
296
+
297
+ After compaction, restart, or confusing history, recover from durable state first: `mission.list` in the project, `mission.list` with `missionScope: "global"` for the user-local cross-project pointer index, then `mission.show` for the relevant mission. `mission.show` refreshes linked async status when available and returns warnings instead of hiding the mission if a linked status file is temporarily unreadable. Use the linked run ids with normal `status`, `steer`, `resume`, or `stop` actions. Project mission JSON remains authoritative over chat history.
298
+
299
+ Routing rule:
300
+ - Same project: ordinary mission-backed subagents.
301
+ - Different project, small/bounded task: ordinary subagent with explicit `cwd`.
302
+ - Different project, substantial or long-running work: open a project-owned Herdr pane rooted there, then give that project Pi session a narrow mission/result contract. Do not model it as ordinary child nesting, and do not expect existing headless runs to move into the pane.
303
+
304
+ Project panes run a separate Pi session from the target directory. Subagents launched inside that pane use that project's config, agents, skills, files, git state, and mission records. The pane binding lives under `<projectRoot>/.pi-subagents/project-panes/herdr.json`.
305
+
306
+ ```typescript
307
+ subagent({ action: "mission.create", mission: { title: "Ship auth refresh", goal: "Implement and validate refresh handling" } })
308
+ subagent({ agent: "worker", task: "Implement the approved plan", missionId: "<mission-id>" })
309
+ subagent({ agent: "scout", task: "Quickly answer whether this file exists", mission: false })
310
+ subagent({ action: "mission.list", missionScope: "global" })
311
+ subagent({ action: "project.open", cwd: "/path/to/other-repo", message: "Own this mission for the project and report back with receipts." })
312
+ subagent({ action: "project.status", cwd: "/path/to/other-repo" })
313
+ subagent({ action: "project.close", cwd: "/path/to/other-repo" })
314
+ subagent({ action: "mission.close", missionId: "<mission-id>", missionStatus: "completed", summary: "Auth refresh shipped and tests pass." })
315
+ ```
320
316
 
321
317
  ## Worktree Isolation
322
318
 
@@ -325,25 +321,30 @@ them share one filesystem view.
325
321
 
326
322
  ```typescript
327
323
  subagent({
328
- tasks: [
329
- { agent: "worker", task: "Implement feature A" },
330
- { agent: "worker", task: "Implement feature B" }
331
- ],
332
- worktree: true
324
+ workflowScript: `
325
+ const results = await runs.all([
326
+ { key: "feature-a", agent: "worker", task: "Implement feature A", worktree: true },
327
+ { key: "feature-b", agent: "worker", task: "Implement feature B", worktree: true }
328
+ ]);
329
+ return results.map(({ key, artifactPaths }) => ({ key, artifactPaths }));
330
+ `
333
331
  })
334
332
  ```
335
333
 
336
- `worktree: true` gives each parallel task its own git worktree branched from
337
- HEAD. This requires a clean git state and is mainly for intentionally parallel
338
- write workflows. On completion, use the versioned aggregate handoff at
339
- `parallelHandoff.path` from foreground details or async status/results instead of scraping the combined
340
- text. Its versioned manifest records child status and output references, full
334
+ `worktree: true` on a `runs.run` / `runs.all` item gives that child its own git
335
+ worktree branched from HEAD. A top-level workflow `worktree: true` makes this the
336
+ default for every child, and a child can opt out with `worktree: false`. This
337
+ requires a clean git state and is mainly for intentionally parallel write
338
+ workflows. On completion, use each child's handoff path from its
339
+ `artifactPaths` instead of scraping combined text. Each manifest records child status and output references, full
341
340
  patch paths and stats, and whether each temporary worktree and branch was
342
- removed. If you want one writer thread and several advisory agents, prefer a
341
+ removed. The manifest is journaled immediately after managed worktree setup, before children run, so abrupt exits retain owned paths and branches for recovery. Dirty or divergent work without a successfully captured patch is preserved with a partial-cleanup warning. Permanently discard recorded preserved work with `subagent({ action: "worktree.discard", handoffPath: "<child handoff path>" })`; authority defaults to interactive confirmation and refuses headlessly, and partial results print manual Git recovery commands. If you want one writer thread and several advisory agents, prefer a
343
342
  single-writer pattern instead.
344
343
 
345
344
  Git worktrees start from tracked files, so ignored or untracked build state
346
- such as `node_modules` may be absent. `pi-subagents` attempts to symlink the
345
+ such as `node_modules` may be absent. The clean-check ignores pi-subagents'
346
+ own `.pi-subagents/` runtime state, including default mission records, but still
347
+ rejects ordinary source/config changes. `pi-subagents` attempts to symlink the
347
348
  root checkout's `node_modules` into each managed worktree when it exists, but
348
349
  agents should still treat dependency setup as an explicit bootstrap step before
349
350
  running tests, typecheck, or builds. If module resolution fails in a fresh
@@ -135,10 +135,10 @@ fixes worth doing now. Parent agents can also apply the same recipes directly
135
135
  with `subagent(...)` when the user describes the workflow in natural language
136
136
  instead of invoking a slash command.
137
137
 
138
- Additional user prompt templates can delegate into `pi-subagents` through the native `/prompt-workflow` and `/chain-prompts` commands. This is useful when a slash command should always run through a particular agent or with forked context. Prompt frontmatter can set `subagent`, `model`, `skill`, `cwd`, `worktree`, `fresh`, `fork`, or `inheritContext` for the native adapter.
138
+ Additional user prompt templates can delegate into `pi-subagents` through the native `/prompt-workflow` command. This is useful when a slash command should always run through a particular agent or with forked context. Prompt frontmatter can set `subagent`, `model`, `skill`, `cwd`, `fresh`, `fork`, or `inheritContext` for the native adapter.
139
139
 
140
140
  ## Extension RPC
141
141
 
142
- Other Pi extensions can call `pi-subagents` through the in-process event bus. The stable v1 channels are `subagents:rpc:v1:ready`, `subagents:rpc:v1:request`, and per-request replies at `subagents:rpc:v1:reply:<requestId>`. Envelopes use `{ version: 1, requestId, method, params }`, and replies use `{ version: 1, requestId, success, data | error }`. `ping` advertises the exact process-local async completion event as `events.asyncComplete` for RPC-spawn consumers.
142
+ Other Pi extensions can call `pi-subagents` through the in-process event bus. The RPC channels are `subagents:rpc:v1:ready`, `subagents:rpc:v1:request`, and per-request replies at `subagents:rpc:v1:reply:<requestId>`. Envelopes use `{ version: 1, requestId, method, params }`, and replies use `{ version: 1, requestId, success, data | error }`. `ping` advertises the exact process-local async completion event as `events.asyncComplete` for RPC-spawn consumers.
143
143
 
144
144
  Methods: `ping`, `status`, `spawn`, `steer`, `interrupt`, `resume`, and `stop`. `ping` capability metadata advertises optional projections: `capabilities.fleetStatus: { version: 1 }` adds bounded current-session `data.fleet` records (opaque reconciliation `key`, resolved `agent`, optional `role`, `model`, `effort`, caller-facing `goal`, `startedAt`, split `{ input, output, total }` tokens, plus `totalActive`/`omitted` overflow counts) to successful `status` replies; `capabilities.launchResolvedExtensions` advertises parent-resolved opaque launch-extension identifiers in status details; `capabilities.runtimeAcknowledgedExtensions` advertises the best-effort child-runtime acknowledgement projection fed by cooperating extensions emitting `subagent:acknowledge-extension`. Foreground `details.results[]` rows carry a stable numeric `index`; correlate children by `(runId, index)` rather than row position. Consumers should read status/result artifacts and RPC projections instead of scraping terminal output and must ignore unknown fields. `spawn` is async-only and rejects management actions, `async: false`, or `clarify: true`; it reuses the normal executor, so discovery, validation, session attribution, configured spawn caps, child-safety depth, artifacts, and async status are shared with the `subagent` tool. `status`, acknowledged async `steer`, and `interrupt` map to the normal control actions. RPC steer disables pause-and-revive recovery and advertises `capabilities.nonRecoveringSteer`, preserving the caller's authority over the exact spawned child. `resume` requires a target plus non-empty message and delegates to the package-owned revival path; it may set a caller-owned `file-only` output path but cannot override the persisted child model, tools, budgets, session ownership, or exclusive session lease. `stop` targets running async runs through the existing timeout control channel. `pi.events` is process-local, so separate Pi processes and child subagents need lifecycle artifact files or `pi-intercom` instead.