@xzzpig/pi-subagents 0.4.2 → 0.6.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 (128) hide show
  1. package/CHANGELOG.md +172 -1
  2. package/README.md +8 -0
  3. package/agents/oracle.md +3 -1
  4. package/agents/reviewer.md +1 -0
  5. package/agents/scout.md +2 -2
  6. package/agents/worker.md +2 -1
  7. package/async-retention-discovery-worker.mjs +180 -0
  8. package/docs/agents.md +79 -2
  9. package/docs/configuration.md +42 -14
  10. package/docs/extension-api.md +45 -2
  11. package/docs/models.md +2 -0
  12. package/docs/observability.md +41 -5
  13. package/docs/tool-reference.md +38 -39
  14. package/docs/workflows.md +173 -3
  15. package/package.json +13 -10
  16. package/prompts/council.md +48 -0
  17. package/skills/council-mode/SKILL.md +230 -0
  18. package/skills/pi-subagents/SKILL.md +8 -4
  19. package/skills/pi-subagents/references/constraints-and-recipes.md +13 -6
  20. package/skills/pi-subagents/references/execution-controls.md +40 -15
  21. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  22. package/skills/pi-subagents/references/multi-lane-orchestration.md +39 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +4 -2
  24. package/src/agents/agent-management.ts +158 -357
  25. package/src/agents/agent-serializer.ts +4 -0
  26. package/src/agents/agents.ts +227 -53
  27. package/src/agents/builtin-names.ts +9 -0
  28. package/src/agents/runtime-agent-registry.ts +422 -0
  29. package/src/agents/skills.ts +1 -1
  30. package/src/api/agents.ts +7 -0
  31. package/src/api/external-job-provider.ts +186 -0
  32. package/src/api/preflight.ts +37 -9
  33. package/src/api/shared-types.ts +2 -0
  34. package/src/extension/config.ts +6 -3
  35. package/src/extension/context-injection.ts +118 -0
  36. package/src/extension/doctor.ts +15 -6
  37. package/src/extension/fanout-child.ts +2 -2
  38. package/src/extension/index.ts +224 -90
  39. package/src/extension/public-execution.ts +31 -2
  40. package/src/extension/rpc.ts +41 -1
  41. package/src/extension/schemas.ts +17 -37
  42. package/src/extension/tool-description.ts +35 -24
  43. package/src/inspectors/herdr/actions.ts +2 -2
  44. package/src/inspectors/herdr/inspector-runner.ts +2 -1
  45. package/src/inspectors/herdr/project-panes.ts +2 -2
  46. package/src/intercom/native-supervisor-channel.ts +32 -10
  47. package/src/missions/lifecycle.ts +6 -1
  48. package/src/missions/store.ts +4 -9
  49. package/src/missions/workflow-state.ts +2 -2
  50. package/src/profiles/profiles.ts +3 -1
  51. package/src/runs/background/active-run-index.ts +31 -8
  52. package/src/runs/background/async-execution.ts +70 -41
  53. package/src/runs/background/async-job-tracker.ts +24 -7
  54. package/src/runs/background/async-resume.ts +49 -16
  55. package/src/runs/background/async-retention.ts +886 -0
  56. package/src/runs/background/async-status-snapshot.ts +14 -5
  57. package/src/runs/background/async-status.ts +39 -53
  58. package/src/runs/background/auto-drain.ts +1 -0
  59. package/src/runs/background/chain-append.ts +3 -33
  60. package/src/runs/background/completion-dedupe.ts +5 -1
  61. package/src/runs/background/completion-replay.ts +22 -12
  62. package/src/runs/background/control-channel.ts +14 -68
  63. package/src/runs/background/fleet-view.ts +68 -19
  64. package/src/runs/background/index-segment.ts +59 -0
  65. package/src/runs/background/inspect-rpc.ts +443 -0
  66. package/src/runs/background/notify.ts +31 -5
  67. package/src/runs/background/result-files.ts +158 -90
  68. package/src/runs/background/result-watcher.ts +124 -20
  69. package/src/runs/background/resume-guidance.ts +8 -5
  70. package/src/runs/background/retained-children.ts +13 -3
  71. package/src/runs/background/run-id-query.ts +7 -0
  72. package/src/runs/background/run-id-resolver.ts +11 -9
  73. package/src/runs/background/run-status.ts +27 -18
  74. package/src/runs/background/scheduled-runs.ts +24 -4
  75. package/src/runs/background/stale-run-reconciler.ts +6 -3
  76. package/src/runs/background/steering.ts +11 -1
  77. package/src/runs/background/subagent-runner.ts +260 -144
  78. package/src/runs/background/subagent-wait.ts +17 -13
  79. package/src/runs/background/terminal-run-index.ts +138 -0
  80. package/src/runs/background/wait-completions.ts +21 -4
  81. package/src/runs/background/wait-subscriptions.ts +81 -2
  82. package/src/runs/background/wait-tool.ts +1 -0
  83. package/src/runs/foreground/async-steering-action.ts +21 -14
  84. package/src/runs/foreground/execution.ts +8 -2
  85. package/src/runs/foreground/subagent-executor.ts +816 -1593
  86. package/src/runs/foreground/workflow-detach-reconcile.ts +262 -0
  87. package/src/runs/foreground/workflow-foreground-steering.ts +6 -5
  88. package/src/runs/shared/acceptance.ts +48 -5
  89. package/src/runs/shared/chain-outputs.ts +1 -3
  90. package/src/runs/shared/external-job-bridge.ts +444 -0
  91. package/src/runs/shared/external-job-runner.ts +286 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +14 -0
  93. package/src/runs/shared/model-exclusions.ts +242 -0
  94. package/src/runs/shared/model-fallback.ts +153 -40
  95. package/src/runs/shared/orca-progress-tabs.ts +84 -22
  96. package/src/runs/shared/parallel-handoff.ts +46 -4
  97. package/src/runs/shared/parallel-utils.ts +4 -15
  98. package/src/runs/shared/permissions.ts +5 -1
  99. package/src/runs/shared/pi-args.ts +8 -1
  100. package/src/runs/shared/session-lease.ts +0 -6
  101. package/src/runs/shared/subagent-control.ts +51 -7
  102. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  103. package/src/runs/shared/workflow-graph.ts +1 -23
  104. package/src/runs/shared/worktree.ts +14 -2
  105. package/src/shared/atomic-json.ts +22 -2
  106. package/src/shared/capacity-resilient-json.ts +102 -0
  107. package/src/shared/completion-owner.ts +14 -0
  108. package/src/shared/file-system-retry.ts +49 -1
  109. package/src/shared/fork-context.ts +59 -1
  110. package/src/shared/model-info.ts +20 -0
  111. package/src/shared/prompt-resources.ts +0 -40
  112. package/src/shared/settings.ts +5 -29
  113. package/src/shared/types.ts +110 -26
  114. package/src/shared/utils.ts +8 -0
  115. package/src/shared/watch-strategy.ts +10 -0
  116. package/src/slash/slash-bridge.ts +2 -1
  117. package/src/slash/slash-commands.ts +47 -7
  118. package/src/slash/slash-live-state.ts +3 -3
  119. package/src/tui/fleet-status.ts +86 -1
  120. package/src/tui/fleet.ts +117 -16
  121. package/src/tui/render.ts +73 -3
  122. package/src/watchdog/change-signature.ts +1 -1
  123. package/src/watchdog/lsp-diagnostics.ts +1 -0
  124. package/src/workflows/chat-progress.ts +2 -2
  125. package/src/workflows/scripted-workflow.ts +320 -79
  126. package/src/workflows/workflow-receipt.ts +140 -0
  127. package/src/runs/foreground/chain-clarify.ts +0 -1354
  128. package/src/runs/foreground/chain-execution.ts +0 -1581
