@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -2,7 +2,7 @@
2
2
 
3
3
  `pi-subagents` reads optional JSON config from `~/.pi/agent/extensions/subagent/config.json`. This page lists every key, plus the environment variables and the settings-file keys that affect config resolution.
4
4
 
5
- Settings-level keys (`subagents.defaultModel`, `defaultProvider`, `defaultThinking`, `defaultExtensions`, `agentOverrides`, `modelScope`, `disableThinking`, `disableBuiltins`, `injectAgents`, watchdog settings) live in Pi settings files, not this config file. `modelScope.agents.<name>` adds per-agent restrictions, and `allow: ["inherit"]` permits the current parent model. See [models.md](models.md), [agents.md](agents.md), and [watchdog.md](watchdog.md).
5
+ Settings-level keys (`subagents.defaultModel`, `defaultProvider`, `defaultThinking`, `defaultExtensions`, `agentOverrides`, `agentScanDirs`, `modelScope`, `disableThinking`, `disableBuiltins`, `injectAgents`, watchdog settings) live in Pi settings files, not this config file. `modelScope.agents.<name>` adds per-agent restrictions, and `allow: ["inherit"]` permits the current parent model. See [models.md](models.md), [agents.md](agents.md), and [watchdog.md](watchdog.md).
6
6
 
7
7
  ## Project root resolution (settings)
8
8
 
@@ -18,13 +18,39 @@ By default, project settings resolve from the nearest parent directory that cont
18
18
 
19
19
  `"git-root"` keeps package discovery, project agents, chains, and `agentOverrides` anchored to the git worktree root when that root also has Pi project config. A nested project can still opt back into nearest-root behavior by setting `"projectRootResolution": "nearest"` in its own `.pi/settings.json`.
20
20
 
21
+ ## Extra agent scan directories (settings)
22
+
23
+ Add recursive user or project agent roots with `subagents.agentScanDirs` in Pi settings:
24
+
25
+ ```json
26
+ {
27
+ "subagents": {
28
+ "agentScanDirs": ["~/.pi/flows/*/agents"]
29
+ }
30
+ }
31
+ ```
32
+
33
+ Entries support `~` expansion. A single `*` path segment expands one directory level, so package-like folders can each expose an `agents/` directory. Missing directories are ignored. Fixed user/project agent directories still win over same-name agents from scan roots.
34
+
35
+ ## `modelExclusions`
36
+
37
+ ```json
38
+ {
39
+ "modelExclusions": {
40
+ "defaultTtlMs": 300000
41
+ }
42
+ }
43
+ ```
44
+
45
+ Controls the duration, in milliseconds, for model exclusions. The default is `86400000` (24 hours), and the maximum is `8000000000000000` so generated expiry timestamps remain valid JavaScript dates. The extension applies this value when it starts or reloads. A lower configured value shortens active cached exclusions from their original `recordedAt`; it never extends an existing expiry. Authentication-related exclusions are ignored when Pi's `auth.json` was modified after the exclusion was recorded; other exclusion types are unaffected. Launches also warn when a candidate is skipped, including the cached reason and expiry. `PI_MODEL_EXCLUSIONS_PATH` changes the exclusion-store path but does not change this TTL.
46
+
21
47
  ## `toolDescriptionMode`
22
48
 
23
49
  ```json
24
50
  { "toolDescriptionMode": "compact" }
25
51
  ```
26
52
 
27
- Controls the parent-facing `subagent` tool description registered at startup. The default registers split prompt metadata: a short tool description plus `promptSnippet` and `promptGuidelines`. Set `"full"` to register the complete description as one tool description, or `"compact"` to keep the execution modes, async/`subagent_wait` guidance, child-safety boundary, management/action split, one-writer review guidance, and artifact/status essentials with less prompt bloat.
53
+ Controls the parent-facing `subagent` tool description registered at startup. The default registers split prompt metadata: a short tool description plus `promptSnippet` and `promptGuidelines`. Set `"full"` to register the complete description as one tool description, or `"compact"` to keep the execution modes, async/`bg_wait` guidance, child-safety boundary, management/action split, one-writer review guidance, and artifact/status essentials with less prompt bloat.
28
54
 
29
55
  `custom` reads `subagent-tool-description.md` from the project config directory, then from `~/.pi/agent/subagent-tool-description.md`. Missing, empty, unreadable, or oversized custom files fall back to the full description. Custom templates may use `{{fullDescription}}`, `{{compactDescription}}`, `{{safetyGuidance}}`, `{{agentDir}}`, and `{{projectConfigDir}}`; the safety guidance is always present so custom prose cannot remove the runtime guardrails. Restart Pi after changing the mode or custom file.
30
56
 
@@ -85,7 +111,7 @@ Pi binds `Ctrl+B` to editor cursor-left by default. The extension shortcut takes
85
111
  }
