@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -4,7 +4,7 @@ Parameters and actions for the `subagent` tool. These are what the LLM passes wh
4
4
 
5
5
  In a fresh parent session, `subagents_enable({})` makes the full `subagent` tool available on the immediately following model request without launching work. Pi may call it when delegation is authorized by the current request or applicable instructions, or to manage existing runs. Direct execution remains the default; task complexity does not grant delegation authority. The public `subagent` name and parameters are unchanged after activation.
6
6
 
7
- Call `{ action: "guide", topic: "tool-reference" }` for this reference or `topic: "workflows"` for [workflow recipes](workflows.md). Use `topic: "agents"` for authoring, `topic: "missions"` for missions/schedules, and `topic: "watchdog"` for watchdog controls. Guide reads do not change the schema or grant authority.
7
+ Call `{ action: "guide", options: { topic: "tool-reference" } }` for this reference or `options: { topic: "workflows" }` for [workflow recipes](workflows.md). Use `topic: "agents"` for authoring, `topic: "missions"` for missions/schedules, and `topic: "watchdog"` for watchdog controls, always inside `options`. Guide reads do not change the schema or grant authority.
8
8
 
9
9
  ## Execution examples
10
10
 
@@ -30,7 +30,7 @@ The host resolves the script and authority internally and records bounded proven
30
30
  ```js
31
31
  { workflow: "./workflows/review.js", args: { target: "src/workflows" }, cwd: "/path/to/project" }
32
32
  { action: "validate", workflow: "./workflows/review.js", args: { target: "src/workflows" } }
33
- { action: "schedule.create", every: "6h", workflow: "./workflows/review.js", args: { target: "src/workflows" } }
33
+ { action: "schedule.create", workflow: "./workflows/review.js", args: { target: "src/workflows" }, options: { every: "6h" } }
34
34
  ```
35
35
 
