@xzzpig/pi-subagents 0.16.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.
- package/CHANGELOG.md +233 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +34 -21
- package/docs/configuration.md +82 -7
- package/docs/extension-api.md +75 -8
- package/docs/missions.md +13 -13
- package/docs/models.md +7 -5
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +5 -5
- package/docs/tool-reference.md +98 -100
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +214 -162
- package/inspector-runner.mjs +1 -1
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +15 -9
- package/prompts/council.md +6 -3
- package/prompts/review-loop.md +1 -1
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +13 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
- package/skills/pi-subagents/references/execution-controls.md +72 -69
- package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
- package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +63 -54
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +132 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +7 -2
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +10 -4
- package/src/extension/fanout-child.ts +20 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +168 -206
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +39 -11
- package/src/extension/schemas.ts +47 -138
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +146 -0
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +26 -16
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +60 -95
- package/src/runs/background/async-job-tracker.ts +91 -56
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +98 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +20 -6
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +16 -4
- package/src/runs/background/runner-aliases.ts +54 -16
- package/src/runs/background/runner-child-launch.ts +4 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +111 -288
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +111 -139
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +715 -258
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +37 -16
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +144 -8
- package/src/runs/shared/child-tool-plan.ts +38 -116
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +5 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +35 -10
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +12 -0
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +4 -1
- package/src/runs/shared/pi-spawn.ts +1 -3
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +36 -9
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/model-info.ts +9 -0
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +73 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +18 -3
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +17 -246
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +4 -5
- package/src/tui/fleet-status.ts +38 -8
- package/src/tui/fleet.ts +21 -6
- package/src/tui/render.ts +166 -71
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +47 -12
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +13 -5
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +16 -16
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +12 -6
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +225 -59
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
package/src/extension/schemas.ts
CHANGED
|
@@ -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}$" }),
|
|
@@ -120,7 +100,7 @@ const ToolBudgetOverride = Type.Object({
|
|
|
120
100
|
soft: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
121
101
|
hard: Type.Integer({ minimum: 1 }),
|
|
122
102
|
block: Type.Optional(ToolBudgetBlock),
|
|
123
|
-
}, { additionalProperties: false, description: "soft
|
|
103
|
+
}, { additionalProperties: false, description: "soft <= hard; after hard block read/grep/find/ls or '*' for all." });
|
|
124
104
|
|
|
125
105
|
const UsageBudgetLimitOverride = Type.Object({
|
|
126
106
|
soft: Type.Optional(Type.Number({ exclusiveMinimum: 0 })),
|
|
@@ -130,7 +110,7 @@ const UsageBudgetLimitOverride = Type.Object({
|
|
|
130
110
|
const UsageBudgetOverride = Type.Object({
|
|
131
111
|
tokens: Type.Optional(UsageBudgetLimitOverride),
|
|
132
112
|
costUsd: Type.Optional(UsageBudgetLimitOverride),
|
|
133
|
-
}, { additionalProperties: false, description: "Root-only reported usage;
|
|
113
|
+
}, { additionalProperties: false, minProperties: 1, description: "tokens or costUsd; soft <= hard. Root-only reported usage; blocks launches. Running children are not stopped." });
|
|
134
114
|
|
|
135
115
|
const WorkflowPreflightLane = Type.Object({
|
|
136
116
|
key: Type.String({ minLength: 1, maxLength: 128 }),
|
|
@@ -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: "
|
|
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
|
|
@@ -279,10 +156,10 @@ const ControlOverrides = Type.Object({
|
|
|
279
156
|
const SubagentParamProperties = {
|
|
280
157
|
agent: Type.Optional(Type.String({ description: "One-child agent or management target." })),
|
|
281
158
|
task: Type.Optional(Type.String({ description: "One-child task; requires agent." })),
|
|
282
|
-
extensionBindings: Type.Optional(Type.Unsafe({ type: "object", maxProperties: 16, additionalProperties: true, description: "Child-only
|
|
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
|
|
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.
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
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),
|
|
@@ -358,7 +236,7 @@ const SubagentParamProperties = {
|
|
|
358
236
|
description: "fresh/fork overrides every child; profile requires agent's declared defaultContext, ignoring config. Omitted: defaultSubagentContext wins over each agent defaultContext; implicit fork needs persisted parent + leaf, else fresh. forkContext may prune forks before spawn.",
|
|
359
237
|
})),
|
|
360
238
|
async: Type.Optional(Type.Boolean({ description: "Background; default asyncByDefault. false only to block parent." })),
|
|
361
|
-
timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "
|
|
239
|
+
timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Foreground and single async runs use config timeoutMs, else 30m; async composites have no default parent deadline. Alias maxRuntimeMs; must agree." })),
|
|
362
240
|
maxRuntimeMs: Type.Optional(Type.Integer({ minimum: 1, description: "Alias timeoutMs (same defaults)." })),
|
|
363
241
|
checkpointBeforeDeadlineMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 2_147_483_647, description: "Async single-agent runs only: the runner requests that the child checkpoint and stop this many ms before the run deadline (best-effort; the deadline kill still applies)." })),
|
|
364
242
|
toolTimeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Per-tool deadline (ms); fast builtins default 5m." })),
|
|
@@ -389,15 +267,46 @@ const SubagentParamProperties = {
|
|
|
389
267
|
outputSchema: Type.Optional(OutputSchemaOverride),
|
|
390
268
|
agentContract: Type.Optional(AgentContractOverride),
|
|
391
269
|
acceptance: Type.Optional(AcceptanceOverride),
|
|
392
|
-
gate: Type.Optional(Type.
|
|
270
|
+
gate: Type.Optional(Type.Unsafe({
|
|
271
|
+
anyOf: [
|
|
272
|
+
{ type: "string", minLength: 1 },
|
|
273
|
+
{ 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 },
|
|
274
|
+
],
|
|
275
|
+
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.",
|
|
276
|
+
})),
|
|
393
277
|
};
|
|
394
278
|
|
|
395
279
|
const SubagentParamsSchema = Type.Object(SubagentParamProperties);
|
|
396
280
|
|
|
397
281
|
export const SubagentParams = keepTopLevelParameterDescriptions(SubagentParamsSchema);
|
|
398
282
|
|
|
399
|
-
|
|
400
|
-
|
|
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;
|
|
401
310
|
}
|
|
402
311
|
|
|
403
312
|
const SubagentWaitParamsSchema = Type.Object({
|
|
@@ -13,12 +13,21 @@ export const SUBAGENT_GUIDE_TOPICS = [
|
|
|
13
13
|
"models",
|
|
14
14
|
"watchdog",
|
|
15
15
|
"extension-api",
|
|
16
|
+
"council",
|
|
16
17
|
] as const;
|
|
17
18
|
|
|
18
19
|
export type SubagentGuideTopic = (typeof SUBAGENT_GUIDE_TOPICS)[number];
|
|
19
20
|
|
|
20
21
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
21
22
|
|
|
23
|
+
// /council must work under `pi --no-skills`, which drops the package skills from context,
|
|
24
|
+
// so this topic serves the council skill together with the references it tells the model to read.
|
|
25
|
+
const COUNCIL_FILES = [
|
|
26
|
+
"skills/council-mode/SKILL.md",
|
|
27
|
+
"skills/council-mode/references/pass-contracts.md",
|
|
28
|
+
"skills/pi-subagents/references/execution-controls.md",
|
|
29
|
+
];
|
|
30
|
+
|
|
22
31
|
function isGuideTopic(value: string): value is SubagentGuideTopic {
|
|
23
32
|
return (SUBAGENT_GUIDE_TOPICS as readonly string[]).includes(value);
|
|
24
33
|
}
|
|
@@ -27,11 +36,10 @@ export function readSubagentGuide(topic = "overview", root = packageRoot): strin
|
|
|
27
36
|
if (!isGuideTopic(topic)) {
|
|
28
37
|
return `Unknown subagents guide topic '${topic}'. Valid topics: ${SUBAGENT_GUIDE_TOPICS.join(", ")}. No files were changed.`;
|
|
29
38
|
}
|
|
30
|
-
const
|
|
31
|
-
? path.join(root, "README.md")
|
|
32
|
-
: path.join(root, "docs", `${topic}.md`);
|
|
39
|
+
const files = topic === "overview" ? ["README.md"] : topic === "council" ? COUNCIL_FILES : [path.join("docs", `${topic}.md`)];
|
|
33
40
|
try {
|
|
34
|
-
|
|
41
|
+
const contents = files.map((file) => fs.readFileSync(path.join(root, file), "utf-8"));
|
|
42
|
+
return files.length === 1 ? contents[0]! : contents.map((content, index) => `<!-- ${files[index]} -->\n\n${content}`).join("\n\n");
|
|
35
43
|
} catch (error) {
|
|
36
44
|
const message = error instanceof Error ? error.message : String(error);
|
|
37
45
|
throw new Error(`Failed to read packaged subagents guide '${topic}': ${message}`, { cause: error instanceof Error ? error : undefined });
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
|
|
4
|
+
import type { ToolActivationMode } from "../shared/types.ts";
|
|
5
|
+
|
|
6
|
+
interface ActivationDetails {
|
|
7
|
+
enabled?: string[];
|
|
8
|
+
missing?: string[];
|
|
9
|
+
unavailable?: string[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const LOADER_NAME = "subagents_enable";
|
|
13
|
+
const SUBAGENT_NAME = "subagent";
|
|
14
|
+
let warnedUnsupportedHost = false;
|
|
15
|
+
|
|
16
|
+
type ToolSelectionMessage = {
|
|
17
|
+
role: string;
|
|
18
|
+
toolsAdded?: readonly { name: string }[];
|
|
19
|
+
toolsRemoved?: readonly { name: string }[];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
function hasNativeToolSelection(messages: readonly ToolSelectionMessage[]): boolean {
|
|
23
|
+
return messages.some((message) => message.role === "system"
|
|
24
|
+
&& (Object.hasOwn(message, "toolsAdded") || Object.hasOwn(message, "toolsRemoved")));
|
|
25
|
+
}
|
|
26
|
+
|
|
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);
|
|
31
|
+
pi.setActiveTools([...new Set(next)]);
|
|
32
|
+
}
|
|
33
|
+
|
|
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 {
|
|
57
|
+
const available = pi.getAllTools();
|
|
58
|
+
if (!Array.isArray(available) || !Array.isArray(pi.getActiveTools())) return true;
|
|
59
|
+
if (!available.some((tool) => tool.name === LOADER_NAME)) return true;
|
|
60
|
+
// SAFETY: The running Pi session manager exposes buildSessionContext, but its read-only extension type omits it.
|
|
61
|
+
const messages = (ctx.sessionManager as typeof ctx.sessionManager & { buildSessionContext(): { messages: ToolSelectionMessage[] } }).buildSessionContext().messages;
|
|
62
|
+
if (hasNativeToolSelection(messages)) {
|
|
63
|
+
// Replayed here because a package-local pi-ai may be older than the running Pi.
|
|
64
|
+
const recorded = new Set<string>();
|
|
65
|
+
for (const message of messages) {
|
|
66
|
+
if (message.role !== "system") continue;
|
|
67
|
+
for (const tool of message.toolsRemoved ?? []) recorded.delete(tool.name);
|
|
68
|
+
for (const tool of message.toolsAdded ?? []) recorded.add(tool.name);
|
|
69
|
+
}
|
|
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;
|
|
74
|
+
}
|
|
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;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function registerSubagentToolActivation(
|
|
82
|
+
pi: ExtensionAPI,
|
|
83
|
+
options: { advertisedPrompt: () => string | undefined | Promise<string | undefined>; mode?: ToolActivationMode },
|
|
84
|
+
): void {
|
|
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") {
|
|
89
|
+
if (!warnedUnsupportedHost) {
|
|
90
|
+
warnedUnsupportedHost = true;
|
|
91
|
+
console.warn("[pi-subagents] Dynamic tool activation requires Pi 0.86.1 or newer; keeping subagent eagerly available.");
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Takes no arguments, but a stray one (DeepSeek sends `{ action: "enable" }`) must not fail validation.
|
|
97
|
+
const parameters = Type.Object({});
|
|
98
|
+
const loader: ToolDefinition<typeof parameters, ActivationDetails> = {
|
|
99
|
+
name: LOADER_NAME,
|
|
100
|
+
...MODEL_ONLY_TOOL,
|
|
101
|
+
label: "Enable Subagents",
|
|
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.",
|
|
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.",
|
|
104
|
+
parameters,
|
|
105
|
+
async execute() {
|
|
106
|
+
if (!pi.getAllTools().some((tool) => tool.name === SUBAGENT_NAME)) return {
|
|
107
|
+
isError: true,
|
|
108
|
+
content: [{ type: "text", text: "Cannot enable unavailable tools: subagent." }],
|
|
109
|
+
details: { unavailable: [SUBAGENT_NAME] },
|
|
110
|
+
};
|
|
111
|
+
try {
|
|
112
|
+
setSelection(pi, true, true);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
return {
|
|
115
|
+
isError: true,
|
|
116
|
+
content: [{ type: "text", text: `Activation failed: ${error instanceof Error ? error.message : String(error)}` }],
|
|
117
|
+
details: { missing: [SUBAGENT_NAME] },
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
if (!pi.getActiveTools().includes(SUBAGENT_NAME)) return {
|
|
121
|
+
isError: true,
|
|
122
|
+
content: [{ type: "text", text: "Activation failed: subagent." }],
|
|
123
|
+
details: { missing: [SUBAGENT_NAME] },
|
|
124
|
+
};
|
|
125
|
+
const advertised = await options.advertisedPrompt();
|
|
126
|
+
return {
|
|
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}` : ""}` }],
|
|
128
|
+
details: { enabled: [SUBAGENT_NAME] },
|
|
129
|
+
};
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
pi.registerTool(loader);
|
|
133
|
+
|
|
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); });
|
|
138
|
+
pi.on("before_agent_start", (event) => {
|
|
139
|
+
if (!loaderSelected) return;
|
|
140
|
+
const available = pi.getAllTools();
|
|
141
|
+
if (!Array.isArray(available) || !available.some((tool) => tool.name === LOADER_NAME)) return;
|
|
142
|
+
const selectedTools = event.systemPromptOptions.selectedTools ??= [...pi.getActiveTools()];
|
|
143
|
+
if (!selectedTools.includes(LOADER_NAME)) selectedTools.push(LOADER_NAME);
|
|
144
|
+
if (!pi.getActiveTools().includes(LOADER_NAME)) pi.setActiveTools([...pi.getActiveTools(), LOADER_NAME]);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
@@ -2,46 +2,77 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import type { ExtensionConfig, ToolDescriptionMode } from "../shared/types.ts";
|
|
4
4
|
import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
|
|
5
|
+
import { resolveDisabledFeatureSurface, type DisabledFeatureSurface, type SubagentSurfaceFeature } from "../shared/disabled-features.ts";
|
|
5
6
|
|
|
6
7
|
const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
|
|
7
8
|
const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
|
|
8
9
|
const AGENT_SELECTION_GUIDANCE = 'First call {action:"list",capabilities:true}: executable, non-disabled agents only; external-cli requires runner.available === true. Passive PATH/PATHEXT/X_OK is not authentication/version/launch proof; preflight is authoritative.';
|
|
9
10
|
const SUBAGENT_FAILURE_RECOVERY_GUIDANCE = "Workflow, child launch, prompt runtime, extension load or child tooling failure is a lane infrastructure blocker. Stop; report exact failure, run/status and repo/cwd/worktree/branch/ref; verify clean worktree or capture partial diff before same-protocol retry or asking the owner. Never silently switch to interactive_shell, pi -ne, Codex/Claude/Cursor CLI or foreground/external mode: governed-workflow fallback requires explicit owner approval, not Pi core's generic pi -ne hint. Explicit foreground/CLI requests and work outside that protocol remain valid.";
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
type FeatureText = (feature: SubagentSurfaceFeature, text: string, disabledText?: string) => string;
|
|
13
|
+
|
|
14
|
+
function featureText(disabled: DisabledFeatureSurface): FeatureText {
|
|
15
|
+
return (feature, text, disabledText = "") => disabled.features.has(feature) ? disabledText : text;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const safetyGuidance = (on: FeatureText) => `SAFETY-CRITICAL SUBAGENT GUIDANCE:
|
|
12
19
|
• Direct parent execution is the default. Invoke subagents only when delegation is authorized by the operator's current request or applicable user/project instructions; task size, complexity, risk, tool-call count, or recipe fit do not independently authorize delegation.
|
|
13
20
|
• ${AGENT_SELECTION_GUIDANCE}
|
|
14
21
|
• ${SUBAGENT_FAILURE_RECOVERY_GUIDANCE}
|
|
15
|
-
• Omit action for execution. For an authorized delegated multi-step/parallel workflow: exactly one top-level subagent workflow call with async:true; children launch only inside it.
|
|
22
|
+
• Omit action for execution. For an authorized delegated multi-step/parallel workflow: exactly one top-level subagent ${on("workflow-scripts", "workflow call with async:true; children launch only inside it", "chain or tasks call with async:true")}.
|
|
16
23
|
• Async follows asyncByDefault (normally true); async:false only to block the parent, not for final reviews/gates. Consume results at dependency barriers. Native async completion wakes this session: return control, no sleep/poll or bg_wait merely for a wake. bg_wait is for provider/detached work without native notification needing a same-turn result.
|
|
17
24
|
• Ordinary child subagents are not orchestrators; only configured fanout within depth/session limits. For an authorized delegated workflow, keep one writer per cwd/worktree and isolate concurrent writers. Use fresh-context read-only reviewers when independent review was requested, then parent synthesis/fixes. Oracle/advisor unknowns use supervisor dialogue; one-shot only when requested.
|
|
18
|
-
• Bind durable output on runs.run/runs.all, not task filename prose; return actual outputReference/outputPathMapping/artifactPaths, evidence and residual risks.
|
|
19
|
-
• children.list: resume only resumable rows. {action:"resume",id,message} detaches a follow-up/challenge with stored agent/model/tool contract.
|
|
20
|
-
• Named resources own authority; raw
|
|
21
|
-
• Inspect asyncId/asyncDir (status.json, events.jsonl, logs) with status/debug.run; control with interrupt/stop/resume/steer. Read {action:"guide",topic:"tool-reference"} for controls/evidence gates.`;
|
|
25
|
+
• Bind durable output ${on("workflow-scripts", "on runs.run/runs.all", "with output")}, not task filename prose; return actual outputReference/outputPathMapping/artifactPaths, evidence and residual risks.
|
|
26
|
+
• children.list is workflow-only, not an exhaustive list of direct native children: resume only resumable rows. When an intended child's exact run id is known, inspect it with {action:"status",id}; if status identifies the candidate, attempt {action:"resume",id,message}. Resume authoritatively checks eligibility, may reject it, and otherwise detaches a follow-up/challenge with the stored agent/model/tool contract. Use a labeled same-role fallback only when no known candidate exists or resume rejects eligibility.${on("workflow-scripts", " Scripts await runs.run(newKey,{resume:runId,task}); continue from latest returned runId. Each distinct resume pass needs a new stable key; same-key reuse requires identical launch parameters.")}
|
|
27
|
+
${on("workflow-scripts", "• Named resources own authority; raw scripts (workflow:true or a path) cannot use runs.host. Granted commands/relative outputs use workflow cwd, never per-step cwd.\n")}• Inspect asyncId/asyncDir (status.json, events.jsonl, logs) with status/debug.run; control with interrupt/stop/resume/steer. Read {action:"guide",topic:"tool-reference"} for controls/evidence gates.`;
|
|
22
28
|
|
|
23
|
-
const
|
|
29
|
+
const scriptExecutionGuidance = (on: FeatureText) => `Delegate one child with {agent,task?}; otherwise set exactly one workflow source, with optional args.
|
|
30
|
+
Workflow script: write it as one \`\`\`js workflow block in this reply, then call subagent({workflow:true,...}). workflow:'./path.js' (any value with '/') loads a file from request cwd; other strings name a resource.
|
|
31
|
+
agent/task exclude workflow; task excludes action. agent may target management actions. action is management/control; validate accepts workflow:true or a path without launching.
|
|
24
32
|
Scripts: JavaScript statement bodies with explicit return, top-level await, plain helpers/Promise chains; nested async function/arrow/method helpers are rejected. Await runs.run('key',{agent,task}) before .output; await runs.all([{key,agent,task},...]) for an ordered array, not a key map. Observe every stored run promise with direct await, Promise.race or Promise.all. Await/return runs.steer(key,message,options?) for a prior key, never raw run ids; queued/delivered/missed/failed receipts are not compliance proof.
|
|
25
|
-
Before advanced orchestration (runs.lanes, rolling fanout, mission state, handoffs), read {action:"guide",topic:"workflows"} or the pi-subagents skill. Raw-script sandboxes add deeply frozen args; all sandboxes provide runs, emit, console, JavaScript and enabled mission state, with no filesystem/shell/Pi tools/host globals. External CLI agents support native options only when their runner declares them; read guide tool-reference before passing model, structured output, acceptance/agentContract, tool budget, fast, fork context or skills/tools.
|
|
26
|
-
Model override: first call {action:"models"}; copy exact provider/id, not agent names. Thinking uses model suffix, not watchdog-only thinking.
|
|
33
|
+
Before advanced orchestration (runs.lanes, rolling fanout, mission state, handoffs), read {action:"guide",topic:"workflows"} or the pi-subagents skill. Raw-script sandboxes add deeply frozen args; all sandboxes provide runs, emit, console, JavaScript and enabled mission state, with no filesystem/shell/Pi tools/host globals. External CLI agents support native options only when their runner declares them; read guide tool-reference before passing model, structured output, acceptance/agentContract, ${on("tool-budgets", "tool budget, ")}fast, fork context or skills/tools.
|
|
34
|
+
Model override: first call {action:"models"}; copy exact provider/id, not agent names. Thinking uses model suffix${on("watchdog", ", not watchdog-only thinking")}.
|
|
27
35
|
Named resources: {workflow:'review',args:{task:'...'}} or {workflow:'run-ci',args:{command:'npm test'}}. Raw scripts also accept bounded plain-data args; raw-script args persist as evidence, so never include secrets. worktree:true requires clean source; baseRef defaults to HEAD at allocation or a supported named ref, never full 40/64-character commit IDs or revision expressions.`;
|
|
28
36
|
|
|
29
|
-
|
|
37
|
+
const structuredExecutionGuidance = (on: FeatureText) => `Delegate one child with {agent,task?}. tasks:[{agent,task},...] runs children in parallel. chain:[{agent,task?,as?} or {parallel:[{agent,task},...]}] runs steps in order; a parallel step waits for all its children and a failed step stops the chain.
|
|
38
|
+
Chain task placeholders: {task} is the top-level task (the original request); {previous} is the prior step's output (a parallel step's outputs in order), and the default when task is omitted; {outputs.name} is the output of an earlier step with as:'name'.
|
|
39
|
+
agent, chain and tasks exclude each other and action. action is management/control; agent may target management actions.
|
|
40
|
+
External CLI agents support native options only when their runner declares them; read guide tool-reference before passing model, structured output, acceptance/agentContract, ${on("tool-budgets", "tool budget, ")}fast, fork context or skills/tools.
|
|
41
|
+
Model override: first call {action:"models"}; copy exact provider/id, not agent names. Thinking uses model suffix${on("watchdog", ", not watchdog-only thinking")}.
|
|
42
|
+
worktree:true requires clean source; baseRef defaults to HEAD at allocation or a supported named ref, never full 40/64-character commit IDs or revision expressions.`;
|
|
43
|
+
|
|
44
|
+
const defaultDescription = (on: FeatureText) => `${on("workflow-scripts", scriptExecutionGuidance(on), structuredExecutionGuidance(on))}\n\n${safetyGuidance(on)}`;
|
|
45
|
+
|
|
46
|
+
const managementDiscovery = (on: FeatureText) => [
|
|
47
|
+
["list/get/models/guide"],
|
|
48
|
+
[on("agent-management", "create/update/delete/eject/disable/enable/reset/refine")],
|
|
49
|
+
[on("missions", "mission.*"), on("schedules", "schedule.*"), on("watchdog", "watchdog.*"), on("panes", "inspector.*, project.*"), on("lane-management", "lane.status/recordMerge/recordSupersession")],
|
|
50
|
+
[on("lane-management", "worktree.discard and plan-only worktree.cleanup")],
|
|
51
|
+
[`doctor${on("spawn-budget-grants", " and grant-spawn-budget")}`],
|
|
52
|
+
].map((group) => group.filter(Boolean).join(", ")).filter(Boolean).join("; ");
|
|
53
|
+
|
|
54
|
+
const fullDescription = (on: FeatureText) => `${defaultDescription(on)}
|
|
55
|
+
|
|
56
|
+
WORKFLOW DETAILS:
|
|
57
|
+
${on("workflow-scripts", "• runs.lanes([{key,stages:[{key,agent,task},{key,resume:'previous',task}]}]) runs first stages together, later stages sequentially per lane. Failures stay lane-local; only explicit structuredOutput.verdict === 'blocked' blocks a successful stage, never reviewer prose.\n")}• ${on("workflow-scripts", "Workflow child controls default onto runs.run/runs.all items; child fields override them.", "Top-level child controls apply to every chain/tasks child.")} worktree:true isolates each child and returns handoff artifacts.${on("usage-budgets", " usageBudget is shared across the workflow; already-running children are not stopped.")}
|
|
58
|
+
• Missions auto-attach${on("missions", " unless mission:false")}; ${on("workflow-scripts", "await state.get(key)/state.set(key,JSONValue) requires a mission. ")}See guide topic missions. Omit acceptance for reviewer/read-only calls; acceptance.review.required requests independent writer review.
|
|
59
|
+
• Management discovery: ${managementDiscovery(on)}. Use guide topics agents, ${on("missions", "missions, ")}observability, tool-reference, configuration, models${on("watchdog", ", watchdog")} or extension-api for exact action fields.${on("schedules", on("workflow-scripts", " Schedules take script inputs, not direct children; recipes live in the missions guide."))}`;
|
|
60
|
+
|
|
61
|
+
const allEnabled = featureText(resolveDisabledFeatureSurface({}));
|
|
62
|
+
|
|
63
|
+
export const SUBAGENT_SAFETY_GUIDANCE = safetyGuidance(allEnabled);
|
|
64
|
+
|
|
65
|
+
export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = defaultDescription(allEnabled);
|
|
30
66
|
|
|
31
67
|
export const SUBAGENT_TOOL_PROMPT_SNIPPET = "For operator-requested delegation, use subagents; compose multi-child work in one workflow call.";
|
|
68
|
+
const STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET = "For operator-requested delegation, use subagents; compose multi-child work in one chain or tasks call.";
|
|
32
69
|
export const SUBAGENT_TOOL_PROMPT_GUIDELINES = [
|
|
33
70
|
"Do not invoke subagents unless the operator requested delegation directly or through applicable instructions.",
|
|
34
71
|
];
|
|
35
72
|
|
|
36
73
|
export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = DEFAULT_SUBAGENT_TOOL_DESCRIPTION;
|
|
37
74
|
|
|
38
|
-
export const FULL_SUBAGENT_TOOL_DESCRIPTION =
|
|
39
|
-
|
|
40
|
-
WORKFLOW DETAILS:
|
|
41
|
-
• runs.lanes([{key,stages:[{key,agent,task},{key,resume:'previous',task}]}]) runs first stages together, later stages sequentially per lane. Failures stay lane-local; only explicit structuredOutput.verdict === 'blocked' blocks a successful stage, never reviewer prose.
|
|
42
|
-
• Workflow child controls default onto runs.run/runs.all items; child fields override them. worktree:true isolates each child and returns handoff artifacts. usageBudget is shared across the workflow; already-running children are not stopped.
|
|
43
|
-
• Missions auto-attach unless mission:false; await state.get(key)/state.set(key,JSONValue) requires a mission. See guide topic missions. Omit acceptance for reviewer/read-only calls; acceptance.review.required requests independent writer review.
|
|
44
|
-
• Management discovery: list/get/models/guide; create/update/delete/eject/disable/enable/reset/refine; mission.*, schedule.*, watchdog.*, inspector.*, project.*, lane.status/recordMerge/recordSupersession; worktree.discard and plan-only worktree.cleanup; doctor and grant-spawn-budget. Use guide topics agents, missions, observability, tool-reference, configuration, models, watchdog or extension-api for exact action fields. Schedules take script inputs, not direct children; recipes live in the missions guide.`;
|
|
75
|
+
export const FULL_SUBAGENT_TOOL_DESCRIPTION = fullDescription(allEnabled);
|
|
45
76
|
|
|
46
77
|
function isToolDescriptionMode(value: unknown): value is ToolDescriptionMode {
|
|
47
78
|
return value === "full" || value === "compact" || value === "custom";
|
|
@@ -55,6 +86,8 @@ export interface ToolDescriptionOptions {
|
|
|
55
86
|
cwd?: string;
|
|
56
87
|
agentDir?: string;
|
|
57
88
|
warn?: (message: string) => void;
|
|
89
|
+
/** Removes lines for disabled features from the default and full descriptions; custom descriptions are unchanged apart from the appended safety guidance. */
|
|
90
|
+
disabledFeatures?: DisabledFeatureSurface;
|
|
58
91
|
}
|
|
59
92
|
|
|
60
93
|
export interface SubagentToolPromptMetadata {
|
|
@@ -62,10 +95,10 @@ export interface SubagentToolPromptMetadata {
|
|
|
62
95
|
promptGuidelines?: string[];
|
|
63
96
|
}
|
|
64
97
|
|
|
65
|
-
export function buildSubagentToolPromptMetadata(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}): SubagentToolPromptMetadata {
|
|
98
|
+
export function buildSubagentToolPromptMetadata(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, disabledFeatures?: DisabledFeatureSurface): SubagentToolPromptMetadata {
|
|
66
99
|
if (config.toolDescriptionMode !== undefined) return {};
|
|
67
100
|
return {
|
|
68
|
-
promptSnippet: SUBAGENT_TOOL_PROMPT_SNIPPET,
|
|
101
|
+
promptSnippet: disabledFeatures?.features.has("workflow-scripts") ? STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET : SUBAGENT_TOOL_PROMPT_SNIPPET,
|
|
69
102
|
promptGuidelines: SUBAGENT_TOOL_PROMPT_GUIDELINES,
|
|
70
103
|
};
|
|
71
104
|
}
|
|
@@ -146,30 +179,32 @@ function loadCustomToolDescription(options?: ToolDescriptionOptions): string | u
|
|
|
146
179
|
return undefined;
|
|
147
180
|
}
|
|
148
181
|
|
|
149
|
-
function withMandatorySafetyGuidance(description: string): string {
|
|
182
|
+
function withMandatorySafetyGuidance(description: string, safety: string): string {
|
|
150
183
|
const customDescription = description
|
|
151
184
|
.split(SUBAGENT_SAFETY_GUIDANCE)
|
|
185
|
+
.flatMap((part) => part.split(safety))
|
|
152
186
|
.flatMap((part) => part.split(SUBAGENT_FAILURE_RECOVERY_GUIDANCE))
|
|
153
187
|
.map((part) => part.trim())
|
|
154
188
|
.filter(Boolean)
|
|
155
189
|
.join("\n\n");
|
|
156
190
|
return customDescription
|
|
157
|
-
? `${customDescription}\n\n${
|
|
158
|
-
:
|
|
191
|
+
? `${customDescription}\n\n${safety}`
|
|
192
|
+
: safety;
|
|
159
193
|
}
|
|
160
194
|
|
|
161
195
|
export function buildSubagentToolDescription(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, options?: ToolDescriptionOptions): string {
|
|
162
|
-
|
|
196
|
+
const on = options?.disabledFeatures ? featureText(options.disabledFeatures) : allEnabled;
|
|
197
|
+
if (config.toolDescriptionMode === undefined) return defaultDescription(on);
|
|
163
198
|
const mode = resolveToolDescriptionMode(config, options);
|
|
164
199
|
let description: string;
|
|
165
|
-
if (mode === "compact") description =
|
|
200
|
+
if (mode === "compact") description = defaultDescription(on);
|
|
166
201
|
else if (mode === "custom") {
|
|
167
202
|
const custom = loadCustomToolDescription(options);
|
|
168
|
-
if (custom) description = withMandatorySafetyGuidance(custom);
|
|
203
|
+
if (custom) description = withMandatorySafetyGuidance(custom, safetyGuidance(on));
|
|
169
204
|
else {
|
|
170
205
|
warn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode "custom"; using full description.`);
|
|
171
|
-
description =
|
|
206
|
+
description = fullDescription(on);
|
|
172
207
|
}
|
|
173
|
-
} else description =
|
|
208
|
+
} else description = fullDescription(on);
|
|
174
209
|
return description;
|
|
175
210
|
}
|