@xzzpig/pi-subagents 0.15.1 → 0.18.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 (135) hide show
  1. package/CHANGELOG.md +178 -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 +19 -12
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/fork-extensions.md +23 -15
  12. package/docs/models.md +5 -3
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +4 -4
  15. package/docs/tool-reference.md +40 -19
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +57 -3
  18. package/inspector-runner.mjs +1 -1
  19. package/package.json +14 -8
  20. package/prompts/council.md +6 -3
  21. package/runner-peer-loader.mjs +4 -7
  22. package/runner-peer-preload.mjs +5 -7
  23. package/skills/pi-subagents/SKILL.md +1 -0
  24. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  25. package/skills/pi-subagents/references/execution-controls.md +6 -4
  26. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  27. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  28. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  29. package/src/agents/agent-eject.ts +3 -3
  30. package/src/agents/agent-management.ts +61 -52
  31. package/src/agents/agent-memory.ts +90 -3
  32. package/src/agents/agent-serializer.ts +4 -4
  33. package/src/agents/agents.ts +125 -51
  34. package/src/agents/global-npm-root.ts +58 -0
  35. package/src/agents/proactive-skills.ts +4 -1
  36. package/src/agents/runtime-agent-registry.ts +14 -11
  37. package/src/agents/skills.ts +42 -9
  38. package/src/api/delegation.ts +15 -0
  39. package/src/api/inspectors.ts +27 -0
  40. package/src/api/preflight.ts +60 -60
  41. package/src/extension/doctor.ts +9 -4
  42. package/src/extension/fanout-child.ts +8 -0
  43. package/src/extension/index.ts +101 -48
  44. package/src/extension/rpc.ts +10 -1
  45. package/src/extension/schemas.ts +12 -6
  46. package/src/extension/subagent-guide.ts +12 -4
  47. package/src/extension/tool-activation.ts +197 -0
  48. package/src/extension/tool-description.ts +1 -1
  49. package/src/inspectors/ghostty/plugin.ts +13 -1
  50. package/src/inspectors/plugins.ts +70 -3
  51. package/src/intercom/intercom-bridge.ts +2 -0
  52. package/src/intercom/native-supervisor-channel.ts +22 -15
  53. package/src/intercom/result-intercom.ts +4 -0
  54. package/src/runs/background/active-async-capacity.ts +3 -25
  55. package/src/runs/background/async-execution.ts +100 -140
  56. package/src/runs/background/async-job-tracker.ts +28 -34
  57. package/src/runs/background/async-resume.ts +16 -8
  58. package/src/runs/background/async-status.ts +2 -0
  59. package/src/runs/background/binary-bootstrap.ts +34 -6
  60. package/src/runs/background/fleet-view.ts +51 -7
  61. package/src/runs/background/notify.ts +93 -7
  62. package/src/runs/background/pid-namespace.ts +18 -0
  63. package/src/runs/background/process-terminal-candidate.ts +98 -0
  64. package/src/runs/background/process-terminal.ts +17 -96
  65. package/src/runs/background/result-watcher.ts +1 -1
  66. package/src/runs/background/retained-children.ts +3 -2
  67. package/src/runs/background/run-child-session.ts +16 -5
  68. package/src/runs/background/run-id-resolver.ts +10 -5
  69. package/src/runs/background/run-status.ts +10 -4
  70. package/src/runs/background/runner-aliases.ts +25 -15
  71. package/src/runs/background/runner-child-launch.ts +1 -2
  72. package/src/runs/background/runner-startup-failure.ts +56 -0
  73. package/src/runs/background/stale-run-reconciler.ts +19 -3
  74. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  75. package/src/runs/background/subagent-runner.ts +96 -287
  76. package/src/runs/background/wait-tool.ts +2 -0
  77. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  78. package/src/runs/foreground/execution.ts +217 -250
  79. package/src/runs/foreground/prompt-audit.ts +3 -9
  80. package/src/runs/foreground/subagent-executor.ts +377 -119
  81. package/src/runs/shared/acceptance.ts +167 -68
  82. package/src/runs/shared/capability-ceiling.ts +4 -1
  83. package/src/runs/shared/child-hooks.ts +1 -16
  84. package/src/runs/shared/child-launch.ts +22 -14
  85. package/src/runs/shared/child-runtime-config.ts +3 -0
  86. package/src/runs/shared/child-session.ts +52 -2
  87. package/src/runs/shared/child-tool-plan.ts +23 -113
  88. package/src/runs/shared/dynamic-fanout.ts +1 -1
  89. package/src/runs/shared/external-cli-runner.ts +3 -1
  90. package/src/runs/shared/external-job-bridge.ts +54 -0
  91. package/src/runs/shared/git-environment.ts +29 -0
  92. package/src/runs/shared/mcp-config-sources.ts +3 -0
  93. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  94. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  95. package/src/runs/shared/model-resolution.ts +6 -1
  96. package/src/runs/shared/nested-events.ts +67 -55
  97. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  98. package/src/runs/shared/parallel-utils.ts +2 -1
  99. package/src/runs/shared/pi-spawn.ts +92 -6
  100. package/src/runs/shared/profile-launch-env.ts +10 -2
  101. package/src/runs/shared/single-output.ts +11 -2
  102. package/src/runs/shared/structured-output.ts +227 -7
  103. package/src/runs/shared/subagent-control.ts +2 -16
  104. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  105. package/src/runs/shared/tool-availability.ts +2 -2
  106. package/src/runs/shared/tool-budget.ts +21 -0
  107. package/src/runs/shared/usage-reconciliation.ts +73 -0
  108. package/src/runs/shared/worktree.ts +35 -8
  109. package/src/shared/child-session-name.ts +4 -2
  110. package/src/shared/fork-context.ts +11 -4
  111. package/src/shared/launch-contract.ts +1 -1
  112. package/src/shared/pruned-fork.ts +69 -56
  113. package/src/shared/types.ts +52 -16
  114. package/src/slash/delegation-adapters.ts +25 -1
  115. package/src/slash/prompt-template-bridge.ts +16 -1
  116. package/src/slash/prompt-workflows.ts +12 -1
  117. package/src/slash/slash-commands.ts +7 -241
  118. package/src/slash/subagent-cost.ts +313 -0
  119. package/src/slash/subagents-admin.ts +28 -29
  120. package/src/tui/fleet-status.ts +24 -2
  121. package/src/tui/fleet.ts +7 -4
  122. package/src/tui/render.ts +53 -19
  123. package/src/watchdog/diff-tool.ts +24 -3
  124. package/src/watchdog/permission-arbiter.ts +13 -15
  125. package/src/watchdog/register-child.ts +10 -2
  126. package/src/watchdog/review.ts +14 -14
  127. package/src/watchdog/runtime.ts +2 -1
  128. package/src/watchdog/turn-delta.ts +11 -5
  129. package/src/workflows/scripted-workflow.ts +109 -23
  130. package/src/workflows/workflow-child-summary.ts +4 -2
  131. package/src/workflows/workflow-settlement.ts +4 -1
  132. package/src/runs/shared/completion-evidence.ts +0 -89
  133. package/src/runs/shared/completion-guard.ts +0 -255
  134. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  135. package/src/runs/shared/task-intent.ts +0 -244