36
36
  Each script below is the ```` ```js workflow ```` block of a reply that then calls `subagent({ workflow: true })`:
@@ -67,49 +67,59 @@ The complete plain-JSON inventory is validated before the first launch (maximum
67
67
 
68
68
  ## Parameter reference
69
69
 
70
+ The `subagent` tool schema lists `agent`, `task`, `workflow`, `args`, `async`, `model`, `cwd`, `worktree`, `output`, `action`, `id` and `message` at the top level and every other field inside `options`, for example `subagent({ action: "status", id: "<run-id>", options: { view: "transcript" } })`. Management fields and the `runId`, `maxRuntimeMs` and `isolation` aliases also keep working at the top level, as in RPC payloads, slash commands, schedules and workflow `runs.run`/`runs.all` items; a field given in both places with different values is rejected.
71
+
72
+ ### Target and management parameters
73
+
70
74
  | Param | Type | Default | Description |
71
75
  |-------|------|---------|-------------|
76
+ | `options` | object | - | Management and control fields; the rows named `options.<name>` below go here. Unknown keys are rejected with the closest valid option. The same fields are also accepted at the top level. |
72
77
  | `agent` | string | - | One direct child or agent-management target. Workflow child agents are set inside `runs.run` or `runs.all`. |
73
78
  | `task` | string | agent default | Direct child's task; requires `agent`, excludes `action` and workflow inputs. `agent` may also select a management target. |
74
- | `action` | string | - | Offline workflow `validate`, agent management (including `guide`, `children.list`, and `refine`/`refine.show`/`refine.rollback`), lane evidence (`lane.status`, `lane.recordMerge`, `lane.recordSupersession`), mission (`mission.create/list/show/update/resolve-decision/attach-run/close`), Inspect actions (`inspector.command/open/status/close`), Herdr project pane (`project.open/status/close`), status/control, plan-only `worktree.cleanup`, schedule, watchdog, or doctor action. |
75
- | `topic` | `overview \| workflows \| agents \| missions \| observability \| tool-reference \| configuration \| models \| watchdog \| extension-api \| council` | `overview` | Packaged guide topic for `action: "guide"`. |
76
- | `config` | object/string | - | Agent config for management create/update. |
77
- | `context` | `fresh \| fork \| profile` | global or per-agent default, else `fresh` | Explicit `fresh` or `fork` overrides every workflow child. `profile` requires the selected agent's declared `defaultContext` and ignores config `defaultSubagentContext`; missing agent defaults fail. When omitted, [`defaultSubagentContext`](configuration.md#defaultsubagentcontext) wins over each agent's `defaultContext`; implicit fork falls back to fresh without a persisted parent session and leaf. Explicit fork is strict. Packaged `worker` defaults to `fresh`; packaged `oracle` and `advisor` default to `fork`. |
78
- | `model` | string | agent default | Call `{action:"models"}` first and copy an exact `provider/id`; bare ids resolve only if unique, and agent names are not model ids. A suffix such as `provider/id:high` (`off/minimal/low/medium/high/xhigh/max`) overrides agent thinking. The `thinking` field is only for `watchdog.configure`, ignored on dispatch. |
79
- | `missionId` | string | - | Attach a workflow to an existing project mission instead of creating its default enclosing mission. |
80
- | `mission` | object/false | auto-create | Override the default enclosing mission with `{ title \| summary, objective?, goal?, budget?, labels? }`. Set exactly one non-empty `title` or `summary`; `objective` and `labels` are optional. `goal` may only be `true`, requires `budget.tokens`, and enables continuation notices. Pass `false` for an intentionally ephemeral workflow with no mission for it or its children and no `state` global. Explicit mission persistence failures are strict. |
81
- | `handoffPath` | string | - | Aggregate handoff manifest for `action: "worktree.discard"` or lane evidence actions, or optional explicit metadata for `action: "worktree.cleanup"`. |
82
- | `repo` | string | runtime cwd | Repository path for `action: "worktree.cleanup"`; plan mode only. The configured worktree base filters candidates by their per-project folder under it but never discovers them. |
83
- | `planId` | string | - | Reserved for a future `worktree.cleanup` apply action; rejected by the current plan-only action. |
84
- | `mode` | `steer \| follow_up \| auto \| plan \| apply` | - | Delivery mode for `action: "steer"`; `worktree.cleanup` currently accepts `plan` only. Apply/removal is reserved for a later change. |
85
- | `laneId` | string | - | Exact `runId` stored in the handoff manifest for `lane.status`, `lane.recordMerge`, or `lane.recordSupersession`. |
86
- | `merge` | object | - | Attested merge evidence for `lane.recordMerge`; requires a positive PR number, full reviewed/merge SHAs, tree-equivalence and post-merge-check statuses, attestor, and timestamp. |
87
- | `supersession` | object | - | Attested replacement-lane evidence for `lane.recordSupersession`; requires a different replacement lane id, attestor, and timestamp. |
88
- | `focus` | boolean | false | Focus the newly split host inspector pane for `action: "inspector.open"` or the new Herdr project pane for `action: "project.open"`; not a standalone action. `inspector.command` is read-only and does not contact Herdr or write a binding. Panes open in the background unless you set `focus: true`. Existing saved project panes can be focused through the public project-pane API when Herdr reports a tab or workspace id. |
89
- | `view` | `fleet \| transcript` | - | Optional `status` view for the active fleet surface or transcript tail inspection. |
90
- | `lines` | number | `80` | Maximum transcript lines for `action: "status", view: "transcript"`; capped at 500. |
91
- | `agentScope` | `user \| project \| both` | `both` | Agent discovery scope. Project wins on collisions. |
92
- | `capabilities` | boolean | `false` | With `action: "list"`, return compact prompt-free rows and `details.agentCapabilities` machine-readable records for each agent's declared/default routing capabilities. External CLI rows also include their command and passive local availability. |
79
+ | `action` | string | - | Offline workflow `validate`, agent management (including `guide`, `children.list`, and `refine`/`refine.show`/`refine.rollback`), lane evidence (`lane.status`, `lane.recordMerge`, `lane.recordSupersession`), mission (`mission.create/list/show/update/resolve-decision/attach-run/close`), Inspect actions (`inspector.command/open/status/close`), Herdr project pane (`project.open/status/close`), status/control, reviewed `worktree.cleanup`, schedule, watchdog, or doctor action. |
80
+ | `options.topic` | `overview \| workflows \| agents \| missions \| observability \| tool-reference \| configuration \| models \| watchdog \| extension-api \| council`, or `<topic>/<section>` | `overview` | Packaged guide topic for `action: "guide"`. A docs topic returns its table of contents; `<topic>/<section>` returns one section. |
81
+ | `options.config` | object/string | - | Agent config for management create/update. |
82
+ | `options.context` | `fresh \| fork \| profile` | global or per-agent default, else `fresh` | Explicit `fresh` or `fork` overrides every workflow child. `profile` requires the selected agent's declared `defaultContext` and ignores config `defaultSubagentContext`; missing agent defaults fail. When omitted, [`defaultSubagentContext`](configuration.md#defaultsubagentcontext) wins over each agent's `defaultContext`; implicit fork falls back to fresh without a persisted parent session and leaf. Explicit fork is strict. Packaged `worker` defaults to `fresh`; packaged `oracle` and `advisor` default to `fork`. |
83
+ | `model` | string | agent default | An exact `provider/id`; bare ids resolve only if unique, and agent names are not model ids. An unknown or ambiguous model fails with up to 5 closest registry ids to copy; `{action:"models"}` lists them all. A suffix such as `provider/id:high` (`off/minimal/low/medium/high/xhigh/max`) overrides agent thinking. The `thinking` field is only for `watchdog.configure`, ignored on dispatch. On the `claude-code` and `claude-code-writer` adapters the model is Claude Code's own alias or id, and the same suffix becomes its `--effort`, bounded by `subagents.maxThinking` and by an enforced `subagents.modelScope`. |
84
+ | `options.missionId` | string | - | Attach a workflow, including each fire of `schedule.create`, to an existing project mission. Scheduled attachment uses ordinary lifecycle and retention rules. |
85
+ | `options.mission` | object/false | auto-create | Override the default enclosing mission with `{ title \| summary, objective?, goal?, budget?, labels? }`. Set exactly one non-empty `title` or `summary`; `objective` and `labels` are optional. `goal` may only be `true`, requires `budget.tokens`, and enables continuation notices. Pass `false` for an intentionally ephemeral workflow with no mission for it or its children and no `state` global. Explicit mission persistence failures are strict. |
86
+ | `options.handoffPath` | string | - | Aggregate handoff manifest for `action: "worktree.discard"` or lane evidence actions, or optional explicit metadata for `action: "worktree.cleanup"`. |
87
+ | `options.repo` | string | runtime cwd | Repository path for `action: "worktree.cleanup"`; required explicitly for apply. The configured worktree base filters candidates by their per-project folder under it but never discovers them. |
88
+ | `options.planId` | string | - | Saved, reviewed cleanup plan ID; required for apply, rejected in plan mode. |
89
+ | `options.mode` | `steer \| follow_up \| auto \| plan \| apply` | - | Delivery mode for `action: "steer"`; `worktree.cleanup` accepts `plan` or `apply`; apply requires an explicit repository and saved plan ID. |
90
+ | `options.laneId` | string | - | Exact `runId` stored in the handoff manifest for `lane.status`, `lane.recordMerge`, or `lane.recordSupersession`. |
91
+ | `options.merge` | object | - | Attested merge evidence for `lane.recordMerge`; requires a positive PR number, full reviewed/merge SHAs, tree-equivalence and post-merge-check statuses, attestor, and timestamp. |
92
+ | `options.supersession` | object | - | Attested replacement-lane evidence for `lane.recordSupersession`; requires a different replacement lane id, attestor, and timestamp. |
93
+ | `options.focus` | boolean | false | Focus the newly split host inspector pane for `action: "inspector.open"` or the new Herdr project pane for `action: "project.open"`; not a standalone action. `inspector.command` is read-only and does not contact Herdr or write a binding. Panes open in the background unless you set `focus: true`. Existing saved project panes can be focused through the public project-pane API when Herdr reports a tab or workspace id. |
94
+ | `options.view` | `fleet \| transcript` | - | Optional `status` view for the active fleet surface or transcript tail inspection. |
95
+ | `options.lines` | number | `80` | Maximum transcript lines for `action: "status"` with `options.view: "transcript"`; capped at 500. |
96
+ | `options.agentScope` | `user \| project \| both` | `both` | Agent discovery scope. Project wins on collisions. |
97
+ | `options.capabilities` | boolean | `false` | With `action: "list"`, return compact prompt-free rows and `details.agentCapabilities` machine-readable records for each agent's declared/default routing capabilities. External CLI rows also include their command and passive local availability. |
98
+
99
+ ### Execution parameters
100
+
101
+ | Param | Type | Default | Description |
102
+ |-------|------|---------|-------------|
93
103
  | `async` | boolean | default-on | Background execution. Workflows default to background. `async:false` blocks the parent until completion. A local foreground child runs inside the parent Pi process and never loads the parent's ambient extensions, but it does inherit the providers those extensions registered. A pane-native remote foreground child instead uses the remote machine's provider discovery and configuration. Agents that need MCP tools (`mcpDirectTools`, or MCP tools from an ambient adapter such as pi-mcp-adapter) must run as background children, which load them inside the detached runner process. |
94
- | `chatProgress` | `auto \| off \| live-card` | `auto` | Workflow chat projection. `auto` renders a live in-chat card only for watched foreground workflows in the same Git repository, including managed worktrees; it is off otherwise. Explicit `live-card` requires `async:false` and the same Git repository. Async workflows have no inline live card, so omit `chatProgress` or use `auto`/`off`; use `async:false` only when the parent must block. |
95
- | `isolation` | `none \| worktree` | - | Workflow child isolation. `none` runs in the shared cwd and does not need Git. `worktree` requires a managed Git worktree. Do not combine it with a contradictory `worktree` value. |
96
- | `baseRef` | string | `HEAD` | `HEAD` or a supported named ref such as `refs/heads/release`, `refs/tags/v1`, or `origin/main`. Full 40/64-character commit IDs and revision expressions such as `HEAD~1` are unsupported. The ref must resolve to a commit at worktree allocation; omitted values default to `HEAD` resolved at that time. Source-checkout cleanliness is still checked. For a workflow script, set it on the outer request as a default or on an individual `runs.run`/`runs.all` child to override it. |
97
- | `timeoutMs` / `maxRuntimeMs` | number | config `timeoutMs`, else 30 min foreground / single-agent async | Optional run-level max runtime in milliseconds. Both aliases may be supplied only when their values agree. When omitted, the global [`timeoutMs`](configuration.md#timeoutms) config provides the default; absent that, foreground and plain single-agent async runs fall back to 30 minutes, while composite async runs (chains, parallel tasks, workflows) stay unbounded at the top level. Expiration of this run-level deadline is terminal. |
98
- | `toolTimeoutMs` | number | fast-tool default | Optional positive hard per-tool-call deadline in milliseconds. Precedence: call value → agent frontmatter → config → `PI_SUBAGENT_TOOL_TIMEOUT_MS`. The timer starts on `tool_execution_start`, clears on the matching `tool_execution_end`, and terminates the run with `timedOut: true` if the tool remains open. When omitted, known-fast built-in tools get a five-minute default; long-running tools get attention notices but no hard default. It never extends the run deadline; `contact_supervisor`, `intercom`, and `bg_wait` are exempt. |
99
- | `checkpointBeforeDeadlineMs` | number | none | Async single-agent runs only. The runner requests that the child "checkpoint and stop" this many milliseconds before the run deadline (finish the current tool call, report changed files, build/test state, remaining work, commit/PR state; start no new work). This best-effort steer uses the normal steering lifecycle at the next tool boundary, so the receipt is visible in status and events; the ordinary deadline kill still applies. Precedence: call value → config `checkpointBeforeDeadlineMs`. Disarmed when the deadline leaves under one second before the checkpoint. |
100
- | `toolBudget` | object | none | Optional child tool-call budget `{ soft?, hard, block? }`: `hard` is a positive integer and `soft`, if set, is a positive integer no greater than `hard`. At `soft` the child is nudged to finalize. After `hard`, configured tools are blocked; `block` defaults to `read`, `grep`, `find`, and `ls`, and accepts either a nonempty array of tool names or `"*"` for every tool call. Final assistant text is never blocked. |
101
- | `usageBudget` | object | none | Optional root-only reported-usage budget `{ tokens?: { soft?, hard }, costUsd?: { soft?, hard } }`. Include at least one metric; each `hard` must be positive and each optional `soft` positive and no greater than its `hard`. Soft limits are status-only. Hard limits prevent later child launches after reported usage is reconciled; already-running children are not stopped and no reservations are made. |
102
- | `extensionBindings` | object | none | Child-only plain JSON keyed by namespaces like `package.name/1` (positive version): at most 16 namespaces, nesting depth 16, 256 total object properties, and 16 KiB of canonical UTF-8 JSON. Native Pi launches only; external runners and retained resumes reject it. |
103
- | `preflight` | object | none | Advisory lane hints for raw scripts (`workflow: true` or a script path) only; not accepted with named workflows or direct children. See [bounded workflows](workflows.md#opt-in-bounded-workflows). |
104
+ | `options.chatProgress` | `auto \| off \| live-card` | `auto` | Workflow chat projection. `auto` renders a live in-chat card only for watched foreground workflows in the same Git repository, including managed worktrees; it is off otherwise. Explicit `live-card` requires `async:false` and the same Git repository. Async workflows have no inline live card, so omit `chatProgress` or use `auto`/`off`; use `async:false` only when the parent must block. |
105
+ | `isolation` | `none \| worktree` | - | Alias kept at the top level; prefer `worktree`. Workflow child isolation. `none` runs in the shared cwd and does not need Git. `worktree` requires a managed Git worktree. Do not combine it with a contradictory `worktree` value. |
106
+ | `options.baseRef` | string | `HEAD` | `HEAD` or a supported named ref such as `refs/heads/release`, `refs/tags/v1`, or `origin/main`. Full 40/64-character commit IDs and revision expressions such as `HEAD~1` are unsupported. The ref must resolve to a commit at worktree allocation; omitted values default to `HEAD` resolved at that time. Source-checkout cleanliness is still checked. For a workflow script, set it on the outer request as a default or on an individual `runs.run`/`runs.all` child to override it. |
107
+ | `options.timeoutMs` | number | config `timeoutMs`, else 30 min foreground / single-agent async | Optional run-level max runtime in milliseconds. The top-level alias `maxRuntimeMs` is also accepted; both must agree. When omitted, the global [`timeoutMs`](configuration.md#timeoutms) config provides the default; absent that, foreground and plain single-agent async runs fall back to 30 minutes, while composite async runs (chains, parallel tasks, workflows) stay unbounded at the top level. Expiration of this run-level deadline is terminal. |
108
+ | `options.toolTimeoutMs` | number | fast-tool default | Optional positive hard per-tool-call deadline in milliseconds. Precedence: call value → agent frontmatter → config → `PI_SUBAGENT_TOOL_TIMEOUT_MS`. The timer starts on `tool_execution_start`, clears on the matching `tool_execution_end`, and terminates the run with `timedOut: true` if the tool remains open. When omitted, known-fast built-in tools get a five-minute default; long-running tools get attention notices but no hard default. It never extends the run deadline; `contact_supervisor`, `intercom`, and `bg_wait` are exempt. |
109
+ | `options.checkpointBeforeDeadlineMs` | number | none | Async single-agent runs only. The runner requests that the child "checkpoint and stop" this many milliseconds before the run deadline (finish the current tool call, report changed files, build/test state, remaining work, commit/PR state; start no new work). This best-effort steer uses the normal steering lifecycle at the next tool boundary, so the receipt is visible in status and events; the ordinary deadline kill still applies. Precedence: call value → config `checkpointBeforeDeadlineMs`. Disarmed when the deadline leaves under one second before the checkpoint. |
110
+ | `options.toolBudget` | object | none | Optional child tool-call budget `{ soft?, hard, block? }`: `hard` is a positive integer and `soft`, if set, is a positive integer no greater than `hard`. At `soft` the child is nudged to finalize. After `hard`, configured tools are blocked; `block` defaults to `read`, `grep`, `find`, and `ls`, and accepts either a nonempty array of tool names or `"*"` for every tool call. Final assistant text is never blocked. |
111
+ | `options.usageBudget` | object | none | Optional root-only reported-usage budget `{ tokens?: { soft?, hard }, costUsd?: { soft?, hard } }`. Include at least one metric; each `hard` must be positive and each optional `soft` positive and no greater than its `hard`. Soft limits are status-only. Hard limits prevent later child launches after reported usage is reconciled; already-running children are not stopped and no reservations are made. |
112
+ | `options.extensionBindings` | object | none | Child-only plain JSON keyed by namespaces like `package.name/1` (positive version): at most 16 namespaces, nesting depth 16, 256 total object properties, and 16 KiB of canonical UTF-8 JSON. Native Pi launches only; external runners and retained resumes reject it. |
113
+ | `options.preflight` | object | none | Advisory lane hints for raw scripts (`workflow: true` or a script path) only; not accepted with named workflows or direct children. See [bounded workflows](workflows.md#opt-in-bounded-workflows). |
104
114
  | `cwd` | string | runtime cwd | Override working directory. With `machine`, the directory on that machine. |
105
- | `machine` | string | - | Herdr saved machine (label or profile id) for external-cli agents; see [agents.md](agents.md#running-external-cli-agents-on-a-herdr-saved-machine). |
106
- | `maxOutput` | object | none | Final output truncation limits `{ bytes?, lines? }`. For child runs it is only applied when set; there is no default cap on the inline path, so use `outputMode: "file-only"` for large outputs. For workflow script results, the Return, Emitted, and Console sections are always capped, at 200 KB / 5000 lines unless `maxOutput` sets other limits. |
107
- | `artifacts` | boolean | true | Write debug artifacts. |
108
- | `includeProgress` | boolean | false | Include full progress in result. |
109
- | `share` | boolean | false | Upload session export to GitHub Gist. |
110
- | `sessionDir` | string | derived | Override session log directory. |
111
- | `acceptance` | string/object/false | inferred | Configure evidence gates. See [Acceptance gates](#acceptance-gates). |
112
- | `gate` | string \| object | - | One host-run verification command, shorthand for `acceptance: { level: "verified", verify: [{ id: "gate", command }] }`. The object form `{ command, output?: "json", schema?, timeoutMs? }` adds a [typed gate](#typed-gates): with `output: "json"`, a passing command's stdout becomes the child's `structuredOutput`. Also valid on individual `runs.run`/`runs.all` items. Rejects `acceptance` except `false` (treated as omitted), rejects retained `resume`, and `output: "json"` rejects `outputSchema`. |
115
+ | `options.machine` | string | - | Herdr saved machine (label or profile id) for external-cli agents; see [agents.md](agents.md#running-external-cli-agents-on-a-herdr-saved-machine). |
116
+ | `options.maxOutput` | object | none | Final output truncation limits `{ bytes?, lines? }`. For child runs it is only applied when set; there is no default cap on the inline path, so use `outputMode: "file-only"` for large outputs. For workflow script results, the Return, Emitted, and Console sections are always capped, at 200 KB / 5000 lines unless `maxOutput` sets other limits. |
117
+ | `options.artifacts` | boolean | true | Write debug artifacts. |
118
+ | `options.includeProgress` | boolean | false | Include full progress in result. |
119
+ | `options.share` | boolean | false | Upload session export to GitHub Gist. |
120
+ | `options.sessionDir` | string | derived | Override session log directory. |
121
+ | `options.acceptance` | string/object/false | inferred | Configure evidence gates. See [Acceptance gates](#acceptance-gates). |
122
+ | `options.gate` | string \| object | - | One host-run verification command, shorthand for `acceptance: { level: "verified", verify: [{ id: "gate", command }] }`. The object form `{ command, output?: "json", schema?, timeoutMs? }` adds a [typed gate](#typed-gates): with `output: "json"`, a passing command's stdout becomes the child's `structuredOutput`. Also valid on individual `runs.run`/`runs.all` items. Rejects `acceptance` except `false` (treated as omitted), rejects retained `resume`, and `output: "json"` rejects `outputSchema`. |
113
123
 
114
124
  ### Budget guidance for writers
115
125
 
@@ -150,7 +160,7 @@ return { first: first.key, rest: rest.map((child) => child.key), receipt };
150
160
 
151
161
  Use `outputMode: "file-only"` when a saved output may be large and the parent only needs a pointer. The returned text is a compact reference like `Output saved to: /abs/report.md (48.2 KB, 2847 lines). Read this file if needed.` Failed runs and save errors still return normal inline output for debugging.
152
162
 
153
- In a workflow script, give each child an explicit output path when later script steps need a durable file reference. A child with only read-only tools does not need direct filesystem access for `output`: it returns the complete artifact in its final response and the runtime persists it. Children with mutation-capable tools retain the direct-write instruction.
163
+ In a workflow script, give each child an explicit output path when later script steps need a durable file reference. A child with only read-only tools does not need direct filesystem access for `output`: it returns the complete artifact in its final response and the runtime persists it. Children with mutation-capable tools retain the direct-write instruction. With `outputSchema`, the runtime persists the structured result as indented JSON instead of the final prose, unless the child wrote the file itself.
154
164
 
155
165
  The `output` field is the API binding; a filename mentioned in task text (for example, `Write your findings to exactly this path: report.md`) is only instruction and does not override runtime routing. When a later workflow step or parent needs a durable file, set `output` on `runs.run`/`runs.all` and return the child’s `outputReference`, `outputPathMapping`, or `artifactPaths`; arbitrary literal strings returned by workflow JavaScript are not rewritten. Omitted child output may use a managed aggregate-derived sibling path.
156
166
 
@@ -181,20 +191,20 @@ For a simple implementation challenge outside a workflow script, send the challe
181
191
 
182
192
  ### Guide
183
193
 
184
- `{ action: "guide" }` reads the packaged `README.md` from the installed version. Pass `topic` to read its packaged `docs/<topic>.md` file instead; see the `topic` parameter table for valid values. The `council` topic returns the packaged `skills/council-mode/SKILL.md` with the references it asks for, so `/council` works when Pi runs with `--no-skills`. Unknown topics list the valid values and do not change files. Use `/subagents-guide [topic]` for the slash equivalent.
194
+ `{ action: "guide" }` reads the packaged `README.md` from the installed version. Pass a docs topic to get the intro of its packaged `docs/<topic>.md` and a table of section addresses, then pass `topic: "<topic>/<section>"` (for example `"tool-reference/acceptance-gates"`) to read one section. A section runs from its heading to the next heading at the same or a higher level, and no response is longer than 8,000 characters: a larger section returns its intro and its subsection addresses. The `council` topic returns the packaged `skills/council-mode/SKILL.md` with the references it asks for, so `/council` works when Pi runs with `--no-skills`. Unknown topics list the valid values, unknown sections list the topic's table of contents, and neither changes files. Use `/subagents-guide [topic]` for the slash equivalent.
185
195
 
186
196
  Agent definitions are not loaded into context by default. Management actions let the LLM discover, inspect, create, update, and delete agents at runtime. An unknown action returns safe next steps (`status` and `list`) and may suggest a close non-destructive action. Destructive actions are only named for a near-complete one-character typo, and suggestions never execute an action.
187
197
 
188
198
  ```ts
