@xzzpig/pi-subagents 0.18.0 → 0.20.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 (108) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +32 -16
  4. package/docs/configuration.md +76 -9
  5. package/docs/extension-api.md +6 -5
  6. package/docs/missions.md +28 -14
  7. package/docs/models.md +8 -4
  8. package/docs/observability.md +10 -5
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +90 -88
  11. package/docs/workflows.md +171 -173
  12. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  13. package/package.json +6 -6
  14. package/prompts/review-loop.md +1 -1
  15. package/skills/council-mode/SKILL.md +1 -1
  16. package/skills/pi-subagents/SKILL.md +12 -5
  17. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
  18. package/skills/pi-subagents/references/execution-controls.md +68 -67
  19. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
  21. package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
  22. package/src/agents/advertised-agent-prompt.ts +21 -41
  23. package/src/agents/agent-management.ts +2 -2
  24. package/src/agents/agents.ts +66 -3
  25. package/src/api/preflight.ts +109 -63
  26. package/src/extension/config.ts +15 -4
  27. package/src/extension/control-notices.ts +3 -0
  28. package/src/extension/doctor.ts +1 -0
  29. package/src/extension/fanout-child.ts +12 -3
  30. package/src/extension/herdr-pi-bridge.ts +2 -0
  31. package/src/extension/index.ts +90 -174
  32. package/src/extension/public-execution.ts +72 -35
  33. package/src/extension/reply-workflow-script.ts +58 -0
  34. package/src/extension/rpc.ts +29 -10
  35. package/src/extension/schemas.ts +40 -135
  36. package/src/extension/tool-activation.ts +57 -108
  37. package/src/extension/tool-description.ts +62 -27
  38. package/src/extension/upgrade-notice.ts +40 -0
  39. package/src/integrations/herdr-status.ts +19 -3
  40. package/src/intercom/native-supervisor-channel.ts +4 -1
  41. package/src/missions/goal-driver.ts +44 -31
  42. package/src/missions/store.ts +10 -1
  43. package/src/profiles/profiles.ts +5 -2
  44. package/src/runs/background/async-execution.ts +146 -59
  45. package/src/runs/background/async-job-tracker.ts +66 -24
  46. package/src/runs/background/async-retention.ts +46 -16
  47. package/src/runs/background/await-async-run.ts +78 -0
  48. package/src/runs/background/chain-root-attachment.ts +4 -4
  49. package/src/runs/background/control-channel.ts +61 -2
  50. package/src/runs/background/notify.ts +5 -0
  51. package/src/runs/background/run-child-session.ts +17 -7
  52. package/src/runs/background/run-status.ts +6 -0
  53. package/src/runs/background/runner-aliases.ts +37 -6
  54. package/src/runs/background/runner-child-launch.ts +3 -0
  55. package/src/runs/background/scheduled-runs.ts +33 -18
  56. package/src/runs/background/stale-run-reconciler.ts +13 -2
  57. package/src/runs/background/subagent-runner.ts +58 -5
  58. package/src/runs/foreground/async-stop-action.ts +17 -3
  59. package/src/runs/foreground/command-action.ts +41 -0
  60. package/src/runs/foreground/execution.ts +145 -131
  61. package/src/runs/foreground/subagent-executor.ts +546 -296
  62. package/src/runs/shared/async-status-projection.ts +5 -0
  63. package/src/runs/shared/child-commands.ts +228 -0
  64. package/src/runs/shared/child-launch.ts +15 -2
  65. package/src/runs/shared/child-session.ts +184 -24
  66. package/src/runs/shared/child-tool-plan.ts +16 -4
  67. package/src/runs/shared/claude-code-adapter.ts +157 -2
  68. package/src/runs/shared/dynamic-fanout.ts +2 -2
  69. package/src/runs/shared/external-cli-preflight.ts +54 -6
  70. package/src/runs/shared/external-cli-runner.ts +5 -1
  71. package/src/runs/shared/mcp-config-sources.ts +2 -1
  72. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -11
  73. package/src/runs/shared/model-resolution.ts +38 -10
  74. package/src/runs/shared/model-scope.ts +28 -9
  75. package/src/runs/shared/nested-events.ts +55 -55
  76. package/src/runs/shared/parallel-utils.ts +4 -0
  77. package/src/runs/shared/pi-spawn.ts +7 -95
  78. package/src/runs/shared/run-history.ts +87 -0
  79. package/src/runs/shared/subagent-control.ts +32 -17
  80. package/src/runs/shared/subagent-prompt-runtime.ts +14 -6
  81. package/src/runs/shared/worktree.ts +1 -1
  82. package/src/shared/disabled-features.ts +123 -0
  83. package/src/shared/extension-context.ts +13 -0
  84. package/src/shared/model-info.ts +9 -0
  85. package/src/shared/required-child-extensions.ts +39 -5
  86. package/src/shared/settings.ts +1 -1
  87. package/src/shared/types.ts +27 -1
  88. package/src/slash/prompt-template-bridge.ts +2 -2
  89. package/src/slash/slash-commands.ts +10 -5
  90. package/src/slash/subagent-cost.ts +9 -5
  91. package/src/slash/subagents-admin.ts +24 -24
  92. package/src/tui/fleet-status.ts +14 -6
  93. package/src/tui/fleet.ts +14 -2
  94. package/src/tui/render.ts +117 -56
  95. package/src/tui/running-tone.ts +28 -0
  96. package/src/watchdog/diff-tool.ts +23 -9
  97. package/src/watchdog/register-child.ts +3 -3
  98. package/src/watchdog/register-main.ts +3 -3
  99. package/src/watchdog/review.ts +2 -2
  100. package/src/watchdog/turn-delta.ts +1 -1
  101. package/src/workflows/chat-progress.ts +2 -2
  102. package/src/workflows/scripted-workflow.ts +117 -37
  103. package/src/workflows/structured-workflow-scripts.ts +177 -0
  104. package/src/workflows/workflow-checklist.ts +6 -0
  105. package/src/workflows/workflow-receipt.ts +10 -4
  106. package/src/workflows/workflow-resources.ts +44 -16
  107. package/src/workflows/workflow-reuse.ts +120 -0
  108. package/src/workflows/workflow-revival.ts +123 -0
