@xzzpig/pi-subagents 0.24.2 → 0.25.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 (258) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/bundle/agent-management.js +4 -4
  3. package/bundle/agents.js +3 -3
  4. package/bundle/child-tool-plan.js +2 -2
  5. package/bundle/chunk-34TUUBRN.js +1107 -0
  6. package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
  7. package/bundle/{chunk-XWWUDWUW.js → chunk-5YEOWNSD.js} +371 -135
  8. package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  9. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  10. package/bundle/{chunk-4UH4WS4G.js → chunk-6MNRKUHY.js} +23 -12
  11. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  12. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  13. package/bundle/chunk-HXRB42AF.js +108 -0
  14. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  15. package/bundle/{chunk-CYY5UMJU.js → chunk-IJWITCC6.js} +411 -249
  16. package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
  17. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  18. package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
  19. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  20. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  21. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  22. package/bundle/{chunk-224WMDIV.js → chunk-KCJFGKVK.js} +350 -123
  23. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  24. package/bundle/chunk-LYKG4FKH.js +523 -0
  25. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  26. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  27. package/bundle/{chunk-BQ2OAB4Q.js → chunk-OSVXFWPG.js} +67 -30
  28. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  29. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  30. package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
  31. package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
  32. package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
  33. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  34. package/bundle/{chunk-O4D5PBVI.js → chunk-YWXILP5N.js} +3 -2
  35. package/bundle/control-channel.js +2 -2
  36. package/bundle/index.js +1 -1
  37. package/bundle/intercom-bridge.js +2 -2
  38. package/bundle/preflight.js +12 -10
  39. package/bundle/project-panes.js +3 -3
  40. package/bundle/workflow-resources.js +1 -1
  41. package/docs/agents.md +27 -6
  42. package/docs/configuration.md +20 -8
  43. package/docs/extension-api.md +18 -1
  44. package/docs/models.md +6 -2
  45. package/docs/observability.md +2 -0
  46. package/docs/tool-reference.md +7 -1
  47. package/docs/workflows.md +30 -2
  48. package/package.json +2 -2
  49. package/skills/pi-subagents/SKILL.md +15 -6
  50. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  51. package/src/agents/agent-management.d.ts +1 -0
  52. package/src/agents/agent-management.js +46 -18
  53. package/src/agents/agent-memory.d.ts +1 -4
  54. package/src/agents/agent-memory.js +1 -4
  55. package/src/agents/agent-serializer.d.ts +2 -0
  56. package/src/agents/agent-serializer.js +1 -1
  57. package/src/agents/agents.d.ts +2 -3
  58. package/src/agents/agents.js +46 -20
  59. package/src/agents/frontmatter.js +1 -8
  60. package/src/agents/global-npm-root.d.ts +1 -0
  61. package/src/agents/global-npm-root.js +11 -3
  62. package/src/agents/skills.d.ts +0 -3
  63. package/src/agents/skills.js +0 -3
  64. package/src/api/preflight.d.ts +3 -1
  65. package/src/api/preflight.js +2 -0
  66. package/src/extension/config.d.ts +1 -0
  67. package/src/extension/config.js +13 -1
  68. package/src/extension/herdr-pi-bridge.js +10 -2
  69. package/src/extension/index.d.ts +0 -13
  70. package/src/extension/index.js +51 -37
  71. package/src/extension/public-execution.d.ts +1 -0
  72. package/src/extension/public-execution.js +4 -0
  73. package/src/extension/reply-workflow-script.js +24 -4
  74. package/src/extension/schemas.d.ts +12 -3
  75. package/src/extension/schemas.js +7 -3
  76. package/src/extension/session-switch.d.ts +25 -0
  77. package/src/extension/session-switch.js +138 -0
  78. package/src/extension/subagent-guide.d.ts +1 -1
  79. package/src/extension/subagent-guide.js +1 -1
  80. package/src/extension/subagent-launch-tool.d.ts +25 -0
  81. package/src/extension/subagent-launch-tool.js +48 -0
  82. package/src/extension/tool-activation.js +55 -15
  83. package/src/extension/tool-description.d.ts +1 -1
  84. package/src/extension/tool-description.js +14 -8
  85. package/src/inspectors/herdr/actions.d.ts +0 -1
  86. package/src/inspectors/herdr/actions.js +0 -1
  87. package/src/inspectors/session-roots-codec.d.ts +0 -1
  88. package/src/inspectors/session-roots-codec.js +0 -1
  89. package/src/inspectors/tmux/actions.d.ts +0 -1
  90. package/src/inspectors/tmux/actions.js +0 -1
  91. package/src/integrations/herdr-status.js +3 -8
  92. package/src/intercom/native-supervisor-channel.js +65 -9
  93. package/src/runs/background/async-execution.d.ts +7 -10
  94. package/src/runs/background/async-execution.js +66 -29
  95. package/src/runs/background/async-job-tracker.js +12 -0
  96. package/src/runs/background/async-resume.d.ts +2 -1
  97. package/src/runs/background/async-resume.js +114 -40
  98. package/src/runs/background/async-retention.d.ts +0 -2
  99. package/src/runs/background/async-retention.js +17 -6
  100. package/src/runs/background/async-status.d.ts +2 -0
  101. package/src/runs/background/async-status.js +4 -0
  102. package/src/runs/background/auto-drain.js +2 -1
  103. package/src/runs/background/boot-id.d.ts +1 -3
  104. package/src/runs/background/boot-id.js +1 -3
  105. package/src/runs/background/completion-batcher.d.ts +3 -4
  106. package/src/runs/background/completion-batcher.js +2 -3
  107. package/src/runs/background/control-channel.d.ts +0 -6
  108. package/src/runs/background/control-channel.js +0 -6
  109. package/src/runs/background/fleet-view.js +2 -3
  110. package/src/runs/background/notify.d.ts +0 -2
  111. package/src/runs/background/notify.js +0 -2
  112. package/src/runs/background/result-watcher.d.ts +1 -0
  113. package/src/runs/background/result-watcher.js +59 -29
  114. package/src/runs/background/resume-guidance.js +4 -2
  115. package/src/runs/background/retained-children.js +2 -1
  116. package/src/runs/background/run-child-session.d.ts +2 -3
  117. package/src/runs/background/run-child-session.js +5 -8
  118. package/src/runs/background/run-status.js +9 -7
  119. package/src/runs/background/runner-aliases.js +15 -0
  120. package/src/runs/background/scheduled-runs.d.ts +3 -1
  121. package/src/runs/background/scheduled-runs.js +13 -16
  122. package/src/runs/background/steering.d.ts +2 -11
  123. package/src/runs/background/steering.js +11 -6
  124. package/src/runs/background/subagent-runner.d.ts +2 -6
  125. package/src/runs/background/subagent-runner.js +88 -70
  126. package/src/runs/background/subagent-wait.js +12 -15
  127. package/src/runs/background/wait-config.d.ts +2 -0
  128. package/src/runs/background/wait-config.js +17 -3
  129. package/src/runs/background/wait-subscriptions.js +124 -12
  130. package/src/runs/background/wait-tool.js +4 -2
  131. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  132. package/src/runs/background/workflow-terminal-proof.js +0 -1
  133. package/src/runs/foreground/async-steering-action.js +24 -9
  134. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  135. package/src/runs/foreground/async-stop-action.js +9 -1
  136. package/src/runs/foreground/execution.d.ts +0 -3
  137. package/src/runs/foreground/execution.js +56 -24
  138. package/src/runs/foreground/prompt-audit.js +1 -0
  139. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  140. package/src/runs/foreground/subagent-executor.js +164 -49
  141. package/src/runs/shared/acceptance.js +69 -26
  142. package/src/runs/shared/async-status-projection.d.ts +2 -0
  143. package/src/runs/shared/async-status-projection.js +10 -0
  144. package/src/runs/shared/child-commands.js +15 -2
  145. package/src/runs/shared/child-hooks.d.ts +1 -7
  146. package/src/runs/shared/child-hooks.js +13 -5
  147. package/src/runs/shared/child-launch.js +6 -2
  148. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  149. package/src/runs/shared/child-session.d.ts +6 -5
  150. package/src/runs/shared/child-session.js +85 -38
  151. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  152. package/src/runs/shared/child-tool-plan.js +0 -1
  153. package/src/runs/shared/claude-code-adapter.js +11 -0
  154. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  155. package/src/runs/shared/external-cli-contract.js +18 -13
  156. package/src/runs/shared/external-cli-runner.js +26 -6
  157. package/src/runs/shared/herdr-connection.js +2 -1
  158. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  159. package/src/runs/shared/herdr-pane-host.js +17 -1
  160. package/src/runs/shared/herdr-placed-run.js +51 -24
  161. package/src/runs/shared/lane-metadata.d.ts +0 -1
  162. package/src/runs/shared/lane-metadata.js +0 -1
  163. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  164. package/src/runs/shared/mcp-config-sources.js +1 -1
  165. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  166. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  167. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  168. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  169. package/src/runs/shared/model-resolution.d.ts +20 -5
  170. package/src/runs/shared/model-resolution.js +55 -50
  171. package/src/runs/shared/model-scope.d.ts +1 -5
  172. package/src/runs/shared/model-scope.js +1 -5
  173. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  174. package/src/runs/shared/mutation-evidence.js +52 -7
  175. package/src/runs/shared/nested-events.d.ts +1 -0
  176. package/src/runs/shared/nested-events.js +1 -1
  177. package/src/runs/shared/parallel-utils.d.ts +0 -1
  178. package/src/runs/shared/permissions.js +5 -3
  179. package/src/runs/shared/placement-host.d.ts +5 -1
  180. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  181. package/src/runs/shared/rex-pane-host.js +0 -2
  182. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  183. package/src/runs/shared/run-launch-folder.js +21 -0
  184. package/src/runs/shared/runner-launcher.d.ts +12 -1
  185. package/src/runs/shared/runner-launcher.js +16 -0
  186. package/src/runs/shared/single-output.d.ts +3 -3
  187. package/src/runs/shared/single-output.js +5 -3
  188. package/src/runs/shared/structured-output.d.ts +8 -0
  189. package/src/runs/shared/structured-output.js +40 -5
  190. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  191. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  192. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  193. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  194. package/src/runs/shared/tool-timeout.js +2 -1
  195. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  196. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  197. package/src/runs/shared/worktree.d.ts +3 -0
  198. package/src/runs/shared/worktree.js +20 -0
  199. package/src/shared/artifacts.d.ts +1 -0
  200. package/src/shared/artifacts.js +132 -22
  201. package/src/shared/capacity-resilient-json.d.ts +1 -1
  202. package/src/shared/child-cache-retention.d.ts +1 -2
  203. package/src/shared/child-cache-retention.js +1 -2
  204. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  205. package/src/shared/fleet-transcript-reader.js +333 -0
  206. package/src/shared/formatters.d.ts +0 -18
  207. package/src/shared/formatters.js +0 -18
  208. package/src/shared/pruned-fork.js +2 -2
  209. package/src/shared/reported-progress.d.ts +1 -0
  210. package/src/shared/reported-progress.js +12 -0
  211. package/src/shared/session-succession.d.ts +16 -1
  212. package/src/shared/session-succession.js +41 -2
  213. package/src/shared/session-warnings.d.ts +7 -0
  214. package/src/shared/session-warnings.js +26 -0
  215. package/src/shared/settings.d.ts +0 -23
  216. package/src/shared/settings.js +3 -35
  217. package/src/shared/status-format.d.ts +1 -0
  218. package/src/shared/status-format.js +1 -1
  219. package/src/shared/types.d.ts +108 -59
  220. package/src/shared/types.js +0 -12
  221. package/src/shared/utils.d.ts +3 -15
  222. package/src/shared/utils.js +4 -22
  223. package/src/shared/wait-tool-name.d.ts +8 -0
  224. package/src/shared/wait-tool-name.js +13 -0
  225. package/src/slash/slash-commands.js +2 -1
  226. package/src/slash/subagent-cost.d.ts +3 -2
  227. package/src/slash/subagent-cost.js +22 -3
  228. package/src/slash/subagents-admin.js +0 -1
  229. package/src/tui/fleet-status.d.ts +0 -5
  230. package/src/tui/fleet-status.js +4 -24
  231. package/src/tui/fleet.js +6 -4
  232. package/src/tui/render.d.ts +0 -9
  233. package/src/tui/render.js +194 -68
  234. package/src/tui/subagent-messages.js +3 -2
  235. package/src/watchdog/model-selection.js +2 -2
  236. package/src/watchdog/permission-arbiter.js +1 -0
  237. package/src/watchdog/register-child.d.ts +2 -3
  238. package/src/watchdog/register-child.js +2 -3
  239. package/src/watchdog/review.d.ts +0 -5
  240. package/src/watchdog/review.js +4 -3
  241. package/src/watchdog/turn-delta.js +2 -1
  242. package/src/workflows/scripted-workflow.d.ts +2 -0
  243. package/src/workflows/scripted-workflow.js +344 -59
  244. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  245. package/src/workflows/structured-workflow-scripts.js +32 -11
  246. package/src/workflows/workflow-launch-record.d.ts +15 -6
  247. package/src/workflows/workflow-launch-record.js +30 -12
  248. package/src/workflows/workflow-receipt.js +36 -53
  249. package/src/workflows/workflow-resources.js +4 -4
  250. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  251. package/src/workflows/workflow-resume-claim.js +3 -3
  252. package/src/workflows/workflow-resume.d.ts +1 -1
  253. package/src/workflows/workflow-resume.js +13 -8
  254. package/src/workflows/workflow-script-worker.d.ts +13 -0
  255. package/src/workflows/workflow-script-worker.js +81 -0
  256. package/workflow-script-process.cjs +36 -0
  257. package/workflow-script-worker.cjs +4 -1
  258. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -1,6 +1,3 @@