86
112
  ```
87
113
 
88
- Opt in to a best-effort Orca observer that creates one Orca terminal tab for each top-level subagent call and mirrors the run's live tool, assistant, stdout, and stderr progress. Parallel and chain children share that one tab, with child section headers in the mirrored log. Tab titles use a persistent worktree-local sequence (`subagents · <run-label> · 1`, `... · 2`, and so on), so separate top-level calls do not reuse the same number. For the same worktree, `orca terminal create` runs one at a time in that sequence so observer tabs appear from left to right as `1`, then `2`, then `3`. This does **not** replace Pi as the runner: native Pi children keep the same process, lifecycle, status, control, artifact, and result paths. External CLI profiles also keep their existing runner and can mirror their stdout/stderr.
114
+ Opt in to a best-effort Orca observer that creates one Orca terminal tab for each top-level subagent call and mirrors the run's live tool and assistant progress. Parallel and chain children share that one tab, with child section headers in the mirrored log. Tab titles use a persistent worktree-local sequence (`subagents · <run-label> · 1`, `... · 2`, and so on), so separate top-level calls do not reuse the same number. For the same worktree, `orca terminal create` runs one at a time in that sequence so observer tabs appear from left to right as `1`, then `2`, then `3`. This does **not** replace Pi as the runner: native Pi children keep the same lifecycle, status, control, artifact, and result paths. External CLI profiles also keep their existing runner and can mirror their stdout/stderr.
89
115
 
90
116
  The integration is off by default and supports macOS and Linux. It is disabled on Windows. When enabled, `pi-subagents` looks for executable `orca` on `PATH`, or uses the executable path in `PI_SUBAGENT_ORCA_BINARY`. If no executable is available, Orca is not running, the cwd is not an Orca-managed worktree, or `terminal create` fails, the authoritative subagent still runs normally. Tab creation is deliberately best-effort and never changes the child result. A passive observer manifest is also written under `<worktree>/.pi/subagents/views/orca/` when possible so future view surfaces can discover the Orca tab without making Orca authoritative.
91
117
 
@@ -109,6 +135,23 @@ Sets `fresh` or `fork` for every subagent launch that omits `context`. This glob
109
135
 
110
136
  With `"fork"`, the setting uses the existing implicit-fork behavior. A launch starts fresh when the parent session file or current leaf is not available. `"fresh"` starts fresh even when the selected agent defaults to fork. Scheduled runs continue to set fresh context explicitly. A runner or provider that does not support fork context keeps its existing rejection behavior.
111
137
 
138
+ ## `forkContext`
139
+
140
+ ```json
141
+ {
142
+ "forkContext": {
143
+ "mode": "pruned",
144
+ "model": "openai-codex/gpt-5.6-luna:max"
145
+ }
146
+ }
147
+ ```
148
+
149
+ Controls how resolved fork launches prepare the inherited session. The default `"full"` mode keeps the complete fork. `"pruned"` mode keeps inherited context exact while it fits the code-owned 64 KiB session budget. On overflow, the required `model` returns short JSON summaries keyed by stable item ids. Tool results spill first, then older assistant and tool context, and user text only when required. It applies to explicit `context: "fork"`, global and agent fork defaults, and `context: "profile"` when the selected profile resolves to fork.
150
+
151
+ Child-visible spilled items contain only the model summary and a stable `{ batchId, itemId }` recovery ref. Raw bodies and their digests, source entry ids, labels, sizes, and tool metadata go to a private `0600` sidecar next to the child session. This release does not add a recovery command or expose that payload to the child model.
152
+
153
+ Pruned forks keep the normal `parentSession` link, child cwd alignment, and fork thinking-block sanitization. Missing model or auth, invalid or incomplete summary JSON, budget overflow, recovery validation failure, and raw overflow leakage all stop the launch before child spawn. The extension never falls back to a full fork or refs-only context after a prune failure.
154
+
112
155
  ## `fleetView`
113
156
 
114
157
  ```json
@@ -155,12 +198,12 @@ Controls the under-editor widget for active background runs. It defaults to `tru
155
198
  ## `waitTool`
156
199
 
157
200
  ```json
158
- { "waitTool": { "enabled": false } }
201
+ { "waitTool": { "enabled": true, "defaultTimeoutMs": 120000 } }
159
202
  ```
160
203
 
161
- Keeps the `subagent_wait` tool registered but makes direct calls return immediately instead of blocking on active subagent or provider work. The default is enabled. You can also set `"waitTool": false`; set `PI_SUBAGENT_WAIT_TOOL_ENABLED=false` (or `0`, `off`, `disabled`) to override config for one process. The effective value is passed explicitly to child runtimes. Headless `agent_end` auto-drain remains a lifecycle safeguard even when direct wait calls are disabled. Invalid config or environment values fail instead of being coerced.
204
+ `defaultTimeoutMs` sets the blocking window used when a `bg_wait` call omits `timeoutMs`; explicit call values win, followed by this setting, then the 30-minute fallback. `bg_wait` is the only registered wait tool. When the window elapses, the tool returns a non-error `window_elapsed` result with the still-active work identities, and that work keeps running. Set `enabled` to `false` to make direct calls return immediately instead of blocking. The default is enabled. You can also set `"waitTool": false`; set `PI_SUBAGENT_WAIT_TOOL_ENABLED=false` (or `0`, `off`, `disabled`) to override config for one process. The effective enabled and default-timeout values are passed explicitly to child runtimes. Headless `agent_end` auto-drain retains its own strict deadline and fails if required work remains unresolved. Invalid config or environment values fail instead of being coerced.
162
205
 
163
- Blocking `subagent_wait({ id: "..." })` keeps the current tool call open until that run changes. By default it returns when a run needs attention. Use `subagent_wait({ stopOnAttention: false })` only for run-to-completion flows that should wait through idle or long-thinking attention; supervisor/contact requests still stop the wait. In a long-lived interactive parent session, `subagent_wait({ id: "...", nonBlocking: true })` instead resolves the prefix once, persists the exact run identity, returns a subscription token immediately, and wakes that session on completion, failure, attention, reconciliation failure, or timeout. Armed subscriptions appear in ordinary `subagent({ action: "status" })` output and are not counted as active child work.
206
+ Blocking `bg_wait({ id: "..." })` keeps the current tool call open until that run changes. By default it returns when a run needs attention. Use `bg_wait({ stopOnAttention: false })` only for run-to-completion flows that should wait through idle or long-thinking attention; supervisor/contact requests still stop the wait. In a long-lived interactive parent session, `bg_wait({ id: "...", nonBlocking: true })` instead resolves the prefix once, persists the exact run identity, returns a subscription token immediately, and wakes that session on completion, failure, attention, reconciliation failure, or timeout. Use it for provider, detached, or other background work without a native completion notification; ordinary async subagent runs notify the parent natively and do not need a wait subscription. Armed subscriptions appear in ordinary `subagent({ action: "status" })` output and are not counted as active child work.
164
207
 
165
208
  This is different from `waitTool.enabled=false`, which returns immediately without registering any future wake. Provider items remain available only to blocking fleet-wide waits; non-blocking subscriptions require one async or remembered detached foreground run id.
166
209
 
@@ -188,7 +231,7 @@ Forces depth-0 internal single, parallel, and chain runs into background mode an
188
231
  { "timeoutMs": 3600000 }
189
232
  ```
190
233
 
191
- Global default runtime deadline, in milliseconds, for subagent runs. It replaces the built-in 30-minute backstop for foreground launches (single, parallel, chain, and workflowScript) and plain single-agent async runs whenever no call-level `timeoutMs`/`maxRuntimeMs` applies. For single-agent launches, selected agent frontmatter `timeoutMs` still wins. This only moves the *default*.
234
+ Global default runtime deadline, in milliseconds, for subagent runs. It replaces the built-in 30-minute backstop for foreground launches (single, parallel, chain, and workflowScript) and plain single-agent async runs whenever no call-level `timeoutMs`/`maxRuntimeMs` applies. For single-agent launches, selected agent frontmatter `timeoutMs` still wins. This only moves the *default*. Expiring this run-level deadline is terminal and does not trigger `fallbackModels`; only provider/model failures reported before the deadline can fall back.
192
235
 
193
236
  Use it when foreground orchestration or plain async single-agent runs need a longer default than 30 minutes. It does not set async composite top-level deadlines, and it does not replace async fan-out child deadlines.
194
237
 
@@ -204,7 +247,7 @@ Optional hard per-tool-call deadline in milliseconds. When configured, a child t
204
247
 