package/CHANGELOG.md CHANGED
@@ -1,6 +1,17 @@
1
1
  # Changelog
2
2
 
3
- ## [Unreleased]
3
+ ## [0.6.0] - 2026-08-23
4
+
5
+ ### Added
6
+ - Context injection: agents that opt in with `injectToContext: true` frontmatter, plus names listed under the new `subagents.injectAgents` setting, are pre-declared to the parent agent in a compact `<available_subagents>` system-prompt block. The union resolves once per session (canonical names or aliases; builtins allowed), stays byte-identical across turns to preserve provider prompt caching, skips disabled and capability-ceiling-restricted agents and spawned child sessions, ignores unknown setting names (reported by `/subagents-doctor`), and never duplicates itself on forked or resumed sessions.
7
+
8
+ ## [0.5.0] - 2026-08-22
9
+
10
+ ### Changed
11
+ - Synced the fork with upstream pi-subagents v0.53.0 (runtime agent registration API, keyed workflow receipts, TTL-based model-fallback exclusion, RPC schedule management, council mode; legacy chain workflow internals removed upstream in #1166).
12
+
13
+ ### Fixed
14
+ - Preserved local compatibility fixes across the merge: `@xzzpig/pi-permission-system` priority in `resolvePermissionSystemExtension()`, foreground tool-result normalization for mixed Pi host event shapes, and the shared `ejectAgentDefinition` helper (adapted to upstream's `availableAgentNames` rename).
4
15
 
5
16
  ## [0.4.2] - 2026-08-20
6
17
 
@@ -13,6 +24,166 @@
13
24
 
14
25
  ### Changed
15
26
  - Synced the fork with upstream pi-subagents v0.50.0 while preserving local compatibility fixes (@xzzpig/pi-permission-system priority in resolvePermissionSystemExtension(), Pi SDK 0.83 streamFn option naming).
27
+ ## [0.53.0] - 2026-08-20
28
+
29
+ ### Highlights
30
+ - Pi extensions can now register runtime agents without writing user or project config.
31
+ - Async workflows are easier to resume because completed children now have durable keyed receipts.
32
+ - Model fallback is less noisy and less wasteful when a model fails or the prompt is too large.
33
+ - Fleet and `/council` now give clearer supervision cues while keeping control in the parent session.
34
+ - Extension RPC hosts can safely inspect status, launch async work, steer children, and manage schedules.
35
+
36
+ ### Added
37
+ - Carry full model registry metadata, including tiered pricing, into normalized model information. Thanks to [@srcKod](https://github.com/srcKod) for #1317.
38
+ - Add runtime agent registration for Pi extensions, with name and alias collision checks. Thanks to [@fmoda3](https://github.com/fmoda3) for #1310.
39
+ - Skip recently failed fallback models for a TTL-backed window during model selection. Thanks to [@srcKod](https://github.com/srcKod) for #1318.
40
+ - Add a schedule-only `manage` method to extension RPC for list/show/history/pause/resume/run/delete, while rejecting unrelated management actions. Thanks to [@aboubakrine](https://github.com/aboubakrine) for #1319.
41
+ - Let agent definitions and `agentOverrides` set a default `outputMode`, while
42
+ call-level output mode stays higher priority. Thanks to [@bbbRye007](https://github.com/bbbRye007) for #1305.
43
+ - Add `context: "profile"` for workflow children that should use the selected
44
+ agent profile's declared context instead of the global default (#1303).
45
+ - Add durable keyed async workflow receipts and resume-by-key selectors for
46
+ retained workflow children (#1302).
47
+ - Add the `resultScanLogging` config to control result scan logging. Thanks to [@apoapostolov](https://github.com/apoapostolov) for #1293.
48
+ - Add packaged `/council` and `council-mode` resources for a bounded,
49
+ supervisor-mediated advisor loop, plus documented model-based `council-*`
50
+ profile examples (#1295).
51
+
52
+ ### Changed
53
+ - Show bounded workflow progress in Fleet detail views while keeping workflow
54
+ parents as the only actionable async items (#1304).
55
+ - Make `/council` easier to supervise with structured advisor contracts,
56
+ aggregate pass receipts, and visible pass checkpoints (#1301).
57
+ - Reuse validated workflow launch fingerprints during `runs.all` batch setup, reducing focused fingerprint bookkeeping time by 48.7% (#1287).
58
+ - Speed up recent terminal run history reads when the marker history is large and the requested limit is small.
59
+ - Reduce repeated serialization while applying async status snapshot byte caps (#1288).
60
+
61
+ ### Fixed
62
+ - Add tolerant `subagent_wait({ stopOnAttention: false })` blocking waits and scale idle attention defaults for higher-thinking children. Thanks to [@elecnix](https://github.com/elecnix) for #1315 and #1316.
63
+ - Add a separate classifier for model context-overflow errors. Thanks to [@srcKod](https://github.com/srcKod) for #1312.
64
+ - Normalize child result metadata before workflow return persistence (#1307).
65
+ - Quote only confidently identified leading Windows executable paths in acceptance verification commands. Thanks to [@srcKod](https://github.com/srcKod) for #1294.
66
+ - Keep forked subagent sessions out of top-level `pi -c` discovery by storing them under the parent session root. Thanks to [@xz-dev](https://github.com/xz-dev) for #1297.
67
+ - Preserve `/council` advisor context defaults during fallback and cross-exam runs (#1298).
68
+
69
+ ## [0.52.1] - 2026-08-20
70
+
71
+ ### Highlights
72
+ - Model setup errors now point to the right alternate provider when there is one clear match.
73
+ - Surf's optional `gpt-pro` package agent has a smoother path to run ChatGPT Pro web jobs through the external-job bridge when the user is logged in.
74
+ - External-job providers can add metadata or extra operations without breaking provider discovery.
75
+ - The packaged skill now includes a concise guide for coordinating multiple tasks, worktrees, and repositories.
76
+ - Pi extension worktrees now have clearer guidance to avoid duplicate auto-loaded tools and shortcuts.
77
+
78
+ ### Fixed
79
+ - Suggest the unique alternate provider model when an explicit qualified subagent model is unavailable, without resolving across providers. Thanks to [@lallenlowe](https://github.com/lallenlowe) for #1280.
80
+ - Accept extra fields on registered external-job providers, such as `kind`, `wakeChannels`, or additional operations. This keeps integrations such as Surf's `gpt-pro` package agent from breaking provider discovery as they add browser-backed job metadata, while job payload validation stays strict.
81
+
82
+ ### Changed
83
+ - Add a pi-subagents reference for coordinating multiple tasks, worktrees, and repositories, including guidance for keeping Pi extension worktrees outside auto-discovered extension directories.
84
+
85
+ ## [0.52.0] - 2026-08-19
86
+
87
+ ### Highlights
88
+ - Async workflows are much harder to break mid-flight: a transient status-file lock, a stalled child, or a paused supervisor hand-off no longer fails or loses an otherwise healthy run.
89
+ - Hosts can now inspect a running or completed async child on demand — task, recent transcript, and final output — without spending a model turn, and that output stays available after delivery.
90
+ - macOS and FreeBSD sandboxes stop warning about setuid `/bin/ps`, and Windows stops flashing console windows during busy runs.
91
+ - Gateway and proxy models work better: children can inherit the parent's session model, and Hugging Face-style `owner/name` model ids resolve correctly.
92
+
93
+ ### Added
94
+ - Add `/subagents-inspect-rpc`, a host-facing bridge command that answers on-demand async child inspection requests with a correlated, bounded `PI_SUBAGENT_INSPECT_JSON:` widget payload (task, transcript window, final output), so RPC hosts can inspect children without a model turn while the live status feed stays small. Thanks to [@yanqianglu](https://github.com/yanqianglu) for #1254.
95
+
96
+ ### Changed
97
+ - Guide oracle plan and design advice through a short same-session consultation when a material tradeoff remains, while keeping the parent as final decision-maker (#1245).
98
+ - Improve bundled role and parent prompts for source-first discovery in noisy codebases (#1247).
99
+ - Make Surf's `gpt-pro` agent an optional package integration instead of a pi-subagents builtin. If you disabled the old builtin workaround, remove `agentOverrides.gpt-pro.disabled` before using Surf's package agent. Thanks to [@binhex](https://github.com/binhex) for #1256.
100
+
101
+ ### Fixed
102
+ - Stop spawning setuid `/bin/ps` for process start identity on macOS and FreeBSD. Sandboxes such as nono no longer report `forbidden-exec-sugid` from session leases, retention locks, external-job claims, or mission state. Those platforms stay fail-closed without pid-reuse detection. Thanks to [@jdumas](https://github.com/jdumas) for #1273.
103
+ - Stop a transient lock on `status.json` (seen on Windows) from failing an already-completed workflow child and aborting its still-running siblings. Status updates after launch now degrade to a `subagent.workflow.status_write_failed` event instead of failing the run, and a throwing `onTrace` host callback can no longer reject a child promise. Follow-up to #1143. Thanks to [@MarcusNeufeldt](https://github.com/MarcusNeufeldt) for #1272.
104
+ - Keep a still-paused workflow result when reconcile republishes updated child output during paused delivery, so a same-state revision is not overwritten or deleted as the old payload.
105
+ - Persist async terminal `status.json` before publishing the result file, so observers cannot see a completed result while the run still looks `running`.
106
+ - Stop Windows opening a console window for each helper process (Git, `gh`, PowerShell, `npm root -g`) spawned during a run, which made a busy run disruptive to work alongside. Thanks to [@MarcusNeufeldt](https://github.com/MarcusNeufeldt) for #1274.
107
+ - Keep completed inspect RPC output available from the durable completion replay after result delivery consumes its one-shot payload, including per-child inline result tails (#1254).
108
+ - After a workflow child detaches for supervisor coordination, clear attention once the reply is delivered, keep `subagent_wait` blocked until the child exits, and reconcile the paused workflow when that child completes — even after the paused payload was already delivered. A timed-out workflow can also resume from its persisted child session when the workflow dir has no recovery descriptor. Thanks to [@skystar567](https://github.com/skystar567) for #1263.
109
+ - Wake the idle parent when an async workflow child needs attention, and persist that control event on the enclosing workflow. Status already showed the stall; the parent notice did not. Thanks to [@Yibo-Zhang](https://github.com/Yibo-Zhang) for #1266.
110
+ - Resolve Hugging Face-style `owner/name` model ids against the registry instead of treating every slash as `provider/id`. Fully qualified `huggingface/owner/name` still wins, and a first path segment that matches a registered provider still means `provider/id`. Thanks to [@mr-brobot](https://github.com/mr-brobot) for #1264.
111
+ - Keep public structured single-child calls synchronous when `asyncByDefault:false` and `async` is omitted. Thanks to [@Nofuture123](https://github.com/Nofuture123) for #1257.
112
+ - Trust the running parent session model when no model is configured, so gateway and proxy parent models can launch children outside the host registry. Thanks to [@Nofuture123](https://github.com/Nofuture123) for #1258.
113
+ - Isolate colliding inherited workflow child output defaults while preserving explicit output collision checks. Thanks to [@Reverier-Xu](https://github.com/Reverier-Xu) for #1253.
114
+ - Show a scheduled run's completion and name the schedule that produced it, so scheduled work no longer finishes silently in a session that cannot attribute it. Thanks to [@albertgwo](https://github.com/albertgwo) for #1246.
115
+ - Show resume-first guidance for failed async runs only when a matching recovery descriptor exists, so missing recovery data no longer points users to a resume command that cannot work. Thanks to [@graadient](https://github.com/graadient) for #1241.
116
+ - Keep bundled agent discovery stable across hot package updates, so long-running sessions do not parse newer bundled agent files with older loaded code. Thanks to [@graadient](https://github.com/graadient) for #1242.
117
+ - Resolve relative extension paths against the defining agent file, so portable agent definitions load child extensions from the declared location. Thanks to [@tayiorbeii](https://github.com/tayiorbeii) for #1249.
118
+
119
+ ## [0.51.0] - 2026-08-18
120
+
121
+ ### Highlights
122
+ - Workflow orchestration is easier to control with stable-key steering, clearer fanout guidance, and a supported external-job runner path.
123
+ - Async runs are harder to lose when storage is full, file access is temporarily denied, identifiers are too long, or multiple Pi windows share one session.
124
+ - macOS reloads and idle sessions do less fragile filesystem watching, which avoids reload hangs without adding always-on work.
125
+ - Herdr and Fleet are less disruptive: panes stay in the background by default, trusted transcripts open cleanly, and live workflow children steer through the right route.
126
+ - The workflow API is cleaner: scripted workflows are the supported path, and removed legacy chain surfaces now have direct migration guidance.
127
+
128
+ ### Added
129
+ - Add stable-key `runs.steer` to `workflowScript`, with routing for foreground and async children, structured receipts, trace entries, and checks for unawaited calls (#1186).
130
+ - Add `runner.type: external-job`, the exported provider bridge, the Surf GPT Pro `gpt-pro` profile, and docs for external advisor data boundaries (#1189).
131
+ - Add `defaultSubagentContext: "fork"` for launches that do not set an explicit context (#1161).
132
+ - Allow `defaultSubagentContext: "fresh"` to override agent fork defaults for launches that do not set an explicit context.
133
+ - Add `PI_SUBAGENT_FS_RETRY_MAX_TOTAL_MS` so hosts can cap filesystem retry waits. Unset by default. Thanks to [@MarcusNeufeldt](https://github.com/MarcusNeufeldt) for #1143.
134
+
135
+ ### Changed
136
+ - Document rolling `workflowScript` fanout with `runs.run`, `Promise.race`, `runs.steer`, and `Promise.all` (#1187).
137
+ - Document scripted chaining as the supported workflow API, with migration examples for removed top-level chain and task inputs.
138
+ - Clarify `workflowScript` fanout guidance: use awaited `runs.all` for ordinary parallel work, and use stored `runs.run` promises only for fully observed advanced rolling fanout (#1229, #1230).
139
+ - Clarify that async workflows do not have inline `live-card` projection (#1229, #1230).
140
+ - Describe `async:false` as a blocking parent wait, not a UI or foreground-only mode.
141
+ - Clarify that subagent reviews and gates should stay async unless the parent must block until completion.
142
+ - Document that a host's session lifetime owns completion wakes, and how to key an idle check on live run state rather than parent activity. Thanks to [@MarcusNeufeldt](https://github.com/MarcusNeufeldt) for #1144.
143
+ - Register the default `subagent` tool prompt as split metadata with a short description, `promptSnippet`, and `promptGuidelines`, while keeping explicit `full`, `compact`, and `custom` description modes.
144
+ - Keep `worktree: true` workflow children on the single-child path while preserving managed patch handoffs.
145
+
146
+ ### Removed
147
+ - Remove unused foreground chain and parallel execution and durable chain management surfaces.
148
+ - Remove legacy subagent tool compatibility fields for append-step control, schedule aliases, async recovery metadata, and string mission goals.
149
+ - Remove chain approval checkpoint steps and the `approve-checkpoint` / `reject-checkpoint` controls.
150
+ - Remove `prompts.render` from `workflowScript`; pass explicit task text to `runs.run` or use `/prompt-workflow` for reusable prompt templates.
151
+
152
+ ### Fixed
153
+ - Avoid Darwin reload hangs by disabling idle native filesystem watchers and using demand-gated delivery for live results, supervisor messages, controls, and steering. Thanks to [@youlikemodernart](https://github.com/youlikemodernart) for #1220.
154
+ - Bound async result session, run, active-run, and result-index path segments so long provider IDs do not break launches or waits with `ENAMETOOLONG`. Thanks to [@hlstwizard](https://github.com/hlstwizard) for #1131 and [@zhouatie](https://github.com/zhouatie) for #1135.
155
+ - Hash result-index session segments that look like Windows paths or file names, keep reading previous URI-encoded keys, and treat `EPERM` and `EACCES` as empty scans. Thanks to [@apoapostolov](https://github.com/apoapostolov) for #1211.
156
+ - Sanitize foreground workflow output path segments derived from provider run IDs, so Windows launches do not fail when tool-call IDs contain path-invalid characters. Thanks to [@maxime-louward-shift](https://github.com/maxime-louward-shift) for #1235.
157
+ - Keep async status and result persistence retrying after temporary `ENOSPC`, quota, or file-descriptor exhaustion errors. Thanks to [@ahmadaccino](https://github.com/ahmadaccino) for #1227.
158
+ - Route async completion notifications and cleanup only to the parent Pi process that launched the run, so concurrent windows sharing one session file cannot consume each other's results. Thanks to [@wangjianming](https://github.com/wangjianming) for #1225.
159
+ - Keep extension reload cleanup scoped to the replaced session runtime, so concurrent Pi sessions in one process do not remove each other's subscriptions or parent-session identity. Thanks to [@ryanbbrown](https://github.com/ryanbbrown) for #1222.
160
+ - Stop failing child runs when an explicit allowlist names `contact_supervisor` without the legacy `intercom` companion. A lone `intercom` entry still requires a real external provider. Thanks to [@MingTeer](https://github.com/MingTeer) for #1207.
161
+ - Add explicit `isolation: "none"` for schema-driven workflows without Git worktree setup, while keeping strict `isolation: "worktree"` behavior. Thanks to [@tlsneo](https://github.com/tlsneo) for #1203.
162
+ - Fail closed when an existing external-job `status.json` is unreadable or malformed, including an invalid `steps` shape.
163
+ - Skip malformed agent definitions during discovery so valid agents still list and launch, while showing configuration errors in management diagnostics (#1200).
164
+ - Resolve `/subagents-generate-profiles` provider probes through the shared Pi executable resolver so configured and Windows-specific Pi commands work. Thanks to [@Wumpf](https://github.com/Wumpf) for #1199.
165
+ - Resolve the workflowScript parser from pi-subagents instead of the caller's working directory, so workflows start in projects that do not install Acorn. Thanks to [@xz-dev](https://github.com/xz-dev) for #1214, following up #1190.
166
+ - Keep workflowScript child-launch tracking working on Bun-built Pi without a hard dependency on V8 promise hooks. Thanks to [@rochecompaan](https://github.com/rochecompaan) for #1158 and [@rholak](https://github.com/rholak) for the version-window diagnosis.
167
+ - Treat provider subscription usage-limit errors as retryable model failures so `fallbackModels` can continue to the next configured model. Thanks to [@dwizzle204](https://github.com/dwizzle204) for #1215.
168
+ - Skip fallback models that are unavailable in the active registry, so shared agent configs still run where their primary model is available. Thanks to [@JPFrancoia](https://github.com/JPFrancoia) for #1147.
169
+ - Preserve workflow async session roots for Herdr inspectors so workflow runs open with the same trusted session-root context as standalone runs. Thanks to [@hank-warren](https://github.com/hank-warren) for #1219.
170
+ - Keep Herdr project and inspector panes in the background by default, and move focus only when callers set `focus: true`. The FleetView inspect key still focuses the pane it opens. Thanks to [@boggylp](https://github.com/boggylp) for #1226.
171
+ - Show FleetView transcript fallbacks for trusted session roots instead of warning about an untrusted session file. Thanks to [@aliceisjustplaying](https://github.com/aliceisjustplaying) for #1154.
172
+ - Route Fleet inspector steering for live in-process workflow children through their foreground routes instead of the detached async queue. Thanks to [@ViktorBarzin](https://github.com/ViktorBarzin) for #1218 and #1216.
173
+ - Serialize same-worktree Orca progress-tab creation so numbered tabs appear left to right in sequence. Thanks to [@hyein-cbio](https://github.com/hyein-cbio) for #1196.
174
+ - Bound repeated async-state queries to active, exact-id, and recent-terminal indexes instead of scanning the full async history (#1162).
175
+ - Move retention directory discovery to a read-only worker so full scans do not block the extension event loop (#1188).
176
+ - Reclaim proven-safe async run and orphan result state after 30 days in bounded, locked cleanup passes with rename-first tombstones (#1163).
177
+ - Sweep expired wait subscriptions armed by another session, so stale records stop accumulating in the subscriptions directory. Thanks to [@MarcusNeufeldt](https://github.com/MarcusNeufeldt) for #1142.
178
+ - Restore and list schedules after their project directory is deleted, and skip orphan schedule directories without letting create reuse stale state. Thanks to [@ELA718](https://github.com/ELA718) for #1171 and [@colinb4987](https://github.com/colinb4987) for #1167.
179
+ - Fall back from an implicit `defaultContext: fork` to `fresh` when the parent session file or current leaf is not available yet. Explicit `context: "fork"` remains fail-fast. Thanks to [@hyein-cbio](https://github.com/hyein-cbio) for #1137.
180
+ - Keep retained workflow children resumable when their managed worktree cwd is preserved in the handoff manifest (#1172).
181
+ - Preserve workflow child task output when neither the workflow nor child configures an output file (#1136).
182
+ - Preserve a child's file-only report when its output path also names the workflow summary output.
183
+ - Keep concurrent async result promotion from deleting a newer payload or another promoter's published result. Thanks to [@albertgwo](https://github.com/albertgwo) for #1130.
184
+ - Keep `mcp:<server>` direct tools available when pi-mcp-adapter cache identity includes a request-header command. Thanks to [@xz-dev](https://github.com/xz-dev) for #1141.
185
+ - Isolate test async state from the user temp root and write each missing-mission sync diagnostic only once (#1164, #1165).
186
+ - Keep structured delegation integration coverage active when the test process inherits a subagent-child environment marker.
16
187
 
17
188
  ## [0.50.0] - 2026-08-15
18
189
 
package/README.md CHANGED
@@ -50,6 +50,10 @@ Installing the extension does not start an automatic reviewer in the background.
50
50
  When you finish implementing, run a reviewer subagent before summarizing.
51
51
  ```
52
52
 
53
+ ### Pre-declaring agents in context (context injection)
54
+
55
+ By default Pi discovers agents by calling `subagent({ action: "list" })`. You can pre-declare selected agents in the parent system prompt so routing happens without that round trip: set `injectToContext: true` in an agent's frontmatter, or list names under `subagents.injectAgents` in settings. The union is injected once per session as a compact block — byte-stable across turns, so prompt caching stays effective. Disabled and capability-restricted agents are never advertised; unknown setting names are ignored and reported by `/subagents-doctor`. See [docs/agents.md](docs/agents.md#context-injection).
56
+
53
57
  ## Builtin agents
54
58
 
55
59
  The extension ships with agents you can use immediately:
@@ -67,12 +71,16 @@ Rule of thumb: `scout` before you understand the code, `researcher` before you t
67
71
 
68
72
  ## Common workflows
69
73
 
74
+ The package includes `/council` and `council-mode`, plus documented model-based
75
+ `council-*` profile examples that you add in your own agent directory.
76
+
70
77
  | Want | Ask naturally |
71
78
  |------|---------------|
72
79
  | Get a second opinion | "Ask oracle to review this plan and challenge assumptions." |
73
80
  | Solve a hard problem | "Use oracle to investigate this bug before we edit." |
74
81
  | Review a diff | "Use reviewer to review this diff." |
75
82
  | Run parallel reviewers | "Run reviewers for correctness, tests, and cleanup." |
83
+ | Debate a material decision | "Use `/council` to convene architect and skeptic advisors." |
76
84
  | Implement then review | "Implement this, then review it." |
77
85
  | Review until clean | "Run a review loop on this change with a max of 3 rounds." |
78
86
  | Execute a plan carefully | "Have worker implement this approved plan, then run reviewers and apply the feedback." |
package/agents/oracle.md CHANGED
@@ -16,7 +16,9 @@ Your primary job is to prevent the main agent from making hidden, conflicting, o
16
16
 
17
17
  Before you do anything else, reconstruct the key inherited decisions, constraints, and open questions from the forked conversation, codebase state, and task. Those decisions form your baseline contract. Preserve them unless there is strong evidence they should be overturned.
18
18
 
19
- If the task is framed as asking or consulting the oracle, treat it as a live consultation unless the parent explicitly requests a one-shot report. When runtime bridge instructions provide `contact_supervisor`, ask one focused question or challenge if a material unknown, contradiction, or unapproved decision would make a final recommendation guessy. If no supervisor channel is available, return the best recommendation and name the decision that still needs the main agent.
19
+ Match search scope to the question. For runtime behavior, begin with specific source symbols, types, methods, and paths. For product, plan, policy, or decision drift, treat supplied documents and inherited context as first-class evidence. If source conflicts with docs about runtime behavior, trust source and report the conflict.
20
+
21
+ If the task asks about asking or consulting the oracle, or asks to ask, consult, discuss with, or come to agreement with the oracle about a plan, design, or architecture decision, treat it as a short live consultation unless the parent explicitly requests a one-shot report. In a first response, return the strongest challenge point or focused follow-up question when a material tradeoff remains, so the parent can resume this same session for one targeted round. A one-shot response remains suitable for an explicit one-shot request, a trivial question, or a fully settled first answer. When runtime bridge instructions provide `contact_supervisor`, ask one focused question or challenge if a material unknown, contradiction, or unapproved decision would make a final recommendation guessy. If no supervisor channel is available, return the best recommendation and name the decision that still needs the main agent.
20
22
 
21
23
  If you need clarification from the main agent and bridge instructions provide `contact_supervisor`, use it with `reason: "need_decision"` and wait for the reply. Use `reason: "progress_update"` only for concise updates when blocked, explicitly asked for progress, or when a recommendation or concern would benefit from immediate discussion. Keep coordination traffic tight and purposeful. Do not narrate your whole review through `contact_supervisor`.
22
24
 
@@ -50,6 +50,7 @@ Review a PR or issue by understanding the context, then verifying:
50
50
  - Tests and docs are updated as needed.
51
51
 
52
52
  ## Working rules
53
+ - Start from the exact diff and named source seam for code-behavior review. Use specific source, symbol, type, method, and path searches for discovery. Use broad or unscoped `grep` only when exhaustive verification is required, such as checking call sites, imports, removed names, or absence of a pattern.
53
54
  - Read the relevant files first. Read plan and progress when the task supplies them.
54
55
  - Repo-local `progress.md` files are allowed scratch/memory files. Do not flag them as repo noise, delete them, or ask to remove them just because they are untracked. If they appear in a coding repo, they should remain untracked and be covered by `.gitignore`.
55
56
  - Do not use shell commands or write files. Report any test or Git command that a supervisor must run.
package/agents/scout.md CHANGED
@@ -12,7 +12,7 @@ defaultProgress: true
12
12
 
13
13
  You are a scouting subagent running inside pi.
14
14
 
15
- Use the provided tools directly. Move fast, but do not guess. Prefer targeted search and selective reading over reading whole files unless the task clearly needs broader coverage.
15
+ Use the provided tools directly. Move fast, but do not guess. Start discovery with task-provided paths and specific symbols, types, methods, filenames, or likely source roots. Use `find` for path discovery. Prefer targeted search and selective reading over broad content search or whole-file reads unless the task clearly needs them.
16
16
 
17
17
  Focus on the minimum context another agent needs in order to act:
18
18
  - relevant entry points
@@ -22,7 +22,7 @@ Focus on the minimum context another agent needs in order to act:
22
22
  - constraints, risks, and open questions
23
23
 
24
24
  Working rules:
25
- - Use `grep`, `find`, `ls`, and `read` to map the area before diving deeper.
25
+ - Use `grep`, `find`, `ls`, and `read` to map the area before diving deeper. Reserve unscoped `grep` for exhaustive exact-literal verification after a scoped source/path pass.
26
26
  - Use `bash` only for non-interactive inspection commands.
27
27
  - When you cite code, use exact file paths and line ranges.
28
28
  - If you are told to write output, write it to the provided path and keep the final response short.
package/agents/worker.md CHANGED
@@ -16,7 +16,7 @@ You are `worker`: the implementation subagent.
16
16
 
17
17
  You are the single writer thread. Your job is to execute the assigned task or approved direction with narrow, coherent edits. The main agent and user remain the decision authority.
18
18
 
19
- Use the provided tools directly. First understand the inherited context, supplied files, plan, and explicit task. Then implement carefully and minimally.
19
+ Use the provided tools directly. First read the inherited context, supplied files, plan, task paths, and named seams. Then implement carefully and minimally. Use broad search only to verify or expand from that starting point.
20
20
 
21
21
  The builtin worker uses a strict tool allowlist. It does not inherit ambient extension tools from the parent session. To use an extension tool, configure a custom agent with the tool name explicitly listed in `tools` and load its provider through `extensions` or `subagentOnlyExtensions`.
22
22
 
@@ -34,6 +34,7 @@ Default responsibilities:
34
34
 
35
35
  Working rules:
36
36
  - Prefer narrow, correct changes over broad rewrites.
37
+ - Preserve source discoverability: use specific names, clear types, one spelling per concept, source-named tests, and definition comments only when they explain a needed constraint.
37
38
  - Do not add speculative scaffolding or future-proofing unless explicitly required.
38
39
  - Do not leave placeholder code, TODOs, or silent scope changes.
39
40
  - Use `bash` for inspection, validation, and relevant tests.
@@ -0,0 +1,180 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { parentPort } from "node:worker_threads";
4
+
5
+ const ACTIVE_RUN_INDEX_DIR = ".active-runs";
6
+ const RESULT_TOMBSTONE_PREFIX = ".deleting-result-";
7
+
8
+ function compareRelative(left, right) {
9
+ if (left < right) return -1;
10
+ if (left > right) return 1;
11
+ return 0;
12
+ }
13
+
14
+ function insertSmallest(entries, candidate, limit) {
15
+ if (limit <= 0) return;
16
+ const index = entries.findIndex((entry) => compareRelative(candidate.relative, entry.relative) < 0);
17
+ if (index === -1) entries.push(candidate);
18
+ else entries.splice(index, 0, candidate);
19
+ if (entries.length > limit) entries.pop();
20
+ }
21
+
22
+ function streamDirWindow(dir, limit, after, relativePath, usable) {
23
+ if (limit <= 0) return { entries: [], rawReads: 0, exhausted: true, cursorCleared: false };
24
+ let handle;
25
+ try {
26
+ handle = fs.opendirSync(dir);
27
+ const next = [];
28
+ const wrapped = [];
29
+ let rawReads = 0;
30
+ while (true) {
31
+ const entry = handle.readSync();
32
+ if (!entry) break;
33
+ rawReads += 1;
34
+ const relative = relativePath(entry);
35
+ if (!usable(entry, relative)) continue;
36
+ const candidate = { relative, name: entry.name };
37
+ insertSmallest(wrapped, candidate, limit);
38
+ if (after === undefined || compareRelative(relative, after) > 0) insertSmallest(next, candidate, limit);
39
+ }
40
+ const cursorCleared = after !== undefined && next.length === 0;
41
+ return { entries: cursorCleared ? wrapped : next, rawReads, exhausted: true, cursorCleared };
42
+ } catch (error) {
43
+ if (error?.code === "ENOENT") return { entries: [], rawReads: 0, exhausted: true, cursorCleared: false };
44
+ throw error;
45
+ } finally {
46
+ handle?.closeSync();
47
+ }
48
+ }
49
+
50
+ function discover(request) {
51
+ const startedAt = Date.now();
52
+ const cursor = structuredClone(request.cursor);
53
+ const raw = { reads: 0, exhausted: {} };
54
+ const record = (source, scan) => {
55
+ raw.reads += scan.rawReads;
56
+ raw.exhausted[source] = scan.exhausted;
57
+ };
58
+ const runScan = streamDirWindow(
59
+ request.asyncDirRoot,
60
+ request.runBudget,
61
+ cursor.runAfter,
62
+ (entry) => entry.name,
63
+ (entry) => entry.isDirectory() && entry.name !== ACTIVE_RUN_INDEX_DIR,
64
+ );
65
+ record("runs", runScan);
66
+ if (runScan.cursorCleared) delete cursor.runAfter;
67
+ const runCandidates = runScan.entries.slice(0, request.runBudget);
68
+ for (const candidate of runCandidates) cursor.runAfter = candidate.relative;
69
+
70
+ const resultCandidates = [];
71
+ const sourceLimit = Math.max(1, Math.ceil(request.resultBudget / 4));
72
+ const addFiles = (dir, kind, cursorTarget, source, budget = sourceLimit) => {
73
+ const remaining = Math.min(budget, request.resultBudget - resultCandidates.length);
74
+ if (remaining <= 0) return 0;
75
+ const before = resultCandidates.length;
76
+ const after = cursorTarget.type === "pending"
77
+ ? cursor.resultPendingAfterBySession?.[cursorTarget.session]
78
+ : cursor[cursorTarget.key];
79
+ const scan = streamDirWindow(
80
+ dir,
81
+ remaining,
82
+ after,
83
+ (entry) => path.relative(request.resultsDir, path.join(dir, entry.name)),
84
+ (entry) => entry.isFile() && (entry.name.startsWith(RESULT_TOMBSTONE_PREFIX) || entry.name.endsWith(".json")),
85
+ );
86
+ record(source, scan);
87
+ if (scan.cursorCleared) {
88
+ if (cursorTarget.type === "pending") delete cursor.resultPendingAfterBySession?.[cursorTarget.session];
89
+ else delete cursor[cursorTarget.key];
90
+ }
91
+ for (const candidate of scan.entries.slice(0, remaining)) {
92
+ const tombstone = candidate.name.startsWith(RESULT_TOMBSTONE_PREFIX);
93
+ resultCandidates.push({
94
+ name: candidate.name,
95
+ relative: candidate.relative,
96
+ kind: tombstone ? "tombstone" : kind,
97
+ cursor: cursorTarget,
98
+ });
99
+ if (cursorTarget.type === "pending") {
100
+ cursor.resultPendingAfterBySession ??= {};
101
+ cursor.resultPendingAfterBySession[cursorTarget.session] = candidate.relative;
102
+ } else cursor[cursorTarget.key] = candidate.relative;
103
+ }
104
+ return resultCandidates.length - before;
105
+ };
106
+
107
+ addFiles(request.resultsDir, "public", { type: "result", key: "resultPublicAfter" }, "results.public");
108
+ const pendingRoot = path.join(request.resultsDir, "result-pending");
109
+ const pendingRemaining = Math.min(request.resultBudget, sourceLimit, request.resultBudget - resultCandidates.length);
110
+ const pendingScan = streamDirWindow(
111
+ pendingRoot,
112
+ pendingRemaining,
113
+ cursor.pendingSessionAfter,
114
+ (entry) => entry.name,
115
+ (entry) => entry.isDirectory(),
116
+ );
117
+ record("results.pendingSessions", pendingScan);
118
+ const livePendingSessions = new Set(pendingScan.entries.map((entry) => entry.relative));
119
+ if (cursor.resultPendingAfterBySession) {
120
+ let pruned = 0;
121
+ for (const session of Object.keys(cursor.resultPendingAfterBySession).sort()) {
122
+ if (pruned >= request.resultBudget) break;
123
+ if (!livePendingSessions.has(session) && !fs.existsSync(path.join(pendingRoot, session))) {
124
+ delete cursor.resultPendingAfterBySession[session];
125
+ pruned += 1;
126
+ }
127
+ }
128
+ if (Object.keys(cursor.resultPendingAfterBySession).length === 0) delete cursor.resultPendingAfterBySession;
129
+ }
130
+ if (pendingScan.cursorCleared) delete cursor.pendingSessionAfter;
131
+ const pendingSessions = pendingScan.entries.slice(0, pendingRemaining);
132
+ let pendingFileBudget = Math.min(sourceLimit, request.resultBudget - resultCandidates.length);
133
+ for (const session of pendingSessions) {
134
+ if (pendingFileBudget <= 0) break;
135
+ cursor.pendingSessionAfter = session.relative;
136
+ pendingFileBudget -= addFiles(
137
+ path.join(pendingRoot, session.name),
138
+ "pending",
139
+ { type: "pending", session: session.relative },
140
+ `results.pending.${session.name}`,
141
+ pendingFileBudget,
142
+ );
143
+ }
144
+ addFiles(path.join(request.resultsDir, "completion-replay"), "replay", { type: "result", key: "resultReplayAfter" }, "results.replay");
145
+ addFiles(path.join(request.resultsDir, "output-archives"), "archive", { type: "result", key: "resultArchiveAfter" }, "results.archive");
146
+
147
+ const cursorOps = [];
148
+ for (const key of ["runAfter", "resultPublicAfter", "resultReplayAfter", "resultArchiveAfter", "pendingSessionAfter"]) {
149
+ if (cursor[key] === request.cursor[key]) continue;
150
+ cursorOps.push(cursor[key] === undefined ? { type: "delete", key } : { type: "set", key, value: cursor[key] });
151
+ }
152
+ const oldPending = request.cursor.resultPendingAfterBySession ?? {};
153
+ const nextPending = cursor.resultPendingAfterBySession ?? {};
154
+ for (const session of new Set([...Object.keys(oldPending), ...Object.keys(nextPending)])) {
155
+ if (oldPending[session] === nextPending[session]) continue;
156
+ cursorOps.push(nextPending[session] === undefined
157
+ ? { type: "delete-pending", session }
158
+ : { type: "set-pending", session, value: nextPending[session] });
159
+ }
160
+ return {
161
+ type: "result",
162
+ passId: request.passId,
163
+ discoveryDurationMs: Math.max(0, Date.now() - startedAt),
164
+ rawReads: raw.reads,
165
+ sourceExhausted: raw.exhausted,
166
+ runCandidates,
167
+ resultCandidates,
168
+ cursorOps,
169
+ };
170
+ }
171
+
172
+ if (!parentPort) throw new Error("Async retention discovery requires a worker parent port.");
173
+ parentPort.on("message", (request) => {
174
+ const passId = request?.passId;
175
+ try {
176
+ parentPort.postMessage(discover(request));
177
+ } catch (error) {
178
+ parentPort.postMessage({ type: "error", passId, error: error instanceof Error ? error.message : String(error) });
179
+ }
180
+ });
package/docs/agents.md CHANGED
@@ -47,6 +47,44 @@ Rule of thumb: `scout` before you understand the code, `researcher` before you t
47
47
 
48
48
  `oracle` is an advisory reviewer that critiques direction and proposes an execution prompt without editing files. `advisor` is the same bundled role under the Claude Code-compatible name.
49
49
 
50
+ ### Optional Surf integration
51
+
52
+ When `surf-cli` is installed and loaded, Surf can expose a `gpt-pro` package agent through the `surf-oracle` external-job provider. It starts through the same `subagent({ agent: "gpt-pro" })` mental model as any other agent, but Surf owns the package agent and provider. Surf maps `model: pro` to ChatGPT GPT-5.6 Sol Pro web mode. pi-subagents does not own that model mapping.
53
+
54
+ If you disabled the old bundled `gpt-pro` workaround with `agentOverrides.gpt-pro.disabled`, remove that override before using Surf's package agent.
55
+
56
+ The Pi async run remains the source of truth for status, artifacts, wake/wait, mission attachment, retention, and diagnostics.
57
+
58
+ Claude Code can be configured as a read-only advisor with `runner.type: external-cli` when the Claude Code CLI is installed and you have verified the flags for your local version. pi-subagents does not ship or enforce Claude Code flags. Use a project or user agent like this only after checking your CLI help:
59
+
60
+ ```yaml
61
+ ---
62
+ name: claude-advisor
63
+ description: Read-only Claude Code advisor through the local CLI
64
+ runner:
65
+ type: external-cli
66
+ command: claude
67
+ args: ["<verified-read-only-flags>"]
68
+ promptDelivery: stdin
69
+ async: true
70
+ ---
71
+
72
+ Review the task and return advice only. Do not edit files.
73
+ ```
74
+
75
+ ### Advisory runner data boundary
76
+
77
+ Native `oracle` runs inside Pi and can use its configured read tools. `claude-advisor` sends the assembled prompt to the configured local external CLI through stdin. An external-job agent sends the assembled prompt to its registered provider. Provider options and a prompt digest are persisted in Pi run state. The prompt text is delivered through the local host bridge to the provider and is not stored in the public result payload. Do not place secrets in advisory prompts unless the target provider is approved to receive them.
78
+
79
+ ### External-job state table
80
+
81
+ | Durable file | Owner | States | Release predicate | Rollback predicate | Stale-head behavior | Fail-closed cases |
82
+ |--------------|-------|--------|-------------------|--------------------|---------------------|-------------------|
83
+ | `status.json` step `runner` and `externalJob` | pi-subagents async runner | `queued`, `running`, `completed`, `failed`, `stopped`, `blocked` | Provider `result` returns terminal data and the async result is written | Provider start/status/result/reattach returns an error | If a status file already has a provider job id, recovery calls `reattach` and `result`; it refuses to start a new prompt when the provider or prompt digest differs | Missing provider, capacity conflict, malformed provider response, bridge timeout, prompt digest mismatch |
84
+ | `result.json` or session result payload | pi-subagents async runner | `complete`, `failed`, `stopped` | All steps reach terminal state and result publication succeeds or is recoverably indexed | Result write fails and pending result repair records the terminal state | Stale status can repair from an existing result file | Unindexed sessionless stale failure |
85
+ | `external-job-requests/` and `external-job-responses/` | Host-mediated provider bridge | pending request, terminal response | Host process writes a matching response and removes the request | Bridge timeout or malformed request response | Requests are operation-scoped. Recovery sends `reattach`/`result`, not `start`, when job metadata exists | Provider not registered, host bridge not loaded, malformed request, provider exception |
86
+ | Provider artifact path | External provider | provider-defined terminal artifact | Provider returns `artifactPath`, or Pi writes returned text to `external-job-<index>.result.md` | Provider reports failure or no result | Existing artifact path is retained in `status.json` | Missing artifact with no text output returns a terminal message instead of inventing content |
87
+
50
88
  The `researcher` builtin uses `web_search`, `fetch_content`, and `get_search_content`. Those require [pi-web-access](https://github.com/nicobailon/pi-web-access):
51
89
 
52
90
  ```bash
@@ -102,7 +140,7 @@ Use these fields when an agent should see more:
102
140
  | `systemPromptMode: append` | Append the agent prompt to Pi's normal base prompt. |
103
141
  | `inheritProjectContext: true` | Keep inherited project instructions from files like `AGENTS.md` and `CLAUDE.md`. |
104
142
  | `inheritSkills: true` | Let the child see Pi's discovered skills catalog. |
105
- | `defaultContext: fork` | Use forked session context when a launch omits `context`; explicit `context: "fresh"` still wins. |
143
+ | `defaultContext: fork` | Prefer forked session context when a launch omits `context`; if the parent has no persisted session file or current leaf yet, the implicit default falls back to `fresh` without a failed first attempt. Explicit `context: "fork"` remains strict, and explicit `context: "fresh"` still wins. |
106
144
 
107
145
  Builtin agents opt into project instruction inheritance by default so they follow repo-specific rules out of the box. `delegate` also uses append mode because its job is orchestration inside the parent workflow.
108
146
 
@@ -140,6 +178,7 @@ acceptanceRole: read-only
140
178
  completionGuard: false
141
179
  interactive: true
142
180
  maxSubagentDepth: 1
181
+ injectToContext: true
143
182
  ---
144
183
 
145
184
  Your system prompt goes here.
@@ -171,7 +210,7 @@ Field notes:
171
210
  | `systemPromptMode` | `replace` by default; `append` keeps Pi's base prompt. |
172
211
  | `inheritProjectContext` | Keeps or strips inherited project instruction blocks. |
173
212
  | `inheritSkills` | Keeps or strips Pi's discovered skills catalog. |
174
- | `defaultContext` | Optional `fresh` or `fork` launch context default for this agent. |
213
+ | `defaultContext` | Optional `fresh` or `fork` launch-context preference. An implicit `fork` falls back to `fresh` when the parent has no persisted session file or current leaf; an explicit launch `context: "fork"` remains strict. |
175
214
  | `skills` | Selects specific skills for the child, regardless of `inheritSkills`. |
176
215
  | `skillPath` | Invocation-private skill files or discovery directories. Relative paths resolve from the agent definition file. Local matches take precedence, while unresolved or unreadable matches fall back to normal skill discovery. This field discovers candidates only; `skills` still selects what the child receives. |
177
216
  | `output` | Default single-agent output file. |
@@ -186,8 +225,46 @@ Field notes:
186
225
  | `completionGuard` | Set `false` only for non-implementation agents that may mention implementation words while using mutation-capable tools such as `bash`. |
187
226
  | `interactive` | Parsed for compatibility but not currently enforced. |
188
227
  | `maxSubagentDepth` | Tightens nested delegation for this agent's children. |
228
+ | `injectToContext` | Advertise this agent in the parent system prompt at session start so the main agent can select it without calling `{ action: "list" }` first. See [Context injection](#context-injection). |
189
229
  | `memory` | Opt-in role-specific persistent memory. See below. |
190
230
 
231
+ ## Context injection
232
+
233
+ By default the parent agent learns which agents exist only by calling `subagent({ action: "list" })`. Context injection pre-declares selected agents in the parent system prompt through a compact `<available_subagents>` block, so routing decisions can happen without a discovery round trip.
234
+
235
+ Two sources contribute, and the union is advertised:
236
+
237
+ 1. Agent files that opt in with `injectToContext: true` in their frontmatter.
238
+ 2. The `subagents.injectAgents` setting, which lists agent names (canonical names or aliases; builtins allowed):
239
+
240
+ ```json
241
+ {
242
+ "subagents": {
243
+ "injectAgents": ["worker", "reviewer", "security-reviewer"]
244
+ }
245
+ }
246
+ ```
247
+
248
+ Rendered block shape:
249
+
250
+ ```text
251
+ <available_subagents>
252
+ The following pre-declared subagents are available.
253
+ Launch them with the subagent tool when a task matches their description.
254
+
255
+ - security-reviewer: Security review specialist
256
+ - worker: Implementation work, including approved oracle handoffs.
257
+ </available_subagents>
258
+ ```
259
+
260
+ Semantics and guarantees:
261
+
262
+ - **Snapshot per session.** The list resolves once at session start (and on reload) and stays byte-identical for every turn, so provider prompt caching is never invalidated mid-session. Edits to agent files or settings take effect in a new session, not the current one; `{ action: "list" }` remains the runtime source of truth.
263
+ - **Only executable agents are advertised.** Disabled agents and agents restricted by the session capability ceiling are never injected.
264
+ - **Children never see it.** Spawned child sessions do not load the parent injection; fanout children can still call `{ action: "list" }`.
265
+ - **Unknown setting names are ignored** and reported by `/subagents-doctor` instead of failing startup.
266
+ - The block is appended only when it is not already present, so forked or resumed sessions never duplicate it.
267
+
191
268
  ## Per-agent persistent memory
192
269
 
193
270
  A recurring custom agent can opt into a durable, role-specific memory scope with the `memory` frontmatter field: