@xzzpig/pi-subagents 0.18.0 → 0.19.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 (95) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +18 -12
  4. package/docs/configuration.md +66 -9
  5. package/docs/extension-api.md +5 -4
  6. package/docs/missions.md +13 -13
  7. package/docs/models.md +2 -2
  8. package/docs/observability.md +2 -2
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +63 -86
  11. package/docs/workflows.md +170 -172
  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 +7 -0
  25. package/src/api/preflight.ts +67 -62
  26. package/src/extension/config.ts +12 -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 +68 -159
  32. package/src/extension/public-execution.ts +69 -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 +36 -133
  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/runs/background/async-execution.ts +58 -53
  42. package/src/runs/background/async-job-tracker.ts +63 -22
  43. package/src/runs/background/async-retention.ts +46 -16
  44. package/src/runs/background/await-async-run.ts +76 -0
  45. package/src/runs/background/chain-root-attachment.ts +4 -4
  46. package/src/runs/background/control-channel.ts +18 -2
  47. package/src/runs/background/notify.ts +5 -0
  48. package/src/runs/background/run-child-session.ts +4 -1
  49. package/src/runs/background/run-status.ts +6 -0
  50. package/src/runs/background/runner-aliases.ts +30 -2
  51. package/src/runs/background/runner-child-launch.ts +3 -0
  52. package/src/runs/background/scheduled-runs.ts +5 -5
  53. package/src/runs/background/subagent-runner.ts +15 -1
  54. package/src/runs/foreground/async-stop-action.ts +17 -3
  55. package/src/runs/foreground/execution.ts +130 -125
  56. package/src/runs/foreground/subagent-executor.ts +487 -288
  57. package/src/runs/shared/async-status-projection.ts +5 -0
  58. package/src/runs/shared/child-launch.ts +15 -2
  59. package/src/runs/shared/child-session.ts +92 -6
  60. package/src/runs/shared/child-tool-plan.ts +15 -3
  61. package/src/runs/shared/dynamic-fanout.ts +1 -1
  62. package/src/runs/shared/mcp-config-sources.ts +2 -1
  63. package/src/runs/shared/mcp-direct-tool-allowlist.ts +103 -11
  64. package/src/runs/shared/model-resolution.ts +29 -9
  65. package/src/runs/shared/model-scope.ts +28 -9
  66. package/src/runs/shared/nested-events.ts +55 -55
  67. package/src/runs/shared/parallel-utils.ts +2 -0
  68. package/src/runs/shared/pi-spawn.ts +7 -95
  69. package/src/runs/shared/subagent-prompt-runtime.ts +2 -0
  70. package/src/runs/shared/worktree.ts +1 -1
  71. package/src/shared/disabled-features.ts +123 -0
  72. package/src/shared/extension-context.ts +13 -0
  73. package/src/shared/model-info.ts +9 -0
  74. package/src/shared/settings.ts +1 -1
  75. package/src/shared/types.ts +21 -0
  76. package/src/slash/prompt-template-bridge.ts +2 -2
  77. package/src/slash/slash-commands.ts +10 -5
  78. package/src/slash/subagents-admin.ts +24 -24
  79. package/src/tui/fleet-status.ts +14 -6
  80. package/src/tui/fleet.ts +14 -2
  81. package/src/tui/render.ts +113 -52
  82. package/src/tui/running-tone.ts +28 -0
  83. package/src/watchdog/diff-tool.ts +23 -9
  84. package/src/watchdog/register-child.ts +3 -3
  85. package/src/watchdog/register-main.ts +3 -3
  86. package/src/watchdog/review.ts +2 -2
  87. package/src/watchdog/turn-delta.ts +1 -1
  88. package/src/workflows/chat-progress.ts +2 -2
  89. package/src/workflows/scripted-workflow.ts +117 -37
  90. package/src/workflows/structured-workflow-scripts.ts +177 -0
  91. package/src/workflows/workflow-checklist.ts +6 -0
  92. package/src/workflows/workflow-receipt.ts +8 -2
  93. package/src/workflows/workflow-resources.ts +37 -12
  94. package/src/workflows/workflow-reuse.ts +120 -0
  95. package/src/workflows/workflow-revival.ts +123 -0