205
248
  Without a configured value, Pi still applies a five-minute hard timeout to known-fast built-in tools: `read`, `grep`, `find`, `ls`, `edit`, `write`, and `structured_output`. Long-running tools such as `bash`, custom tools, and MCP tools do not get a hard default. They get the normal open-tool attention notice after `activeNoticeAfterMs` and remain bounded by the run-level deadline.
206
249
 
207
- The tool timer tracks each active `toolCallId` separately and never extends the run-level deadline: when the remaining run budget is shorter, the ordinary run-level timeout wins. `contact_supervisor`, `intercom`, and `subagent_wait` are exempt because their legitimate purpose can be to wait for a human, supervisor, or child run. Use hard tool timeouts only for wedge protection; an elapsed timeout is not a mutation-safe boundary. Configured values must be positive integers no greater than `2147483647`; invalid or out-of-range values are rejected with a visible error rather than silently ignored.
250
+ The tool timer tracks each active `toolCallId` separately and never extends the run-level deadline: when the remaining run budget is shorter, the ordinary run-level timeout wins. `contact_supervisor`, `intercom`, and `bg_wait` are exempt because their legitimate purpose can be to wait for a human, supervisor, or background run. Use hard tool timeouts only for wedge protection; an elapsed timeout is not a mutation-safe boundary. Configured values must be positive integers no greater than `2147483647`; invalid or out-of-range values are rejected with a visible error rather than silently ignored.
208
251
 
209
252
  ## `globalConcurrencyLimit`
210
253
 
@@ -212,7 +255,9 @@ The tool timer tracks each active `toolCallId` separately and never extends the
212
255
  { "globalConcurrencyLimit": 20 }
213
256
  ```
214
257
 
215
- Caps simultaneously running children inside existing durable legacy multi-child runs. New orchestration uses `workflowScript` and `runs.all`.
258
+ Caps simultaneously running children inside one run, including durable legacy multi-child runs and `workflowScript` launches through `runs.run`/`runs.all`. Queued workflow children retain their stable keys and begin when a running sibling releases capacity. The default is `20`.
259
+
260
+ Inline or file-backed top-level workflow calls may set a positive safe-integer `globalConcurrencyLimit` to override this value for that workflow. The override is workflow-only and is not forwarded to child calls.
216
261
 
217
262
  ## `maxSubagentSpawnsPerSession`
218
263
 
@@ -232,6 +277,8 @@ Optionally caps the total number of child subagent launches during one parent se
232
277
 
233
278
  Caps cumulative logical child admissions in one top-level run tree. The default is `64`. `PI_SUBAGENT_MAX_SPAWNS_PER_RUN` overrides the config when it is a positive integer. Invalid, zero, or missing values fall back to the configured positive value or `64`.
234
279
 
280
+ Inline or file-backed top-level workflow calls may set a positive safe-integer `maxSubagentSpawnsPerRun`; it overrides the environment and config for that workflow. Inherited nested budgets remain authoritative, and the override is not forwarded to child calls.
281
+
235
282
  The budget counts single launches, expanded `tasks`/`count`, static chain steps and parallel groups, actual dynamic `expand` items, appended chain steps, workflow children, and nested child calls. Static and materialized dynamic groups are admitted atomically. Startup retries, model fallback, and retained-child resume reuse the original logical child claim. Claims are never released or refunded. This cap is independent from the session-wide cumulative spawn budget and `globalConcurrencyLimit`.
236
283
 
237
284
  ## `maxActiveAsyncRunsPerSession`
@@ -244,6 +291,14 @@ Optionally caps concurrently active top-level async runs owned by one parent ses
244
291
 
245
292
  Queued, running, paused, and needs-attention runs retain capacity. Runner-backed slots release only after terminal logical state and matching observed process-terminal proof from #1030. Missing, malformed, or unknown cleanup proof retains the slot. A terminal async workflow releases after its controller is gone and every launched child is accounted for: awaited foreground children are covered by workflow settlement, while actual background children still require observed process-terminal proof. Resume transfers the source slot without a second charge. Dismissal and history cleanup do not release capacity.
246
293
 
294
+ When the runner is gone but process cleanup proof remains unknown, configure a bounded policy reclaim under `capacity.abandonedSlotReleaseAfterMs`:
295
+
296
+ ```json
297
+ { "maxActiveAsyncRunsPerSession": 4, "capacity": { "abandonedSlotReleaseAfterMs": 1200000 } }
298
+ ```
299
+
300
+ The default is `1200000` milliseconds (20 minutes). The policy releases only a failed terminal run whose runner PID is dead and whose last activity is older than the threshold. A live or unknown PID, a non-failed terminal state, a recent run, or missing activity timestamp retains the slot. Set the value to `false` to keep strict retention. Valid configured durations range from 5 minutes through 24 hours. Policy release is reported as `abandoned-timeout` with `processProof: unknown`; it is not observed process-terminal proof and may reclaim capacity while an orphan child still exists.
301
+
247
302
  This limit bounds current top-level async load. It is separate from cumulative `maxSubagentSpawnsPerSession`, `maxSubagentSpawnsPerRun`, and `globalConcurrencyLimit`.
248
303
 
249
304
  `subagent({ action: "status" })`, fleet status, and `subagent({ action: "doctor" })` expose used, effective limit, and remaining active capacity. Static chains and parallel calls fail before creating run artifacts or starting partial work when their declared capacity cannot fit. Later retries or unbounded dynamic work are not guaranteed by that preflight.
@@ -299,7 +354,7 @@ Routes relative `output` paths for single-agent `/run` calls under this director
299
354
  { "maxSubagentDepth": 1 }
300
355
  ```
301
356
 
302
- Controls nested delegation when no inherited `PI_SUBAGENT_MAX_DEPTH` is already in effect. Per-agent `maxSubagentDepth` can tighten the limit for that agent's child runs, but cannot relax an inherited stricter limit. This applies even to children that explicitly declare `tools: subagent`; at the cap, execution fanout is blocked instead of silently hiding nested work.
357
+ Controls nested delegation when no stricter limit is inherited from the launching child's runtime config. Per-agent `maxSubagentDepth` can tighten the limit for that agent's child runs, but cannot relax an inherited stricter limit. This applies even to children that explicitly declare `tools: subagent` or `allowNestedSubagents: true`; at the cap, execution fanout is blocked instead of silently hiding nested work.
303
358
 
304
359
  ## `PI_SUBAGENT_PI_BINARY`
305
360
 
@@ -307,17 +362,7 @@ Controls nested delegation when no inherited `PI_SUBAGENT_MAX_DEPTH` is already
307
362
  export PI_SUBAGENT_PI_BINARY=/path/to/pi-or-wrapper