@@ -114,7 +114,7 @@ pi.events.emit("subagents:rpc:v1:request", {
114
114
  });
115
115
  ```
116
116
 
117
- The RPC methods are `ping`, `status`, `manage`, `spawn`, `steer`, `interrupt`, `stop`, and `resume`. `status`, `manage`, `steer`, `interrupt`, and `resume` reuse normal package-owned actions.
117
+ The RPC methods are `ping`, `status`, `manage`, `spawn`, `steer`, `interrupt`, `stop`, `resume`, and `cost`. `status`, `manage`, `steer`, `interrupt`, and `resume` reuse normal package-owned actions.
118
118
 
119
119
  Method notes:
120
120
 
@@ -122,6 +122,7 @@ Method notes:
122
122
  - `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.
123
123
  - `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.
124
124
  - `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.
125
+ - `cost` returns the same parent-plus-child accounting `/subagent-cost` renders, as data: `{ version: 1, parent, children, childTotal, total, unresolvedAsyncChildren }`, where each usage is `{ input, output, cacheRead, cacheWrite, cost, turns }` and each child carries `label`, `agent`, `runId`, `usage`, and `sessionFile` when known. It is read-only and walks the current session branch plus existing run artifacts, so request it on your own turn boundaries (for example after `agent_settled` or an async completion wake), not on a timer. `unresolvedAsyncChildren` counts async children whose metadata could not be read; treat `childTotal` as a lower bound when it is non-zero, exactly as documented for `/subagent-cost` in [observability.md](observability.md). `ping.capabilities.cost` advertises `{ version: 1 }`.
125
126
  - `stop` targets current-session top-level async runs through the stop control channel and records a `stopped` lifecycle instead of reporting a timeout.