@@ -3,6 +3,8 @@
3
3
  */
4
4
 
5
5
  import { Type } from "typebox";
6
+ import type { DisabledFeatureSurface } from "../shared/disabled-features.ts";
7
+ import { MAX_ARGS_BYTES, MAX_ARGS_DEPTH, MAX_ARGS_FIELDS, MAX_ARGS_ITEMS } from "../workflows/workflow-resources.ts";
6
8
 
7
9
  function keepTopLevelParameterDescriptions<T extends object>(schema: T): T {
8
10
  return pruneNestedDescriptions(schema, []);
@@ -38,27 +40,11 @@ const SkillOverride = Type.Unsafe({
38
40
  description: "Skills: names/CSV/array; false disables, true uses default.",
39
41
  });
40
42
 
41
- const OutputOverride = Type.Unsafe({
42
- anyOf: [
43
- { type: "string" },
44
- { type: "boolean" },
45
- ],
46
- description: "Output filename/path (string), or false to disable file output",
47
- });
48
-
49
43
  const OutputModeOverride = Type.String({
50
44
  enum: ["inline", "file-only"],
51
45
  description: "Default inline; file-only requires output path.",
52
46
  });
53
47
 
54
- const ReadsOverride = Type.Unsafe({
55
- anyOf: [
56
- { type: "array", items: { type: "string" } },
57
- { type: "boolean" },
58
- ],
59
- description: "Files to read before running (array of filenames), or false to disable",
60
- });
61
-
62
48
  const JsonSchemaObject = Type.Unsafe({
63
49
  type: "object",
64
50
  additionalProperties: true,
@@ -83,7 +69,7 @@ const AcceptanceOverride = Type.Unsafe({
83
69
  },
84
70
  {
85
71
  type: "string",
86
- pattern: "^\\s*\\{",
72
+ pattern: "^\\s*\\{[\\s\\S]*$",
87
73
  },
88
74
  { type: "boolean" },
89
75
  { type: "object", additionalProperties: true },
@@ -95,11 +81,6 @@ const AgentContractOverride = Type.Object({
95
81
  version: Type.Integer({ minimum: 1, maximum: 1, description: "Enable compatibility behavior for this run/child." }),
96
82
  }, { additionalProperties: false, description: "Compatibility behavior. Omit for the default behavior." });
97
83
 
98
- const ChainGateOverride = Type.String({
99
- enum: ["execution", "acceptance"],
100
- description: "For chain steps with agentContract, choose whether the chain advances on execution success or acceptance success. Defaults to execution.",
101
- });
102
-
103
84
  const WorkflowLaneMetadata = Type.Object({
104
85
  version: Type.Integer({ minimum: 1, maximum: 1 }),
105
86
  key: Type.String({ minLength: 1, maxLength: 128, pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" }),
@@ -145,110 +126,7 @@ const WorkflowPreflightOverride = Type.Object({
145
126
  version: Type.Integer({ minimum: 1, maximum: 1 }),
146
127
  coverage: Type.Optional(Type.String({ enum: ["complete", "partial"] })),
147
128
  lanes: Type.Array(WorkflowPreflightLane, { maxItems: 64 }),
148
- }, { additionalProperties: false, description: "workflowScript/workflowScriptPath only; display-only hints; coverage warns." });
149
-
150
- // Parallel task item (within a parallel step)
151
- export const ParallelTaskSchema = Type.Object({
152
- agent: Type.String(),
153
- task: Type.Optional(Type.String({ description: "Task template with {task}, {previous}, {chain_dir} variables. Defaults to {previous}." })),
154
- phase: Type.Optional(Type.String({ description: "Optional phase/group label for status and graph rendering." })),
155
- label: Type.Optional(Type.String({ description: "Optional user-facing label for this parallel task." })),
156
- as: Type.Optional(Type.String({ description: "Optional safe identifier used as {outputs.name} in later chain steps." })),
157
- outputSchema: Type.Optional(OutputSchemaOverride),
158
- cwd: Type.Optional(Type.String()),
159
- machine: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Herdr saved machine id or label." })),
160
- count: Type.Optional(Type.Integer({ minimum: 1, description: "Repeat this parallel task N times with the same settings." })),
161
- output: Type.Optional(OutputOverride),
162
- outputMode: Type.Optional(OutputModeOverride),
163
- reads: Type.Optional(ReadsOverride),
164
- progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
165
- skill: Type.Optional(SkillOverride),
166
- model: Type.Optional(Type.String({ description: "Override model for this task" })),
167
- fast: Type.Optional(Type.Boolean({ description: "Opt into priority service tier for supported native OpenAI-Codex child models. This can increase quota or cost." })),
168
- toolBudget: Type.Optional(ToolBudgetOverride),
169
- acceptance: Type.Optional(AcceptanceOverride),
170
- agentContract: Type.Optional(AgentContractOverride),
171
- gateOn: Type.Optional(ChainGateOverride),
172
- });
173
-
174
- export const DynamicExpandSchema = Type.Object({
175
- from: Type.Object({
176
- output: Type.String({ description: "Prior named structured output to expand from." }),
177
- path: Type.String({ description: "JSON Pointer into the structured output, e.g. /items." }),
178
- }, { additionalProperties: false }),
179
- item: Type.Optional(Type.String({ description: "Template variable name for each item. Defaults to item." })),
180
- key: Type.Optional(Type.String({ description: "JSON Pointer relative to each item for stable child ids." })),
181
- maxItems: Type.Optional(Type.Integer({ minimum: 0, description: "Required fanout bound unless configured globally." })),
182
- onEmpty: Type.Optional(Type.String({ enum: ["skip", "fail"], description: "Empty input behavior. Defaults to skip." })),
183
- }, { additionalProperties: false });
184
-
185
- export const DynamicParallelTemplateSchema = Type.Object({
186
- agent: Type.String(),
187
- task: Type.Optional(Type.String({ description: "Task template with {item}, {item.path}, {task}, {previous}, {chain_dir}, and {outputs.name} variables." })),
188
- phase: Type.Optional(Type.String({ description: "Optional phase/group label for status and graph rendering." })),
189
- label: Type.Optional(Type.String({ description: "Optional user-facing label; item templates are supported." })),
190
- outputSchema: Type.Optional(OutputSchemaOverride),
191
- cwd: Type.Optional(Type.String()),
192
- machine: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Herdr saved machine id or label." })),
193
- output: Type.Optional(OutputOverride),
194
- outputMode: Type.Optional(OutputModeOverride),
195
- reads: Type.Optional(ReadsOverride),
196
- progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
197
- skill: Type.Optional(SkillOverride),
198
- model: Type.Optional(Type.String({ description: "Override model for this task" })),
199
- fast: Type.Optional(Type.Boolean({ description: "Opt into priority service tier for supported native OpenAI-Codex child models. This can increase quota or cost." })),
200
- toolBudget: Type.Optional(ToolBudgetOverride),
201
- acceptance: Type.Optional(AcceptanceOverride),
202
- agentContract: Type.Optional(AgentContractOverride),
203
- gateOn: Type.Optional(ChainGateOverride),
204
- }, { additionalProperties: false });
205
-
206
- export const DynamicCollectSchema = Type.Object({
207
- as: Type.String({ description: "Safe output name for the ordered collected result array." }),
208
- outputSchema: Type.Optional(JsonSchemaObject),
209
- }, { additionalProperties: false });
210
-
211
- // Flattened so chain steps do not need an object-shape anyOf/oneOf union.
212
- export const ChainItem = Type.Object({
213
- agent: Type.Optional(Type.String({ description: "Sequential step agent name" })),
214
- task: Type.Optional(Type.String({
215
- description: "Task template with variables: {task}=original request, {previous}=prior step's text response, {chain_dir}=shared folder, {outputs.name}=prior named output. Required for first step, defaults to '{previous}' for subsequent steps."
216
- })),
217
- phase: Type.Optional(Type.String({ description: "Optional phase/group label for status and graph rendering." })),
218
- label: Type.Optional(Type.String({ description: "Optional user-facing label for this chain step." })),
219
- as: Type.Optional(Type.String({ description: "Optional safe identifier used as {outputs.name} in later chain steps." })),
220
- outputSchema: Type.Optional(OutputSchemaOverride),
221
- cwd: Type.Optional(Type.String()),
222
- machine: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Herdr saved machine id or label." })),
223
- output: Type.Optional(OutputOverride),
224
- outputMode: Type.Optional(OutputModeOverride),
225
- reads: Type.Optional(ReadsOverride),
226
- progress: Type.Optional(Type.Boolean({ description: "Enable progress.md tracking in {chain_dir}" })),
227
- skill: Type.Optional(SkillOverride),
228
- model: Type.Optional(Type.String({ description: "Override model for this step" })),
229
- fast: Type.Optional(Type.Boolean({ description: "Opt into priority service tier for supported native OpenAI-Codex child models. This can increase quota or cost." })),
230
- toolBudget: Type.Optional(ToolBudgetOverride),
231
- acceptance: Type.Optional(AcceptanceOverride),
232
- agentContract: Type.Optional(AgentContractOverride),
233
- gateOn: Type.Optional(ChainGateOverride),
234
- parallel: Type.Optional(Type.Unsafe({
235
- anyOf: [
236
- Type.Array(ParallelTaskSchema, { minItems: 1, description: "Tasks to run in parallel" }),
237
- DynamicParallelTemplateSchema,
238
- ],
239
- description: "Static parallel tasks array, or a single dynamic fanout child template when expand/collect are present.",
240
- })),
241
- expand: Type.Optional(DynamicExpandSchema),
242
- collect: Type.Optional(DynamicCollectSchema),
243
- concurrency: Type.Optional(Type.Number({ description: "Max concurrent tasks (default: 4)" })),
244
- failFast: Type.Optional(Type.Boolean({ description: "Stop on first failure (default: false)" })),
245
- worktree: Type.Optional(Type.Boolean({
246
- description: "Create isolated git worktrees for each parallel task."
247
- })),
248
- }, {
249
- description: "Chain step: use {agent, task?, ...} for sequential, {parallel: [...]} for static concurrent execution, or {expand, parallel: {...}, collect} for dynamic fanout.",
250
- additionalProperties: false,
251
- });
129
+ }, { additionalProperties: false, description: "workflow: true or a script path only; display-only hints; coverage warns." });
252
130
 
253
131
  // Runtime mission handlers validate these untrusted nested objects loudly. Keeping
254
132
  // their provider schema shallow avoids repeating a full durable-record schema in
@@ -282,7 +160,7 @@ const SubagentParamProperties = {
282
160
  extensionBindings: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Child-only plain JSON; package.name/1; depth 16, 256 props, 16 KiB." })),
283
161
  // Management action (when present, tool operates in management mode)
284
162
  action: Type.Optional(Type.String({ minLength: 1,
285
- description: "Management/control only; omit for execution. validate accepts either script input. Discover actions with guide topic tool-reference."
163
+ description: "Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with guide topic tool-reference."
286
164
  })),
287
165
  capabilities: Type.Optional(Type.Boolean({ description: "list: compact capability rows/details without system prompts." })),
288
166
  name: Type.Optional(Type.String({ description: "schedule.create name." })),
@@ -303,6 +181,7 @@ const SubagentParamProperties = {
303
181
  supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
304
182
  index: Type.Optional(Type.Integer({ minimum: 0, description: "Zero-based child/transcript index." })),
305
183
  childId: Type.Optional(Type.String({ minLength: 1, maxLength: 256, description: "Child-scoped stop identity." })),
184
+ toolCallId: Type.Optional(Type.String({ description: "Command tool-call id." })),
306
185
  view: Type.Optional(Type.String({
307
186
  enum: ["fleet", "transcript"],
308
187
  description: "status view: fleet overview or transcript tail with id/dir and optional index.",
@@ -325,7 +204,7 @@ const SubagentParamProperties = {
325
204
  timezone: Type.Optional(Type.String()),
326
205
  overlap: Type.Optional(Type.String({ enum: ["skip"] })),
327
206
  catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed schedule occurrences; default latest." })),
328
- missionId: Type.Optional(Type.String()),
207
+ missionId: Type.Optional(Type.String({ description: "Existing mission to attach to a workflow or schedule.create; read guide missions for lifecycle and retention." })),
329
208
  mission: Type.Optional(Type.Unsafe({ ...MissionLaunchOverride, description: "false disables; true invalid. Object: exactly one non-empty title or summary; objective/labels optional; goal only true, requires budget.tokens." })),
330
209
  missionUpdate: Type.Optional(Type.Unsafe({ ...MissionUpdateOverride, description: "Mission patch; read guide missions." })),
331
210
  missionStatus: Type.Optional(Type.String()),
@@ -341,10 +220,11 @@ const SubagentParamProperties = {
341
220
  ],
342
221
  description: "create/update agent config; object or JSON string."
343
222
  })),
344
- workflow: Type.Optional(Type.String({ minLength: 1, description: "Extension-owned workflow resource." })),
345
- args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Bounded plain-JSON args for named, inline, or file-backed workflows; raw-script args are exposed deeply frozen and persisted, so do not include secrets." })),
346
- workflowScript: Type.Optional(Type.String({ minLength: 1, description: "Inline JavaScript statement body; raw/unknown provenance, no runs.host. Use explicit return and top-level await; see tool guidance/guide workflows." })),
347
- workflowScriptPath: Type.Optional(Type.String({ minLength: 1, description: "Raw script file; host reads from request cwd before sandbox. Mutually exclusive with workflowScript and workflow." })),
223
+ workflow: Type.Optional(Type.Unsafe<string | true>({
224
+ anyOf: [{ type: "boolean" }, { type: "string", minLength: 1 }],
225
+ description: "true: run the one ```js workflow block written in this same reply (false invalid). String with '/': script file read from request cwd. Other string: named workflow resource. Raw scripts (true or path) have no runs.host.",
226
+ })),
227
+ args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: MAX_ARGS_FIELDS, additionalProperties: true, description: `Plain-JSON args for workflow; ${MAX_ARGS_FIELDS} fields/object, ${MAX_ARGS_ITEMS} items/array, depth ${MAX_ARGS_DEPTH}, ${MAX_ARGS_BYTES / 1024} KiB total; raw-script args are exposed deeply frozen and persisted, so do not include secrets.` })),
348
228
  globalConcurrencyLimit: Type.Optional(Type.Integer({ minimum: 1 })),
349
229
  maxSubagentSpawnsPerRun: Type.Optional(Type.Integer({ minimum: 1 })),
350
230
  preflight: Type.Optional(WorkflowPreflightOverride),
@@ -394,7 +274,7 @@ const SubagentParamProperties = {
394
274
  { type: "string", minLength: 1 },
395
275
  { type: "object", properties: { command: { type: "string", minLength: 1 }, output: { type: "string", enum: ["json"] }, schema: { type: "object" }, timeoutMs: { type: "integer", minimum: 1 } }, required: ["command"], additionalProperties: false },
396
276
  ],
397
- description: "Host gate command run after the child finishes: a string, or { command, output: \"json\", schema?, timeoutMs? } whose passing stdout becomes structuredOutput (not with outputSchema). Cannot be combined with acceptance; an explicit acceptance of false is treated as omitted.",
277
+ description: "Host gate command run after the child finishes: a string, or an object; with output \"json\", passing stdout becomes structuredOutput (not with outputSchema). Cannot be combined with acceptance except false (treated as omitted).",
398
278
  })),
399
279
  };
400
280
 
@@ -402,8 +282,33 @@ const SubagentParamsSchema = Type.Object(SubagentParamProperties);
402
282
 
403
283
  export const SubagentParams = keepTopLevelParameterDescriptions(SubagentParamsSchema);
404
284
 
405
- export function createSubagentParamsSchema(): typeof SubagentParams {
406
- return SubagentParams;
285
+ // Replaces workflow scripts when disabledFeatures lists "workflow-scripts". Kept small because every
286
+ // field is sent on every request; the executor validates step shapes and placeholders strictly.
287
+ const StructuredTask = { type: "object", properties: { agent: { type: "string", minLength: 1 }, task: { type: "string" } }, required: ["agent", "task"], additionalProperties: false };
288
+ const StructuredWorkflowProperties = {
289
+ action: Type.Optional(Type.String({ minLength: 1, description: "Management/control only; omit for execution. Discover actions with guide topic tool-reference." })),
290
+ task: Type.Optional(Type.String({ description: "One-child task with agent, or the original request ({task}) with chain/tasks." })),
291
+ tasks: Type.Optional(Type.Unsafe({ type: "array", minItems: 1, items: StructuredTask, description: "Parallel children; results in order." })),
292
+ // Flattened step: {agent, task?, as?} or {parallel}; no object-shape union for provider converters.
293
+ chain: Type.Optional(Type.Unsafe({
294
+ type: "array",
295
+ minItems: 1,
296
+ items: { type: "object", properties: { agent: { type: "string", minLength: 1 }, task: { type: "string" }, as: { type: "string" }, parallel: { type: "array", minItems: 1, items: StructuredTask } }, additionalProperties: false },
297
+ description: "Sequential steps: {agent,task?,as?} or {parallel:[{agent,task}]}.",
298
+ })),
299
+ };
300
+
301
+ export function createSubagentParamsSchema(disabled?: DisabledFeatureSurface): typeof SubagentParams {
302
+ if (!disabled || disabled.params.size === 0) return SubagentParams;
303
+ const structured = disabled.features.has("workflow-scripts");
304
+ const enabledProperties = Object.fromEntries(Object.entries(SubagentParamProperties).flatMap(([name, schema]) => {
305
+ if (disabled.params.has(name)) return [];
306
+ if (structured && name === "action") return [[name, StructuredWorkflowProperties.action]];
307
+ if (structured && name === "task") return [[name, StructuredWorkflowProperties.task], ["tasks", StructuredWorkflowProperties.tasks], ["chain", StructuredWorkflowProperties.chain]];
308
+ return [[name, schema]];
309
+ }));
310
+ // SAFETY: only optional properties are dropped or added; the executor rejects disabled options and admits chain/tasks at runtime.
311
+ return keepTopLevelParameterDescriptions(Type.Object(enabledProperties)) as typeof SubagentParams;
407
312
  }
408
313
 
409
314
  const SubagentWaitParamsSchema = Type.Object({
@@ -1,9 +1,7 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
1
  import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
4
2
  import { Type } from "typebox";
5
- import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../shared/utils.ts";
6
- import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot, resolveRunningPiPackageRoot, type PiSpawnDeps } from "../runs/shared/pi-spawn.ts";
3
+ import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
4
+ import type { ToolActivationMode } from "../shared/types.ts";
7
5
 
8
6
  interface ActivationDetails {
9
7
  enabled?: string[];
@@ -13,90 +11,8 @@ interface ActivationDetails {
13
11
 
14
12
  const LOADER_NAME = "subagents_enable";
15
13
  const SUBAGENT_NAME = "subagent";
16
- const MINIMUM_DYNAMIC_TOOLS_VERSION = [0, 86, 1] as const;
17
- const UNSUPPORTED_HOST_MESSAGE = "Dynamic tool activation requires Pi 0.86.1 or newer";
18
14
  let warnedUnsupportedHost = false;
19
15
 
20
- /** Returns why dynamic tool activation is unavailable, or undefined when the host supports it. */
21
- export function unsupportedDynamicToolsReason(pi: ExtensionAPI, deps: PiSpawnDeps = {}): string | undefined {
22
- if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") return UNSUPPORTED_HOST_MESSAGE;
23
- const probe = probeHostPiVersion(deps);
24
- if ("reason" in probe) return probe.reason;
25
- return supportsMinimumVersion(probe.version) ? undefined : `${UNSUPPORTED_HOST_MESSAGE} (detected ${probe.version} in ${probe.root})`;
26
- }
27
-
28
- type HostPiProbe = { version: string; root: string } | { reason: string };
29
-
30
- /**
31
- * The host SDK is not a dependency of this package, so a bare module
32
- * resolution only works where it happens to be installed next to us (a
33
- * repository checkout with devDependencies). Distributed installs read the
34
- * version from the Pi that owns the session instead: argv ownership, Pi's
35
- * package directory, the explicit subagents override, then validated compiled
36
- * image layouts. A
37
- * selected root must expose a valid manifest — failures are reported rather
38
- * than silently falling through to a different Pi installation.
39
- */
40
- function probeHostPiVersion(deps: PiSpawnDeps): HostPiProbe {
41
- const runningRoot = resolveRunningPiPackageRoot(deps);
42
- // Only the running host and an explicit override identify the Pi that owns this
43
- // session. An SDK reached through our own install tree cannot be proven to be
44
- // that installation, so it may inform the reason but never the gate: dynamic
45
- // activation stays off until the host is verified.
46
- if (runningRoot && "reason" in runningRoot) return runningRoot;
47
- if (runningRoot) return readHostPiManifest(runningRoot.root, runningRoot.source === "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT", deps.readFileSync, deps.platform);
48
- const installedRoot = resolveInstalledPiPackageRoot();
49
- return { reason: installedRoot
50
- ? `Could not verify the running Pi installation; ${installedRoot} is not confirmed to be the host that owns this session`
51
- : "Could not locate the running Pi installation to verify dynamic tool support" };
52
- }
53
-
54
- function readHostPiManifest(
55
- root: string,
56
- fromOverride: boolean,
57
- readFileSync: (filePath: string, encoding: "utf-8") => string = (filePath, encoding) => fs.readFileSync(filePath, encoding),
58
- platform: NodeJS.Platform = process.platform,
59
- ): HostPiProbe {
60
- const manifestPath = (platform === "win32" ? path.win32 : path.posix).join(root, "package.json");
61
- let source: string;
62
- try {
63
- source = readFileSync(manifestPath, "utf-8");
64
- } catch (error) {
65
- return { reason: `Could not read the Pi package manifest at ${manifestPath}: ${errorMessage(error)}` };
66
- }
67
- let parsed: unknown;
68
- try {
69
- parsed = JSON.parse(source);
70
- } catch (error) {
71
- return { reason: `Invalid Pi package manifest at ${manifestPath}: ${errorMessage(error)}` };
72
- }
73
- if (!isRecord(parsed) || parsed.name !== PI_CODING_AGENT_PACKAGE) {
74
- return { reason: `${manifestPath} is not ${PI_CODING_AGENT_PACKAGE}${fromOverride ? ` (${PI_CODING_AGENT_PACKAGE_ROOT_ENV} override)` : ""}` };
75
- }
76
- return typeof parsed.version === "string" && parsed.version
77
- ? { version: parsed.version, root }
78
- : { reason: `The Pi package manifest at ${manifestPath} has no version` };
79
- }
80
-
81
- function errorMessage(error: unknown): string {
82
- return error instanceof Error ? error.message : String(error);
83
- }
84
-
85
- function isRecord(value: unknown): value is Record<string, unknown> {
86
- return typeof value === "object" && value !== null && !Array.isArray(value);
87
- }
88
-
89
- export function supportsMinimumVersion(version: string): boolean {
90
- const parsed = version.split(".").slice(0, 3).map(Number);
91
- if (parsed.length !== 3 || parsed.some((part) => !Number.isInteger(part) || part < 0)) return false;
92
- for (let index = 0; index < 3; index++) {
93
- const part = parsed[index]!;
94
- const minimum = MINIMUM_DYNAMIC_TOOLS_VERSION[index]!;
95
- if (part !== minimum) return part > minimum;
96
- }
97
- return true;
98
- }
99
-
100
16
  type ToolSelectionMessage = {
101
17
  role: string;
102
18
  toolsAdded?: readonly { name: string }[];
@@ -108,42 +24,71 @@ function hasNativeToolSelection(messages: readonly ToolSelectionMessage[]): bool
108
24
  && (Object.hasOwn(message, "toolsAdded") || Object.hasOwn(message, "toolsRemoved")));
109
25
  }
110
26
 
111
- function setSelection(pi: ExtensionAPI, includeSubagent: boolean): void {
112
- const active = pi.getActiveTools();
113
- const next = includeSubagent ? [...active, SUBAGENT_NAME] : active.filter((name) => name !== SUBAGENT_NAME);
114
- if (!next.includes(LOADER_NAME)) next.push(LOADER_NAME);
27
+ function setSelection(pi: ExtensionAPI, includeSubagent: boolean, includeLoader: boolean): void {
28
+ const next = pi.getActiveTools().filter((name) => (includeSubagent || name !== SUBAGENT_NAME) && (includeLoader || name !== LOADER_NAME));
29
+ if (includeSubagent) next.push(SUBAGENT_NAME);
30
+ if (includeLoader) next.push(LOADER_NAME);
115
31
  pi.setActiveTools([...new Set(next)]);
116
32
  }
117
33
 
118
- function applyRecordedSelection(pi: ExtensionAPI, ctx: ExtensionContext): void {
34
+ // Mirrors pi-ai's per-API transcript handling: without these flags, a mid-conversation tool change
35
+ // makes Pi resend the conversation under a new leading system message, missing the prompt cache.
36
+ function addsToolsWithoutCheckpoint(model: ExtensionContext["model"]): boolean {
37
+ const compat = model?.compat as {
38
+ supportsMidConvoSystemMessages?: boolean;
39
+ supportsMidConvoToolChanges?: boolean;
40
+ supportsMidConvoToolAdditions?: boolean;
41
+ supportsAdditionalTools?: boolean;
42
+ supportsToolSearch?: boolean;
43
+ } | undefined;
44
+ if (!model || compat?.supportsMidConvoSystemMessages !== true) return false;
45
+ switch (model.api) {
46
+ case "anthropic-messages": return compat.supportsMidConvoToolChanges === true;
47
+ case "openai-completions": return compat.supportsMidConvoToolAdditions === true;
48
+ case "openai-responses":
49
+ case "openai-codex-responses":
50
+ case "azure-openai-responses": return compat.supportsAdditionalTools === true || compat.supportsToolSearch === true;
51
+ default: return false;
52
+ }
53
+ }
54
+
55
+ // Returns whether the loader is selected for this session.
56
+ function applyRecordedSelection(pi: ExtensionAPI, ctx: ExtensionContext, mode: "auto" | "dynamic"): boolean {
119
57
  const available = pi.getAllTools();
120
- if (!Array.isArray(available) || !Array.isArray(pi.getActiveTools())) return;
121
- if (!available.some((tool) => tool.name === LOADER_NAME)) return;
58
+ if (!Array.isArray(available) || !Array.isArray(pi.getActiveTools())) return true;
59
+ if (!available.some((tool) => tool.name === LOADER_NAME)) return true;
122
60
  // SAFETY: The running Pi session manager exposes buildSessionContext, but its read-only extension type omits it.
123
61
  const messages = (ctx.sessionManager as typeof ctx.sessionManager & { buildSessionContext(): { messages: ToolSelectionMessage[] } }).buildSessionContext().messages;
124
62
  if (hasNativeToolSelection(messages)) {
125
- // Only this tool's membership matters; a package-local pi-ai may be older than the running Pi.
126
- let selected = false;
63
+ // Replayed here because a package-local pi-ai may be older than the running Pi.
64
+ const recorded = new Set<string>();
127
65
  for (const message of messages) {
128
66
  if (message.role !== "system") continue;
129
- if (message.toolsRemoved?.some((tool) => tool.name === SUBAGENT_NAME)) selected = false;
130
- if (message.toolsAdded?.some((tool) => tool.name === SUBAGENT_NAME)) selected = true;
67
+ for (const tool of message.toolsRemoved ?? []) recorded.delete(tool.name);
68
+ for (const tool of message.toolsAdded ?? []) recorded.add(tool.name);
131
69
  }
132
- setSelection(pi, selected);
133
- return;
70
+ // "auto" never adds the loader to a transcript that did not declare it: that is itself a tool change.
71
+ const loaderSelected = mode === "dynamic" || recorded.has(LOADER_NAME);
72
+ setSelection(pi, recorded.has(SUBAGENT_NAME), loaderSelected);
73
+ return loaderSelected;
134
74
  }
135
- setSelection(pi, messages.length > 0 && pi.getActiveTools().includes(SUBAGENT_NAME));
75
+ // "auto" goes eager only for an empty session; any history keeps the tools it already sent.
76
+ const eager = mode === "auto" && messages.length === 0 && !addsToolsWithoutCheckpoint(ctx.model);
77
+ setSelection(pi, eager || (messages.length > 0 && pi.getActiveTools().includes(SUBAGENT_NAME)), !eager);
78
+ return !eager;
136
79
  }
137
80
 
138
81
  export function registerSubagentToolActivation(
139
82
  pi: ExtensionAPI,
140
- options: { advertisedPrompt: () => string | undefined | Promise<string | undefined> },
83
+ options: { advertisedPrompt: () => string | undefined | Promise<string | undefined>; mode?: ToolActivationMode },
141
84
  ): void {
142
- const unsupportedReason = unsupportedDynamicToolsReason(pi);
143
- if (unsupportedReason) {
85
+ const mode = options.mode ?? "auto";
86
+ // Same as --exclude-tools subagents_enable: without the loader, subagent stays active.
87
+ if (mode === "eager") return;
88
+ if (typeof pi.getAllTools !== "function" || typeof pi.getActiveTools !== "function" || typeof pi.setActiveTools !== "function") {
144
89
  if (!warnedUnsupportedHost) {
145
90
  warnedUnsupportedHost = true;
146
- console.warn(`[pi-subagents] ${unsupportedReason}; keeping subagent eagerly available.`);
91
+ console.warn("[pi-subagents] Dynamic tool activation requires Pi 0.86.1 or newer; keeping subagent eagerly available.");
147
92
  }
148
93
  return;
149
94
  }
@@ -152,6 +97,7 @@ export function registerSubagentToolActivation(
152
97
  const parameters = Type.Object({});
153
98
  const loader: ToolDefinition<typeof parameters, ActivationDetails> = {
154
99
  name: LOADER_NAME,
100
+ ...MODEL_ONLY_TOOL,
155
101
  label: "Enable Subagents",
156
102
  description: "Enable pi-subagents delegation and management tools without launching work. Call when delegation is authorized by the current request or applicable user/project instructions, or when managing existing runs. Direct execution is the default; complexity alone never authorizes delegation. Full tools are available on the next model request.",
157
103
  promptSnippet: "pi-subagents is installed. For authorized specialist, independent-review, or parallel work, call subagents_enable, then subagent. Authorization must come from the current request or applicable instructions; complexity alone is not authorization.",
@@ -163,7 +109,7 @@ export function registerSubagentToolActivation(
163
109
  details: { unavailable: [SUBAGENT_NAME] },
164
110
  };
165
111
  try {
166
- setSelection(pi, true);
112
+ setSelection(pi, true, true);
167
113
  } catch (error) {
168
114
  return {
169
115
  isError: true,
@@ -178,16 +124,19 @@ export function registerSubagentToolActivation(
178
124
  };
179
125
  const advertised = await options.advertisedPrompt();
180
126
  return {
181
- content: [{ type: "text", text: `Enabled: subagent. On the next model request, call subagent({action:\"list\",capabilities:true}) for current capabilities.${advertised ? `\n\n${advertised}` : ""}` }],
127
+ content: [{ type: "text", text: `Enabled: subagent. If your tool list includes subagent (possibly prefixed), call subagent({action:\"list\",capabilities:true}). Otherwise, wait for the next user prompt; do not retry now. Start Pi with --exclude-tools subagents_enable to keep subagent always available.${advertised ? `\n\n${advertised}` : ""}` }],
182
128
  details: { enabled: [SUBAGENT_NAME] },
183
129
  };
184
130
  },
185
131
  };
186
132
  pi.registerTool(loader);
187
133
 
188
- pi.on("session_start", (_event, ctx) => applyRecordedSelection(pi, ctx));
189
- pi.on("session_tree", (_event, ctx) => applyRecordedSelection(pi, ctx));
134
+ // Decided at session start and tree navigation only; switching models keeps the session's tools.
135
+ let loaderSelected = true;
136
+ pi.on("session_start", (_event, ctx) => { loaderSelected = applyRecordedSelection(pi, ctx, mode); });
137
+ pi.on("session_tree", (_event, ctx) => { loaderSelected = applyRecordedSelection(pi, ctx, mode); });
190
138
  pi.on("before_agent_start", (event) => {
139
+ if (!loaderSelected) return;
191
140
  const available = pi.getAllTools();
192
141
  if (!Array.isArray(available) || !available.some((tool) => tool.name === LOADER_NAME)) return;
193
142
  const selectedTools = event.systemPromptOptions.selectedTools ??= [...pi.getActiveTools()];