308
363
  ```
309
364
 
310
- Overrides the command used to launch child Pi processes. Package wrappers can set this to their own `pi`/agent binary so subagents inherit wrapper flags, environment setup, and bundled resources without relying on `PATH` ordering. Empty or whitespace-only values are ignored.
311
-
312
- ## `PI_SUBAGENT_TASK_DELIVERY`
313
-
314
- ```bash
315
- export PI_SUBAGENT_TASK_DELIVERY=file # auto | file (default: auto)
316
- ```
317
-
318
- Controls how the task text reaches the child Pi process. `auto` (default) passes short tasks as an inline argv token and writes tasks longer than 8000 characters to a temp `task.md` referenced as `@<path>`. `file` always uses a temp file, keeping the task out of argv entirely.
319
-
320
- Use `file` on hosts where endpoint protection (EDR) pre-execution scanning denies child processes whose command line embeds a long natural-language task — that denial surfaces as an immediate zero-activity `SIGKILL`. Independently of this setting, startup retries automatically escalate to file delivery after an unexplained zero-activity `SIGKILL`. Empty, whitespace-only, or unrecognized values fall back to `auto`.
365
+ Overrides the `pi` command pi-subagents spawns for Herdr project panes (`action: "project.open"`) and for the profile model probe. Package wrappers can set this to their own `pi` binary so those launches inherit wrapper flags, environment setup, and bundled resources without relying on `PATH` ordering. Empty or whitespace-only values are ignored. It does not affect children: foreground children are sessions inside the parent Pi process and background children are sessions inside the detached runner process, and neither spawns a `pi` binary. Background children require pi installed as the npm package (`@earendil-works/pi-coding-agent`), because the runner imports pi's packages from that package directory; a standalone pi binary has no package directory, and background launches fail with an error saying so.
321
366
 
322
367
  ## `intercomBridge`
323
368
 
@@ -349,7 +394,21 @@ The default injected guidance tells children to use `contact_supervisor` with `r
349
394
  { "worktreeBaseDir": "/Users/matt/code/.worktrees/pi-subagents" }
350
395
  ```
351
396
 
352
- Sets the base directory for `worktree: true` runs. Relative paths resolve from the repository root, `~/...` expands to your home directory, and `PI_SUBAGENTS_WORKTREE_DIR` is used when config is unset. The default remains the system temp directory.
397
+ Sets the native dedicated root directory for `worktree: true` runs. Relative paths resolve from the repository root, `~/...` expands to your home directory, and `PI_SUBAGENTS_WORKTREE_DIR` is used when config is unset. When native allocation is used and both are unset, the dedicated root defaults to `{dirname(repoRoot)}/worktrees`, a `worktrees` directory alongside the repository checkout.
398
+
399
+ Each native worktree leaf is `{dedicatedRoot}/{projectName}/pi-worktree-{runId}-{index}`, where `{projectName}` is the repository directory name (`basename(repoRoot)`), `{runId}` identifies the run, and `{index}` counts the children within the run. `worktreeBaseDir` and `PI_SUBAGENTS_WORKTREE_DIR` override only the dedicated root; the `{projectName}/pi-worktree-{runId}-{index}` nesting under it always applies for native allocation. Unsafe locations are rejected instead of created: setup fails when the dedicated root sits inside the repository checkout or the Pi extensions directory, or when a worktree would land directly inside the repository parent.
400
+
401
+ ## `worktreeProvider`
402
+
403
+ ```json
404
+ { "worktreeProvider": "auto", "worktreeBranchPrefix": "pi-subagents/" }
405
+ ```
406
+
407
+ Selects the managed worktree allocator: `auto` (the default) uses Worktrunk when its machine-readable interface is available and otherwise falls back to Pi's native Git worktrees; `native` always uses Pi's Git implementation; and `worktrunk` fails closed when Worktrunk is unavailable or incompatible. A configured `worktreeBaseDir` (or `PI_SUBAGENTS_WORKTREE_DIR`) selects native allocation and cannot be combined with explicit `worktrunk`.
408
+
409
+ `worktreeBranchPrefix` is normalized as a Git ref namespace and defaults to `pi-subagents/`. Branch names include readable task/lane identity plus run and fan-out indexes. Pi continues to own setup hooks, launch, handoff/diff evidence, resume, and cleanup; Worktrunk is used only to allocate and report the worktree path.
410
+
411
+ Set `worktree` to `true` to make managed worktree isolation the default for launches that omit the per-call `worktree` flag. A per-call value still takes precedence.
353
412
 
354
413
  ## `worktreeSetupHook`
355
414
 
@@ -28,10 +28,11 @@ The RPC methods are `ping`, `status`, `manage`, `spawn`, `steer`, `interrupt`, `
28
28
  Method notes:
29
29
 
30
30
  - `manage` exposes a narrow schedule-only allowlist: `schedule.list`, `schedule.show`, `schedule.history`, `schedule.pause`, `schedule.resume`, `schedule.run`, and `schedule.delete`. All actions except `schedule.list` require `id`. Mission, agent, config, worktree, and arbitrary management actions are rejected before executor dispatch. `ping.capabilities.managementActions` advertises the exact allowlist.
31
- - `spawn` accepts structured single-child execution (`agent`, `task?`) or `workflowScript` and is async-only: omit `async` or set `async: true`, omit `clarify`, and do not pass management `action` values. It goes through the same executor as the `subagent` tool, so agent discovery, validation, session attribution, configured spawn caps, child-safety depth, artifacts, and async status all behave the same.
31
+ - `spawn` accepts structured single-child execution (`agent`, `task?`), inline `workflowScript`, or `workflowScriptPath` and is async-only: omit `async` or set `async: true`, omit `clarify`, and do not pass management `action` values. Relative script paths resolve against the request `cwd`. It goes through the same executor as the `subagent` tool, so agent discovery, validation, session attribution, configured spawn caps, child-safety depth, artifacts, and async status all behave the same.
32
32
  - `steer` requires an async run `id` (plus optional child `index`) and a non-empty `message`; its reply preserves the normal acknowledged-delivery result. Optional `mode` values are `steer` (default), `follow_up`, and `auto`, and receipts include `deliveryStatus: "delivered" | "queued"`. RPC steering disables the direct tool's pause-and-revive recovery in every mode so an extension keeps authority over the exact child it spawned; `ping.capabilities.nonRecoveringSteer` advertises this guarantee.
33
33
  - `resume` requires a run target and non-empty `message`. It delegates to the existing revival path, which validates current-session ownership, persisted session/recovery metadata, stopped/live state, capability ceilings, and the exclusive session lease before returning the new async run details. Callers may request a `file-only` output path for the revived result without overriding its model, tools, or budgets. `ping.capabilities.resume` advertises this seam.
34
34
  - `stop` targets current-session top-level async runs through the stop control channel and records a `stopped` lifecycle instead of reporting a timeout.