126
127
  - `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.
127
128
 
@@ -136,6 +137,7 @@ Capability advertisements on `ping`:
136
137
  - `resume` — the revival seam described above.
137
138
  - `statusProjection: { version: 1, untargeted: "in-memory-when-ready", targeted: "executor" }` — untargeted status may use restored bounded projections; targeted or rich status remains executor-backed.
138
139
  - `fleetStatus: { version: 1 }` — successful `status` replies additionally include `data.fleet`.
140
+ - `cost: { version: 1 }` — the `cost` method is available and returns the versioned report shape above.
139
141
 
140
142
  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.
141
143
 
@@ -188,6 +190,8 @@ const registration = request.result.registration;
188
190
 
189
191
  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.
190
192
 
193
+ A registered agent follows the operator's subagent model settings like any other agent: `subagents.defaultModel`, `defaultProvider`, and `defaultThinking` fill a definition that omits `model` or `thinking`, and the `model`, `defaultProvider`, `fast`, and `thinking` fields of `agentOverrides.<name>` win over the definition. Every other definition field stays extension-owned, and other override fields are ignored for runtime agents. Set `model` in the definition only when the agent must not follow operator model settings; `model: "inherit"` selects the parent session model explicitly.
194
+
191
195
  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.
192
196
 
193
197
  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.
@@ -329,7 +333,7 @@ Identity:
329
333
  Results:
330
334
 
331
335
  - Result mode is explicit. Text remains literal even when it looks like JSON. Structured mode returns the separately captured, schema-validated JSON value.
332
- - Terminal usage reports input, output, cache-read, cache-write, cost, turns, tool calls, and duration alongside the effective model and thinking level when known.
336
+ - Terminal usage reports input, output, cache-read, cache-write, cost, turns, tool calls, and duration alongside the effective model and thinking level when known. Native child totals are reconciled per attempt from post-prompt session messages: complete persisted fields replace live aggregates, while incomplete fields retain them.
333
337
 
334
338
  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.
335
339
 
@@ -433,7 +437,7 @@ The provider returns handles with `providerJobId`, `state`, optional `handleUrl`
433
437
 
434
438
  `followUp(input)` is optional. When it is present, a completed external-job run can be continued with `subagent({ action: "resume", id: "<run>", message: "..." })`. Pi sends the completed parent provider job id plus a stable `requestId` and `requestDigest`. The provider must continue that parent conversation or fail closed. It must not open a fresh thread when the parent conversation is missing.
435
439
 
436
- The async runner process does not import provider internals. It writes operation requests into its async run directory. The parent Pi process services those requests against the registered provider and writes operation responses. If the provider is not registered, the bridge fails closed with an actionable error. If a run is recovered after provider job metadata exists, the runner calls `reattach` and `result`; it does not call `start` or `follow-up` again.
440
+ The async runner process does not import provider internals. It writes operation requests into its async run directory. The Pi process of the session that launched the run services those requests against the registered provider and writes operation responses. A child session services the external-job runs it launches. Register the provider in that child too, for example through the child agent's `extensions`. If the provider is not registered, the bridge fails closed with an actionable error. If a run is recovered after provider job metadata exists, the runner calls `reattach` and `result`; it does not call `start` or `follow-up` again.
437
441
 
438
442
  ## Inspect integration
439
443
 
@@ -446,7 +450,69 @@ subagent({ action: "inspector.status", id: "<run-id>", index: 0 })
446
450
  subagent({ action: "inspector.close", id: "<run-id>", index: 0 })
447
451
  ```
