@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
package/docs/models.md CHANGED
@@ -82,13 +82,13 @@ For a persistent role override:
82
82
  }
83
83
  ```
84
84
 
85
- `subagents.defaultModel` and `subagents.defaultProvider` apply to builtin, package, user, and project agents. `defaultModel` fills only agents that do not set `model` in frontmatter. `defaultProvider` is also applied to frontmatter and override models so bare ids resolve against the intended provider. Per-run model overrides and `agentOverrides.<name>.model` win over frontmatter and the global default. The same `agentOverrides` block can change `tools`, `skills`, inherited context, prompt text, or disable an agent (see [agents.md](agents.md)); matching custom-agent frontmatter is replaced for any field set by the override.
85
+ `subagents.defaultModel` and `subagents.defaultProvider` apply to builtin, package, user, project, and runtime-registered agents. `defaultModel` fills only agents that do not set `model` in frontmatter or in their runtime definition. `defaultProvider` is also applied to frontmatter and override models so bare ids resolve against the intended provider. Per-run model overrides and `agentOverrides.<name>.model` win over frontmatter and the global default. The same `agentOverrides` block can change `tools`, `skills`, inherited context, prompt text, or disable an agent (see [agents.md](agents.md)); matching custom-agent frontmatter is replaced for any field set by the override. Runtime-registered agents take only `model`, `defaultProvider`, `fast`, and `thinking` from `agentOverrides.<name>`; their other definition fields stay owned by the registering extension.
86
86
 
87
87
  ## Fast mode
88
88
 
89
89
  Set `fast: true` on a run, in agent frontmatter, or in `subagents.agentOverrides.<name>.fast` to request the OpenAI priority service tier for supported native OpenAI-Codex children. This can use a higher quota tier or cost more. It is off by default.
90
90
 
91
- Fast mode fails before launch unless the resolved model is on the allowlist. The current allowlist is `openai-codex/gpt-5.6-luna` and `openai-codex/gpt-5.6-sol`. External runners, Anthropic models, and other providers do not use fast mode.
91
+ Fast mode fails before launch unless the resolved model is a native `openai-codex/*` model. External runners, Anthropic models, and other providers do not use fast mode.
92
92
 
93
93
  ## Recommended model tiering (optional)
94
94
 
@@ -158,7 +158,9 @@ Project settings win over user settings. Use `agentOverrides.<name>.extensions`
158
158
  }
159
159
  ```
160
160
 
161
- A non-array value, an array containing a non-string entry, or an empty/whitespace-only string raises a settings error naming `defaultExtensions` and the offending settings file, matching the validation pattern used by `defaultModel` and `defaultThinking`.
161
+ Set `subagents.defaultSubagentOnlyExtensions` to give agents without a `subagentOnlyExtensions` field a shared child-only extension list while preserving ambient extension discovery. An empty array is an explicit empty default but, unlike `defaultExtensions: []`, does not disable ambient extensions. An agent's frontmatter list (including `[]`) suppresses the default; user and then project `agentOverrides.<name>.subagentOnlyExtensions` replace it or clear it with `false`. Lists are not combined.
162
+
163
+ The two defaults resolve independently, with an explicitly present project value winning over the user value. If both are set, `defaultExtensions` still disables ambient discovery and the child-only paths are loaded alongside its allowlist. Both reject non-arrays, non-string or blank entries with an error naming the setting and source file. Extension paths execute trusted code, so use project defaults only for trusted repositories and extensions.
162
164
 
163
165
  ## Inspecting the live mapping
164
166
 
@@ -204,7 +206,7 @@ To keep subagents inside a budget or compliance profile, enforce a model scope.
204
206
  }
205
207
  ```
206
208
 
207
- - `allow` is a list of glob patterns matched against the resolved `provider/id` (only `*` is special, case-insensitive). The literal `inherit` means the current parent session model.
209
+ - `allow` is a list of glob patterns matched against the resolved `provider/id` (only `*` is special, case-insensitive). The literal `inherit` means the current parent session model. The literal `scoped` means every model in the parent session's scoped-model set (pi's `/scoped-models`); when that set is empty, it means the same as `inherit`. Because `scoped` is reserved, it cannot match a provider literally named `scoped`.
208
210
  - `agents.<name>` adds a second allow-list for that agent. The model must pass both the global list and the matching agent list, so an agent rule cannot weaken the global rule. Agent rules inherit `enforce` and `strict` when those fields are absent.
209
211
  - A top-level `enforce: true` with only agent allow-lists restricts only those named agents. Unknown names are allowed so settings can be shared across projects and machines.
210
212
  - Models you pass explicitly — the tool-call `model`, `--model`, or a clarify pick — error and abort the run.
@@ -214,7 +216,7 @@ To keep subagents inside a budget or compliance profile, enforce a model scope.
214
216
 
215
217
  Model scope is policy only. It rejects or warns; it does not select a cheaper model. Set `agentOverrides.worker.model` to choose a worker model and use `modelScope.agents.worker` to prevent a per-run override from escaping that restriction.
216
218
 
217
- `inherit` expands in the parent process at each launch. It is never sent to the child as a model id. A nested child therefore inherits its immediate parent's current model, not the original top-level model. If no parent model is available, an enforced `inherit` entry does not match and fails closed.
219
+ `inherit` and `scoped` expand in the parent process at each launch. They are never sent to the child as model ids. A nested child therefore inherits its immediate parent's current model, not the original top-level model. `scoped` uses the scoped-model set at launch, so a mid-session `/scoped-models` change applies to the next child; background runs keep the set captured when the run started. Pi reports an empty set when the session is unscoped, either because nothing is configured or because no configured pattern matches an available model, and then lets the parent use every model. In that case `scoped` behaves exactly as `inherit`, which is narrower. If no parent model is available, an enforced `inherit` or `scoped` entry does not match and fails closed.
218
220
 
219
221
  Project `modelScope` settings replace the complete user `modelScope`, as with the existing project-over-user settings precedence. Project settings are trusted and can therefore replace user restrictions.
220
222
 
@@ -27,6 +27,12 @@ subagent({ action: "status", id: "..." }) // one run
27
27
 
28
28
  Or ask naturally: "Show me the current async runs."
29
29
 
30
+ ### Usage and cost accounting
31
+
32
+ Run `/subagent-cost` for the parent session's combined parent and child token usage and cost. It includes completed async workflow children when their persisted receipts and metadata remain available. Missing child metadata is reported as unavailable when the receipt identifies that child. If the workflow receipt itself is missing, unreadable, invalid, or non-terminal, affected children can be omitted from the total without an unavailable count, so treat the result as a lower bound when run artifacts are unavailable.
33
+
34
+ Pi's built-in session totals do not automatically include child usage delivered only by an async completion notification. Those notifications are custom messages, and Pi's public custom-message API does not carry accounted usage. `/subagent-cost` is therefore the supported accounting view for async child usage; do not infer child totals from Pi's footer or `/session` alone. Other extensions can read the same report as data through the in-process RPC `cost` method (see [extension-api.md](extension-api.md#in-process-event-bus-rpc)) instead of scraping the slash output.
35
+
30
36
  The under-editor async widget gives a short view while work runs. Its expand key follows your Pi keybinding:
31
37
 
32
38
  ```text
@@ -40,7 +46,7 @@ async subagent worker · background
40
46
 
41
47
  To inspect one background child in text, use `subagent({ action: "status", id: "...", view: "transcript" })`; add `index` for a specific child in a parallel or chain run.
42
48
 
43
- In Pi fullscreen mode with mouse dispatch (verified with Pi TUI 0.85.1), left-click
49
+ In Pi fullscreen mode with mouse dispatch, left-click
44
50
  anywhere on the async widget's header row to fold it into a live one-line status
45
51
  summary. Click again to restore the usual layout. No knowledge of extension commands
46
52
  or keyboard shortcuts is needed. The summary counts the widget's tracked runs,
@@ -206,16 +212,20 @@ Nested fanout status is stored as compact sidecar event/registry metadata and me
206
212
 
207
213
  Consumers should read these JSON files instead of scraping terminal output. Unknown fields and event types should be ignored for forward compatibility.
208
214
 
209
- RPC hosts that need low-latency child-stop UI hints can subscribe to the
210
- `subagent:child-status` event advertised by RPC `ping` as `events.childStatus`.
211
- The payload uses `type: "subagent.child-status"`, `version: 1`, `runId`,
212
- `childId`, `status` (`"stopping"` or `"stopped"`), `ts`, and optional child
213
- metadata such as `stepIndex`, `agent`, `childRunId`, `workflowKey`, `phase`, and
214
- `label`. These events are observer hints only. They can duplicate across RPC and
215
- async replay paths, and they are not replayed after a host restart. Status
216
- snapshots remain authoritative for recovery and final state. Child stop control
217
- still uses the normal `stop` request with `childId`; there is no separate child
218
- stop API.
215
+ Companion UIs and RPC hosts that need low-latency child lifecycle hints can
216
+ subscribe to the `subagent:child-status` event advertised by RPC `ping` as
217
+ `events.childStatus`. The payload uses `type: "subagent.child-status"`,
218
+ `version: 1`, `runId`, `childId`, `status` (`"started"`, `"stopping"`, or
219
+ `"stopped"`), `ts`, and optional child metadata such as `asyncDir`, `stepIndex`,
220
+ `agent`, `childRunId`, `workflowKey`, `phase`, and `label`. Async
221
+ Workflow script roots emit `"started"` once the keyed child has a concrete
222
+ launch identity; `childId` and `workflowKey` are the stable workflow key, while
223
+ `stepIndex` is only a convenience projection for the current status snapshot.
224
+ These events are observer hints only. They can duplicate across the live event
225
+ bus and async replay paths, and they are not replayed after a host restart.
226
+ Status snapshots remain authoritative for recovery and final state. Child stop
227
+ control still uses the normal `stop` request with `childId`; there is no separate
228
+ child stop API.
219
229
 
220
230
  ### Status and result fields
221
231
 
@@ -296,7 +306,7 @@ Session files are stored under a per-run session directory. With `context: "fork
296
306
 
297
307
  ## Completion notifications
298
308
 
299
- Async completions belong only to the originating session. The result watcher emits `subagent:async-complete`, and the extension consumes that event to record completion state.
309
+ Async completions belong only to the originating session. The result watcher emits `subagent:async-complete` for detached runs. Awaited workflow children emit it when they settle, with `awaitedByWorkflow: true`, `parentWorkflowRunId`, and `triggerTurn: false`. They do not send a separate child notification or turn.
300
310
 
301
311
  Successful sibling completions are held briefly and delivered as a quiet grouped completion when they finish within a short window (see `completionBatch` in [configuration.md](configuration.md)), avoiding unread markers on inactive tabs. Failed and paused completions remain visible and fire immediately.
302
312
 
@@ -307,7 +317,7 @@ Async events:
307
317
  - `subagent:async-started`
308
318
  - `subagent:async-complete`
309
319
 
310
- The `subagent:async-started` payload includes `task`, the backwards-compatible first child task truncated to 50 characters, and `goal`, the workflow-level caller task truncated to 120 characters (falling back to the first child task). Companion UI extensions can combine `goal`, `workflowGraph`, and the live lifecycle artifacts under `asyncDir` without scraping terminal output.
320
+ For regular async starts, the `subagent:async-started` payload includes redacted `task` and `goal` prompt fields. Async workflow script roots emit the same event with `mode: "workflow"` after their initial `status.json` is durable; workflow roots can omit `task`, and any included prompt fields are redacted. Their keyed children are then announced dynamically through `subagent:child-status`. Companion UI extensions can combine those hints with the authoritative live lifecycle artifacts under `asyncDir` without scraping terminal output.
311
321
 
312
322
  Intercom delivery events:
313
323
 
@@ -1,6 +1,6 @@
1
1
  # Standalone background execution
2
2
 
3
- Supported standalone target: **official Pi 0.85.1, Linux x64**. Keep its adjacent release assets with the executable. Other versions, operating systems, architectures and packagers are outside the fully validated support target; limited experimental Windows coverage is described below.
3
+ Supported standalone target: **official Pi 0.86.1, Linux x64**. Keep its adjacent release assets with the executable. Other versions, operating systems, architectures and packagers are outside the fully validated support target; limited experimental Windows coverage is described below.
4
4
 
5
5
  Pi's extension loader supplies its embedded SDK to `binary-bootstrap.ts`, which awaits the existing configured runner before exiting. Startup authorization, revival leases, controls, disposal and process-close observation remain shared with npm. Each independent run has its own host; native sessions inside that run share it. No per-session CLI protocol, runtime download/install, alternate SDK or foreground fallback is introduced. Npm Pi keeps its Node runner, peer aliases and detected npm `PI_PACKAGE_DIR` override (including refusal when no npm root exists).
6
6
 
@@ -10,7 +10,7 @@ Implementation and lifecycle fixtures derive from [@xz-dev](https://github.com/x
10
10
 
11
11
  The resolver recognizes Bun's Windows virtual entrypoint prefixes, `B:/~BUN/` and `B:\~BUN\`, alongside `/$bunfs/`. It launches the real `process.execPath` (or the existing executable override). The `B:` prefix is virtual, not the installation drive; `pi-native.exe` is not a required executable name.
12
12
 
13
- A local Windows x64 smoke passed with **xz-dev/pi `0.85.1-xz.169.1.gb5f4d0ff`, Bun 1.4.2**: a fresh async worker executed a read-only Git command, returned its result, delivered the native completion notification, and exited with code 0 and no remaining runner process. This is not validation of the official Windows distribution or every Bun-compiled Pi host. Windows remains **experimental**: the full standalone lifecycle matrix has not been validated there.
13
+ Windows remains **experimental**: the full standalone lifecycle matrix has not been validated there or for every Bun-compiled Pi host.
14
14
 
15
15
  Node-hosted npm Pi keeps its existing runner path and is not affected by this virtual-entrypoint detection defect. Installing only the pi-subagents extension through npm does not change a Bun-compiled Pi host into an npm Pi host.
16
16
 
@@ -33,17 +33,17 @@ The `official-standalone` CI job runs this gate. Both archive and executable has
33
33
 
34
34
  The matrix covers public launch/notification, workflows, same-run concurrent sessions, parallel stop, targeted steer/interrupt, child/tool/run deadlines, missing bootstrap, post-spawn persistence/authorization failures, SDK initialization failure, malformed bootstrap input/EOF with an authorized positive control, and competing revival. The provider is deterministic, but SDK sessions, runner and public extension are real. Only startup-failure writes are faulted.
35
35
 
36
- `matrix.json` records complete/partial results; `inputs.json` freezes source identities and every mode must use the same package hash. Inspect per-mode logs, `identity.json`, lifecycle/notification evidence, `status.json` and `process-terminal.json`. A persisted result is not exit proof: the gate separately awaits observed close, verifies dead PIDs before sandbox teardown and checks session shutdown/lease release. CI retains receipts and at most 32 MiB compressed lifecycle evidence. Contributor-head passes do not establish acceptance for a different integration snapshot.
36
+ `matrix.json` records complete/partial results with per-mode durations; `inputs.json` freezes source identities. The candidate is built and packed once and every mode must use that package hash. Modes run one at a time; they are CPU-bound and miss their deadlines when run concurrently. Inspect per-mode logs, `identity.json`, lifecycle/notification evidence, `status.json` and `process-terminal.json`. A persisted result is not exit proof: the gate separately awaits observed close, verifies dead PIDs before sandbox teardown and checks session shutdown/lease release. CI retains receipts and at most 32 MiB compressed lifecycle evidence. Contributor-head passes do not establish acceptance for a different integration snapshot.
37
37
 
38
38
  For a focused diagnostic, use `node test/smoke/standalone-background.mjs "$release_dir/pi/pi" "$(mktemp -d)/check" bootstrap-errors` (or another matrix mode). A focused pass is not the complete gate.
39
39
 
40
40
  ## Npm regressions and local trial
41
41
 
42
- Existing npm clean-install CI covers real SDK 0.85.1. The standalone CI job also checks the public npm launch path without execution-time network:
42
+ Existing npm clean-install CI covers real SDK 0.86.1. The standalone CI job also checks the public npm launch path without execution-time network:
43
43
 
44
44
  ```bash
45
45
  npm_checks="$(mktemp -d)"
46
- node test/smoke/clean-install.mjs "$npm_checks/sdk" 0.85.1
46
+ node test/smoke/clean-install.mjs "$npm_checks/sdk" 0.86.1
47
47
  node test/smoke/npm-background.mjs "$npm_checks/sdk" "$npm_checks/launch"
48
48
  ```
49
49
 
@@ -2,17 +2,21 @@
2
2
 
3
3
  Parameters and actions for the `subagent` tool. These are what the LLM passes when it calls the tool; most users ask naturally or use slash commands instead.
4
4
 
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
+
5
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.
6
8
 
7
9
  ## Execution examples
8
10
 
9
- Chaining is code-driven through `workflowScript`. Use `await runs.run(...)` for sequential steps and `await runs.all([{ key, agent, task }, ...])` for ordinary parallel fanout. `runs.all` resolves to an ordered array, not a key map, so use indexes, destructuring, or `.map(...)`, not `results.<key>`. Do not read `.output` from an unawaited `runs.run` launch. Stored `runs.run` promises are only for the advanced rolling fanout pattern under [Workflow steering](#workflow-steering), where every promise is later observed with direct `await`, `Promise.race`, or `Promise.all`. Legacy top-level `chain`, `tasks`, and `parallel` inputs are not supported. Helper functions must be plain functions or explicit Promise chains. Nested `async function` helpers, async arrows, and async methods are rejected so child-launch tracking stays portable across Node and Bun. For permission-sensitive host calls, use an extension-owned named resource such as `{ workflow: "run-ci", args: { command: "npm test" } }`; raw public `workflowScript`/`workflowScriptPath` inputs have unknown resource provenance and cannot call `runs.host`. A resolved resource may internally use `runs.host(key, { kind: "command", command, timeoutMs, output?, role?, provider? })` within its authority ceiling; there is no per-step `cwd`, and commands and relative output paths use the workflow `cwd`. Set `cwd` on the outer `subagent({...})` request instead, or put a trusted directory change in the command (for example, `cd /path/to/worktree && npm test`).
11
+ Chaining is code-driven through a workflow script. Write the script as one ```` ```js workflow ```` fenced block in the reply, then call `subagent({ workflow: true, ... })` in the same reply. A `workflow` string containing `/` is a script file, and any other string is a named resource. `workflowScript` and `workflowScriptPath` were removed; use these forms instead.
12
+
13
+ Use `await runs.run(...)` for sequential steps and `await runs.all([{ key, agent, task }, ...])` for ordinary parallel fanout. `runs.all` resolves to an ordered array, not a key map, so use indexes, destructuring, or `.map(...)`, not `results.<key>`. Do not read `.output` from an unawaited `runs.run` launch. Stored `runs.run` promises are only for the advanced rolling fanout pattern under [Workflow steering](#workflow-steering), where every promise is later observed with direct `await`, `Promise.race`, or `Promise.all`. Legacy top-level `chain`, `tasks`, and `parallel` inputs are not supported, except that `disabledFeatures: ["workflow-scripts"]` replaces workflow scripts with top-level `chain` and `tasks` (see [configuration](configuration.md#chain-and-tasks-without-workflow-scripts)). Helper functions must be plain functions or explicit Promise chains. Nested `async function` helpers, async arrows, and async methods are rejected so child-launch tracking stays portable across Node and Bun. For permission-sensitive host calls, use an extension-owned named resource such as `{ workflow: "run-ci", args: { command: "npm test" } }`; raw scripts (`workflow: true` or a script path) have unknown resource provenance and cannot call `runs.host`. A resolved resource may internally use `runs.host(key, { kind: "command", command, timeoutMs, output?, role?, provider? })` within its authority ceiling; there is no per-step `cwd`, and commands and relative output paths use the workflow `cwd`. Set `cwd` on the outer `subagent({...})` request instead, or put a trusted directory change in the command (for example, `cd /path/to/worktree && npm test`).
10
14
 
11
- Use `{ action: "validate", workflowScript }` to check statically decidable syntax and structure without launching children. It returns `{ ok, errors }` and fails the tool call when `ok` is false. Literal child `baseRef` values are checked against the runtime ref policy. Dynamic keys and values remain subject to runtime checks; static validation does not guess them.
15
+ Use `{ action: "validate", workflow: true }` (or a script path) to check statically decidable syntax and structure without launching children. It returns `{ ok, errors }` and fails the tool call when `ok` is false. Literal child `baseRef` values are checked against the runtime ref policy. Dynamic keys and values remain subject to runtime checks; static validation does not guess them.
12
16
 
13
- Use `workflowScriptPath` instead of `workflowScript` to load the same JavaScript statement body from a file. The two fields are mutually exclusive. Relative paths resolve against the request `cwd`, and absolute paths pass through. The host reads the file before validation, scheduling, or sandbox execution. The workflow sandbox still has no filesystem access. Missing, unreadable, and empty files fail as file input errors.
17
+ Use `workflow: "./path/to/script.js"` to load the same JavaScript statement body from a file. Relative paths resolve against the request `cwd`, and absolute paths pass through. The host reads the file before validation, scheduling, or sandbox execution. The workflow sandbox still has no filesystem access. Missing, unreadable, and empty files fail as file input errors.
14
18
 
15
- Raw inline and file-backed scripts accept bounded plain-JSON `args`, including during `validate` and `schedule.create`. Omitted raw args become `{}`; supplied args are deeply frozen in the sandbox. Normalized args persist in run and schedule evidence for diagnosis and exact replay, so never include secrets. Args are data only and do not grant `runs.host` authority.
19
+ Raw reply-block and file-backed scripts accept bounded plain-JSON `args`, including during `validate` and `schedule.create`. Omitted raw args become `{}`; supplied args are deeply frozen in the sandbox. Normalized args persist in run and schedule evidence for diagnosis and exact replay, so never include secrets. Args are data only and do not grant `runs.host` authority.
16
20
 
17
21
  For permission-extension interoperability, use one of the package-owned named resources with bounded `args` instead of caller-supplied workflow text:
18
22
 
@@ -21,66 +25,41 @@ For permission-extension interoperability, use one of the package-owned named re
21
25
  { workflow: "run-ci", args: { command: "npm test" } }
22
26
  ```
23
27
 
24
- The host resolves the script and authority internally and records bounded provenance in workflow details and receipts. Named resources cannot be combined with `agent`, `task`, `workflowScript`, or `workflowScriptPath`; user/project resource registries are not part of this first slice.
28
+ The host resolves the script and authority internally and records bounded provenance in workflow details and receipts. Named resources cannot be combined with `agent` or `task`; user/project resource registries are not part of this first slice.
25
29
 
26
30
  ```js
27
- { workflowScriptPath: "workflows/review.js", args: { target: "src/workflows" }, cwd: "/path/to/project" }
28
- { action: "validate", workflowScriptPath: "workflows/review.js", args: { target: "src/workflows" } }
29
- { action: "schedule.create", every: "6h", workflowScriptPath: "workflows/review.js", args: { target: "src/workflows" } }
31
+ { workflow: "./workflows/review.js", args: { target: "src/workflows" }, cwd: "/path/to/project" }
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" } }
30
34
  ```
31
35
 
32
- ```js
36
+ Each script below is the ```` ```js workflow ```` block of a reply that then calls `subagent({ workflow: true })`:
37
+
38
+ ```js workflow
33
39
  // One child; return the child promise explicitly
34
- { workflowScript: `return runs.run("main", { agent: "scout", task: "Analyze the auth flow" })` }
40
+ return runs.run("main", { agent: "scout", task: "Analyze the auth flow" });
41
+ ```
35
42
 
43
+ ```js workflow
36
44
  // Sequential workflow
37
- { workflowScript: `
38
- const scan = await runs.run("scan", { agent: "scout", task: "Analyze auth" });
39
- return (await runs.run("implement", { agent: "worker", task: "Implement from: " + scan.output })).output;
40
- ` }
45
+ const scan = await runs.run("scan", { agent: "scout", task: "Analyze auth" });
46
+ return (await runs.run("implement", { agent: "worker", task: "Implement from: " + scan.output })).output;
47
+ ```
41
48
 
49
+ ```js workflow
42
50
  // Parallel workflow
43
- { workflowScript: `
44
- const results = await runs.all([
45
- { key: "backend", agent: "reviewer", task: "Review backend" },
46
- { key: "frontend", agent: "reviewer", task: "Review frontend" }
47
- ]);
48
- return results.map(result => result.output);
49
- ` }
51
+ const results = await runs.all([
52
+ { key: "backend", agent: "reviewer", task: "Review backend" },
53
+ { key: "frontend", agent: "reviewer", task: "Review frontend" }
54
+ ]);
55
+ return results.map(result => result.output);
50
56
  ```
51
57
 
52
58
  ### Parallel sequential lanes
53
59
 
54
- Use `runs.lanes(lanes)` inside a `workflowScript` when several independent lanes each have ordered stages. This helper composes the existing workflow child runner; it does not add a top-level `lanes` parameter or a second persistence/cleanup system.
60
+ Use `runs.lanes(lanes)` inside a workflow script when several independent lanes each have ordered stages. This helper composes the existing workflow child runner; it does not add a top-level `lanes` parameter or a second persistence/cleanup system.
55
61
 
56
- ```js
57
- { workflowScript: `
58
- const board = await runs.lanes([
59
- { key: "api", stages: [
60
- { key: "writer", agent: "worker", task: "Implement the API change" },
61
- { key: "challenge", resume: "previous", task: "Challenge the implementation" },
62
- { key: "review", agent: "reviewer", task: "Review the API lane" }
63
- ] },
64
- { key: "ui", stages: [
65
- { key: "writer", agent: "worker", task: "Implement the UI change" },
66
- { key: "review", agent: "reviewer", task: "Review the UI lane" }
67
- ] }
68
- ]);
69
- return board.map((lane) => ({
70
- key: lane.key,
71
- state: lane.state,
72
- failedStage: lane.failedStage,
73
- stages: lane.stages.map((stage) => ({
74
- key: stage.key,
75
- state: stage.state,
76
- ok: stage.ok,
77
- runId: stage.runId,
78
- outputReference: stage.outputReference,
79
- verdict: stage.verdict
80
- }))
81
- }));
82
- ` }
83
- ```
62
+ See the [staged-lane example](workflows.md#parallel-sequential-lanes) (guide topic `workflows`).
84
63
 
85
64
  The first stage of each lane is launched by one existing `runs.all(...)` batch. Later stages run in lane order. Set `resume: "previous"` on a later stage to continue the preceding retained child; the helper requires that child’s returned `runId` and delegates to the existing resume checks. Stage keys are local to the lane, and generated child keys are `<lane>.<stage>`.
86
65
 
@@ -93,9 +72,9 @@ The complete plain-JSON inventory is validated before the first launch (maximum
93
72
  | `agent` | string | - | One direct child or agent-management target. Workflow child agents are set inside `runs.run` or `runs.all`. |
94
73
  | `task` | string | agent default | Direct child's task; requires `agent`, excludes `action` and workflow inputs. `agent` may also select a management target. |
95
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. |
96
- | `topic` | `overview \| workflows \| agents \| missions \| observability \| tool-reference \| configuration \| models \| watchdog \| extension-api` | `overview` | Packaged guide topic for `action: "guide"`. |
75
+ | `topic` | `overview \| workflows \| agents \| missions \| observability \| tool-reference \| configuration \| models \| watchdog \| extension-api \| council` | `overview` | Packaged guide topic for `action: "guide"`. |
97
76
  | `config` | object/string | - | Agent config for management create/update. |
98
- | `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`, `oracle`, and `advisor` default to `fork`. |
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`. |
99
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. |
100
79
  | `missionId` | string | - | Attach a workflow to an existing project mission instead of creating its default enclosing mission. |
101
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. |
@@ -112,23 +91,25 @@ The complete plain-JSON inventory is validated before the first launch (maximum
112
91
  | `agentScope` | `user \| project \| both` | `both` | Agent discovery scope. Project wins on collisions. |
113
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. |
114
93
  | `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. |
115
- | `chatProgress` | `auto \| off \| live-card` | `auto` | WorkflowScript 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. |
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. |
116
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. |
117
- | `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 workflowScript, set it on the outer request as a default or on an individual `runs.run`/`runs.all` child to override it. |
118
- | `timeoutMs` / `maxRuntimeMs` | number | config `timeoutMs`, else 30 min foreground / single-agent async | Optional run-level max runtime in milliseconds. 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. |
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. |
119
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. |
120
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. |
121
- | `toolBudget` | object | none | Optional child tool-call budget `{ soft?, hard, block? }`. At `soft` the child is nudged to finalize. After `hard`, configured tools are blocked; `block` defaults to `read`, `grep`, `find`, and `ls`, while `"*"` blocks every tool call. Final assistant text is never blocked. |
122
- | `usageBudget` | object | none | Optional root-only reported-usage budget `{ tokens?: { soft?, hard }, costUsd?: { soft?, 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. |
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). |
123
104
  | `cwd` | string | runtime cwd | Override working directory. With `machine`, the directory on that machine. |
124
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). |
125
- | `maxOutput` | object | 200KB, 5000 lines | Final output truncation limits. |
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. |
126
107
  | `artifacts` | boolean | true | Write debug artifacts. |
127
108
  | `includeProgress` | boolean | false | Include full progress in result. |
128
109
  | `share` | boolean | false | Upload session export to GitHub Gist. |
129
110
  | `sessionDir` | string | derived | Override session log directory. |
130
111
  | `acceptance` | string/object/false | inferred | Configure evidence gates. See [Acceptance gates](#acceptance-gates). |
131
- | `gate` | string | - | One host-run verification command, shorthand for `acceptance: { level: "verified", verify: [{ id: "gate", command }] }`. Also valid on individual `runs.run`/`runs.all` items. Rejects `acceptance` except `false` (treated as omitted), and rejects retained `resume`. |
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`. |
132
113
 
133
114
  ### Budget guidance for writers
134
115
 
@@ -142,7 +123,7 @@ Explicit `context: "fork"` fails fast when the parent session is not persisted,
142
123
 
143
124
  When the inherited transcript contains signed Anthropic `thinking` / `redacted_thinking` blocks, `pi-subagents` strips those provider-private blocks from the forked child session: a thinking signature is bound to the session that produced it and cannot be replayed into a branch. The child keeps its requested thinking level and reasons fresh from its first turn; sanitizing the inherited transcript is not a downgrade. Explicit `context: "fork"` never silently downgrades to `fresh`.
144
125
 
145
- In workflow runs that omit `context`, each `runs.run` child follows the global `defaultSubagentContext` when set, then its own `defaultContext`. Without the global setting, a fresh-default scout can run fresh beside a fork-default worker. If the parent session file or current leaf is not available yet, implicit fork-default children run fresh. Pass explicit `context: "fork"` or `context: "fresh"` when you intentionally want one context for every child.
126
+ In workflow runs that omit `context`, each `runs.run` child follows the global `defaultSubagentContext` when set, then its own `defaultContext`. Without the global setting, a fresh-default worker can run fresh beside a fork-default oracle. If the parent session file or current leaf is not available yet, implicit fork-default children run fresh. Pass explicit `context: "fork"` or `context: "fresh"` when you intentionally want one context for every child.
146
127
 
147
128
  ### Workflow steering
148
129
 
@@ -152,26 +133,24 @@ The workflow trace records the attempt and receipt. Always await, return, or inc
152
133
 
153
134
  For advanced rolling fanout, keep the launched `runs.run` promises in ordinary JavaScript data only when every promise is later observed with direct `await`, `Promise.race`, or `Promise.all`. `Promise.race` gives the next completed child, `runs.steer` can challenge a still-running keyed sibling, and `Promise.all` collects the rest. No separate `runs.start`, `runs.next`, or `runs.collect` API is exposed.
154
135
 
155
- ```js
156
- { workflowScript: `
157
- let pending = [
158
- { key: "writer", promise: runs.run("writer", { agent: "worker", task: "Draft the fix" }).then((result) => ({ key: "writer", result })) },
159
- { key: "reviewer", promise: runs.run("reviewer", { agent: "reviewer", task: "Review likely risks" }).then((result) => ({ key: "reviewer", result })) }
160
- ];
161
- const first = await Promise.race(pending.map((child) => child.promise));
162
- pending = pending.filter((child) => child.key !== first.key);
163
- const target = pending[0];
164
- const receipt = await runs.steer(target.key, "Use this early review:\n" + first.result.output, { mode: "auto" });
165
- const rest = await Promise.all(pending.map((child) => child.promise));
166
- return { first: first.key, rest: rest.map((child) => child.key), receipt };
167
- ` }
136
+ ```js workflow
137
+ let pending = [
138
+ { key: "writer", promise: runs.run("writer", { agent: "worker", task: "Draft the fix" }).then((result) => ({ key: "writer", result })) },
139
+ { key: "reviewer", promise: runs.run("reviewer", { agent: "reviewer", task: "Review likely risks" }).then((result) => ({ key: "reviewer", result })) }
140
+ ];
141
+ const first = await Promise.race(pending.map((child) => child.promise));
142
+ pending = pending.filter((child) => child.key !== first.key);
143
+ const target = pending[0];
144
+ const receipt = await runs.steer(target.key, "Use this early review:\n" + first.result.output, { mode: "auto" });
145
+ const rest = await Promise.all(pending.map((child) => child.promise));
146
+ return { first: first.key, rest: rest.map((child) => child.key), receipt };
168
147
  ```
169
148
 
170
149
  ### Output mode details
171
150
 
172
151
  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.
173
152
 
174
- In workflowScript, 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.
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.
175
154
 
176
155
  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.
177
156
 
@@ -179,24 +158,22 @@ Workflows get `await state.get(key)` and `await state.set(key, value)` through t
179
158
 
180
159
  ### Retained children
181
160
 
182
- Completed workflow children from the current parent session stay addressable as retained children. `{ action: "children.list" }` lists up to the last 10 with their run ids and explicit `resumable` or `not resumable` state. Resume only rows reported `resumable`; if no row is resumable, start a same-role fallback challenge and label it as fallback. A later workflow continues a resumable child by passing `resume` instead of `agent`:
161
+ Completed workflow children from the current parent session stay addressable as retained children. `{ action: "children.list" }` lists up to the last 10 with their run ids and explicit `resumable` or `not resumable` state. This workflow-only roster is not an exhaustive list of direct native children. Resume only rows reported `resumable`. When the exact run id of an intended direct child is known, inspect it with `{ action: "status", id: "<run-id>" }`; if status identifies the candidate, attempt `{ action: "resume", id: "<run-id>", message: "..." }`. Resume performs the authoritative eligibility check and may reject the attempt. Start a same-role fallback challenge, labeled as fallback, only when no known candidate exists or resume rejects eligibility. A later workflow continues a resumable child by passing `resume` instead of `agent`:
183
162
 
184
- ```js
185
- { workflowScript: `
186
- let writer = await runs.run("implement", { agent: "worker", task: "Implement the accepted contract" });
187
- for (const pass of [1, 2]) {
188
- if (!writer.runId) throw new Error("writer did not return a retained run id");
189
- writer = await runs.run("followup-" + pass, { resume: writer.runId, task: "Revisit pass " + pass + ": " + writer.output });
190
- }
191
- return writer;
192
- ` }
163
+ ```js workflow
164
+ let writer = await runs.run("implement", { agent: "worker", task: "Implement the accepted contract" });
165
+ for (const pass of [1, 2]) {
166
+ if (!writer.runId) throw new Error("writer did not return a retained run id");
167
+ writer = await runs.run("followup-" + pass, { resume: writer.runId, task: "Revisit pass " + pass + ": " + writer.output });
168
+ }
169
+ return writer;
193
170
  ```
194
171
 
195
172
  Each workflow key identifies one result lane. Use a new stable workflow key for every distinct retained resume pass; same-key calls are reused only when launch parameters are identical, and incompatible parameters are rejected.
196
173
 
197
- Inside `workflowScript`, `await runs.run(key, { resume, task })` waits for the revived child to finish and returns its completed output and new `runId`. Each resume can return a new retained run id, so loops must continue from the latest returned `runId`. Top-level `{ action: "resume" }` remains detached and returns a background-run receipt.
174
+ Inside a workflow script, `await runs.run(key, { resume, task })` waits for the revived child to finish and returns its completed output and new `runId`. Each resume can return a new retained run id, so loops must continue from the latest returned `runId`. Top-level `{ action: "resume" }` remains detached and returns a background-run receipt. When it revives a failed async workflow child (or a failed revival of one), the revived run becomes that key's latest run: workflow `status` adds `Revived → <run>: <state>` under the key, and keyed `resume: { workflowRunId, key, latest: true }` continues from it with lineage `[original, revived, ...]`. If the workflow was still running, the receipt it writes when it ends adds the revived runs to the key's lineage, and its completion notice keeps the child's failed result with the same `Revived →` line. The workflow's return value and state are not changed, notices already delivered are not rewritten, and a key accepts at most 16 chained revivals. Reviving a completed, paused, or stopped child does not change its key.
198
175
 
199
- For a simple implementation challenge outside a workflow script, send the challenge through `subagent({ action: "resume", id: "<retained-writer-run>", message: "Reconsider the implementation and make any better current-scope change." })` only when `children.list` reports that retained writer as `resumable`. If no retained writer is resumable, start a same-role fallback challenge and record why it is a fallback. Use workflow `runs.run({ resume })` only when the script must await the revived writer output before the next step. Do not use `steer` as the sole challenge action for a completed retained child; `steer` with `mode: "follow_up"` only queues text for the next `resume`.
176
+ For a simple implementation challenge outside a workflow script, send the challenge through `subagent({ action: "resume", id: "<retained-writer-run>", message: "Reconsider the implementation and make any better current-scope change." })` when `children.list` reports that retained writer as `resumable`, or attempt it after exact-id status inspection identifies a known direct-child candidate. Status is advisory; resume authoritatively checks eligibility and may reject missing recovery requirements. If there is no known candidate or resume rejects eligibility, start a same-role fallback challenge and record why it is a fallback. Use workflow `runs.run({ resume })` only when the script must await the revived writer output before the next step. Do not use `steer` as the sole challenge action for a completed retained child; `steer` with `mode: "follow_up"` only queues text for the next `resume`.
200
177
 
201
178
  `resume` and `agent` are mutually exclusive. The revived child keeps its stored agent, model, and tool contract. `gate` is rejected on retained resume items because resume uses the retained child contract.
202
179
 
@@ -204,7 +181,7 @@ For a simple implementation challenge outside a workflow script, send the challe
204
181
 
205
182
  ### Guide
206
183
 
207
- `{ action: "guide" }` reads the packaged `README.md` from the installed version. Pass `topic` to read its packaged `docs/<topic>.md` file instead. Valid topics are `overview`, `workflows`, `agents`, `missions`, `observability`, `tool-reference`, `configuration`, `models`, `watchdog`, and `extension-api`. Unknown topics list the valid values and do not change files. Use `/subagents-guide [topic]` for the slash equivalent.
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.
208
185
 
209
186
  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.
210
187
 
@@ -242,7 +219,7 @@ Agent definitions are not loaded into context by default. Management actions let
242
219
 
243
220
  { action: "update", agent: "code-analysis.scout", config: { model: "openai/gpt-4o" } }
244
221
  { action: "update", agent: "code-analysis.scout", config: { acceptance: "" } } // clear the frontmatter default
245
- { action: "update", agent: "code-analysis.scout", config: { acceptanceRole: false } } // restore inferred name fallback
222
+ { action: "update", agent: "code-analysis.scout", config: { acceptanceRole: false } } // restore default lightweight attestation
246
223
  { action: "delete", agent: "scout" }
247
224
 
248
225
  { action: "eject", agent: "reviewer" }
@@ -269,7 +246,7 @@ Rules:
269
246
 
270
247
  ### Schedule controls
271
248
 
272
- Use `schedule.create` with `workflowScript` or `workflowScriptPath`, 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.
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.
273
250
 
274
251
  ## Lane merge evidence and cleanup eligibility
275
252
 
@@ -349,7 +326,7 @@ subagent({ action: "doctor" })
349
326
 
350
327
  - Multi-child async runs and remembered foreground single, parallel, or chain runs can be revived by passing `index` to choose the child.
351
328
  - Nested runs can be resumed by nested id when their live route or persisted nested session metadata is available.
352
- - Completed external-job runs can use the same `resume` action as a provider follow-up when the registered provider exposes `followUp(input)`. Running external-job parents fail closed with guidance to wait for completion. Unsupported providers fail with an update/reload message.
329
+ - Completed external-job runs, including nested runs, can use the same `resume` action as a provider follow-up when the registered provider exposes `followUp(input)`. Running external-job parents fail closed with guidance to wait for completion. Unsupported providers fail with an update/reload message.
353
330
  - Revive starts a new child session from the old session context; it does not resume the live session, and it requires the chosen child to have a persisted `.jsonl` session file.
354
331
  - Direct revival takes an exclusive cross-process lease on the canonical session file until the new child finishes. A concurrent attempt fails before Pi is spawned and identifies the owning revived run; dead-owner leases are reclaimed only when staleness can be proved.
355
332
 
@@ -381,6 +358,8 @@ The `/subagents-steer <run-id> [--child <child-id>] <message>` slash command is
381
358
 
382
359
  Every run resolves an effective acceptance policy. Callers may omit `acceptance` for the inferred default, or set it on single runs, top-level parallel task items, chain steps, static parallel tasks, and dynamic fanout templates.
383
360
 
361
+ Checked writers reject staged files by default. When a parent intentionally starts a single writer with reviewed staged content, opt in with `acceptance: { level: "checked", preserveStagedIndex: true }`. The host captures the repository-wide index tree immediately before each launch (including each retained resume) and accepts only if `git write-tree` produces the same tree at completion. Working-tree-only fixes are allowed; child-created staging is rejected. Capture or terminal Git failures, including an unavailable or unmerged index, fail closed. This option does not stage or restore files and should not be used for concurrent writers sharing one worktree.
362
+
384
363
  Prefer an inline JSON object. JSON-encoded object strings are tolerated only during input normalization; invalid strings fail closed. `true` is invalid. Supported evidence kinds are `changed-files`, `tests-added`, `commands-run`, `validation-output`, `residual-risks`, `no-staged-files`, `diff-summary`, `review-findings`, and `manual-notes`. For example: `{level:"checked",evidence:["commands-run","changed-files"],review:{required:true}}`. Evidence levels end at `verified`; independent review is a separate gate, not a stronger evidence level.
385
364
 
386
365
  ```ts
@@ -400,23 +379,38 @@ Prefer an inline JSON object. JSON-encoded object strings are tolerated only dur
400
379
 
401
380
  When one host-run command is the entire verification contract, use the `gate` shorthand instead of a full `acceptance` object:
402
381
 
403
- ```js
404
- { workflowScript: `return runs.run("impl", { agent: "worker", task: "Implement the fix", gate: "npm test" })` }
382
+ ```js workflow
383
+ return runs.run("impl", { agent: "worker", task: "Implement the fix", gate: "npm test" });
405
384
  ```
406
385
 
407
386
  `gate` normalizes to verified acceptance with that single command, so the runtime executes it on the host and records the result as evidence. Verification results are memoized per tracked workspace state and effective environment, so an unchanged tree does not rerun the same command. Use explicit `acceptance.verify` when you need multiple commands, timeouts, or custom criteria. `gate` rejects `acceptance` except `false` (treated as omitted), and rejects retained `resume` items. With `worktree: true`, the gate runs inside the child's managed worktree.
408
387
 
388
+ ### Typed gates
389
+
390
+ A gate given as `{ command, output: "json" }` runs like a string gate, and then parses the command's stdout:
391
+
392
+ ```js workflow
393
+ return runs.run("review", {
394
+ agent: "reviewer", task: "Review the change", output: "reports/review.md", outputMode: "file-only",
395
+ gate: { command: "classify --report reports/review.md", output: "json",
396
+ schema: { type: "object", properties: { verdict: { enum: ["ok", "blocked"] } }, required: ["verdict"] } }
397
+ });
398
+ ```
399
+
400
+ - The command runs after the child's output file is saved, in the child's cwd or managed worktree, so it can read what the child wrote.
401
+ - A passing command must print one JSON document on stdout (at most 12,000 characters). The parsed value becomes `result.structuredOutput`, is recorded on the verify run as `structuredOutput`, and is projected into `status.json`. When `schema` is given, the value must validate against it.
402
+ - Empty, truncated, non-JSON, or schema-invalid stdout marks the gate `failed` with a `structuredOutputError`; explicit acceptance then fails the run, exactly as a non-zero exit would. The verdict is never silently dropped.
403
+ - Typed gates are never memoized: their input (a report, a log) can change without the tracked tree changing.
404
+ - `output: "json"` cannot be combined with an `outputSchema` from any source: the launch `outputSchema` param or the agent's frontmatter, paired with `gate`, an explicit `acceptance.verify` entry, or the agent's `defaultAcceptance`. Preflight rejects the launch and names both sources. A child has exactly one structured-output source.
405
+ - `runs.lanes` treats a bridged `structuredOutput.verdict === "blocked"` like any other blocked stage. Scripts read the value as `result.structuredOutput`.
406
+
409
407
  ### Levels and inference
410
408
 
411
409
  Acceptance evidence levels are `auto`, `none`, `attested`, `checked`, and `verified`. `acceptance: "auto"` is the default.
412
410
 
413
- Review is a separate gate configured with `acceptance.review`:
414
-
415
- - Async, risky, and dynamic writer contexts infer checked evidence plus `review: { agent: "reviewer", required: true }`.
416
- - Tasks classified as read-only infer no acceptance by default, including reviews of release, migration, or security work; those topics do not turn a read-only task into implementation. With role metadata omitted, unknown risk-topic tasks retain their gate even when the agent name suggests a reviewer. Explicit acceptance requests still apply.
417
- - Normal writer tasks infer checked evidence without review.
411
+ Automatic inference uses only the declared structured role: `acceptanceRole: "writer"` infers checked evidence, with `review: { agent: "reviewer", required: true }` for async and dynamic writers; `"read-only"` infers none; and an omitted role infers lightweight attestation. Task wording, risk vocabulary, and agent names do not affect inference. Explicit acceptance can raise or add policy, while `{ level: "none", reason: "..." }` disables inferred gates according to the existing policy rules.
418
412
 
419
- Agent frontmatter or `subagents.agentOverrides` may set `acceptanceRole: "read-only" | "writer"` for ambiguous tasks. Explicit task mutation or no-edit intent wins over that role, while omitted metadata preserves the existing reviewer/scout/worker name heuristics. The role affects acceptance inference only and does not change tool access.
413
+ Agent frontmatter or `subagents.agentOverrides` may set `acceptanceRole`. The role affects acceptance inference only and does not change tool access. Review is a separate gate configured with `acceptance.review`.
420
414
 
421
415
  Edge cases:
422
416
 
@@ -495,8 +489,12 @@ Intentionally unsupported: native Pi child options such as model override, struc
495
489
 
496
490
  Pass `share: true` to export a full session to HTML, upload it to a secret GitHub Gist through your `gh` credentials, and return a `https://shittycodingagent.ai/session/?<gistId>` URL.
497
491
 
498
- ```ts
499
- { workflowScript: `return runs.run("main", { agent: "scout", task: "..." })`, share: true }
492
+ ```js workflow
493
+ return runs.run("main", { agent: "scout", task: "..." });
494
+ ```
495
+
496
+ ```js
497
+ subagent({ workflow: true, share: true });
500
498
  ```
501
499
 
502
500
  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.
package/docs/watchdog.md CHANGED
@@ -181,3 +181,5 @@ Values are `allow`, `ask`, and `deny`. Agent rules override global ones, omitted
181
181
  `ask` pauses that exact tool call and sends a bounded, redacted preview to a one-call arbiter owned by the child watchdog, using the configured child-watchdog model. The arbiter returns only `approve` or `deny` and does not notify the parent. A disabled watchdog, missing model/auth, timeout, malformed response, or runtime error denies the call with a clear error. Requests and decisions are written to bounded audit JSONL. `contact_supervisor` and the optional `pi-intercom` extension are never permission-gated.
182
182
 
183
183
  Bash is always passed through; bash rules are rejected. Use `pi-guard` for command-level policy. Children are pi sessions inside the parent process (foreground) or the detached runner process (background), not separate `pi` binaries, so there is no per-child command wrapper; load `pi-guard` into a child through the agent's `extensions` or `subagentOnlyExtensions`, and background children also pick it up as an ambient extension. External CLI profiles are opaque processes, so native permissions cannot intercept their tools; launches with effective `ask` or `deny` rules are rejected for external CLI agents.
184
+
185
+ Detached runners receive `PI_SUBAGENT_PARENT_SESSION` from their exact launch and retain it for that dedicated process. Root and in-process foreground hosts do not publish a global parent identity because multiple Pi sessions can share a host. Environment-only permission extensions therefore cannot safely forward foreground `ask` requests; that path remains unsupported until the extension accepts a session-scoped target. Native child permissions are unaffected.