35
+ - `status` keeps targeted and rich requests on the executor-backed path. A request with no `id`, `runId`, `dir`, `index`, `view`, or `lines` may use the restored in-memory projections and a short summary; when the live state is missing, stale, session-mismatched, or not restored, it falls back to normal executor status. Status `view`, `lines`, and `index` are forwarded for targeted transcript/fleet requests. Successful replies retain `text`, `details`, `fleet`, and `asyncSnapshot`; the short summary intentionally omits canonical filesystem details, wait subscriptions, and budget annotations.
35
36
 
36
37
  Capability advertisements on `ping`:
37
38
 
@@ -42,6 +43,7 @@ Capability advertisements on `ping`:
42
43
  - `processTerminalProof` — the process-terminal proof status (see [observability.md](observability.md#process-terminal-proof)).
43
44
  - `nonRecoveringSteer` — RPC steering never pauses-and-revives.
44
45
  - `resume` — the revival seam described above.
46
+ - `statusProjection: { version: 1, untargeted: "in-memory-when-ready", targeted: "executor" }` — untargeted status may use restored bounded projections; targeted or rich status remains executor-backed.
45
47
  - `fleetStatus: { version: 1 }` — successful `status` replies additionally include `data.fleet`.
46
48
 
47
49
  Structured delegation progress updates carry `runId` as soon as foreground execution allocates it, so a caller can retain the package-owned revival target even if its own tool turn is interrupted before the terminal response. Foreground `details.results[]` rows also include a numeric `index` that is unique within the run and stable across partial progress snapshots and the final result; use `(runId, index)` instead of row position to correlate single, counted parallel, and chain children.
@@ -54,10 +56,51 @@ Entries are bounded, current-session public display records with an opaque recon
54
56
 
55
57
  The DTO intentionally never exposes run, async, or tool IDs. Clients must ignore unknown fields and fall back to status text when the capability is absent.
56
58
 
59
+ `data.asyncSnapshot` is a separate bounded projection included on successful status replies when available. Its `runs[].id` contains the async run id; unlike the fleet DTO, it is not an opaque display key. Fleet keys remain opaque and must not be interpreted as run or async identifiers.
60
+
57
61
  ### Scope
58
62
 
59
63
  `pi.events` is in-process only. It does not reach separate Pi processes or child subagents; use the file lifecycle artifacts or `pi-intercom` for cross-process coordination.
60
64
 
65
+ ## Runtime agent registration from independent extensions
66
+
67
+ An independently installed Pi extension can register an agent with the installed `pi-subagents` owner through the process-local `pi-subagents:runtime-agent-register:v1` event. Emit after extension setup, such as during `session_start`. Event delivery is synchronous, so the owner writes the result onto the request before `emit()` returns.
68
+
69
+ ```typescript
70
+ const request: {
71
+ version: 1;
72
+ name: string;
73
+ definition: {
74
+ description: string;
75
+ systemPrompt: string;
76
+ tools?: readonly string[];
77
+ };
78
+ result?:
79
+ | { ok: true; registration: { dispose(): void } }
80
+ | { ok: false; error: Error };
81
+ } = {
82
+ version: 1,
83
+ name: "runtime-probe-agent",
84
+ definition: {
85
+ description: "Agent registered by an independent extension",
86
+ systemPrompt: "Return the words runtime probe.",
87
+ tools: [],
88
+ },
89
+ };
90
+
91
+ pi.events.emit("pi-subagents:runtime-agent-register:v1", request);
92
+ if (!request.result) throw new Error("pi-subagents is not installed or not ready");
93
+ if (!request.result.ok) throw request.result.error;
94
+ const registration = request.result.registration;
95
+ // Call registration.dispose() during your extension cleanup.
96
+ ```
97
+
98
+ If `pi-subagents` is a resolvable dependency of the consumer package, `pi-subagents/agents` exports `RUNTIME_AGENT_REGISTER_EVENT`, the request/result types, and `registerAgentViaEvents()` for the same contract. A separately installed Pi package is not automatically a Node dependency of another package. In that case, use the event contract directly instead of a runtime import. A type-only development dependency is optional.
99
+
100
+ The installed owner applies the existing runtime-agent validation, collision checks, limits, runtime source metadata, and cleanup. If more than one owner listens, the first handler that writes `request.result` wins. Unsupported versions, malformed requests, and registration failures return `{ ok: false, error }`. No result means no compatible owner handled the event.
101
+
102
+ This contract is process-local. It does not register agents in child sessions or other Pi processes, and it does not change package discovery or package resolution.
103
+
61
104
  ## External jobs in FleetView
62
105
 
63
106
  Use `pi-subagents/external-runs` to publish display-only current-session jobs owned by another extension:
@@ -90,7 +133,7 @@ updateExternalRun(ctx.sessionManager.getSessionId(), "dependency-review", {
90
133
  unregisterExternalRun(ctx.sessionManager.getSessionId(), "dependency-review");
91
134
  ```
92
135
 
93
- The API validates and caches bounded display fields when the caller registers or updates a job. FleetView reads that cache only. It does not poll caller code. `snapshotExternalRuns(sessionId)` and `listExternalRuns(sessionId)` return bounded current-session snapshots. By default, malformed cached records throw with the validation error. Display-only Fleet callers can pass `{ ignoreMalformed: true, onMalformedRecord }` to remove bad records and keep rendering with a programmatic diagnostic.
136
+ The API validates and caches bounded display fields when the caller registers or updates a job. FleetView reads that cache only. It does not poll caller code. `snapshotExternalRuns(sessionId)` and `listExternalRuns(sessionId)` return bounded current-session snapshots. Snapshots filter the session-qualified cache key before inspecting record fields; API-written records avoid repeated normalization through module-private provenance, while records replaced or mutated through the process-local registry are validated on demand. By default, malformed records for the requested session throw with the validation error. Display-only Fleet callers can pass `{ ignoreMalformed: true, onMalformedRecord }` to remove bad records and keep rendering with a programmatic diagnostic.
94
137
 
95
138
  External jobs are observational. The caller owns execution, persistence, cancellation, and result delivery. FleetView does not expose stop, steer, resume, cancel, or Herdr controls for them. Supplied report and transcript paths are shown as bounded text only; FleetView does not read arbitrary external paths.
96
139
 
@@ -126,7 +169,7 @@ Preflight covers ordinary single-agent launch resolution:
126
169
  - Fresh/fork context, effective model and thinking, skill and tool resolution, direct MCP selections, runtime/configured extensions.
127
170
  - Artifact/session paths, async lifecycle/status/result/event/process-terminal paths, package/lifecycle versions, capability-ceiling audit data, and stable digests.
128
171
 
129
- `launchContractDigest` is the canonical digest of the caller task, effective system prompt (including the resolved `turnBudget` prompt augmentation when supplied), model candidates, effective tools/extensions/MCP (including inherited capability ceilings), output binding, and structured-output schema that ordinary foreground and async execution report in results/status/events and metadata.
172
+ `launchContractDigest` is the canonical digest of the caller task, effective system prompt, model candidates, effective tools/extensions/MCP (including inherited capability ceilings), output binding, and structured-output schema that ordinary foreground and async execution report in results/status/events and metadata.
130
173
 
131
174
  Boundaries:
132
175
 
@@ -210,6 +253,8 @@ Results:
210
253
  - Result mode is explicit. Text remains literal even when it looks like JSON. Structured mode returns the separately captured, schema-validated JSON value.
211
254
  - Terminal usage reports input, output, cache-read, cache-write, cost, turns, tool calls, and duration alongside the effective model and thinking level when known.
212
255
 
256
+ Live update events are bounded progress snapshots, not patches, so consumers should replace the prior snapshot rather than merge it as a delta. Structured delegation coalesces heartbeats whose delegation-visible progress and recent output are unchanged; a duration-only heartbeat therefore does not produce another update. The terminal response remains authoritative for the complete result, error, and final usage details.
257
+
213
258
  Bounds:
214
259
 
215
260
  - Schemas are capped at 64 KiB; tasks and returned text/structured values are capped at 1 MiB, with smaller bounds on identity/configuration strings and a maximum `timeoutMs` of 2,147,483,647.
@@ -260,7 +305,7 @@ Schedules created while a ceiling is active are rejected until durable schedule
260
305
 
261
306
  ## Background-work provider API
262
307
 
263
- Other Pi extensions can make their current-session jobs visible to `subagent_wait` through the process-local provider contract:
308
+ Other Pi extensions can make their current-session jobs visible to `bg_wait` through the process-local provider contract:
264
309
 
265
310
  ```ts
266
311
  import { registerBackgroundWorkProvider } from "@xzzpig/pi-subagents/background-work";
@@ -268,8 +313,8 @@ import { registerBackgroundWorkProvider } from "@xzzpig/pi-subagents/background-
268
313
  const dispose = registerBackgroundWorkProvider({
269
314
  name: "my-background-extension",
270
315
  wakeChannels: ["my-extension:job-finished"],
271
- listActiveWork: () => jobs
272
- .filter((job) => job.status === "running")
316
+ listActiveWork: (context) => jobs
317
+ .filter((job) => job.status === "running" && (!context || job.ownerSessionId === context.sessionId))
273
318
  .map((job) => ({ id: job.id, sessionId: job.ownerSessionId })),
274
319
  reconcile: ({ sessionId, nowMs }) => reconcileJobs(sessionId, nowMs),
275
320
  });
@@ -277,13 +322,16 @@ const dispose = registerBackgroundWorkProvider({
277
322
 
278
323
  Semantics:
279
324
 
280
- - Each item needs a stable provider-local ID and the exact Pi session ID that owns it. `subagent_wait` captures those identities rather than a count, so one job finishing while another starts still satisfies first-completion waits without losing the replacement.
325
+ - Each item needs a stable provider-local ID and the exact Pi session ID that owns it. `bg_wait` captures those identities rather than a count, so one job finishing while another starts still satisfies first-completion waits without losing the replacement.
326
+ - `listActiveWork` receives an optional `{ sessionId, nowMs }` context during snapshots. Providers can use `sessionId` to avoid scanning unrelated work; existing zero-argument `() => items` providers continue to work, and returned items are still validated and filtered to the exact requested session.
281
327
  - It filters snapshots to the active session, fails closed if a provider disappears while its work is tracked, and surfaces malformed snapshots or provider errors with provider context.
282
328
  - Wake channels only shorten polling; validated snapshots remain authoritative.
283
329
  - Providers share a registry through `Symbol.for("pi-subagents.background-work.v1")`, allowing independently loaded extension modules to meet in one Pi process.
284
330
  - Registration is reload-safe: a new provider with the same name replaces the old callback, and the old disposer cannot remove the replacement. Call the disposer during extension shutdown when possible.
285
331
 
286
- Child processes do not gain provider tools or extensions automatically. Add `subagent_wait` to the child agent's `tools` allowlist and load each provider through `extensions` or `subagentOnlyExtensions`. The parent's effective `waitTool` setting is serialized through foreground, async, resume, chain, parallel, and fanout launch paths; `PI_SUBAGENT_WAIT_TOOL_ENABLED` keeps precedence.
332
+ Children do not gain provider tools or extensions automatically. Add `bg_wait` to the child agent's `tools` allowlist and load each provider through `extensions` or `subagentOnlyExtensions`. The parent's effective `waitTool` setting reaches every child through its typed runtime config; `PI_SUBAGENT_WAIT_TOOL_ENABLED` keeps precedence in the parent.
333
+
334
+ Foreground children never load the parent's ambient extensions: they share the parent's process, and loading them would start a second copy of every ambient extension, including this one, inside it. Agents that need MCP tools (`mcpDirectTools`, or MCP tools from an ambient adapter such as pi-mcp-adapter) or models from a provider extension must run as background children (`async: true`), which load the ambient extensions inside the detached runner process unless the agent sets `extensions` or the capability ceiling denies extensions.
287
335
 
288
336
  ## External job provider bridge
289
337
 
@@ -315,7 +363,7 @@ When Pi runs inside [Herdr](https://herdr.dev), pi-subagents automatically repor
315
363
  - The bridge is enabled only when Herdr supplies `HERDR_ENV=1` and `HERDR_PANE_ID`; outside Herdr it registers no listeners or timers.
316
364
  - It restores current-session active runs after `/reload` or `/resume`, refreshes metadata while work is active, and clears it on completion or shutdown.
317
365
  - The bridge uses Herdr's existing `herdr:blocked` sibling event when an async child needs attention, and emits `herdr:busy` while async work remains. Herdr versions that support the sibling event keep the pane's semantic state `working`; older versions ignore it safely and still display the metadata label while the Pi integration remains the lifecycle authority.
318
- - The owning Pi session is the only publisher for its own pane metadata. While active subagents exist, it reports a compact `title-suffix` token: one active run uses that agent name, two or more use the active-run count, and attention adds `⚠`. The suffix is cleared when active work reaches zero.
366
+ - The owning Pi session is the only publisher for its own pane metadata. When an active workflow has an explicit bounded `label`, the newest active label appears in the summary and compact `title-suffix`; overlapping completion restores the previous active label. Raw task and goal prompts never enter Herdr metadata. Without a label, one active run uses its agent name and two or more use the active-run count. Attention adds `⚠`, and the suffix is cleared when active work reaches zero.
319
367
 
320
368
  To show the reported label in the expanded Agent sidebar, include `state_text` or `$summary` in its row layout:
321
369
 
@@ -337,7 +385,7 @@ subagent({ action: "inspector.status", id: "<run-id>", index: 0 })
337
385
  subagent({ action: "inspector.close", id: "<run-id>", index: 0 })
338
386
  ```
339
387
 
340
- The inspector is a raw dashboard pane, not the child process and not a literal attach. It reads lifecycle/status/output/mission artifacts and sends `steer` or `stop` through pi-subagents' existing control inbox. Closing it never stops the run.
388
+ The inspector is a raw dashboard pane, not the child session and not a literal attach. It reads lifecycle/status/output/mission artifacts and sends `steer` or `stop` through pi-subagents' existing control inbox. Closing it never stops the run.
341
389
 
342
390
  Herdr remains optional. Ordinary launches stay headless, and missing/older Herdr versions affect only Herdr-specific inspector and project-pane actions. FleetView opens the selected active async child with `H`. Use `focus` only with `inspector.open`; Herdr 0.7.5 cannot focus an arbitrary existing raw pane id.
343
391
 
@@ -380,7 +428,7 @@ The API returns discriminated structured results with canonical project root, bi
380
428
 
381
429
  A host that embeds this extension owns whether completion wakes can be delivered at all.
382
430
 
383
- Ordinary async and foreground completion wakes use `registerSubagentNotify` and `sendCompletion`. They listen for completion events and deliver through `pi.sendMessage(..., { triggerTurn })`. Session shutdown stops the result watcher and disposes this completion notifier. `createWaitSubscriptionManager` is separate: it is the explicit non-blocking `subagent_wait` subscription path, not the ordinary completion wake path.
431
+ Ordinary async and foreground completion wakes use `registerSubagentNotify` and `sendCompletion`. They listen for completion events and deliver through `pi.sendMessage(..., { triggerTurn })`. Session shutdown stops the result watcher and disposes this completion notifier. `createWaitSubscriptionManager` is separate: it is the explicit non-blocking `bg_wait` subscription path for work without native notification, not the ordinary completion wake path.
384
432
 
385
433
  Detached children do not stop when the session does. They are the host process's children, not the session's, so the run keeps going, completes, and notifies nobody. What is lost is the notification, not the work.
386
434
 
@@ -405,8 +453,15 @@ The main runtime files in this repository:
405
453
  | `src/extension/index.ts` | Extension registration, tool registration, message/render wiring. |
406
454
  | `src/agents/agents.ts` | Agent and chain discovery, frontmatter parsing. |
407
455
  | `src/runs/foreground/subagent-executor.ts` | Main execution routing for single, parallel, chain, management, status, interrupt, and doctor actions. |
408
- | `src/runs/foreground/execution.ts` | Core foreground `runSync` handling. |
409
- | `src/runs/background/subagent-runner.ts` | Detached async runner. |
456
+ | `src/runs/foreground/execution.ts` | Core foreground `runSync` handling: drives one in-process child session per attempt. |
457
+ | `src/runs/shared/child-session.ts` | In-process child session factory (`createAgentSession` behind an injectable seam) and the shared model runtime; used by both launch paths. |
458
+ | `src/runs/shared/child-launch.ts` | Builds the tool plan, typed child runtime config, and session launch for a child in either host process. |
459
+ | `src/runs/shared/child-tool-plan.ts` | Tool, MCP, and extension resolution for a child launch. |
460
+ | `src/runs/shared/child-runtime-config.ts` | `ChildRuntimeConfig`: everything the child-side hooks need. |
461
+ | `src/runs/shared/child-hooks.ts` | The inline hook extensions every child gets (prompt runtime, fast mode, fanout). |
462
+ | `src/runs/background/subagent-runner.ts` | Detached async runner; hosts background child sessions in its own process. |
463
+ | `src/runs/background/run-child-session.ts` | Drives one background child session and mirrors its events into the run artifacts. |
464
+ | `src/runs/background/runner-aliases.ts` | Aliases the host peer packages to the installed pi package for the runner (`JITI_ALIAS`). |
410
465
  | `src/runs/background/async-execution.ts` | Background launch support. |
411
466
  | `src/runs/background/async-status.ts` | Status discovery and formatting for async runs. |
412
467
  | `src/workflows/scripted-workflow.ts` / `src/runs/foreground/subagent-executor.ts` | Scripted workflow orchestration and child launch routing. |
@@ -414,4 +469,4 @@ The main runtime files in this repository:
414
469
  | `src/runs/shared/worktree.ts` | Git worktree isolation. |
415
470
  | `src/intercom/intercom-bridge.ts` | Runtime intercom bridge instructions and diagnostics. |
416
471
  | `src/extension/schemas.ts` / `src/shared/types.ts` | Tool schemas, shared types, and event constants. |
417
- | `test/unit/` / `test/integration/` / `test/e2e/` | Unit, loader-based integration, and real-session E2E tests. |
472
+ | `test/unit/` / `test/integration/` | Unit and loader-based integration tests. |
package/docs/missions.md CHANGED
@@ -95,6 +95,7 @@ subagent({
95
95
  id: "evening-review",
96
96
  name: "Evening review",
97
97
  at: "+30m",
98
+ baseRef: "refs/heads/release",
98
99
  workflowScript: `return runs.run("main", { agent: "reviewer", task: "Review the current diff." })`
99
100
  })
100
101
  ```
@@ -112,6 +113,7 @@ Manage schedules with `schedule.list`, `schedule.show`, `schedule.history`, `sch
112
113
  Behavior:
113
114
 
114
115
  - Runs always launch async with fresh context and disable automatic mission creation; mission attachment is deferred from this first slice.
116
+ - An optional top-level `baseRef` selects the safe Git ref used by managed worktrees (default `HEAD`); it is persisted with the schedule and forwarded on every fire. The source checkout must still be clean.
115
117
  - Definitions, bounded history, append-only events, and per-run receipts are stored with mode `0600`.
116
118
  - `overlap` is currently fixed to `skip`; `catchUp` supports `latest` (default) and `none`.
117
119
  - `schedule.run-due` lets an external launcher start due project work without making `pi-subagents` a daemon.
package/docs/models.md CHANGED
@@ -8,9 +8,10 @@ Builtin agents inherit your current Pi default model. This keeps new installs fr
8
8
  - `subagents.defaultProvider` — a provider preference for bare model ids, such as `llama-3`, when multiple providers expose the same id.
9
9
  - `subagents.agentOverrides.<name>.model` — pin one role.
10
10
  - `subagents.agentOverrides.<name>.defaultProvider` — choose or clear the provider preference for one role.
11
+ - `subagents.agentOverridesByProvider.<provider>.<name>` — layer role fields for the active parent provider.
11
12
  - Per-run overrides — for one launch only.
12
13
 
13
- Precedence, strongest first: per-run override → agent frontmatter `model` → `agentOverrides.<name>.model` → `subagents.defaultModel` → the parent session model. A provider preference does not replace this order; it only resolves bare model ids when the active registry has more than one match. Fully qualified `provider/model` strings still win exactly.
14
+ Precedence, strongest first: per-run override → provider-scoped role override → `agentOverrides.<name>.model` → agent frontmatter `model` → `subagents.defaultModel` → the parent session model. A provider preference does not replace this order; it only resolves bare model ids when the active registry has more than one match. Fully qualified `provider/model` strings still win exactly.
14
15
 
15
16
  Use `model: "inherit"` in agent frontmatter or `agentOverrides.<name>.model` to select the current parent session model explicitly.
16
17
 
@@ -36,6 +37,28 @@ In `~/.pi/agent/settings.json` (user) or the project config settings file (`.pi/
36
37
  }
37
38
  ```
38
39
 
40
+ To keep one role definition but configure it differently for work and personal providers, add the unambiguous provider map beside `agentOverrides`:
41
+
42
+ ```json
43
+ {
44
+ "subagents": {
45
+ "agentOverrides": {
46
+ "worker": { "thinking": "medium" }
47
+ },
48
+ "agentOverridesByProvider": {
49
+ "github-copilot": {
50
+ "worker": { "model": "github-copilot/gpt-5-mini" }
51
+ },
52
+ "openrouter": {
53
+ "worker": { "model": "openrouter/openai/gpt-5-mini" }
54
+ }
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ The provider key comes from the active parent session model (or an explicit host `preferredProvider`) before fallback selection. Provider-scoped fields layer over the ordinary override in the same settings file; project settings still win over user settings. A fallback attempt does not switch the selected provider configuration.
61
+
39
62
  For one run, put the override in the command:
40
63
 
41
64
  ```text
@@ -51,14 +74,14 @@ For a persistent role override with a backup model for provider failures:
51
74
  "reviewer": {
52
75
  "model": "anthropic/claude-sonnet-4",
53
76
  "thinking": "high",
54
- "fallbackModels": ["openai/gpt-5-mini"]
77
+ "fallbackModels": ["openai-codex/gpt-5.6-luna:low"]
55
78
  }
56
79
  }
57
80
  }
58
81
  }
59
82
  ```
60
83
 
61
- `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` still win, and explicit agent frontmatter still wins over the global default. The same `agentOverrides` block can change `tools`, `skills`, inherited context, prompt text, or disable a builtin (see [agents.md](agents.md)). Matching user and project agents also receive override fields that their frontmatter leaves unset, so a shared project config agent can keep the persona while local settings choose the model or provider.
84
+ `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.
62
85
 
63
86
  ## Fast mode
64
87
 
@@ -77,7 +100,7 @@ A setup that works well in practice: route agents by task shape instead of runni
77
100
 
78
101
  The routing rule: use the capability tiers (1–3) when the task is well-scoped, and the intent tier (4) when scoping or judging is the task itself.
79
102
 
80
- Give tier-4 agents cross-provider `fallbackModels` so subscription usage limits degrade gracefully instead of failing the run. Fallback triggers on rate-limit and overload errors automatically:
103
+ Give tier-4 agents cross-provider `fallbackModels` so subscription usage limits degrade gracefully instead of failing the run. Fallback triggers on retryable provider/model failures such as rate-limit, overload, unavailable-model, and provider-reported timeout errors. The outer run-level `timeoutMs` / `maxRuntimeMs` deadline is terminal and does not start another fallback attempt:
81
104
 
82
105
  ```yaml
83
106
  ---
@@ -93,7 +116,7 @@ One interaction worth knowing for tier 4: forked context over an Anthropic paren
93
116
 
94
117
  ## Thinking level defaults
95
118
 
96
- Set `subagents.defaultThinking` to give builtin, package, user, and project agents without a `thinking` value a shared thinking level, independent of the parent session's default. Project settings win over user settings. Explicit frontmatter, `agentOverrides.<name>.thinking`, and per-run thinking overrides still win. `thinking: false` remains an explicit opt-out:
119
+ Set `subagents.defaultThinking` to give builtin, package, user, and project agents without a `thinking` value a shared thinking level, independent of the parent session's default. Project settings win over user settings. Matching `agentOverrides.<name>.thinking` and per-run thinking overrides replace frontmatter; otherwise explicit frontmatter remains in effect. `thinking: false` remains an explicit opt-out:
97
120
 
98
121
  ```json
99
122
  {
@@ -106,7 +129,7 @@ Set `subagents.defaultThinking` to give builtin, package, user, and project agen
106
129
  }
107
130
  ```
108
131
 
109
- If your provider rejects model IDs with thinking suffixes, set `subagents.disableThinking: true` in user or project settings. That clears bundled builtin thinking defaults in one place. An explicit higher-precedence `agentOverrides.<name>.thinking` value can opt a role back in. Existing custom-agent frontmatter remains authoritative.
132
+ If your provider rejects model IDs with thinking suffixes, set `subagents.disableThinking: true` in user or project settings. That clears bundled builtin thinking defaults in one place. An explicit higher-precedence `agentOverrides.<name>.thinking` value can opt a role back in or replace custom-agent frontmatter thinking.
110
133
 
111
134
  ### Thinking ceiling
112
135
 
@@ -131,7 +154,7 @@ Set `subagents.defaultExtensions` to give builtin, package, user, and project ag
131
154
  - Empty array: sets `extensions: []` for agents that do not explicitly define it, disabling ambient extension loading.
132
155
  - Non-empty array: supplies that allowlist to agents that do not explicitly define one.
133
156
 
134
- Project settings win over user settings. Use `agentOverrides.<name>.extensions` for per-agent settings; explicit custom-agent frontmatter remains authoritative.
157
+ Project settings win over user settings. Use `agentOverrides.<name>.extensions` for per-agent settings; a matching override replaces custom-agent frontmatter for that field.
135
158
 
136
159
  ```json
137
160
  {
@@ -182,9 +205,9 @@ To keep subagents inside a budget or compliance profile, enforce a model scope.
182
205
  "modelScope": {
183
206
  "enforce": true,
184
207
  "strict": true,
185
- "allow": ["inherit", "openai/gpt-5-*"],
208
+ "allow": ["inherit", "openai/gpt-5-*", "openai-codex/gpt-5.6-*"],
186
209
  "agents": {
187
- "worker": { "allow": ["openai/gpt-5-mini"] },
210
+ "worker": { "allow": ["openai-codex/gpt-5.6-luna"] },
188
211
  "reviewer": { "allow": ["inherit"] }
189
212
  }
190
213
  }