448
452
 
449
- `inspector.command` returns a standalone runner command without contacting a host or writing a binding. `inspector.open` selects an available bundled inspector plugin. `status` and `close` select the plugin that owns the run binding and report clearly when that plugin does not support the requested lifecycle action. Without an available plugin, `open` fails closed with an actionable message; ordinary launches remain headless. Closing an inspector never stops the run.
453
+ `inspector.command` returns a standalone runner command without contacting a host or writing a binding. `inspector.open` selects an available built-in or externally registered inspector plugin. `status` and `close` select the plugin that owns the run binding and report clearly when that plugin does not support the requested lifecycle action. Without an available plugin, `open` fails closed with an actionable message; ordinary launches remain headless. Closing an inspector never stops the run.
454
+
455
+ ### Register an external inspector
456
+
457
+ A loaded Pi extension can add an inspector through the synchronous
458
+ `pi-subagents:inspector-register:v1` event. This lets terminal integrations use
459
+ Fleet's existing Enter/H actions without modifying pi-subagents. Registration
460
+ adds no runner, tool, or configuration option.
461
+
462
+ ```ts
463
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
464
+ import type { InspectorRegistration, InspectorRegistrationRequest } from "pi-subagents/inspectors";
465
+ import { myInspector } from "./my-inspector.ts"; // Your InspectorPlugin implementation.
466
+
467
+ export default function (pi: ExtensionAPI) {
468
+ let registration: InspectorRegistration | undefined;
469
+ pi.on("session_start", () => {
470
+ registration?.dispose();
471
+ const request: InspectorRegistrationRequest = { version: 1, plugin: myInspector };
472
+ pi.events.emit("pi-subagents:inspector-register:v1", request);
473
+ if (!request.result) throw new Error("pi-subagents inspector registration is unavailable.");
474
+ if (!request.result.ok) throw request.result.error;
475
+ registration = request.result.registration;
476
+ });
477
+ pi.on("session_shutdown", () => registration?.dispose());
478
+ }
479
+ ```
480
+
481
+ `pi-subagents/inspectors` exports the event name as `INSPECTOR_REGISTER_EVENT`,
482
+ the request and registration types, and the existing `InspectorPlugin`,
483
+ `InspectorContext`, `InspectorLaunch`, `InspectorParams`, and `InspectorTarget`
484
+ types. When pi-subagents is a resolvable dependency, `registerInspector(pi, plugin)`
485
+ emits the same request and returns the registration or throws. Independently
486
+ installed extensions can use the event directly; type-only imports need only a
487
+ development dependency and create no runtime module dependency.
488
+
489
+ An `InspectorPlugin` supplies:
490
+
491
+ - `name`: 1–128 letters, digits, dots, underscores, or hyphens, starting with a letter or digit.
492
+ - `available(context)`: whether this terminal host can open an inspector; may be async.
493
+ - `open(context, launch, params)`: open the supplied inspector command and return an `AgentToolResult<Details>`, like the built-in plugins. `launch.executable` and `launch.argv` carry the existing runner, target, trusted session roots, and steer/stop permission flags. Preserve these arguments and respect `params.focus`.
494
+ - `owns(context)`: synchronously check whether the provider owns an inspector binding for this target.
495
+ - Optional `status(context)` and `close(context)`: inspect or close that binding, returning the same result type. Closing an inspector must not stop the subagent.
496
+
497
+ The existing dispatcher tries Herdr, then Ghostty, then external providers in
498
+ registration order. Names are case-sensitive; duplicate names and the built-in
499
+ names `herdr` and `ghostty` are rejected. A selected provider's failure is not
500
+ retried through another provider. Status/close use the first provider whose
501
+ `owns` returns true; unavailable lifecycle methods remain explicit errors.
502
+ Providers own their pane bindings and must verify ownership before closing one.
503
+
504
+ Registrations belong to the pi-subagents runtimes listening on the Pi event bus,
505
+ not the consumer module; they survive runtime replacement, are isolated from
506
+ child runtimes and other Pi instances, and are cleared when the last owner shuts
507
+ down or reloads. Disposal is idempotent, removes callbacks without closing panes,
508
+ and takes effect even while Fleet is open because it resolves providers per
509
+ action. Providers receive the current action context, so do not capture a stale
510
+ session context; dispose before re-registering on session changes. Unsupported
511
+ versions and malformed plugins return `{ ok: false, error }`, and the first owner
512
+ to fill `result` handles the request.
513
+
514
+ This is a trusted-code integration, not a sandbox. Registration does not change
515
+ run resolution, child-safe restrictions, authority policy, or supervisor routing.
450
516
 