189
199
  { action: "list" }
190
- { action: "list", agentScope: "project" }
191
- { action: "list", capabilities: true }
200
+ { action: "list", options: { agentScope: "project" } }
201
+ { action: "list", options: { capabilities: true } }
192
202
  { action: "get", agent: "scout" }
193
203
  { action: "models" }
194
204
  { action: "models", agent: "reviewer" }
195
205
  { action: "get", agent: "code-analysis.scout" }
196
206
 
197
- { action: "create", config: {
207
+ { action: "create", options: { config: {
198
208
  name: "Code Scout",
199
209
  package: "code-analysis",
200
210
  description: "Scans codebases for patterns and issues",
@@ -214,24 +224,24 @@ Agent definitions are not loaded into context by default. Management actions let
214
224
  output: "context.md",
215
225
  reads: "shared-context.md",
216
226
  progress: true
217
- }}
227
+ }}}
218
228
 
219
229
 
220
- { action: "update", agent: "code-analysis.scout", config: { model: "openai/gpt-4o" } }
221
- { action: "update", agent: "code-analysis.scout", config: { acceptance: "" } } // clear the frontmatter default
222
- { action: "update", agent: "code-analysis.scout", config: { acceptanceRole: false } } // restore default lightweight attestation
230
+ { action: "update", agent: "code-analysis.scout", options: { config: { model: "openai/gpt-4o" } } }
231
+ { action: "update", agent: "code-analysis.scout", options: { config: { acceptance: "" } } } // clear the frontmatter default
232
+ { action: "update", agent: "code-analysis.scout", options: { config: { acceptanceRole: false } } } // restore default lightweight attestation
223
233
  { action: "delete", agent: "scout" }
