@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
@@ -53,6 +53,25 @@ export type PublicSubagentExecutionNormalization<T> =
53
53
  | { ok: true; params: T }
54
54
  | { ok: false; error: string; mode: PublicSubagentExecutionMode };
55
55
 
56
+ const RAW_SCRIPT_FORMS = "workflow: true or a workflow script path";
57
+ const REMOVED_WORKFLOW_SCRIPT = "workflowScript was removed; write the script in one ```js workflow block in this reply and call subagent({ workflow: true }), or pass a script file as workflow: \"./path/to/script.js\".";
58
+ const REMOVED_WORKFLOW_SCRIPT_PATH = "workflowScriptPath was removed; pass the script file as workflow: \"./path/to/script.js\" (a workflow value containing '/' is a path).";
59
+
60
+ /** A workflow value containing "/" or "\" is a script path; named workflow resource names contain neither. */
61
+ export function isWorkflowScriptPath(workflow: string): boolean {
62
+ return workflow.includes("/") || workflow.includes("\\");
63
+ }
64
+
65
+ /**
66
+ * Model tool calls supply script text only through workflow: true (the reply block) or a script path.
67
+ * workflowScript remains the internal carrier for slash, prompt-workflow, scheduled, RPC, and named-resource launches.
68
+ */
69
+ export function removedModelWorkflowFieldError(params: object): string | undefined {
70
+ if (Object.hasOwn(params, "workflowScript")) return REMOVED_WORKFLOW_SCRIPT;
71
+ if (Object.hasOwn(params, "workflowScriptPath")) return REMOVED_WORKFLOW_SCRIPT_PATH;
72
+ return undefined;
73
+ }
74
+
56
75
  export function validateWorkflowCapacityOverrides(params: PublicSubagentExecutionParams): string | undefined {
57
76
  for (const [name, value] of [
58
77
  ["globalConcurrencyLimit", params.globalConcurrencyLimit],
@@ -66,7 +85,7 @@ export function validateWorkflowCapacityOverrides(params: PublicSubagentExecutio
66
85
  * Enforce the public execution cutover before requests reach the executor.
67
86
  * Internal runs.run children and structured owned delegation bypass this boundary.
68
87
  */
69
- export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T): PublicSubagentExecutionNormalization<T> {
88
+ export function normalizePublicSubagentExecution<T extends PublicSubagentExecutionParams>(params: T, options: { structuredWorkflows?: boolean } = {}): PublicSubagentExecutionNormalization<T> {
70
89
  for (const field of ["resource", "resourceProvenance", "workflowResource", "workflowResourceProvenance", "workflowResourcePermit", "resourcePermit", "permit"] as const) {
71
90
  if (Object.hasOwn(params, field) && (params as Record<string, unknown>)[field] !== undefined) {
72
91
  return { ok: false, error: "Public execution does not accept workflow resource provenance or permit fields.", mode: params.action === undefined ? "workflow" : "management" };
@@ -79,19 +98,25 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
79
98
  return { ok: false, error: error instanceof Error ? error.message : String(error), mode: params.action === undefined ? "workflow" : "management" };
80
99
  }
81
100
  }
82
- if (params.workflowScript !== undefined && params.workflowScriptPath !== undefined) {
83
- return { ok: false, error: "workflowScript and workflowScriptPath are mutually exclusive.", mode: "workflow" };
101
+ if (params.workflowScriptPath !== undefined) {
102
+ return { ok: false, error: REMOVED_WORKFLOW_SCRIPT_PATH, mode: params.action === undefined ? "workflow" : "management" };
84
103
  }
85
- const hasNamedWorkflow = params.workflow !== undefined;
86
- if (hasNamedWorkflow && (typeof params.workflow !== "string" || !params.workflow.trim())) {
87
- return { ok: false, error: "workflow must be a non-empty named workflow resource.", mode: "workflow" };
104
+ // Some MCP clients send the boolean branch of the workflow union as the string "true" (#2600).
105
+ // Coerce it here so no path can resolve it as a named resource or script file called "true".
106
+ if (params.workflow === "true") params = { ...params, workflow: true };
107
+ const workflow = params.workflow;
108
+ if (workflow !== undefined && workflow !== true && (typeof workflow !== "string" || !workflow.trim())) {
109
+ return { ok: false, error: "workflow must be true (the ```js workflow block in this reply), a script path containing '/', or a named workflow resource.", mode: "workflow" };
88
110
  }
89
- if (hasNamedWorkflow && (params.workflowScript !== undefined || params.workflowScriptPath !== undefined)) {
90
- return { ok: false, error: "workflow is mutually exclusive with workflowScript and workflowScriptPath.", mode: "workflow" };
111
+ const hasNamedWorkflow = typeof workflow === "string" && !isWorkflowScriptPath(workflow);
112
+ // workflowScript is the internal script carrier; model tool calls cannot set it.
113
+ if (workflow !== undefined && params.workflowScript !== undefined) {
114
+ return { ok: false, error: "workflow cannot be combined with an internal workflowScript.", mode: "workflow" };
91
115
  }
92
- const hasWorkflowInput = params.workflowScript !== undefined || params.workflowScriptPath !== undefined || hasNamedWorkflow;
116
+ const hasRawScript = params.workflowScript !== undefined || (workflow !== undefined && !hasNamedWorkflow);
117
+ const hasWorkflowInput = hasRawScript || hasNamedWorkflow;
93
118
  if (!hasWorkflowInput && params.args !== undefined) {
94
- return { ok: false, error: "args requires workflow, workflowScript, or workflowScriptPath.", mode: "workflow" };
119
+ return { ok: false, error: "args requires workflow.", mode: "workflow" };
95
120
  }
96
121
  const hasCapacityOverride = params.globalConcurrencyLimit !== undefined || params.maxSubagentSpawnsPerRun !== undefined;
97
122
  if (hasCapacityOverride) {
@@ -99,19 +124,17 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
99
124
  if (capacityOverrideError) return { ok: false, error: capacityOverrideError, mode: params.action === undefined ? "workflow" : "management" };
100
125
  const validatesSpawnBudget = typeof params.action === "string" && params.action.trim() === "validate"
101
126
  && params.globalConcurrencyLimit === undefined && params.maxSubagentSpawnsPerRun !== undefined;
102
- if ((params.action !== undefined && !validatesSpawnBudget) || hasNamedWorkflow || (params.workflowScript === undefined && params.workflowScriptPath === undefined)) {
103
- return { ok: false, error: "Workflow capacity overrides are only supported on top-level workflowScript or workflowScriptPath calls; validate accepts maxSubagentSpawnsPerRun for static budget checks.", mode: params.action === undefined ? "workflow" : "management" };
127
+ if ((params.action !== undefined && !validatesSpawnBudget) || !hasRawScript) {
128
+ return { ok: false, error: `Workflow capacity overrides are only supported on top-level ${RAW_SCRIPT_FORMS} calls; validate accepts maxSubagentSpawnsPerRun for static budget checks.`, mode: params.action === undefined ? "workflow" : "management" };
104
129
  }
105
130
  }
106
131
  if (params.preflight !== undefined && !hasWorkflowInput) {
107
- return { ok: false, error: "preflight requires workflowScript or workflowScriptPath.", mode: params.action === undefined ? "workflow" : "management" };
132
+ return { ok: false, error: `preflight requires ${RAW_SCRIPT_FORMS}.`, mode: params.action === undefined ? "workflow" : "management" };
108
133
  }
109
- if (params.preflight !== undefined && hasNamedWorkflow && params.workflowScript === undefined && params.workflowScriptPath === undefined) {
134
+ if (params.preflight !== undefined && hasNamedWorkflow) {
110
135
  return { ok: false, error: "preflight is not supported with named workflow resources.", mode: "workflow" };
111
136
  }
112
- const hasValidWorkflowInput = (typeof params.workflowScript === "string" && Boolean(params.workflowScript.trim()))
113
- || (typeof params.workflowScriptPath === "string" && Boolean(params.workflowScriptPath.trim()))
114
- || (typeof params.workflow === "string" && Boolean(params.workflow.trim()));
137
+ const hasValidWorkflowInput = workflow !== undefined || (typeof params.workflowScript === "string" && Boolean(params.workflowScript.trim()));
115
138
  if (params.isolation !== undefined) {
116
139
  if (params.isolation !== "none" && params.isolation !== "worktree") {
117
140
  return { ok: false, error: "isolation must be 'none' or 'worktree'.", mode: hasWorkflowInput ? "workflow" : "management" };
@@ -131,7 +154,7 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
131
154
  }
132
155
  const action = params.action;
133
156
  if (action !== undefined && (typeof action !== "string" || !action.trim())) {
134
- return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflowScript.", mode: "management" };
157
+ return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflow.", mode: "management" };
135
158
  }
136
159
  const normalizedAction = typeof action === "string" ? action.trim() : undefined;
137
160
  if (params.baseRef !== undefined && normalizedAction !== undefined && normalizedAction !== "resume" && normalizedAction !== "schedule.create") {
@@ -141,55 +164,69 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
141
164
  return { ok: false, error: "Named workflow resource execution must omit action.", mode: "management" };
142
165
  }
143
166
  if (params.clarify !== undefined) {
144
- return { ok: false, error: "Public workflowScript execution does not support clarify UI.", mode: "workflow" };
167
+ return { ok: false, error: "Public workflow execution does not support clarify UI.", mode: "workflow" };
145
168
  }
146
169
  if (params.chainName !== undefined) {
147
- return { ok: false, error: "Durable chain management was removed; use workflowScript or /prompt-workflow for repeatable workflows.", mode: "management" };
170
+ return { ok: false, error: "Durable chain management was removed; use a workflow script or /prompt-workflow for repeatable workflows.", mode: "management" };
148
171
  }
149
172
  if (params.config && typeof params.config === "object" && !Array.isArray(params.config) && Object.prototype.hasOwnProperty.call(params.config, "steps")) {
150
- return { ok: false, error: "Durable chain definitions were removed; use workflowScript or /prompt-workflow for repeatable workflows.", mode: "management" };
173
+ return { ok: false, error: "Durable chain definitions were removed; use a workflow script or /prompt-workflow for repeatable workflows.", mode: "management" };
151
174
  }
152
175
  if (params.resume !== undefined) {
153
- return { ok: false, error: "Top-level resume execution is not available. Put resume on a workflowScript runs.run/runs.all item.", mode: "workflow" };
176
+ return { ok: false, error: "Top-level resume execution is not available. Put resume on a workflow script runs.run/runs.all item.", mode: "workflow" };
154
177
  }
155
- const hasLegacyOrchestration = params.tasks !== undefined || params.chain !== undefined || params.parallel !== undefined || params.concurrency !== undefined || params.chainDir !== undefined;
178
+ // action: "chain"/"tasks"/"parallel" stays a legacy error even where top-level chain/tasks are accepted.
179
+ const legacyOrchestrationAction = ["parallel", "tasks", "chain"].includes(normalizedAction?.toLowerCase() ?? "");
180
+ const hasStructuredWorkflow = options.structuredWorkflows === true && !legacyOrchestrationAction && (params.tasks !== undefined || params.chain !== undefined);
181
+ const hasLegacyOrchestration = (!hasStructuredWorkflow && (params.tasks !== undefined || params.chain !== undefined)) || params.parallel !== undefined || params.concurrency !== undefined || params.chainDir !== undefined;
156
182
  if (hasLegacyOrchestration) {
157
- return { ok: false, error: "Legacy top-level chain and parallel inputs were removed; use workflowScript.", mode: normalizedAction ? "management" : "workflow" };
183
+ return { ok: false, error: `Legacy top-level chain and parallel inputs were removed; use a workflow script (${RAW_SCRIPT_FORMS}).`, mode: normalizedAction ? "management" : "workflow" };
184
+ }
185
+ if (hasStructuredWorkflow) {
186
+ if (params.tasks !== undefined && params.chain !== undefined) {
187
+ return { ok: false, error: "Pass either tasks or chain, not both.", mode: "workflow" };
188
+ }
189
+ const field = params.tasks !== undefined ? "tasks" : "chain";
190
+ // workflow and workflowScript were already rejected by the workflow-scripts feature check.
191
+ for (const [name, value] of [["action", params.action], ["agent", params.agent], ["step", params.step]] as const) {
192
+ if (value !== undefined) return { ok: false, error: `${field} cannot be combined with ${name}.`, mode: normalizedAction ? "management" : "workflow" };
193
+ }
194
+ return { ok: true, params };
158
195
  }
159
196
  if (normalizedAction !== undefined) {
160
197
  const legacyAction = normalizedAction.toLowerCase();
161
198
  if (legacyAction === "append-step") {
162
- return { ok: false, error: "Legacy append-step control was removed from the public subagent tool; use current workflowScript orchestration.", mode: "management" };
199
+ return { ok: false, error: "Legacy append-step control was removed from the public subagent tool; use workflow script orchestration.", mode: "management" };
163
200
  }
164
201
  if (legacyAction === "approve-checkpoint" || legacyAction === "reject-checkpoint") {
165
- return { ok: false, error: "Legacy checkpoint approval controls were removed from the public subagent tool; use current workflowScript orchestration.", mode: "management" };
202
+ return { ok: false, error: "Legacy checkpoint approval controls were removed from the public subagent tool; use workflow script orchestration.", mode: "management" };
166
203
  }
167
204
  if (legacyAction === "single") {
168
205
  return { ok: false, error: "action='single' is not supported. Omit action and pass { agent, task } for one child.", mode: "workflow" };
169
206
  }
170
207
  if (legacyAction === "parallel" || legacyAction === "tasks" || legacyAction === "chain") {
171
- return { ok: false, error: "Legacy top-level chain and parallel inputs were removed; use workflowScript.", mode: "workflow" };
208
+ return { ok: false, error: `Legacy top-level chain and parallel inputs were removed; use a workflow script (${RAW_SCRIPT_FORMS}).`, mode: "workflow" };
172
209
  }
173
210
  if (normalizedAction === "validate") {
174
211
  if (params.agent !== undefined || params.task !== undefined || params.step !== undefined) {
175
- return { ok: false, error: "validate requires workflowScript or workflowScriptPath and does not accept direct agent, task, or step execution fields.", mode: "management" };
212
+ return { ok: false, error: `validate requires ${RAW_SCRIPT_FORMS} and does not accept direct agent, task, or step execution fields.`, mode: "management" };
176
213
  }
177
214
  if (!hasValidWorkflowInput) {
178
- return { ok: false, error: "validate requires a non-empty workflowScript or workflowScriptPath.", mode: "management" };
215
+ return { ok: false, error: `validate requires ${RAW_SCRIPT_FORMS}.`, mode: "management" };
179
216
  }
180
217
  return { ok: true, params: { ...params, action: normalizedAction } };
181
218
  }
182
219
  if (normalizedAction === "schedule.create") {
183
220
  if (params.agent !== undefined || params.task !== undefined || params.step !== undefined) {
184
- return { ok: false, error: "schedule.create requires workflowScript or workflowScriptPath and does not accept direct agent, task, or step execution fields.", mode: "management" };
221
+ return { ok: false, error: `schedule.create requires ${RAW_SCRIPT_FORMS} and does not accept direct agent, task, or step execution fields.`, mode: "management" };
185
222
  }
186
223
  if (!hasValidWorkflowInput) {
187
- return { ok: false, error: "schedule.create requires a non-empty workflowScript or workflowScriptPath.", mode: "management" };
224
+ return { ok: false, error: `schedule.create requires ${RAW_SCRIPT_FORMS}.`, mode: "management" };
188
225
  }
189
226
  return { ok: true, params: { ...params, action: normalizedAction } };
190
227
  }
191
228
  if (hasWorkflowInput) {
192
- return { ok: false, error: "Workflow execution must omit action; only validate and schedule.create accept action with workflowScript or workflowScriptPath.", mode: "management" };
229
+ return { ok: false, error: `Workflow execution must omit action; only validate and schedule.create accept action with ${RAW_SCRIPT_FORMS}.`, mode: "management" };
193
230
  }
194
231
  if (params.task !== undefined) {
195
232
  return { ok: false, error: "Structured single-child task cannot be combined with a management/control action.", mode: "management" };
@@ -197,10 +234,10 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
197
234
  return { ok: true, params: { ...params, action: normalizedAction } };
198
235
  }
199
236
  if (params.step !== undefined) {
200
- return { ok: false, error: "step is not a public execution field; use workflowScript for orchestration.", mode: "workflow" };
237
+ return { ok: false, error: `step is not a public execution field; use a workflow script (${RAW_SCRIPT_FORMS}) for orchestration.`, mode: "workflow" };
201
238
  }
202
239
  if (hasWorkflowInput && (params.agent !== undefined || params.task !== undefined)) {
203
- return { ok: false, error: "Structured single-child execution cannot be combined with workflow, workflowScript, or workflowScriptPath.", mode: "workflow" };
240
+ return { ok: false, error: "Structured single-child execution cannot be combined with workflow.", mode: "workflow" };
204
241
  }
205
242
  if (params.agent !== undefined || params.task !== undefined) {
206
243
  if (typeof params.agent !== "string" || !params.agent.trim()) {
@@ -219,7 +256,7 @@ export function normalizePublicSubagentExecution<T extends PublicSubagentExecuti
219
256
  };
220
257
  }
221
258
  if (!hasValidWorkflowInput) {
222
- return { ok: false, error: "Execution requires either { agent, task? } for one child, a named workflow resource, or a non-empty workflowScript or workflowScriptPath for orchestration.", mode: "workflow" };
259
+ return { ok: false, error: "Execution requires either { agent, task? } for one child or workflow (true, a script path, or a named workflow resource) for orchestration.", mode: "workflow" };
223
260
  }
224
261
  return { ok: true, params };
225
262
  }
@@ -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 || 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 || 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();