451
517
  ### Herdr inspector plugin
452
518
 
@@ -8,8 +8,8 @@ files stay byte-identical to upstream.
8
8
  ## Sandbox profiles
9
9
 
10
10
  Use `sandbox: <profile-name>` only for a native Pi child. The profile is resolved
11
- from the global `pi-sandbox` configuration, never from an agent file or a project
12
- profile registry:
11
+ from the global `pi-sandbox` configuration and, when the project is trusted,
12
+ from the project `.pi/sandbox.json` registry — never from an agent file:
13
13
 
14
14
  ```yaml
15
15
  ---
@@ -37,24 +37,28 @@ failure and never excludes the model from later runs.
37
37
  The field is rejected for `external-cli` and `external-job` runners because they
38
38
  do not host a Pi child extension. It also cannot be an object, `false`, an empty
39
39
  value, or an inline allow/deny policy. Define the actual network and filesystem
40
- rules in global `pi-sandbox` `profiles` instead.
40
+ rules in `pi-sandbox` `profiles` (global, or trusted project) instead.
41
41
 
42
42
  A profile chosen by a project-scoped agent or project override is used only when
43
43
  the host marks that project trusted. Otherwise the launch reports an actionable
44
- trust error. In a headless child, accesses outside the profile's preconfigured
45
- network/read/write rules are blocked; pi-sandbox does not use Permission System
46
- or supervisor forwarding to ask the parent for an approval. See
44
+ trust error. A project's own profile definitions likewise participate only for a
45
+ trusted project; an untrusted project's `profiles` registry is ignored with a
46
+ warning and never fails the launch. In a headless child, accesses outside the
47
+ profile's preconfigured network/read/write rules are blocked; pi-sandbox does not
48
+ use Permission System or supervisor forwarding to ask the parent for an approval.
49
+ See
47
50
  [`pi-sandbox`'s README](https://github.com/xzzpig/pi-extensions/tree/main/packages/pi-sandbox#named-profiles-for-subagents)
48
51
  for profile inheritance and merge rules.
49
52
 
50
53
  ## Permission profiles
51
54
 
52
55
  Use `permission-profile: <name>` to select a named policy profile from the
53
- **global-only** `profiles` registry in `pi-permission-system`'s config
54
- (`<agentDir>/extensions/pi-permission-system/config.json`). It is a selector
55
- only — the actual rules (tool scalars, `bash`/`mcp`/`skill`/`external_directory`
56
- pattern maps, `'*'` fallback) live in that registry and always resolve from the
57
- child's own global config:
56
+ `profiles` registry in `pi-permission-system`'s config — the global file
57
+ (`<agentDir>/extensions/pi-permission-system/config.json`) and, when the project
58
+ is trusted, the project file (`<cwd>/.pi/extensions/pi-permission-system/config.json`).
59
+ It is a selector only — the actual rules (tool scalars, `bash`/`mcp`/`skill`/`external_directory`
60
+ pattern maps, `'*'` fallback) live in those registries and always resolve from the
61
+ child's own configuration:
58
62
 
59
63
  ```yaml