224
234
 
225
235
  { action: "eject", agent: "reviewer" }
226
- { action: "eject", agent: "reviewer", agentScope: "project" }
236
+ { action: "eject", agent: "reviewer", options: { agentScope: "project" } }
227
237
  { action: "disable", agent: "reviewer" }
228
- { action: "enable", agent: "reviewer", agentScope: "project" }
238
+ { action: "enable", agent: "reviewer", options: { agentScope: "project" } }
229
239
  { action: "reset", agent: "reviewer" }
230
240
  ```
231
241
 
232
242
  Rules:
233
243
 
234
- - `capabilities: true` changes `action: "list"` to compact one-line rows and adds `details.agentCapabilities: { agents, restrictedCount, capabilityCeilingSources? }`. Each agent row includes source, aliases, runner type/capabilities, tools, MCP direct tools, mutation tools, model/thinking, default async/timeout, declared acceptance policy/role, output path/mode, skills/extensions, and whether the current capability ceiling allows execution. External CLI rows include `runner.command`, `runner.available`, and a bounded `runner.unavailableReason` when passive PATH/PATHEXT/X_OK lookup cannot find the command. It never includes an agent's system prompt. Rows show declared/default capabilities and command discoverability, not authentication, version compatibility, or successful launch; launch preflight remains authoritative.
244
+ - `options.capabilities: true` changes `action: "list"` to compact one-line rows and adds `details.agentCapabilities: { agents, restrictedCount, capabilityCeilingSources? }`. Each agent row includes source, aliases, runner type/capabilities, tools, MCP direct tools, mutation tools, model/thinking, default async/timeout, declared acceptance policy/role, output path/mode, skills/extensions, and whether the current capability ceiling allows execution. External CLI rows include `runner.command`, `runner.available`, and a bounded `runner.unavailableReason` when passive PATH/PATHEXT/X_OK lookup cannot find the command. It never includes an agent's system prompt. Rows show declared/default capabilities and command discoverability, not authentication, version compatibility, or successful launch; launch preflight remains authoritative.
235
245
  - `create` uses `config.scope`, not `agentScope`.
236
246
  - `config.name` is the local frontmatter name; optional `config.package` registers the runtime name as `{package}.{name}` and is saved as separate `name` and `package` frontmatter.
237
247
  - `config.aliases` accepts a comma-separated string, string array, or `false` to clear aliases. Aliases resolve to the canonical agent name for execution and are shown by `list`/`get`.
@@ -246,7 +256,7 @@ Rules:
246
256
 
247
257
  ### Schedule controls
248
258
 
249
- Use `schedule.create` with `workflow: true` or a script path, not a direct child. `at` accepts a delay like `+10m` or an ISO timestamp with timezone; `every` accepts fixed intervals. `sessionOnly:true` binds restoration/execution to the creating session file; omitted/false is project-wide. Recurring `quiet:true` keeps successful automatic fires visible without a parent turn; failed, stopped or paused runs still wake the parent. One-shot `at` and manual `schedule.run` stay noisy unless that launch passes `quiet:true`. See [missions and schedules](missions.md#schedules) for examples and list/show/history/pause/resume/run/run-due/delete. Calendar selectors (`on`, `timezone`) and schedule mission attachment are deferred. `baseRef` resolves only at worktree allocation and still requires a clean source checkout.
259
+ Use `schedule.create` with `workflow: true` or a script path, not a direct child. `at` accepts a delay like `+10m` or an ISO timestamp with timezone; `every` accepts fixed intervals or `day`/`week` with `at:"HH:mm"` and an explicit IANA `timezone` (or `UTC`). Weekly `on` is a non-empty array of `mon`–`sun`; daily schedules omit it. Missing local times are skipped; repeated times fire once at their first instant. `sessionOnly:true` binds restoration/execution to the creating session file; omitted/false is project-wide. Recurring `quiet:true` keeps successful automatic fires visible without a parent turn; failed, stopped or paused runs still wake the parent. One-shot `at` and manual `schedule.run` stay noisy unless that launch passes `quiet:true`. An optional `missionId` attaches an existing mission on every fire and exposes its workflow state, using ordinary mission lifecycle and retention rules; `mission.close` does not pause the schedule. See [missions and schedules](missions.md#schedules) for examples and list/show/history/pause/resume/run/run-due/delete. `baseRef` resolves only at worktree allocation and still requires a clean source checkout.
250
260
 
251
261
  ## Lane merge evidence and cleanup eligibility
252
262
 
@@ -255,29 +265,33 @@ Lane evidence actions update an existing parallel handoff manifest at an explici
255
265
  ```ts