@@ -0,0 +1,58 @@
1
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+
4
+ const WORKFLOW_FENCE = /^```(?:js|javascript) workflow[ \t]*$/;
5
+ const OPEN_FENCE = /^(`{3,}|~{3,})/;
6
+ const CLOSE_FENCE = /^(`{3,}|~{3,})[ \t]*$/;
7
+
8
+ export type ReplyWorkflowScript = { script: string } | { error: string };
9
+
10
+ /**
11
+ * Pi persists the whole assistant message before running its tool calls, so the
12
+ * message that issued this subagent call is on the branch and carries the script.
13
+ */
14
+ export function readReplyWorkflowScript(sessionManager: Pick<ExtensionContext["sessionManager"], "getBranch">, toolCallId: string): ReplyWorkflowScript {
15
+ const branch = sessionManager.getBranch();
16
+ for (let index = branch.length - 1; index >= 0; index--) {
17
+ const entry = branch[index]!;
18
+ if (entry.type !== "message") continue;
19
+ const message = entry.message;
20
+ if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
21
+ if (!message.content.some((block) => block.type === "toolCall" && block.id === toolCallId)) continue;
22
+ return scriptFromReply(message.content);
23
+ }
24
+ return { error: "workflow: true only works from a model subagent tool call whose assistant message contains the ```js workflow block; other callers must pass a script path such as workflow: \"./script.js\"." };
25
+ }
26
+
27
+ function scriptFromReply(content: AssistantMessage["content"]): ReplyWorkflowScript {
28
+ const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent"
29
+ && block.arguments?.workflow === true).length;
30
+ if (replyCalls > 1) return { error: `This reply has ${replyCalls} subagent calls with workflow: true; a reply can carry only one. Pass other scripts as workflow file paths.` };
31
+ const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
32
+ const { blocks, unclosed } = workflowBlocks(text);
33
+ if (unclosed) return { error: "The ```js workflow block in this reply is not closed." };
34
+ if (blocks.length !== 1) return { error: `workflow: true requires exactly one \`\`\`js workflow fenced block in the same reply as the tool call; found ${blocks.length}.` };
35
+ const script = blocks[0]!;
36
+ if (!script.trim()) return { error: "The ```js workflow block in this reply is empty." };
37
+ return { script };
38
+ }
39
+
40
+ /** Collects ```js workflow / ```javascript workflow fenced blocks, skipping the bodies of other fences. */
41
+ function workflowBlocks(text: string): { blocks: string[]; unclosed: boolean } {
42
+ const lines = text.split("\n");
43
+ const blocks: string[] = [];
44
+ let fence: { marker: string; tagged: boolean; start: number } | undefined;
45
+ for (let index = 0; index < lines.length; index++) {
46
+ const line = lines[index]!.replace(/\r$/, "");
47
+ if (!fence) {
48
+ const open = OPEN_FENCE.exec(line);
49
+ if (open) fence = { marker: open[1]!, tagged: WORKFLOW_FENCE.test(line), start: index + 1 };
50
+ continue;
51
+ }
52
+ const close = CLOSE_FENCE.exec(line);
53
+ if (!close || close[1]![0] !== fence.marker[0] || close[1]!.length < fence.marker.length) continue;
54
+ if (fence.tagged) blocks.push(lines.slice(fence.start, index).join("\n"));
55
+ fence = undefined;
56
+ }
57
+ return { blocks, unclosed: fence?.tagged === true };
58
+ }
@@ -22,6 +22,7 @@ import {
22
22
  import { sanitizeDisplayText, truncateDisplayText } from "../shared/display-text.ts";
23
23
  import { readStatus } from "../shared/utils.ts";
24
24
  import { SubagentParams } from "./schemas.ts";
25
+ import { disabledFeatureUseError, type DisabledFeatureSurface } from "../shared/disabled-features.ts";
25
26
  import { normalizePublicSubagentExecution } from "./public-execution.ts";
26
27
  import { collectSubagentCost, SUBAGENT_COST_REPORT_VERSION } from "../slash/subagent-cost.ts";
27
28
  import { ASYNC_STATUS_SNAPSHOT_KIND, ASYNC_STATUS_SNAPSHOT_VERSION, buildAsyncStatusSnapshotForState } from "../runs/background/async-status-snapshot.ts";
@@ -318,6 +319,11 @@ interface RegisterSubagentRpcBridgeOptions {
318
319
  now?: () => number;
319
320
  /** Native live state, projected into the optional public fleet-status capability. */
320
321
  state?: SubagentState;
322
+ disabledFeatures?: DisabledFeatureSurface;
323
+ }
324
+
325
+ function enabledManagementActions(options: RegisterSubagentRpcBridgeOptions): string[] {
326
+ return SUBAGENT_RPC_MANAGEMENT_ACTIONS.filter((action) => !options.disabledFeatures?.actions.has(action));
321
327
  }
322
328
 
323
329
  class SubagentRpcError extends Error {
@@ -438,14 +444,14 @@ function sessionData(ctx: ExtensionContext | null): { cwd?: string; sessionId?:
438
444
  };
439
445
  }
440
446
 
441
- function pingData(ctx: ExtensionContext | null) {
447
+ function pingData(ctx: ExtensionContext | null, options: RegisterSubagentRpcBridgeOptions) {
442
448
  return {
443
449
  version: SUBAGENT_RPC_PROTOCOL_VERSION,
444
450
  methods: [...SUBAGENT_RPC_METHODS],
445
451
  capabilities: {
446
452
  status: true,
447
453
  statusProjection: { version: 1, untargeted: "in-memory-when-ready", targeted: "executor" },
448
- managementActions: [...SUBAGENT_RPC_MANAGEMENT_ACTIONS],
454
+ managementActions: enabledManagementActions(options),
449
455
  fleetStatus: { version: 1 },
450
456
  asyncStatusSnapshot: { kind: ASYNC_STATUS_SNAPSHOT_KIND, version: ASYNC_STATUS_SNAPSHOT_VERSION },
451
457
  asyncSpawn: true,
@@ -485,12 +491,13 @@ async function executeChecked(
485
491
  return dataFromToolResult(result);
486
492
  }
487
493
 
488
- function manageParams(params: unknown): SubagentParamsLike {
494
+ function manageParams(params: unknown, options: RegisterSubagentRpcBridgeOptions): SubagentParamsLike {
489
495
  const input = assertRecordParams(params, "manage");
490
496
  if (typeof input.action !== "string" || !(SUBAGENT_RPC_MANAGEMENT_ACTIONS as readonly string[]).includes(input.action)) {
497
+ const enabled = enabledManagementActions(options);
491
498
  throw new SubagentRpcError(
492
499
  "invalid_params",
493
- `RPC manage action must be one of: ${SUBAGENT_RPC_MANAGEMENT_ACTIONS.join(", ")}.`,
500
+ enabled.length > 0 ? `RPC manage action must be one of: ${enabled.join(", ")}.` : "RPC manage actions are all disabled by config.",
494
501
  );
495
502
  }
496
503
  if (input.id !== undefined && (typeof input.id !== "string" || !input.id.trim())) {
@@ -513,8 +520,20 @@ function manageParams(params: unknown): SubagentParamsLike {
513
520
  return output;
514
521
  }
515
522
 
516
- function spawnParams(params: unknown): SubagentParamsLike {
517
- const input = assertRecordParams(params, "spawn");
523
+ function spawnParams(params: unknown, options: RegisterSubagentRpcBridgeOptions): SubagentParamsLike {
524
+ const { script, ...input } = assertRecordParams(params, "spawn");
525
+ if (Object.hasOwn(input, "workflowScript")) throw new SubagentRpcError("invalid_params", "RPC spawn workflowScript was removed; pass inline script text as script.");
526
+ if (Object.hasOwn(input, "workflowScriptPath")) throw new SubagentRpcError("invalid_params", "RPC spawn workflowScriptPath was removed; pass the file as workflow: \"./path/to/script.js\".");
527
+ if (input.workflow === true) throw new SubagentRpcError("invalid_params", "RPC spawn has no reply block for workflow: true; pass inline script text as script or a file as workflow: \"./path/to/script.js\".");
528
+ if (script !== undefined) {
529
+ if (typeof script !== "string" || !script.trim()) throw new SubagentRpcError("invalid_params", "RPC spawn script must be a non-empty string.");
530
+ if (input.workflow !== undefined) throw new SubagentRpcError("invalid_params", "RPC spawn script cannot be combined with workflow.");
531
+ // The executor's internal carrier; the model-facing tool cannot set it.
532
+ input.workflowScript = script;
533
+ }
534
+ // With workflow scripts disabled, name the setting before normalization can report a script-shape error instead.
535
+ const disabledFeatureError = options.disabledFeatures?.features.has("workflow-scripts") ? disabledFeatureUseError(input, options.disabledFeatures, "RPC spawn") : undefined;
536
+ if (disabledFeatureError) throw new SubagentRpcError("invalid_params", disabledFeatureError);
518
537
  const normalized = normalizePublicSubagentExecution(input);
519
538
  if (!normalized.ok) throw new SubagentRpcError("invalid_params", normalized.error);
520
539
  if (normalized.params.action !== undefined) {
@@ -708,14 +727,14 @@ async function handleRequest(
708
727
  fleetKeys: FleetKeyState,
709
728
  ): Promise<unknown> {
710
729
  const ctx = options.getContext();
711
- if (request.method === "ping") return pingData(ctx);
730
+ if (request.method === "ping") return pingData(ctx, options);
712
731
  if (!ctx) throw new SubagentRpcError("no_active_session", "No active extension context for subagent RPC.");
713
732
 
714
733
  if (request.method === "manage") {
715
- return executeChecked(options, ctx, request.requestId, request.method, manageParams(request.params));
734
+ return executeChecked(options, ctx, request.requestId, request.method, manageParams(request.params, options));
716
735
  }
717
736
  if (request.method === "spawn") {
718
- return executeChecked(options, ctx, request.requestId, request.method, spawnParams(request.params));
737
+ return executeChecked(options, ctx, request.requestId, request.method, spawnParams(request.params, options));
719
738
  }
720
739
  if (request.method === "status") {
721
740
  const statusParams = normalizeStatusParams(request.params);
@@ -848,7 +867,7 @@ export function registerSubagentRpcBridge(options: RegisterSubagentRpcBridgeOpti
848
867
 
849
868
  return {
850
869
  emitReady: (ctx) => {
851
- options.events.emit(SUBAGENT_RPC_READY_EVENT, pingData(ctx ?? options.getContext()));
870
+ options.events.emit(SUBAGENT_RPC_READY_EVENT, pingData(ctx ?? options.getContext(), options));
852
871
  },
853
872
  dispose: () => {
854
873
  if (typeof unsubscribe === "function") unsubscribe();
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  import { Type } from "typebox";
6
+ import type { DisabledFeatureSurface } from "../shared/disabled-features.ts";
6
7
 
7
8
  function keepTopLevelParameterDescriptions<T extends object>(schema: T): T {
8
9
  return pruneNestedDescriptions(schema, []);
@@ -38,27 +39,11 @@ const SkillOverride = Type.Unsafe({
38
39
  description: "Skills: names/CSV/array; false disables, true uses default.",
39
40
  });
40
41
 
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
42
  const OutputModeOverride = Type.String({
50
43
  enum: ["inline", "file-only"],
51
44
  description: "Default inline; file-only requires output path.",
52
45
  });
53
46
 
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
47
  const JsonSchemaObject = Type.Unsafe({
63
48
  type: "object",
64
49
  additionalProperties: true,
@@ -83,7 +68,7 @@ const AcceptanceOverride = Type.Unsafe({
83
68
  },
84
69
  {
85
70
  type: "string",
86
- pattern: "^\\s*\\{",
71
+ pattern: "^\\s*\\{[\\s\\S]*$",
87
72
  },
88
73
  { type: "boolean" },
89
74
  { type: "object", additionalProperties: true },
@@ -95,11 +80,6 @@ const AgentContractOverride = Type.Object({
95
80
  version: Type.Integer({ minimum: 1, maximum: 1, description: "Enable compatibility behavior for this run/child." }),
96
81
  }, { additionalProperties: false, description: "Compatibility behavior. Omit for the default behavior." });
97
82
 
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
83
  const WorkflowLaneMetadata = Type.Object({
104
84
  version: Type.Integer({ minimum: 1, maximum: 1 }),
105
85
  key: Type.String({ minLength: 1, maxLength: 128, pattern: "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$" }),
@@ -145,110 +125,7 @@ const WorkflowPreflightOverride = Type.Object({
145
125
  version: Type.Integer({ minimum: 1, maximum: 1 }),
146
126
  coverage: Type.Optional(Type.String({ enum: ["complete", "partial"] })),
147
127
  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
- });
128
+ }, { additionalProperties: false, description: "workflow: true or a script path only; display-only hints; coverage warns." });
252
129
 
253
130
  // Runtime mission handlers validate these untrusted nested objects loudly. Keeping
254
131
  // their provider schema shallow avoids repeating a full durable-record schema in
@@ -282,7 +159,7 @@ const SubagentParamProperties = {
282
159
  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
160
  // Management action (when present, tool operates in management mode)
284
161
  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."
162
+ description: "Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with guide topic tool-reference."
286
163
  })),
287
164
  capabilities: Type.Optional(Type.Boolean({ description: "list: compact capability rows/details without system prompts." })),
288
165
  name: Type.Optional(Type.String({ description: "schedule.create name." })),
@@ -341,10 +218,11 @@ const SubagentParamProperties = {
341
218
  ],
342
219
  description: "create/update agent config; object or JSON string."
343
220
  })),
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." })),
221
+ workflow: Type.Optional(Type.Unsafe<string | true>({
222
+ anyOf: [{ type: "boolean" }, { type: "string", minLength: 1 }],
223
+ 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.",
224
+ })),
225
+ args: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Bounded plain-JSON args for workflow; raw-script args are exposed deeply frozen and persisted, so do not include secrets." })),
348
226
  globalConcurrencyLimit: Type.Optional(Type.Integer({ minimum: 1 })),
349
227
  maxSubagentSpawnsPerRun: Type.Optional(Type.Integer({ minimum: 1 })),
350
228
  preflight: Type.Optional(WorkflowPreflightOverride),
@@ -402,8 +280,33 @@ const SubagentParamsSchema = Type.Object(SubagentParamProperties);
402
280
 
403
281
  export const SubagentParams = keepTopLevelParameterDescriptions(SubagentParamsSchema);
404
282
 
405
- export function createSubagentParamsSchema(): typeof SubagentParams {
406
- return SubagentParams;
283
+ // Replaces workflow scripts when disabledFeatures lists "workflow-scripts". Kept small because every
284
+ // field is sent on every request; the executor validates step shapes and placeholders strictly.
285
+ const StructuredTask = { type: "object", properties: { agent: { type: "string", minLength: 1 }, task: { type: "string" } }, required: ["agent", "task"], additionalProperties: false };
286
+ const StructuredWorkflowProperties = {
287
+ action: Type.Optional(Type.String({ minLength: 1, description: "Management/control only; omit for execution. Discover actions with guide topic tool-reference." })),
288
+ task: Type.Optional(Type.String({ description: "One-child task with agent, or the original request ({task}) with chain/tasks." })),
289
+ tasks: Type.Optional(Type.Unsafe({ type: "array", minItems: 1, items: StructuredTask, description: "Parallel children; results in order." })),
290
+ // Flattened step: {agent, task?, as?} or {parallel}; no object-shape union for provider converters.
291
+ chain: Type.Optional(Type.Unsafe({
292
+ type: "array",
293
+ minItems: 1,
294
+ items: { type: "object", properties: { agent: { type: "string", minLength: 1 }, task: { type: "string" }, as: { type: "string" }, parallel: { type: "array", minItems: 1, items: StructuredTask } }, additionalProperties: false },
295
+ description: "Sequential steps: {agent,task?,as?} or {parallel:[{agent,task}]}.",
296
+ })),
297
+ };
298
+
299
+ export function createSubagentParamsSchema(disabled?: DisabledFeatureSurface): typeof SubagentParams {
300
+ if (!disabled || disabled.params.size === 0) return SubagentParams;
301
+ const structured = disabled.features.has("workflow-scripts");
302
+ const enabledProperties = Object.fromEntries(Object.entries(SubagentParamProperties).flatMap(([name, schema]) => {
303
+ if (disabled.params.has(name)) return [];
304
+ if (structured && name === "action") return [[name, StructuredWorkflowProperties.action]];
305
+ if (structured && name === "task") return [[name, StructuredWorkflowProperties.task], ["tasks", StructuredWorkflowProperties.tasks], ["chain", StructuredWorkflowProperties.chain]];
306
+ return [[name, schema]];
307
+ }));
308
+ // SAFETY: only optional properties are dropped or added; the executor rejects disabled options and admits chain/tasks at runtime.
309
+ return keepTopLevelParameterDescriptions(Type.Object(enabledProperties)) as typeof SubagentParams;
407
310
  }
408
311
 
409
312
  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()];