60
64
  ---
@@ -72,8 +76,8 @@ installed `pi-permission-system` extension into the child launch even when
72
76
  `extensions` is an explicit allowlist, so the child's permission system applies
73
77
  the selected profile. The env channel carries a bare validated name — raw
74
78
  policy is never transmitted — and the rules are always read from the child's
75
- own global config, so the profile means the same policy regardless of which
76
- host launches the agent. Selection precedence inside the permission system is
79
+ own config, so the profile means the same policy regardless of which host
80
+ launches the agent. Selection precedence inside the permission system is
77
81
  env > project agent file > global agent file.
78
82
 
79
83
  The launch fails closed when a profile is declared but `pi-permission-system`
@@ -88,8 +92,12 @@ its pre-change behavior exactly.
88
92
  The profile merges between the project config and the agent's own `permission:`
89
93
  block: patterns the profile does not mention keep the lower scopes' rules
90
94
  (global denies survive), and `permission:` overrides the profile per pattern.
91
- A profile selected by a **project** agent file participates only when the host
92
- marks that project trusted.
95
+ A same-named global and trusted-project profile merge per pattern (origins
96
+ `profile-global` / `profile-project`), so a global denial the project profile
97
+ does not mention survives. A profile selected by a **project** agent file
98
+ participates only when the host marks that project trusted; a project's
99
+ profile definitions are likewise applied only for a trusted project, and an
100
+ untrusted project's registry is ignored with a warning.
93
101
 
94
102
  ## Context injection
95
103
 
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
 
@@ -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
+ `workflowScript` 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 `workflowScript` 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
 
@@ -39,11 +39,11 @@ For a focused diagnostic, use `node test/smoke/standalone-background.mjs "$relea
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,6 +2,8 @@
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
@@ -93,9 +95,9 @@ The complete plain-JSON inventory is validated before the first launch (maximum
93
95
  | `agent` | string | - | One direct child or agent-management target. Workflow child agents are set inside `runs.run` or `runs.all`. |
94
96
  | `task` | string | agent default | Direct child's task; requires `agent`, excludes `action` and workflow inputs. `agent` may also select a management target. |
95
97
  | `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"`. |
98
+ | `topic` | `overview \| workflows \| agents \| missions \| observability \| tool-reference \| configuration \| models \| watchdog \| extension-api \| council` | `overview` | Packaged guide topic for `action: "guide"`. |
97
99
  | `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`. |
100
+ | `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
101
  | `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
102
  | `missionId` | string | - | Attach a workflow to an existing project mission instead of creating its default enclosing mission. |
101
103
  | `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. |
@@ -115,20 +117,22 @@ The complete plain-JSON inventory is validated before the first launch (maximum
115
117
  | `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. |
116
118
  | `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
119
  | `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. |
120
+ | `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
121
  | `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