1
- /**
2
- * TypeBox schemas for subagent tool parameters
3
- */
4
1
  import { Type } from "typebox";
5
2
  import type { DisabledFeatureSurface } from "../shared/disabled-features.ts";
6
3
  /** Full flat parameter shape accepted by RPC, slash, scheduled and workflow callers. */
@@ -10,6 +7,7 @@ export declare const SubagentFlatParams: Type.TObject<{
10
7
  extensionBindings: Type.TOptional<Type.TUnsafe<unknown>>;
11
8
  action: Type.TOptional<Type.TString>;
12
9
  capabilities: Type.TOptional<Type.TBoolean>;
10
+ search: Type.TOptional<Type.TString>;
13
11
  name: Type.TOptional<Type.TString>;
14
12
  id: Type.TOptional<Type.TString>;
15
13
  runId: Type.TOptional<Type.TString>;
@@ -22,6 +20,7 @@ export declare const SubagentFlatParams: Type.TObject<{
22
20
  supersession: Type.TOptional<Type.TUnsafe<unknown>>;
23
21
  index: Type.TOptional<Type.TInteger>;
24
22
  childId: Type.TOptional<Type.TString>;
23
+ drain: Type.TOptional<Type.TBoolean>;
25
24
  toolCallId: Type.TOptional<Type.TString>;
26
25
  view: Type.TOptional<Type.TString>;
27
26
  lines: Type.TOptional<Type.TInteger>;
@@ -104,6 +103,10 @@ export declare const SubagentFlatParams: Type.TObject<{
104
103
  agentScope: Type.TOptional<Type.TString>;
105
104
  cwd: Type.TOptional<Type.TString>;
106
105
  machine: Type.TOptional<Type.TString>;
106
+ requireLauncher: Type.TOptional<Type.TObject<{
107
+ name: Type.TString;
108
+ definitionDigest: Type.TString;
109
+ }>>;
107
110
  artifacts: Type.TOptional<Type.TBoolean>;
108
111
  includeProgress: Type.TOptional<Type.TBoolean>;
109
112
  share: Type.TOptional<Type.TBoolean>;
@@ -139,6 +142,7 @@ export declare const SUBAGENT_OPTION_KEYS: readonly string[];
139
142
  export declare const SubagentOptionParams: Type.TObject<{
140
143
  extensionBindings: Type.TOptional<Type.TUnsafe<unknown>>;
141
144
  capabilities: Type.TOptional<Type.TBoolean>;
145
+ search: Type.TOptional<Type.TString>;
142
146
  name: Type.TOptional<Type.TString>;
143
147
  dir: Type.TOptional<Type.TString>;
144
148
  handoffPath: Type.TOptional<Type.TString>;
@@ -149,6 +153,7 @@ export declare const SubagentOptionParams: Type.TObject<{
149
153
  supersession: Type.TOptional<Type.TUnsafe<unknown>>;
150
154
  index: Type.TOptional<Type.TInteger>;
151
155
  childId: Type.TOptional<Type.TString>;
156
+ drain: Type.TOptional<Type.TBoolean>;
152
157
  toolCallId: Type.TOptional<Type.TString>;
153
158
  view: Type.TOptional<Type.TString>;
154
159
  lines: Type.TOptional<Type.TInteger>;
@@ -223,6 +228,10 @@ export declare const SubagentOptionParams: Type.TObject<{
223
228
  }>>;
224
229
  agentScope: Type.TOptional<Type.TString>;
225
230
  machine: Type.TOptional<Type.TString>;
231
+ requireLauncher: Type.TOptional<Type.TObject<{
232
+ name: Type.TString;
233
+ definitionDigest: Type.TString;
234
+ }>>;
226
235
  artifacts: Type.TOptional<Type.TBoolean>;
227
236
  includeProgress: Type.TOptional<Type.TBoolean>;
228
237
  share: Type.TOptional<Type.TBoolean>;
@@ -1,7 +1,5 @@
1
- /**
2
- * TypeBox schemas for subagent tool parameters
3
- */
4
1
  import { Type } from "typebox";
2
+ import { RUNNER_LAUNCHER_NAME_PATTERN } from "../shared/types.js";
5
3
  import { MAX_ARGS_BYTES, MAX_ARGS_DEPTH, MAX_ARGS_FIELDS, MAX_ARGS_ITEMS } from "../workflows/workflow-resources.js";
6
4
  function keepTopLevelParameterDescriptions(schema) {
7
5
  return pruneNestedDescriptions(schema, []);
@@ -143,6 +141,7 @@ const SubagentParamProperties = {
143
141
  description: "Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with {action:\"guide\",options:{topic:\"tool-reference\"}}."
144
142
  })),
145
143
  capabilities: Type.Optional(Type.Boolean({ description: "list: compact capability rows/details without system prompts." })),
144
+ search: Type.Optional(Type.String({ minLength: 1, description: "list: case-insensitive match on agent name, alias, or description." })),
146
145
  name: Type.Optional(Type.String({ description: "schedule.create name." })),
147
146
  id: Type.Optional(Type.String({
148
147
  description: "Run id/prefix for status/control."
@@ -161,6 +160,7 @@ const SubagentParamProperties = {
161
160
  supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
162
161
  index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child/transcript index." })),
163
162
  childId: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Child-scoped stop identity." })),
163
+ drain: Type.Optional(Type.Boolean({ description: "stop: a live async workflow starts no new children; started ones finish." })),
164
164
  toolCallId: Type.Optional(Type.String({ description: "Command tool-call id." })),
165
165
  view: Type.Optional(Type.String({
166
166
  enum: ["fleet", "transcript"],
@@ -228,6 +228,10 @@ const SubagentParamProperties = {
228
228
  agentScope: Type.Optional(Type.String({ description: "user/project/both (default); project wins collisions." })),
229
229
  cwd: Type.Optional(Type.String({ description: "Execution/project-pane directory." })),
230
230
  machine: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Herdr saved machine id or label (runs an external CLI agent), a Rex host named in settings (runs a Pi child), or \"local\" (a Pi child in a Rex pane here). On another machine, cwd is a directory there." })),
231
+ requireLauncher: Type.Optional(Type.Object({
232
+ name: Type.String({ pattern: RUNNER_LAUNCHER_NAME_PATTERN.source }),
233
+ definitionDigest: Type.String({ pattern: "^[0-9a-f]{64}$" }),
234
+ }, { additionalProperties: false, description: "Top-level single async launch only: refuse unless the agent runs under this launcher with this definition digest (preflight agent.definitionDigest)." })),
231
235
  artifacts: Type.Optional(Type.Boolean({ description: "Debug artifacts; default true." })),
232
236
  includeProgress: Type.Optional(Type.Boolean({ description: "Full result progress; default false." })),
233
237
  share: Type.Optional(Type.Boolean({ description: "Upload session to GitHub Gist; default false." })),
@@ -0,0 +1,25 @@
1
+ import type { ExtensionContext, SessionShutdownEvent } from "@earendil-works/pi-coding-agent";
2
+ import type { SubagentState } from "../shared/types.ts";
3
+ type SwitchReason = "new" | "resume" | "fork";
4
+ export type SessionSwitchContext = Pick<ExtensionContext, "mode" | "hasUI"> & {
5
+ ui: Pick<ExtensionContext["ui"], "select" | "notify">;
6
+ };
7
+ interface SessionSwitchDeps {
8
+ state: SubagentState;
9
+ asyncDirRoot: string;
10
+ resultsDir: string;
11
+ hasPendingResults(): boolean;
12
+ hasPendingSupervisorRequest(): boolean;
13
+ }
14
+ /**
15
+ * Asks what happens to this session's outstanding background work when a UI session switches away. Without a UI or
16
+ * outstanding work the switch proceeds and the next session inherits the work. The prompt never enters model history.
17
+ */
18
+ export declare function createSessionSwitchGuard(deps: SessionSwitchDeps): {
19
+ beforeSwitch(reason: SwitchReason, ctx: SessionSwitchContext): Promise<{
20
+ cancel: true;
21
+ } | undefined>;
22
+ sessionShutdown(event: SessionShutdownEvent): void;
23
+ dispose(): void;
24
+ };
25
+ export {};
@@ -0,0 +1,138 @@
1
+ import { isActiveAsyncState } from "../runs/background/active-run-index.js";
2
+ import { listAsyncRuns } from "../runs/background/async-status.js";
3
+ import { reconcileNestedAsyncDescendants } from "../runs/background/stale-run-reconciler.js";
4
+ import { ownsRun } from "../runs/shared/run-ownership.js";
5
+ import { collectNestedRuns, projectNestedEvents } from "../runs/shared/nested-events.js";
6
+ import { keepSessionWork, releaseSessionWork } from "../shared/session-succession.js";
7
+ import { readStatus } from "../shared/utils.js";
8
+ const STAY = "Stay here";
9
+ const TAKE = "Switch and take the work";
10
+ const LEAVE = "Switch and leave the work here";
11
+ const RPC_PROMPT_TIMEOUT_MS = 60_000;
12
+ /**
13
+ * Asks what happens to this session's outstanding background work when a UI session switches away. Without a UI or
14
+ * outstanding work the switch proceeds and the next session inherits the work. The prompt never enters model history.
15
+ */
16
+ export function createSessionSwitchGuard(deps) {
17
+ let leave;
18
+ let checking = false;
19
+ const lifetime = new AbortController();
20
+ const activeRunCount = (sessionId) => {
21
+ const runs = new Set(listAsyncRuns(deps.asyncDirRoot, {
22
+ sessionId, states: ["queued", "running"], resultsDir: deps.resultsDir, includeNested: false,
23
+ }).map((run) => run.id));
24
+ // Include launch receipts whose active-index marker has not landed yet.
25
+ for (const job of deps.state.asyncJobs.values()) {
26
+ if (runs.has(job.asyncId) || !ownsRun(sessionId, job.sessionId) || !isActiveAsyncState(job.status))
27
+ continue;
28
+ let active = true;
29
+ // An unreadable status could be a live run, so it counts as outstanding instead of refusing every switch.
30
+ try {
31
+ const status = readStatus(job.asyncDir);
32
+ active = !status || isActiveAsyncState(status.state);
33
+ }
34
+ catch { /* active */ }
35
+ if (active)
36
+ runs.add(job.asyncId);
37
+ }
38
+ for (const id of deps.state.workflowControllers?.keys() ?? [])
39
+ runs.add(id);
40
+ return runs.size;
41
+ };
42
+ const hasNestedWork = (sessionId) => {
43
+ const routes = new Map();
44
+ for (const job of deps.state.asyncJobs.values()) {
45
+ if (!ownsRun(sessionId, job.sessionId))
46
+ continue;
47
+ if (job.nestedRoute)
48
+ routes.set(job.nestedRoute.rootRunId, job.nestedRoute);
49
+ else if (collectNestedRuns(job.nestedChildren).some((run) => isActiveAsyncState(run.state)))
50
+ return true;
51
+ }
52
+ for (const control of deps.state.foregroundControls.values()) {
53
+ if (control.sessionId && !ownsRun(sessionId, control.sessionId))
54
+ continue;
55
+ if (control.nestedRoute)
56
+ routes.set(control.nestedRoute.rootRunId, control.nestedRoute);
57
+ }
58
+ for (const route of deps.state.retainedForegroundNestedRoutes?.values() ?? [])
59
+ routes.set(route.rootRunId, route);
60
+ if (deps.state.retainedNestedLookupRoutes?.sessionId === sessionId) {
61
+ for (const route of deps.state.retainedNestedLookupRoutes.routes.values())
62
+ routes.set(route.rootRunId, route);
63
+ }
64
+ return [...routes.values()].some((route) => {
65
+ reconcileNestedAsyncDescendants(route, { resultsDir: deps.resultsDir });
66
+ return collectNestedRuns(projectNestedEvents(route).children).some((run) => isActiveAsyncState(run.state));
67
+ });
68
+ };
69
+ return {
70
+ async beforeSwitch(reason, ctx) {
71
+ if (lifetime.signal.aborted || checking)
72
+ return { cancel: true };
73
+ leave = undefined; // A choice belongs to this switch attempt only.
74
+ if (!ctx.hasUI)
75
+ return;
76
+ checking = true;
77
+ try {
78
+ const sessionId = deps.state.currentSessionId;
79
+ if (!sessionId)
80
+ throw new Error("The current session identity is unavailable.");
81
+ const runs = activeRunCount(sessionId);
82
+ const nested = hasNestedWork(sessionId);
83
+ const results = deps.hasPendingResults();
84
+ const questions = deps.hasPendingSupervisorRequest();
85
+ if (runs === 0 && !nested && !results && !questions)
86
+ return;
87
+ const title = [
88
+ "pi-subagents: switch sessions?",
89
+ "",
90
+ "Background subagent work in this session:",
91
+ ...(runs > 0 ? [` ${runs} run${runs === 1 ? "" : "s"} queued or running`] : []),
92
+ ...(nested ? [" Nested subagents still running"] : []),
93
+ ...(results ? [" Undelivered results"] : []),
94
+ ...(questions ? [" Questions awaiting a reply"] : []),
95
+ ].join("\n");
96
+ const choice = await ctx.ui.select(title, [STAY, TAKE, LEAVE], { signal: lifetime.signal, timeout: ctx.mode === "rpc" ? RPC_PROMPT_TIMEOUT_MS : undefined });
97
+ if (lifetime.signal.aborted || deps.state.currentSessionId !== sessionId)
98
+ return { cancel: true };
99
+ if (choice === TAKE)
100
+ return;
101
+ if (choice === LEAVE) {
102
+ leave = { sessionId, reason };
103
+ return;
104
+ }
105
+ return { cancel: true };
106
+ }
107
+ catch (error) {
108
+ const message = error instanceof Error ? error.message : String(error);
109
+ // Pi ignores thrown switch hooks; always return cancel, even if the UI is stale.
110
+ try {
111
+ if (!lifetime.signal.aborted)
112
+ ctx.ui.notify(`Session switch cancelled: ${message}`, "warning");
113
+ }
114
+ catch { /* The context may already be stale. */ }
115
+ return { cancel: true };
116
+ }
117
+ finally {
118
+ checking = false;
119
+ }
120
+ },
121
+ // Recorded only once the switch commits, so a switch another extension cancels keeps the default handoff.
122
+ sessionShutdown(event) {
123
+ const left = leave;
124
+ leave = undefined;
125
+ const sessionId = deps.state.currentSessionId;
126
+ if (!sessionId)
127
+ return;
128
+ if (left && left.sessionId === sessionId && left.reason === event.reason)
129
+ keepSessionWork(sessionId);
130
+ else
131
+ releaseSessionWork(sessionId);
132
+ },
133
+ dispose() {
134
+ leave = undefined;
135
+ lifetime.abort();
136
+ },
137
+ };
138
+ }
@@ -1,4 +1,4 @@
1
1
  export declare const SUBAGENT_GUIDE_TOPICS: readonly ["overview", "workflows", "agents", "missions", "observability", "tool-reference", "configuration", "models", "watchdog", "extension-api", "council"];
2
2
  export type SubagentGuideTopic = (typeof SUBAGENT_GUIDE_TOPICS)[number];
3
- /** Reads a guide topic. Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
3
+ /** Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
4
4
  export declare function readSubagentGuide(topic?: string, root?: string): string;
@@ -88,7 +88,7 @@ function readGuideFiles(topic, files, root) {
88
88
  throw new Error(`Failed to read packaged subagents guide '${topic}': ${message}`, { cause: error instanceof Error ? error : undefined });
89
89
  }
90
90
  }
91
- /** Reads a guide topic. Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
91
+ /** Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
92
92
  export function readSubagentGuide(topic = "overview", root = packageRoot) {
93
93
  const separator = topic.indexOf("/");
94
94
  const name = separator === -1 ? topic : topic.slice(0, separator);
@@ -0,0 +1,25 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { Type, type Static } from "typebox";
3
+ declare const parameters: Type.TObject<{
4
+ workflowRunId: Type.TString;
5
+ key: Type.TString;
6
+ agent: Type.TOptional<Type.TString>;
7
+ task: Type.TOptional<Type.TString>;
8
+ cwd: Type.TOptional<Type.TString>;
9
+ model: Type.TOptional<Type.TString>;
10
+ async: Type.TOptional<Type.TBoolean>;
11
+ worktree: Type.TOptional<Type.TBoolean>;
12
+ resume: Type.TOptional<Type.TString>;
13
+ commands: Type.TOptional<Type.TArray<Type.TObject<{
14
+ command: Type.TString;
15
+ cwd: Type.TOptional<Type.TString>;
16
+ env: Type.TOptional<Type.TRecord<"^.*$", Type.TString>>;
17
+ }>>>;
18
+ output: Type.TOptional<Type.TString>;
19
+ }>;
20
+ export type SubagentLaunchArgs = Static<typeof parameters>;
21
+ /** Not declared to the model, so the system prompt and tool list stay unchanged. */
22
+ export declare function registerSubagentLaunchTool(pi: ExtensionAPI): void;
23
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
24
+ export declare function approveWorkflowChildLaunch(ctx: ExtensionContext, describe: () => SubagentLaunchArgs, signal: AbortSignal): Promise<string | undefined>;
25
+ export {};
@@ -0,0 +1,48 @@
1
+ import { Type } from "typebox";
2
+ const SUBAGENT_LAUNCH_TOOL = "subagent_launch";
3
+ const parameters = Type.Object({
4
+ workflowRunId: Type.String(),
5
+ key: Type.String(),
6
+ agent: Type.Optional(Type.String()),
7
+ task: Type.Optional(Type.String()),
8
+ cwd: Type.Optional(Type.String()),
9
+ model: Type.Optional(Type.String()),
10
+ async: Type.Optional(Type.Boolean()),
11
+ worktree: Type.Optional(Type.Boolean()),
12
+ resume: Type.Optional(Type.String()),
13
+ commands: Type.Optional(Type.Array(Type.Object({
14
+ command: Type.String(),
15
+ cwd: Type.Optional(Type.String()),
16
+ env: Type.Optional(Type.Record(Type.String(), Type.String())),
17
+ }))),
18
+ output: Type.Optional(Type.String()),
19
+ });
20
+ /** Not declared to the model, so the system prompt and tool list stay unchanged. */
21
+ export function registerSubagentLaunchTool(pi) {
22
+ pi.registerTool({
23
+ name: SUBAGENT_LAUNCH_TOOL,
24
+ label: "Subagent launch",
25
+ description: "A workflow is about to start this subagent. Blocking this call stops that child from starting.",
26
+ parameters,
27
+ exposure: "deferred",
28
+ async execute() {
29
+ return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: {} };
30
+ },
31
+ });
32
+ }
33
+ /** Offers a workflow child start to the session's `tool_call` handlers; returns the refusal, if any. */
34
+ export async function approveWorkflowChildLaunch(ctx, describe, signal) {
35
+ // Starts with no tool call behind them (schedule ticks, auto-resume, RPC) have no executeTool, and a tool
36
+ // allowlist that leaves the tool out unregisters it: no handler could see the call in either case.
37
+ if (!("executeTool" in ctx))
38
+ return undefined;
39
+ const toolCtx = ctx;
40
+ if (!toolCtx.tools.some((tool) => tool.name === SUBAGENT_LAUNCH_TOOL))
41
+ return undefined;
42
+ const args = describe();
43
+ const outcome = await toolCtx.executeTool(SUBAGENT_LAUNCH_TOOL, args, { signal });
44
+ if (!outcome.isError)
45
+ return undefined;
46
+ const reason = outcome.result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
47
+ return `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}`;
48
+ }
@@ -2,28 +2,35 @@ import { Type } from "typebox";
2
2
  import { MODEL_ONLY_TOOL } from "../shared/extension-context.js";
3
3
  import { registerPinnedTool } from "./declaration-pinning.js";
4
4
  import { listBackgroundWorkProviders } from "../api/background-work.js";
5
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../shared/wait-tool-name.js";
5
6
  import { CONTACT_SUPERVISOR_TOOL_NAME as SUPERVISOR_NAME, NATIVE_SUPERVISOR_TOOL_NAME as PARENT_SUPERVISOR_NAME } from "../intercom/native-supervisor-channel.js";
6
7
  const LOADER_NAME = "subagents_enable";
7
8
  const SUBAGENT_NAME = "subagent";
8
- // Declared with subagent, or once background-work providers exist (they report work only bg_wait reads).
9
- const WAIT_NAME = "bg_wait";
9
+ // The wait tool (bg_wait unless config.waitTool.name renames it) is declared with subagent, or once
10
+ // background-work providers exist (they report work only the wait tool reads).
10
11
  // SUPERVISOR_NAME is declared with subagent: a fork launched through it then declares exactly this session's tools.
11
12
  // PARENT_SUPERVISOR_NAME (answering this session's children) is declared with subagent too, unless the session already
12
13
  // declared it: a changed tool set would miss the prompt cache. The channel declares it when a child request arrives.
13
- const UNLOAD_SENTINELS = new Set([LOADER_NAME, SUBAGENT_NAME, WAIT_NAME]);
14
+ const isUnloadSentinel = (name) => name === LOADER_NAME || name === SUBAGENT_NAME || name === waitToolName();
15
+ // Every bg_wait pi-subagents has registered (since 0.61.0) takes nonBlocking and stopOnAttention; another extension's
16
+ // bg_wait (@99percentpeople/pi-background-tasks takes id and timeout) does not.
17
+ function isOwnWaitDefinition(tool) {
18
+ const properties = tool.parameters?.properties;
19
+ return typeof properties === "object" && properties !== null && Object.hasOwn(properties, "nonBlocking") && Object.hasOwn(properties, "stopOnAttention");
20
+ }
14
21
  function hasNativeToolSelection(messages) {
15
22
  return messages.some((message) => message.role === "system"
16
23
  && (Object.hasOwn(message, "toolsAdded") || Object.hasOwn(message, "toolsRemoved")));
17
24
  }
18
25
  function setSelection(pi, includeSubagent, includeLoader, includeWait, restore = [], keepParentSupervisor = false) {
19
26
  const next = [...pi.getActiveTools(), ...restore].filter((name) => (includeSubagent || (name !== SUBAGENT_NAME && name !== SUPERVISOR_NAME && (keepParentSupervisor || name !== PARENT_SUPERVISOR_NAME)))
20
- && (includeLoader || name !== LOADER_NAME) && (includeWait || name !== WAIT_NAME));
27
+ && (includeLoader || name !== LOADER_NAME) && (includeWait || name !== waitToolName()));
21
28
  if (includeSubagent)
22
29
  next.push(SUBAGENT_NAME, SUPERVISOR_NAME, PARENT_SUPERVISOR_NAME);
23
30
  if (includeLoader)
24
31
  next.push(LOADER_NAME);
25
32
  if (includeWait)
26
- next.push(WAIT_NAME);
33
+ next.push(waitToolName());
27
34
  pi.setActiveTools([...new Set(next)]);
28
35
  }
29
36
  // Mirrors pi-ai's per-API transcript handling: without these flags, a mid-conversation tool change
@@ -49,7 +56,16 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
49
56
  if (!available.some((tool) => tool.name === LOADER_NAME))
50
57
  return true;
51
58
  // SAFETY: The running Pi session manager exposes buildSessionContext, but its read-only extension type omits it.
52
- const messages = ctx.sessionManager.buildSessionContext().messages;
59
+ let messages = ctx.sessionManager.buildSessionContext().messages;
60
+ // A compaction checkpoint (the system message before the summary) folds the branch's earlier system messages into
61
+ // one declaration, which hides an extension unload before the compaction. Replay those messages instead, as Pi
62
+ // restores the session's tools from them.
63
+ if (messages[0]?.role === "system" && messages[1]?.role === "compactionSummary") {
64
+ const branch = ctx.sessionManager.getBranch();
65
+ const history = branch.slice(0, branch.findLastIndex((entry) => entry.type === "compaction"))
66
+ .flatMap((entry) => entry.type === "message" && entry.message.role === "system" ? [entry.message] : []);
67
+ messages = [...history, ...messages.slice(1)];
68
+ }
53
69
  // A compaction without a checkpoint leaves its summary first, with no system message before it: the
54
70
  // declarations from before it are lost, even when no tool selection was recorded after it.
55
71
  const lost = messages.find((message) => message.role === "system" || message.role === "compactionSummary")?.role === "compactionSummary";
@@ -60,6 +76,8 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
60
76
  const declaredSentinels = new Set();
61
77
  // Tools the surviving transcript says something about: an addition, or a removal that is not an unload.
62
78
  const evidenced = new Set();
79
+ // Whether the latest bg_wait declaration was this extension's wait tool, from before a waitTool.name rename.
80
+ let legacyWaitIsOwn = false;
63
81
  for (const message of messages) {
64
82
  if (message.role !== "system")
65
83
  continue;
@@ -67,12 +85,12 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
67
85
  // While this extension is loaded, the loader, subagent or bg_wait stays declared, so a removal of declared
68
86
  // sentinels that leaves none of them is that unload, not a choice, and the selection from before it stands.
69
87
  // Pi removes only declared tools, so a removal naming an undeclared sentinel is a choice.
70
- const removedSentinels = (message.toolsRemoved ?? []).filter((tool) => UNLOAD_SENTINELS.has(tool.name));
88
+ const removedSentinels = (message.toolsRemoved ?? []).filter((tool) => isUnloadSentinel(tool.name));
71
89
  const allDeclared = removedSentinels.every((tool) => declaredSentinels.has(tool.name));
72
90
  for (const tool of message.toolsRemoved ?? [])
73
91
  declaredSentinels.delete(tool.name);
74
92
  for (const tool of message.toolsAdded ?? [])
75
- if (UNLOAD_SENTINELS.has(tool.name))
93
+ if (isUnloadSentinel(tool.name))
76
94
  declaredSentinels.add(tool.name);
77
95
  const unloaded = removedSentinels.length > 0 && allDeclared && declaredSentinels.size === 0;
78
96
  for (const tool of message.toolsRemoved ?? []) {
@@ -86,6 +104,8 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
86
104
  for (const tool of message.toolsAdded ?? []) {
87
105
  recorded.add(tool.name);
88
106
  evidenced.add(tool.name);
107
+ if (tool.name === DEFAULT_WAIT_TOOL_NAME)
108
+ legacyWaitIsOwn = isOwnWaitDefinition(tool);
89
109
  }
90
110
  }
91
111
  // The loader and subagent record one activation state (cold, warm, eager); bg_wait and subagent_supervisor
@@ -101,17 +121,20 @@ function applyRecordedSelection(pi, ctx, mode, replyOwed) {
101
121
  // A new process restores the transcript's tools, where the unload left this extension's tools inactive; only
102
122
  // /reload re-adds them. Restoring them keeps a sentinel declared, so a later unload is recognised too. Tools of
103
123
  // other extensions, and tools excluded for this process (not registered, so not in getAllTools), stay as they are.
124
+ // A transcript from before a waitTool.name rename records the wait tool as bg_wait; that record stands for the
125
+ // renamed tool while the transcript says nothing about the new name and its latest bg_wait was this extension's.
126
+ const waitRecord = waitToolName() !== DEFAULT_WAIT_TOOL_NAME && !evidenced.has(waitToolName()) && legacyWaitIsOwn ? DEFAULT_WAIT_TOOL_NAME : waitToolName();
104
127
  const source = unloadedNames.size > 0 ? available.find((tool) => tool.name === LOADER_NAME)?.sourceInfo.path : undefined;
105
128
  const restore = source === undefined ? [] : available
106
129
  .filter((tool) => unloadedNames.has(tool.name) && recorded.has(tool.name) && tool.sourceInfo.path === source)
107
130
  .map((tool) => tool.name);
108
- setSelection(pi, recorded.has(SUBAGENT_NAME) || startsEager, loaderSelected, recorded.has(WAIT_NAME) || (!evidenced.has(WAIT_NAME) && startsEager), replyOwed ? [...restore, PARENT_SUPERVISOR_NAME] : restore, replyOwed || recorded.has(PARENT_SUPERVISOR_NAME));
131
+ setSelection(pi, recorded.has(SUBAGENT_NAME) || startsEager, loaderSelected, recorded.has(waitRecord) || (!evidenced.has(waitRecord) && startsEager), replyOwed ? [...restore, PARENT_SUPERVISOR_NAME] : restore, replyOwed || recorded.has(PARENT_SUPERVISOR_NAME));
109
132
  return loaderSelected;
110
133
  }
111
134
  // "auto" goes eager only for an empty session; any history keeps the tools it already sent.
112
135
  const eager = mode === "auto" && messages.length === 0 && !addsToolsWithoutCheckpoint(ctx.model);
113
136
  const kept = (name) => eager || (messages.length > 0 && pi.getActiveTools().includes(name));
114
- setSelection(pi, kept(SUBAGENT_NAME), !eager, kept(WAIT_NAME), replyOwed ? [PARENT_SUPERVISOR_NAME] : [], replyOwed || messages.length > 0);
137
+ setSelection(pi, kept(SUBAGENT_NAME), !eager, kept(waitToolName()), replyOwed ? [PARENT_SUPERVISOR_NAME] : [], replyOwed || messages.length > 0);
115
138
  return !eager;
116
139
  }
117
140
  export function registerSubagentToolActivation(pi, options) {
@@ -159,19 +182,36 @@ export function registerSubagentToolActivation(pi, options) {
159
182
  },
160
183
  };
161
184
  registerPinnedTool(pi, loader);
162
- // Decided at session start and tree navigation only; switching models keeps the session's tools.
185
+ // Decided at session start and tree navigation. Pi declares a session's first tools only with its first request, so a
186
+ // model switch before then decides again; later switches keep the session's tools.
163
187
  let loaderSelected = true;
188
+ // The loader and subagent state the last decision left, until the first request (agent_start). A different live
189
+ // state is a choice made since, and stands.
190
+ let undeclared;
191
+ const activationState = () => [LOADER_NAME, SUBAGENT_NAME].map((name) => pi.getActiveTools().includes(name)).join();
164
192
  const replyOwed = () => options.hasPendingSupervisorRequest?.() === true;
165
- pi.on("session_start", (_event, ctx) => { loaderSelected = applyRecordedSelection(pi, ctx, mode, replyOwed()); });
166
- pi.on("session_tree", (_event, ctx) => { loaderSelected = applyRecordedSelection(pi, ctx, mode, replyOwed()); });
193
+ const decide = (ctx) => {
194
+ loaderSelected = applyRecordedSelection(pi, ctx, mode, replyOwed());
195
+ undeclared = Array.isArray(pi.getActiveTools()) ? activationState() : undefined;
196
+ };
197
+ pi.on("session_start", (_event, ctx) => decide(ctx));
198
+ pi.on("session_tree", (_event, ctx) => decide(ctx));
199
+ pi.on("agent_start", () => { undeclared = undefined; });
200
+ // Only while idle: a run being prepared or started may already have fixed its first tools.
201
+ pi.on("model_select", (_event, ctx) => {
202
+ if (mode === "auto" && ctx.isIdle() && undeclared === activationState() && loaderSelected !== addsToolsWithoutCheckpoint(ctx.model)
203
+ // SAFETY: as in applyRecordedSelection.
204
+ && ctx.sessionManager.buildSessionContext().messages.length === 0)
205
+ decide(ctx);
206
+ });
167
207
  pi.on("before_agent_start", (event) => {
168
208
  const available = pi.getAllTools();
169
209
  if (!Array.isArray(available) || !available.some((tool) => tool.name === LOADER_NAME))
170
210
  return;
171
211
  // Another extension's background-work provider reports work only bg_wait can wait for, so a session with one
172
212
  // declares bg_wait without enabling subagent, including when the provider registered after session start.
173
- const providedWait = available.some((tool) => tool.name === WAIT_NAME) && listBackgroundWorkProviders().length > 0;
174
- const names = [...(loaderSelected ? [LOADER_NAME] : []), ...(providedWait ? [WAIT_NAME] : [])];
213
+ const providedWait = available.some((tool) => tool.name === waitToolName()) && listBackgroundWorkProviders().length > 0;
214
+ const names = [...(loaderSelected ? [LOADER_NAME] : []), ...(providedWait ? [waitToolName()] : [])];
175
215
  if (names.length === 0)
176
216
  return;
177
217
  const selectedTools = event.systemPromptOptions.selectedTools ??= [...pi.getActiveTools()];
@@ -9,7 +9,7 @@ export interface ToolDescriptionOptions {
9
9
  cwd?: string;
10
10
  agentDir?: string;
11
11
  warn?: (message: string) => void;
12
- /** Removes lines for disabled features from the default and full descriptions; custom descriptions are unchanged apart from the appended safety guidance. */
12
+ /** Removes lines for disabled features from the default and full descriptions, including the ones custom templates insert with placeholders. */
13
13
  disabledFeatures?: DisabledFeatureSurface;
14
14
  }
15
15
  export declare function buildSubagentToolPromptMetadata(config?: Pick<ExtensionConfig, "toolDescriptionMode">, disabledFeatures?: DisabledFeatureSurface): {
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.js";
4
4
  import { resolveDisabledFeatureSurface } from "../shared/disabled-features.js";
5
+ import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../shared/wait-tool-name.js";
5
6
  const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
6
7
  const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
7
8
  function featureText(disabled) {
@@ -81,15 +82,15 @@ function customDescriptionPaths(options) {
81
82
  path.join(agentDir, CUSTOM_TOOL_DESCRIPTION_FILE),
82
83
  ];
83
84
  }
84
- function renderCustomTemplate(template, options) {
85
+ function renderCustomTemplate(template, on, options) {
85
86
  const cwd = options?.cwd ?? process.cwd();
86
87
  const agentDir = options?.agentDir ?? getAgentDir();
87
88
  const projectConfigDir = getProjectConfigDir(cwd);
88
89
  const variables = {
89
- fullDescription: () => FULL_SUBAGENT_TOOL_DESCRIPTION,
90
- full: () => FULL_SUBAGENT_TOOL_DESCRIPTION,
91
- compactDescription: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,
92
- compact: () => COMPACT_SUBAGENT_TOOL_DESCRIPTION,
90
+ fullDescription: () => fullDescription(on),
91
+ full: () => fullDescription(on),
92
+ compactDescription: () => essentials(on),
93
+ compact: () => essentials(on),
93
94
  safetyGuidance: () => SUBAGENT_SAFETY_GUIDANCE,
94
95
  safety: () => SUBAGENT_SAFETY_GUIDANCE,
95
96
  agentDir: () => agentDir,
@@ -103,7 +104,7 @@ function renderCustomTemplate(template, options) {
103
104
  return raw;
104
105
  });
105
106
  }
106
- function loadCustomToolDescription(options) {
107
+ function loadCustomToolDescription(on, options) {
107
108
  for (const filePath of customDescriptionPaths(options)) {
108
109
  let stat;
109
110
  try {
@@ -129,7 +130,7 @@ function loadCustomToolDescription(options) {
129
130
  warn(options, `Ignoring empty custom tool description '${filePath}'.`);
130
131
  continue;
131
132
  }
132
- const rendered = renderCustomTemplate(template, options).trim();
133
+ const rendered = renderCustomTemplate(template, on, options).trim();
133
134
  if (!rendered) {
134
135
  warn(options, `Ignoring custom tool description '${filePath}' because it rendered empty.`);
135
136
  continue;
@@ -153,6 +154,11 @@ function withMandatorySafetyGuidance(description) {
153
154
  : SUBAGENT_SAFETY_GUIDANCE;
154
155
  }
155
156
  export function buildSubagentToolDescription(config = {}, options) {
157
+ const description = describeSubagentTool(config, options);
158
+ const name = waitToolName();
159
+ return name === DEFAULT_WAIT_TOOL_NAME ? description : description.replace(/\bbg_wait\b/g, name);
160
+ }
161
+ function describeSubagentTool(config, options) {
156
162
  const on = options?.disabledFeatures ? featureText(options.disabledFeatures) : allEnabled;
157
163
  if (config.toolDescriptionMode === undefined)
158
164
  return essentials(on);
@@ -160,7 +166,7 @@ export function buildSubagentToolDescription(config = {}, options) {
160
166
  if (mode === "compact")
161
167
  return essentials(on);
162
168
  if (mode === "custom") {
163
- const custom = loadCustomToolDescription(options);
169
+ const custom = loadCustomToolDescription(on, options);
164
170
  if (custom)
165
171
  return withMandatorySafetyGuidance(custom);
166
172
  warn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode "custom"; using full description.`);
@@ -18,7 +18,6 @@ export interface HerdrInspectorBinding {
18
18
  }
19
19
  export declare function bindingPath(asyncDir: string, index?: number): string;
20
20
  export declare function readHerdrInspectorBinding(asyncDir: string, index?: number): HerdrInspectorBinding | undefined;
21
- /** Read a binding only when it belongs to the requested inspector target. */
22
21
  export declare function readHerdrInspectorBindingForTarget(target: InspectorTarget): HerdrInspectorBinding | undefined;
23
22
  export declare function openHerdrInspector(context: InspectorContext, launch: InspectorLaunch, params: InspectorParams, client: HerdrClient): Promise<AgentToolResult<Details>>;
24
23
  export declare function statusHerdrInspector(context: InspectorContext, client: HerdrClient): Promise<AgentToolResult<Details>>;
@@ -28,7 +28,6 @@ export function readHerdrInspectorBinding(asyncDir, index) {
28
28
  return undefined;
29
29
  }
30
30
  }
31
- /** Read a binding only when it belongs to the requested inspector target. */
32
31
  export function readHerdrInspectorBindingForTarget(target) {
33
32
  const binding = readHerdrInspectorBinding(target.asyncDir, target.index);
34
33
  if (!binding || binding.runId !== target.runId || binding.childIndex !== target.index)
@@ -11,5 +11,4 @@
11
11
  * a way that could still fail as new characters are added upstream.
12
12
  */
13
13
  export declare function encodeSessionRoots(roots: readonly string[]): string;
14
- /** Decodes a `--session-roots` argument produced by {@link encodeSessionRoots}. */
15
14
  export declare function decodeSessionRoots(raw: string): string[];
@@ -18,7 +18,6 @@ function parseStringArray(value) {
18
18
  return undefined;
19
19
  return value;
20
20
  }
21
- /** Decodes a `--session-roots` argument produced by {@link encodeSessionRoots}. */
22
21
  export function decodeSessionRoots(raw) {
23
22
  try {
24
23
  const decoded = parseStringArray(JSON.parse(Buffer.from(raw, "base64").toString("utf-8")));
@@ -18,7 +18,6 @@ export interface TmuxInspectorBinding {
18
18
  }
19
19
  export declare function bindingPath(asyncDir: string, index?: number): string;
20
20
  export declare function readTmuxInspectorBinding(asyncDir: string, index?: number): TmuxInspectorBinding | undefined;
21
- /** Read a binding only when it belongs to the requested inspector target. */
22
21
  export declare function readTmuxInspectorBindingForTarget(target: InspectorTarget): TmuxInspectorBinding | undefined;
23
22
  export declare function openTmuxInspector(context: InspectorContext, launch: InspectorLaunch, focus: boolean, client: TmuxClient): Promise<AgentToolResult<Details>>;
24
23
  export declare function statusTmuxInspector(context: InspectorContext, client: TmuxClient): Promise<AgentToolResult<Details>>;
@@ -28,7 +28,6 @@ export function readTmuxInspectorBinding(asyncDir, index) {
28
28
  return undefined;
29
29
  }
30
30
  }
31
- /** Read a binding only when it belongs to the requested inspector target. */
32
31
  export function readTmuxInspectorBindingForTarget(target) {
33
32
  const binding = readTmuxInspectorBinding(target.asyncDir, target.index);
34
33
  if (!binding || binding.runId !== target.runId || binding.childIndex !== target.index)