256
266
  subagent({
257
267
  action: "lane.recordMerge",
258
- laneId: "<manifest-run-id>",
259
- handoffPath: "/path/to/handoff.json",
260
- merge: {
261
- prNumber: 123,
262
- reviewedHead: "<40-character-sha>",
263
- mergeCommit: "<40-character-sha>",
264
- treeEquivalent: true,
265
- postMergeChecks: "recorded",
266
- attestedBy: "operator",
267
- attestedAt: "2026-08-27T16:23:00.000Z"
268
+ options: {
269
+ laneId: "<manifest-run-id>",
270
+ handoffPath: "/path/to/handoff.json",
271
+ merge: {
272
+ prNumber: 123,
273
+ reviewedHead: "<40-character-sha>",
274
+ mergeCommit: "<40-character-sha>",
275
+ treeEquivalent: true,
276
+ postMergeChecks: "recorded",
277
+ attestedBy: "operator",
278
+ attestedAt: "2026-08-27T16:23:00.000Z"
279
+ }
268
280
  }
269
281
  })
270
282
  subagent({
271
283
  action: "lane.recordSupersession",
272
- laneId: "<manifest-run-id>",
273
- handoffPath: "/path/to/handoff.json",
274
- supersession: {
275
- supersededBy: "<replacement-lane-id>",
276
- attestedBy: "operator",
277
- attestedAt: "2026-08-27T16:23:00.000Z"
284
+ options: {
285
+ laneId: "<manifest-run-id>",
286
+ handoffPath: "/path/to/handoff.json",
287
+ supersession: {
288
+ supersededBy: "<replacement-lane-id>",
289
+ attestedBy: "operator",
290
+ attestedAt: "2026-08-27T16:23:00.000Z"
291
+ }
278
292
  }
279
293
  })
280
- subagent({ action: "lane.status", laneId: "<manifest-run-id>", handoffPath: "/path/to/handoff.json" })
294
+ subagent({ action: "lane.status", options: { laneId: "<manifest-run-id>", handoffPath: "/path/to/handoff.json" } })
281
295
  ```
282
296
 
283
297
  The manifest stores one of these fail-closed eligibility states: `active` (an owning child is still running), `terminal-eligible` (complete merge evidence and recorded post-merge checks), `terminal-blocked` with a reason, `superseded-eligible` (an explicit replacement attestation), or `unknown` (missing or malformed evidence/manifest). Each attestation stores a digest of the manifest facts it covered; later group, worktree, or patch changes downgrade that evidence to `terminal-blocked` until it is recorded again. A terminal update recomputes a previously stored `active` state from the current child statuses and evidence. Conflicting reviewed heads and mismatched lane ids are rejected as stale. Existing workflow receipts remain immutable.
@@ -294,19 +308,19 @@ For backlog lanes and other subagent-governed workflows, external/foreground/CLI
294
308
 
295
309
  ```ts
296
310
  subagent({ action: "status" })
297
- subagent({ action: "status", view: "fleet" })
311
+ subagent({ action: "status", options: { view: "fleet" } })
298
312
  subagent({ action: "status", id: "<run-id>" })
299
- subagent({ action: "status", id: "<run-id>", view: "transcript", index: 0, lines: 80 })
313
+ subagent({ action: "status", id: "<run-id>", options: { view: "transcript", index: 0, lines: 80 } })
300
314
  subagent({ action: "status", id: "<nested-run-id>" })
301
315
  subagent({ action: "interrupt", id: "<run-id>" })
302
316
  subagent({ action: "interrupt", id: "<nested-run-id>" })
303
317
  subagent({ action: "stop", id: "<run-id>" })
304
318
  subagent({ action: "resume", id: "<run-id>", message: "follow-up question after it pauses or finishes" })
305
- subagent({ action: "resume", id: "<run-id>", index: 1, message: "follow-up for child 2" })
319
+ subagent({ action: "resume", id: "<run-id>", message: "follow-up for child 2", options: { index: 1 } })
306
320
  subagent({ action: "resume", id: "<nested-run-id>", message: "follow-up for a nested child" })
307
321
  subagent({ action: "steer", id: "<run-id>", message: "guidance for the running child" })
308
- subagent({ action: "steer", id: "<run-id>", mode: "follow_up", message: "check this after the current turn" })
309
- subagent({ action: "steer", id: "<run-id>", index: 1, mode: "auto", message: "guidance for child 2" })
322
+ subagent({ action: "steer", id: "<run-id>", message: "check this after the current turn", options: { mode: "follow_up" } })
323
+ subagent({ action: "steer", id: "<run-id>", message: "guidance for child 2", options: { index: 1, mode: "auto" } })
310
324
  subagent({ action: "doctor" })
311
325
  ```
312
326
 
@@ -320,6 +334,31 @@ subagent({ action: "doctor" })
320
334
  - Inside child-safe fanout mode, bare `status` requires an id when no local foreground run is active, so children cannot enumerate unrelated top-level async runs.
321
335
  - Bare `interrupt` still targets only the visible top-level run; interrupting a nested run requires its explicit nested id.
322
336
 
337
+ ### Command controls
338
+
339
+ Command controls target direct local native Pi children that explicitly select both `bash` and `subagent_command`, in foreground or async runs. They require the owning parent session, a run `id`, an explicit `index` for multi-child runs, and the exact `toolCallId` for mutations. Nested, external, and custom shell backends do not expose this controller. Custom bash extensions keep their own registered `subagent_command` tool. If a custom bash backend does not provide that tool, an explicitly required `subagent_command` remains available and reports an unsupported-backend error. Native supervisor command controls are unavailable for custom backends.
340
+
341
+ ```ts
342
+ subagent({ action: "command.status", id: "<run-id>", options: { index: 0 } })
343
+ subagent({ action: "command.yield", id: "<run-id>", options: { index: 0, toolCallId: "<call-id>" } })
344
+ subagent({ action: "command.cancel", id: "<run-id>", options: { index: 0, toolCallId: "<call-id>" } })
345
+ subagent({ action: "command.status", id: "<run-id>", options: { index: 0, toolCallId: "<call-id>" } })
346
+ ```
347
+
348
+ `command.yield` releases the selected blocking tool call without restarting the process. `command.cancel` aborts only that command through Pi's native bash cancellation; the child receives a tool error and can continue. `cancel_requested` acknowledges the request, while `cancelled` confirms the backend settled. A stale id never targets a later command. Run-scoped `interrupt` remains separate.
349
+
350
+ Enable command controls by including both `bash` and `subagent_command` in the agent or call's `tools` allowlist. Tool ceilings and `excludeTools` still apply. Without this explicit selection, bash keeps its original tool schema and backend; no command controller, inbox watcher, or command-state writes are added. Inside an enabled child:
351
+
352
+ ```ts
353
+ bash({ command: "npm run dev", yieldTimeMs: 1000 })
354
+ subagent_command({ action: "status", toolCallId: "<returned-call-id>", waitMs: 1000 })
355
+ subagent_command({ action: "cancel", toolCallId: "<returned-call-id>", waitMs: 1000 })
356
+ ```
357
+
358
+ `yieldTimeMs` and `waitMs` range from 0 to 30,000 milliseconds. Omitting `yieldTimeMs` preserves completion-waiting behavior. Yielded handles are not successful exits. Status includes running/yielded/cancel-requested states and completed/failed/cancelled terminal states, a bounded output tail, and Pi's full-output file path when available. Recent terminal history retains 20 commands; active commands remain tracked.
359
+
360
+ Commands remain owned by the child session. Normal completion with unfinished commands cancels them and fails the run. Interrupt, stop, timeout, and disposal clean up owned commands. Controls do not transfer processes out of the child or create detached services. Native bash `timeout` remains command-scoped; `toolTimeoutMs` covers an open tool call and does not become a yielded process deadline.
361
+
323
362
  ### resume
324
363
 
325
364
  `resume` revives a paused, completed, or failed async/foreground child by starting a new child from its stored session file. Stopped runs remain non-resumable, and it does not interrupt a live top-level async child. Use `steer` for acknowledged live async guidance.
@@ -366,15 +405,19 @@ Prefer an inline JSON object. JSON-encoded object strings are tolerated only dur
366
405
  {
367
406
  agent: "worker",
368
407
  task: "Implement the fix",
369
- acceptance: {
370
- level: "verified",
371
- criteria: ["Patch the bug without widening scope"],
372
- evidence: ["changed-files", "tests-added", "commands-run", "residual-risks", "no-staged-files"],
373
- verify: [{ id: "focused", command: "npm test", timeoutMs: 120000 }]
408
+ options: {
409
+ acceptance: {
410
+ level: "verified",
411
+ criteria: ["Patch the bug without widening scope"],
412
+ evidence: ["changed-files", "tests-added", "commands-run", "residual-risks", "no-staged-files"],
413
+ verify: [{ id: "focused", command: "npm test", timeoutMs: 120000 }]
414
+ }
374
415
  }
375
416
  }
376
417
  ```
377
418
 
419
+ A direct tool call passes `acceptance` inside `options`; a workflow `runs.run` item passes it as a plain field.
420
+
378
421
  ### One-command gates
379
422
 
380
423
  When one host-run command is the entire verification contract, use the `gate` shorthand instead of a full `acceptance` object:
@@ -494,7 +537,22 @@ return runs.run("main", { agent: "scout", task: "..." });
494
537
  ```
495
538
 
496
539
  ```js
497
- subagent({ workflow: true, share: true });
540
+ subagent({ workflow: true, options: { share: true } });
498
541
  ```
499
542
 
500
543
  This is disabled by default. Session data may contain source code, paths, environment variables, credentials, or other sensitive output. You need `gh` installed and authenticated.
544
+
545
+ ### Reviewed worktree cleanup
546
+
547
+ `worktree.cleanup` first saves a plan without removing anything:
548
+
549
+ ```ts
550
+ subagent({ action: "worktree.cleanup", options: { repo: "/path/to/repo", mode: "plan" } })
551
+ subagent({ action: "worktree.cleanup", options: { repo: "/path/to/repo", mode: "apply", planId: "<reviewed-plan-id>" } })
552
+ ```
553
+
554
+ Apply uses the existing `authorityPolicy.discardWorktree` (`confirm` by default). It checks the saved plan's repository, hash and 30-minute expiry, then rechecks only reviewed candidates under a repository lock shared with retained resume admission. Only a clean, contained, provably owned terminal worktree with durable evidence can be removed. Dirty or untracked files, ignored files, Git locks, active ownership, recorded native session dependencies, retained resume admission, changed heads and missing artifacts keep the tree. Every local branch is retained; apply never forces removal or prunes unrelated Git metadata.
555
+
556
+ Cleanup also requires the canonical base directory recorded when the worktree was created. Older handoffs without that proof remain kept; planning never infers it from the current location. A path redirected outside its creation directory or an invalid handoff manifest prevents removal. Apply validates the full manifest under its write lock before recording a removal attempt or invoking Git.
557
+
558
+ The plan is claimed once before deletion and records progress in a durable receipt. Repeating a claimed plan displays its receipt without attempting more removals. It can repair a journaled removal's handoff fact only when that directory and Git registration are both gone; a recreated path is retained. After an interruption, inspect the receipt and create a fresh plan for additional work. Cleanup failures leave child outcomes and artifacts intact. `worktree.discard` remains the separate explicitly authorized destructive discard operation.
package/docs/watchdog.md CHANGED
@@ -46,13 +46,15 @@ you ─▶ agent turn ─▶ edits repo ─▶ agent_end ─▶ watchdog review
46
46
  └─ warning: low/medium user entry, or high steered message
47
47
  ```
48
48
 
49
- Collapsed warnings show the title and evidence line. Expanded warnings show evidence, recommended action, importance, category, and source:
49
+ A warning shows as one `[subagent] watchdog concern` or `[subagent] watchdog blocker` line, like every other message pi-subagents shows in the chat. Pi's expand key, or a click on the line, opens it to the summary, evidence, recommended action, importance, category, and source:
50
50
 
51
51
  ```
52
- ● Subagent watchdog Blocker (displayed): Claims tests passed without running them
53
- Evidence: The transcript claims `npm test` passed but no test command appears in the tool log.
54
- Recommended action: Run the focused test before finishing.
55
- Importance: High · Category: Test Gap · Source: main
52
+ [subagent] watchdog blocker
53
+
54
+ Subagent watchdog Blocker (displayed): Claims tests passed without running them
55
+ Evidence: The transcript claims npm test passed but no test command appears in the tool log.
56
+ Recommended action: Run the focused test before finishing.
57
+ Importance: High · Category: Test Gap · Source: main
56
58
  ```
57
59
 
58
60
  When consecutive boundary reviews raise the same warning, the agent is not making progress. After `stalemateRepeats` identical warnings in a row (default 3), the warning is shown as `stalemate`, no continuation is triggered, and the turn ends. Your next prompt resets the count.
@@ -110,7 +112,7 @@ Omit `main.model` to inherit the session model and thinking level. A `main.model
110
112
 
111
113
  The watchdog resolves one reviewer model and makes one review call. Unavailable models fail visibly; rate limits, quota, authentication, provider timeouts, findings, clarification, cancellation, and the overall watchdog deadline never switch models automatically. An inherited model keeps the current session model and thinking level.
112
114
 
113
- Agents can call `subagent({ action: "watchdog.recommend-model" })` and `subagent({ action: "watchdog.configure", model: "recommended", scope: "session" | "user" | "project" })`. They should use `scope: "session"` unless you ask for a lasting default.
115
+ Agents can call `subagent({ action: "watchdog.recommend-model" })` and `subagent({ action: "watchdog.configure", model: "recommended", options: { scope: "session" | "user" | "project" } })`. They should use `options: { scope: "session" }` unless you ask for a lasting default.
114
116
 
115
117
  ## Optional main-session clarification
116
118
 
package/docs/workflows.md CHANGED
@@ -12,6 +12,8 @@ clarify → scout → worker → fresh reviewers → worker
12
12
 
13
13
  Packaged `worker` defaults to fresh context so implementation starts from its assigned brief instead of the parent's unfinished conversation. Packaged `oracle` and `advisor` default to forked context; if the parent has no persisted session file or current leaf yet, that implicit default falls back to `fresh`. Explicit `context`, `context: "profile"`, and global `defaultSubagentContext` still override these profile defaults.
14
14
 
15
+ Launch children in the background (`async` follows `asyncByDefault`, normally true) and consume each result at the point a later step depends on it. Native completion wakes the parent session, so the parent returns control instead of sleeping or polling. Use `async: false` only when the parent must block, not for final reviews or gates. When an oracle or advisor reaches an unknown that needs a decision, it asks through supervisor dialogue; use a one-shot oracle call only when one was requested.
16
+
15
17
  Child-safety boundaries are enforced at runtime:
16
18
 
17
19
  - Child sessions do not receive the bundled `pi-subagents` skill.
@@ -27,7 +29,7 @@ Stop and report the exact failure, run/status, and repository/cwd/worktree/branc
27
29
 
28
30
  Failed workflow details and async `status.json` include `workflow.failureKind` as `validation`, `script`, `child`, `return-serialization`, `timeout`, `detached-child`, or `runtime`. `validation` means the host rejected the script before it ran (syntax or portability) or at completion (unawaited calls); errors thrown into a running script, including rejected `runs.run` parameters and runtime `SyntaxError`s, are `script` because the script could catch them, and failed children are `child`. `runtime` covers host setup and infrastructure failures, such as an unavailable cwd or a crashed worker. A workflow that is stopped or reloaded is not a failure and has no `failureKind`.
29
31
 
30
- When `/reload`, a session resume, or a pi-web project switch replaces the extension runtime, a running async workflow stops with `workflow.stopCause: "runtime-replaced"` in `status.json`, and its awaited async children keep running. When the same workflow script is launched again with the same `args` in that session, a `runs.run` with the same key and params returns a child that already finished successfully without launching it, and waits for a child that is still running instead of starting another. Those results carry `reused: true`, their step and trace entry are marked `reused`, and the new run records `workflow.reusedFrom`. Failed and stopped children, and children that ran in-process, launch again. Reuse applies only when the newest run of that script and args in the session was stopped this way; a user stop or a completed run ends it.
32
+ When `/reload`, a session resume, or a pi-web project switch replaces the extension runtime, a running async workflow stops with `workflow.stopCause: "runtime-replaced"` in `status.json`, and its awaited async children keep running. Its in-process foreground children are stopped, including ones that detached to ask their supervisor. When the same workflow script is launched again with the same `args` in that session, a `runs.run` with the same key and params returns a child that already finished successfully without launching it, and waits for a child that is still running instead of starting another. Those results carry `reused: true`, their step and trace entry are marked `reused`, and the new run records `workflow.reusedFrom`. Failed and stopped children, and children that ran in-process, launch again. Reuse applies only when the newest run of that script and args in the session was stopped this way; a user stop or a completed run ends it.
31
33
 
32
34
  Pi core may print a generic `pi -ne` extension-load hint; that out-of-repo hint is not protocol-approved fallback. A verified compaction abort may continue the retained child once on its already resolved model; it does not authorize an execution-mode or model switch.
33
35
 
@@ -49,11 +51,13 @@ Add `autofix` to `/parallel-review` or `/parallel-cleanup` to apply only the syn
49
51
 
50
52
  Use direct `{ agent, task }` for one bounded child. Use a workflow script when the parent needs a stable keyed child, sequence, fanout, steering, retry, or aggregation. For ordinary parallel fanout, use `await runs.all([{ key, agent, task }, ...])`. It resolves to an ordered array, not a key map, so use indexes, destructuring, or `.map(...)`, not `results.<key>`. Do not read `.output` from unawaited `runs.run` launches. Store a `runs.run` promise only when the script later observes it with `await`, `Promise.race`, or `Promise.all`, such as steering a live child before awaiting its result. Scripts are ordinary JavaScript statement bodies. Use an explicit `return` for a useful result.
51
53
 
54
+ Use top-level `await`, plain helper functions, or Promise chains; nested async functions, async arrows, and async methods are rejected (see [opt-in bounded workflows](#opt-in-bounded-workflows)).
55
+
52
56
  The `workflow` field selects the script source:
53
57
 
54
- - `workflow: true` runs the one ```` ```js workflow ```` fenced block written in the same assistant reply as the `subagent` call. The script is plain text in the reply, so it needs no JSON string escaping. A reply can carry exactly one such block and one `workflow: true` call; zero or several blocks fail. A line containing only ```` ``` ```` (three or more backticks, optionally followed by spaces or tabs) ends the block, so keep Markdown fences inside quoted strings.
58
+ - `workflow: true` runs the one ```` ```js workflow ```` fenced block written in the same assistant reply as the `subagent` call. The script is plain text in the reply, so it needs no JSON string escaping. A reply can carry exactly one such block and one `workflow: true` call; zero or several blocks fail. A reply with no tagged block may instead carry exactly one plain ```` ```js ```` block, which then runs. A line containing only ```` ``` ```` (three or more backticks, optionally followed by spaces or tabs) ends the block, so keep Markdown fences inside quoted strings.
55
59
  - A string containing `/` (or `\` in a Windows path), such as `workflow: "./workflows/review.js"`, is a script file.
56
- - Any other string, such as `workflow: "review"`, is a [named workflow resource](#named-workflow-resources-for-permission-extensions).
60
+ - Any other string, such as `workflow: "review"`, is a [named workflow resource](#named-workflow-resources-for-permission-extensions). The string `"true"` is read as `workflow: true`, because some MCP clients send the boolean as a string.
57
61
 
58
62
  `workflow: true` works only from a model tool call. Slash commands, RPC, and schedules pass scripts through their own inputs. Examples below that show only a ```` ```js workflow ```` block run with `subagent({ workflow: true })` in the same reply.
59
63
 
@@ -104,9 +108,12 @@ Use a named workflow resource when a permission or policy extension needs to dis
104
108
  ```js
105
109
  subagent({ workflow: "review", args: { task: "Review the change" } });
106
110
  subagent({ workflow: "run-ci", args: { command: "npm test" } });
111
+ subagent({ workflow: "parallel", args: { tasks: [{ agent: "reviewer", task: "Review src/api" }, { agent: "scout", task: "Map the tests" }] } });
107
112
  ```
108
113
 
109
- The host resolves the name and validates bounded plain-JSON `args` before starting the workflow. Resource provenance is recorded in workflow details and receipts for downstream permission/policy checks. Resource authority is not caller-supplied: `runs.host` is available only when the resolved resource explicitly grants the requested host key and command. Reply-block (`workflow: true`) and file-path scripts remain raw, unknown-provenance inputs, so their `runs.host` calls are unavailable through the public execution boundary. Named resources cannot be combined with `agent` or `task`; this first slice ships only the package-owned `review` and `run-ci` resources, not a user/project resource registry.
114
+ The host resolves the name and validates bounded plain-JSON `args` before starting the workflow. Resource provenance is recorded in workflow details and receipts for downstream permission/policy checks. Resource authority is not caller-supplied: `runs.host` is available only when the resolved resource explicitly grants the requested host key and command. Reply-block (`workflow: true`) and file-path scripts remain raw, unknown-provenance inputs, so their `runs.host` calls are unavailable through the public execution boundary. Named resources cannot be combined with `agent` or `task`; the package ships the `review`, `run-ci` and `parallel` resources, not a user/project resource registry.
115
+
116
+ `parallel` runs independent children together without writing a script: `args.tasks` is a list of `{ agent, task }` items, the children run in one `runs.all` batch, and the result lists each child's output in order. A failed child fails the workflow. Use a workflow script when steps depend on each other.
110
117
 
111
118
  ### Opt-in bounded workflows
112
119
 
@@ -120,9 +127,11 @@ return runs.run("review", { agent: "reviewer", task: "Review:\n" + scan.output }
120
127
  ```js
121
128
  subagent({
122
129
  workflow: true,
123
- timeoutMs: 900000,
124
- toolBudget: { soft: 40, hard: 60 },
125
- usageBudget: { tokens: { soft: 100000, hard: 150000 } }
130
+ options: {
131
+ timeoutMs: 900000,
132
+ toolBudget: { soft: 40, hard: 60 },
133
+ usageBudget: { tokens: { soft: 100000, hard: 150000 } }
134
+ }
126
135
  });
127
136
  ```
128
137
 
@@ -395,7 +404,7 @@ A plain workflow creates one enclosing mission by default. Its children do not c
395
404
 
396
405
  ### Repeatable workflows
397
406
 
398
- Use stable child keys and keep process logic in ordinary JavaScript. `runs.run` launches one child, `runs.all` launches independent children together, and later steps can use each completed child's `output`. Put long task text in arrays joined with `"\n"` so Markdown fences do not conflict with the script string.
407
+ Use stable child keys and keep process logic in ordinary JavaScript. `runs.run` launches one child, `runs.all` launches independent children together, and later steps can use each completed child's `output`. Put long task text in arrays joined with `"\n"` so Markdown fences do not conflict with the script string. Pass long child briefs as files and put only their paths in task text, not the briefs themselves in `args`, which is limited to 16 KiB.
399
408
 
400
409
  For a process you run often, save the task as a prompt template under `.pi/prompts/` or `~/.pi/agent/prompts/` and launch it with `/prompt-workflow`. The adapter compiles prompt steps into a workflow script, so templates describe the work instead of embedding raw `subagent` tool calls. You can ask the parent agent to create or update these prompt files from a process described in natural language.
401
410
 
@@ -517,7 +526,7 @@ For A → B → C, C's request belongs to B, not A. B can escalate a separate qu
517
526
 
518
527
  Child-side routine completion handoffs are not expected. If a child appears stalled, needs-attention notices show up in the parent session with useful next actions, such as checking `subagent({ action: "status" })`, interrupting the run, or nudging the child.
519
528
 
520
- If a workflow script child detaches through `contact_supervisor`, the enclosing async workflow stays `paused` until that child exits. Then the extension reconciles it to `complete` or `failed`. Wait on the child until that happens.
529
+ If a workflow script child detaches through `contact_supervisor`, the enclosing async workflow stays `paused` until that child exits. Then the extension reconciles it to `complete` or `failed`. Wait on the child until that happens. A detached child that runs in-process (not as an async child) is stopped if the extension runtime is replaced before it finishes; `status` on its run id then shows it as stopped with the reason.
521
530
 
522
531
  If messages do not show up, run `/subagents-doctor`. Advanced users can tune the bridge with `intercomBridge` in [configuration.md](configuration.md).
523
532
 
package/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import type {} from "./src/types/pi-runtime-compat.d.ts";
3
3
  import { HERDR_PI_MODE_ENV } from "./src/runs/shared/herdr-pi-protocol.ts";
4
+ import { loadedPackageVersion, readInstalledPackageVersion } from "./src/shared/package-version.ts";
4
5
 
5
6
  const registerExtension = process.env[HERDR_PI_MODE_ENV] === "1"
6
7
  ? (await import("./src/extension/herdr-pi-bridge.ts")).default
@@ -9,5 +10,9 @@ const registerExtension = process.env[HERDR_PI_MODE_ENV] === "1"
9
10
  : (await import("./src/extension/index.ts")).default;
10
11
 
11
12
  export default function registerSubagentExtension(pi: ExtensionAPI): void {
13
+ const installedVersion = readInstalledPackageVersion();
14
+ if (installedVersion !== loadedPackageVersion) {
15
+ throw new Error(`pi-subagents ${installedVersion} is installed, but this Pi process still has ${loadedPackageVersion} loaded. Restart Pi to load the update; /reload cannot replace extension modules that Node has already loaded.`);
16
+ }
12
17
  registerExtension?.(pi);
13
18
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xzzpig/pi-subagents",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
5
5
  "author": "Nico Bailon",
6
6
  "license": "MIT",
@@ -36,6 +36,7 @@
36
36
  "pi-package",
37
37
  "pi",
38
38
  "pi-coding-agent",
39
+ "extension",
39
40
  "subagents",
40
41
  "ai",
41
42
  "agents",
@@ -92,6 +93,7 @@
92
93
  },
93
94
  "dependencies": {
94
95
  "@xzzpig/pi-components": "0.4.0",
96
+ "@js-temporal/polyfill": "0.5.1",
95
97
  "acorn": "8.18.0",
96
98
  "jiti": "2.7.0",
97
99
  "undici": "8.10.2",
@@ -119,8 +121,8 @@
119
121
  "pack:pkg": "npm run build:pkg && npm pack ./dist-pkg",
120
122
  "typecheck": "tsc --noEmit",
121
123
  "test": "npm run test:unit",
122
- "test:unit": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --import ./test/support/isolated-temp-root.mjs --test test/unit/*.test.ts",
123
- "test:integration": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --import ./test/support/register-loader.mjs --test test/integration/*.test.ts",
124
+ "test:unit": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --import ./test/support/isolated-temp-root.mjs --import ./test/support/fork-test-environment.mjs --test test/unit/*.test.ts",
125
+ "test:integration": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --import ./test/support/register-loader.mjs --import ./test/support/fork-test-environment.mjs --test test/integration/*.test.ts",
124
126
  "test:smoke:tool-activation": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --test test/smoke/tool-activation.test.ts",
125
127
  "test:all": "npm run test:unit && npm run test:integration"
126
128
  }
@@ -9,7 +9,7 @@ decide which feedback is valid, and write the final memo. Advisors do not talk
9
9
  directly or see peer transcripts by default. This is not free-form agent chat.
10
10
 
11
11
  Before you orchestrate, load the council protocol with
12
- `subagent({ action: "guide", topic: "council" })`. If only `subagents_enable`
12
+ `subagent({ action: "guide", options: { topic: "council" } })`. If only `subagents_enable`
13
13
  is available, call it first; `subagent` is available on the next request. The
14
14
  guide returns the packaged council-mode skill and the references it asks you to
15
15
  read, so it also works when Pi runs with `--no-skills`.
@@ -87,7 +87,7 @@ that runner explicitly supports the option.
87
87
 
88
88
  ## Read the reference for the branch
89
89
 
90
- For exact API fields and worked examples, call `subagent({action:"guide",topic:"tool-reference"})` or `topic:"workflows"`. The compact tool definition is not the recipe catalog; use `topic:"missions"` for mission updates and schedules.
90
+ For exact API fields and worked examples, call `subagent({action:"guide",options:{topic:"tool-reference"}})` or `topic:"workflows"`. The compact tool definition is not the recipe catalog; use `topic:"missions"` for mission updates and schedules.
91
91
 
92
92
  | Branch | Read |
93
93
  | --- | --- |
@@ -64,7 +64,7 @@ its overhead. Recipes select a shape; they do not authorize delegation:
64
64
 
65
65
  ## Error Handling
66
66
 
67
- - **Unknown agent:** run `subagent({ action: "list" })`; check scope/precedence and author new orchestration as a workflow script, not legacy chains.
67
+ - **Unknown agent:** the error lists the available agents and the directories searched; check scope/precedence and author new orchestration as a workflow script, not legacy chains.
68
68
  - **Setup, discovery, or intercom confusion:** run `subagent({ action: "doctor" })`.
69
69
  - **Max subagent depth exceeded:** flatten the workflow or raise `maxSubagentDepth` in config.
70
70
  - **Missing session file for a fork:** persist the parent session before using `context: "fork"`.