122
  | `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. |
123
+ | `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. |
124
+ | `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. |
125
+ | `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. |
126
+ | `preflight` | object | none | Advisory lane hints for `workflowScript` or `workflowScriptPath` only; not accepted with named workflows or direct children. See [bounded workflows](workflows.md#opt-in-bounded-workflows). |
123
127
  | `cwd` | string | runtime cwd | Override working directory. With `machine`, the directory on that machine. |
124
128
  | `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. |
129
+ | `maxOutput` | object | none | Final output truncation limits `{ bytes?, lines? }`. Only applied when set; there is no default cap on the inline path, so use `outputMode: "file-only"` for large outputs. |
126
130
  | `artifacts` | boolean | true | Write debug artifacts. |
127
131
  | `includeProgress` | boolean | false | Include full progress in result. |
128
132
  | `share` | boolean | false | Upload session export to GitHub Gist. |
129
133
  | `sessionDir` | string | derived | Override session log directory. |
130
134
  | `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`. |
135
+ | `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
136
 
133
137
  ### Budget guidance for writers
134
138
 
@@ -142,7 +146,7 @@ Explicit `context: "fork"` fails fast when the parent session is not persisted,
142
146
 
143
147
  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
148
 
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.
149
+ 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
150
 
147
151
  ### Workflow steering
148
152
 
@@ -179,7 +183,7 @@ Workflows get `await state.get(key)` and `await state.set(key, value)` through t
179
183
 
180
184
  ### Retained children
181
185
 
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`:
186
+ 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
187
 
184
188
  ```js
185
189
  { workflowScript: `
@@ -196,7 +200,7 @@ Each workflow key identifies one result lane. Use a new stable workflow key for
196
200
 
197
201
  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.
198
202
 
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`.
203
+ 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
204
 
201
205
  `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
206
 
@@ -204,7 +208,7 @@ For a simple implementation challenge outside a workflow script, send the challe
204
208
 
205
209
  ### Guide
206
210
 
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.
211
+ `{ 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
212
 
209
213
  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
214
 
@@ -242,7 +246,7 @@ Agent definitions are not loaded into context by default. Management actions let
242
246
 
243
247
  { action: "update", agent: "code-analysis.scout", config: { model: "openai/gpt-4o" } }
244
248
  { 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
249
+ { action: "update", agent: "code-analysis.scout", config: { acceptanceRole: false } } // restore default lightweight attestation
246
250
  { action: "delete", agent: "scout" }
247
251
 
248
252
  { action: "eject", agent: "reviewer" }
@@ -349,7 +353,7 @@ subagent({ action: "doctor" })
349
353
 
350
354
  - Multi-child async runs and remembered foreground single, parallel, or chain runs can be revived by passing `index` to choose the child.
351
355
  - 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.
356
+ - 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
357
  - 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
358
  - 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
359
 
@@ -381,6 +385,8 @@ The `/subagents-steer <run-id> [--child <child-id>] <message>` slash command is
381
385
 
382
386
  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
387
 
388
+ 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.
389
+
384
390
  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
391
 
386
392
  ```ts
@@ -406,17 +412,32 @@ When one host-run command is the entire verification contract, use the `gate` sh
406
412
 
407
413
  `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
414
 
415
+ ### Typed gates
416
+
417
+ A gate given as `{ command, output: "json" }` runs like a string gate, and then parses the command's stdout:
418
+
419
+ ```js
420
+ { workflowScript: `return runs.run("review", {
421
+ agent: "reviewer", task: "Review the change", output: "reports/review.md", outputMode: "file-only",
422
+ gate: { command: "classify --report reports/review.md", output: "json",
423
+ schema: { type: "object", properties: { verdict: { enum: ["ok", "blocked"] } }, required: ["verdict"] } }
424
+ })` }
425
+ ```
426
+
427
+ - 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.
428
+ - 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.
429
+ - 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.
430
+ - Typed gates are never memoized: their input (a report, a log) can change without the tracked tree changing.
431
+ - `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.
432
+ - `runs.lanes` treats a bridged `structuredOutput.verdict === "blocked"` like any other blocked stage. Scripts read the value as `result.structuredOutput`.
433
+
409
434
  ### Levels and inference
410
435
 
411
436
  Acceptance evidence levels are `auto`, `none`, `attested`, `checked`, and `verified`. `acceptance: "auto"` is the default.
412
437
 
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.
438
+ 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
439
 
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.
440
+ 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
441
 
421
442
  Edge cases:
422
443
 
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.