@xzzpig/pi-subagents 0.20.0 → 0.21.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 +154 -0
- package/README.md +1 -1
- package/agents/oracle.md +8 -19
- package/agents/researcher.md +0 -3
- package/agents/reviewer.md +17 -61
- package/agents/scout.md +1 -4
- package/agents/worker.md +8 -25
- package/docs/agents.md +72 -7
- package/docs/configuration.md +58 -7
- package/docs/extension-api.md +36 -11
- package/docs/fork-extensions.md +1 -0
- package/docs/missions.md +34 -17
- package/docs/models.md +1 -1
- package/docs/observability.md +10 -5
- package/docs/tool-reference.md +117 -84
- package/docs/watchdog.md +8 -6
- package/docs/workflows.md +16 -7
- package/index.ts +5 -0
- package/package.json +5 -3
- package/prompts/council.md +1 -1
- package/skills/pi-subagents/SKILL.md +1 -1
- package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
- package/skills/pi-subagents/references/execution-controls.md +16 -16
- package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
- package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +9 -1
- package/src/agents/agent-management.ts +4 -0
- package/src/agents/agent-memory.ts +3 -3
- package/src/agents/agent-scope.ts +4 -0
- package/src/agents/agent-serializer.ts +8 -1
- package/src/agents/agents.ts +191 -145
- package/src/api/preflight.ts +8 -4
- package/src/extension/config.ts +21 -2
- package/src/extension/context-injection.ts +6 -1
- package/src/extension/control-notices.ts +1 -9
- package/src/extension/declaration-pinning.ts +164 -0
- package/src/extension/doctor.ts +7 -10
- package/src/extension/fanout-child.ts +7 -8
- package/src/extension/index.ts +114 -132
- package/src/extension/reply-workflow-script.ts +20 -11
- package/src/extension/rpc.ts +11 -6
- package/src/extension/schemas.ts +34 -30
- package/src/extension/subagent-guide.ts +86 -6
- package/src/extension/subagent-options.ts +47 -0
- package/src/extension/tool-activation.ts +3 -2
- package/src/extension/tool-description.ts +51 -68
- package/src/inspectors/actions.ts +37 -11
- package/src/inspectors/plugins.ts +3 -2
- package/src/inspectors/tmux/actions.ts +204 -0
- package/src/inspectors/tmux/client.ts +85 -0
- package/src/inspectors/tmux/plugin.ts +21 -0
- package/src/integrations/herdr-status.ts +18 -49
- package/src/integrations/program-status.ts +215 -0
- package/src/intercom/native-supervisor-channel.ts +77 -4
- package/src/intercom/result-intercom.ts +3 -2
- package/src/intercom/supervisor-ui.ts +2 -174
- package/src/missions/store.ts +25 -5
- package/src/profiles/profiles.ts +24 -21
- package/src/runs/background/active-async-capacity.ts +58 -8
- package/src/runs/background/async-execution.ts +143 -38
- package/src/runs/background/async-job-tracker.ts +11 -4
- package/src/runs/background/async-resume.ts +5 -2
- package/src/runs/background/await-async-run.ts +14 -9
- package/src/runs/background/binary-bootstrap.ts +2 -1
- package/src/runs/background/calendar-schedule.ts +90 -0
- package/src/runs/background/chain-root-attachment.ts +9 -5
- package/src/runs/background/fleet-view.ts +5 -5
- package/src/runs/background/notify.ts +185 -12
- package/src/runs/background/result-files.ts +116 -5
- package/src/runs/background/result-watcher.ts +99 -66
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/run-child-session.ts +16 -2
- package/src/runs/background/run-id-resolver.ts +8 -5
- package/src/runs/background/run-status.ts +21 -16
- package/src/runs/background/runner-child-launch.ts +1 -0
- package/src/runs/background/runner-http-dispatcher.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +256 -61
- package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
- package/src/runs/background/subagent-runner.ts +32 -12
- package/src/runs/background/subagent-wait.ts +38 -19
- package/src/runs/background/terminal-run-index.ts +46 -1
- package/src/runs/background/wait-completions.ts +1 -0
- package/src/runs/background/wait-tool.ts +33 -23
- package/src/runs/background/workflow-terminal-proof.ts +39 -22
- package/src/runs/foreground/async-stop-action.ts +48 -22
- package/src/runs/foreground/execution.ts +94 -52
- package/src/runs/foreground/foreground-history.ts +1 -0
- package/src/runs/foreground/subagent-executor.ts +207 -77
- package/src/runs/shared/child-commands.ts +2 -1
- package/src/runs/shared/child-hooks.ts +4 -3
- package/src/runs/shared/child-launch.ts +3 -0
- package/src/runs/shared/child-session.ts +41 -24
- package/src/runs/shared/child-tool-plan.ts +13 -26
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/fork-command-result.ts +10 -0
- package/src/runs/shared/herdr-placed-run.ts +5 -4
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
- package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
- package/src/runs/shared/model-resolution.ts +30 -1
- package/src/runs/shared/nested-events.ts +5 -0
- package/src/runs/shared/parallel-handoff.ts +56 -8
- package/src/runs/shared/parallel-utils.ts +2 -0
- package/src/runs/shared/partial-output.ts +48 -0
- package/src/runs/shared/runner-launcher.ts +25 -0
- package/src/runs/shared/single-output.ts +53 -0
- package/src/runs/shared/structured-output.ts +14 -7
- package/src/runs/shared/subagent-control.ts +3 -3
- package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
- package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
- package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
- package/src/runs/shared/worktree-lock.ts +29 -0
- package/src/runs/shared/worktree.ts +12 -1
- package/src/shared/atomic-json.ts +4 -2
- package/src/shared/edit-distance.ts +33 -0
- package/src/shared/file-lease.ts +74 -0
- package/src/shared/formatters.ts +1 -5
- package/src/shared/model-info.ts +22 -0
- package/src/shared/package-version.ts +17 -0
- package/src/shared/parent-wake.ts +79 -0
- package/src/shared/pruned-fork.ts +7 -1
- package/src/shared/runtime-module-path.ts +19 -0
- package/src/shared/settings-file-lease.ts +36 -0
- package/src/shared/types.ts +36 -2
- package/src/shared/utils.ts +8 -6
- package/src/slash/slash-commands.ts +3 -3
- package/src/slash/subagents-admin.ts +2 -1
- package/src/tui/fleet-native-transcript.ts +2 -0
- package/src/tui/fleet-transcript.ts +12 -3
- package/src/tui/fleet.ts +11 -8
- package/src/tui/render.ts +27 -19
- package/src/tui/subagent-messages.ts +305 -0
- package/src/watchdog/diff-tool.ts +2 -2
- package/src/watchdog/register-main.ts +2 -22
- package/src/watchdog/render.ts +2 -24
- package/src/watchdog/runtime.ts +6 -4
- package/src/watchdog/settings.ts +18 -13
- package/src/watchdog/tool-actions.ts +2 -2
- package/src/workflows/scripted-workflow.ts +20 -6
- package/src/workflows/workflow-resources.ts +11 -0
package/src/extension/rpc.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
|
3
3
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { Compile } from "typebox/compile";
|
|
5
5
|
import { resolveAsyncRunLocation } from "../runs/background/async-resume.ts";
|
|
6
|
-
import {
|
|
6
|
+
import { deliverAsyncRunStop } from "../runs/foreground/async-stop-action.ts";
|
|
7
7
|
import { reconcileAsyncRun } from "../runs/background/stale-run-reconciler.ts";
|
|
8
8
|
import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
|
|
9
9
|
import { resolveCurrentSessionId } from "../shared/session-identity.ts";
|
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
} from "../shared/types.ts";
|
|
22
22
|
import { sanitizeDisplayText, truncateDisplayText } from "../shared/display-text.ts";
|
|
23
23
|
import { readStatus } from "../shared/utils.ts";
|
|
24
|
-
import {
|
|
24
|
+
import { SubagentFlatParams } from "./schemas.ts";
|
|
25
25
|
import { disabledFeatureUseError, type DisabledFeatureSurface } from "../shared/disabled-features.ts";
|
|
26
26
|
import { normalizePublicSubagentExecution } from "./public-execution.ts";
|
|
27
27
|
import { collectSubagentCost, SUBAGENT_COST_REPORT_VERSION } from "../slash/subagent-cost.ts";
|
|
@@ -336,7 +336,7 @@ class SubagentRpcError extends Error {
|
|
|
336
336
|
}
|
|
337
337
|
}
|
|
338
338
|
|
|
339
|
-
const subagentParamsValidator = Compile(
|
|
339
|
+
const subagentParamsValidator = Compile(SubagentFlatParams);
|
|
340
340
|
|
|
341
341
|
export function subagentRpcReplyEvent(requestId: string): string {
|
|
342
342
|
return `${SUBAGENT_RPC_REPLY_EVENT_PREFIX}${requestId}`;
|
|
@@ -685,8 +685,9 @@ function stopAsyncRun(
|
|
|
685
685
|
if (status.sessionId !== currentSessionId) {
|
|
686
686
|
throw new SubagentRpcError("not_found", `Async run '${runId}' was not found in the active session.`);
|
|
687
687
|
}
|
|
688
|
-
|
|
689
|
-
|
|
688
|
+
const pausedWholeRun = status.state === "paused" && childId === undefined;
|
|
689
|
+
if (status.state !== "running" && status.state !== "queued" && !pausedWholeRun) {
|
|
690
|
+
throw new SubagentRpcError("invalid_state", `Async run ${runId} is ${status.state}; stop only supports running or queued async runs, or a paused whole run.`);
|
|
690
691
|
}
|
|
691
692
|
if (childId !== undefined) {
|
|
692
693
|
const resolution = resolveAsyncStatusChild(status, childId);
|
|
@@ -698,19 +699,23 @@ function stopAsyncRun(
|
|
|
698
699
|
}
|
|
699
700
|
|
|
700
701
|
try {
|
|
701
|
-
|
|
702
|
+
const failure = deliverAsyncRunStop({
|
|
702
703
|
asyncDir: location.asyncDir,
|
|
704
|
+
status,
|
|
705
|
+
resultsDir,
|
|
703
706
|
pid: status.pid,
|
|
704
707
|
kill: options.kill,
|
|
705
708
|
now: options.now,
|
|
706
709
|
source: "rpc-stop",
|
|
707
710
|
...(child ? { targetIndex: child.index, childId: child.id } : {}),
|
|
708
711
|
});
|
|
712
|
+
if (failure) throw new Error(`Stop request persisted for paused async run ${runId}, but terminal proof is not ready (${failure}). Retry stop after runner shutdown is observed.`);
|
|
709
713
|
} catch (error) {
|
|
710
714
|
throw new SubagentRpcError("execution_failed", error instanceof Error ? error.message : String(error));
|
|
711
715
|
}
|
|
712
716
|
if (child) emitChildStopping(runId, location.asyncDir, child);
|
|
713
717
|
|
|
718
|
+
// This is an acceptance receipt, not terminal proof, even when a proven paused run was sealed.
|
|
714
719
|
return {
|
|
715
720
|
runId,
|
|
716
721
|
asyncDir: location.asyncDir,
|
package/src/extension/schemas.ts
CHANGED
|
@@ -64,7 +64,6 @@ const AcceptanceOverride = Type.Unsafe({
|
|
|
64
64
|
{
|
|
65
65
|
type: "string",
|
|
66
66
|
enum: ["reviewed"],
|
|
67
|
-
deprecated: true,
|
|
68
67
|
description: "Invalid as an explicit policy. Recognized only so preflight can explain that reviewed is an achieved status.",
|
|
69
68
|
},
|
|
70
69
|
{
|
|
@@ -160,7 +159,7 @@ const SubagentParamProperties = {
|
|
|
160
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." })),
|
|
161
160
|
// Management action (when present, tool operates in management mode)
|
|
162
161
|
action: Type.Optional(Type.String({ minLength: 1,
|
|
163
|
-
description: "Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with guide
|
|
162
|
+
description: "Management/control only; omit for execution. validate accepts workflow: true or a script path. Discover actions with {action:\"guide\",options:{topic:\"tool-reference\"}}."
|
|
164
163
|
})),
|
|
165
164
|
capabilities: Type.Optional(Type.Boolean({ description: "list: compact capability rows/details without system prompts." })),
|
|
166
165
|
name: Type.Optional(Type.String({ description: "schedule.create name." })),
|
|
@@ -174,8 +173,8 @@ const SubagentParamProperties = {
|
|
|
174
173
|
description: "Async directory for status/control."
|
|
175
174
|
})),
|
|
176
175
|
handoffPath: Type.Optional(Type.String({ description: "Existing manifest for worktree/lane actions." })),
|
|
177
|
-
repo: Type.Optional(Type.String({ description: "
|
|
178
|
-
planId: Type.Optional(Type.String({ description: "
|
|
176
|
+
repo: Type.Optional(Type.String({ description: "Cleanup repo; apply requires it." })),
|
|
177
|
+
planId: Type.Optional(Type.String({ description: "Reviewed cleanup plan for apply." })),
|
|
179
178
|
laneId: Type.Optional(Type.String({ minLength: 1, maxLength: 128, description: "Exact manifest run id for lane actions." })),
|
|
180
179
|
merge: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordMerge evidence; read guide tool-reference." })),
|
|
181
180
|
supersession: Type.Optional(Type.Unsafe({ type: "object", additionalProperties: true, description: "lane.recordSupersession evidence; read guide tool-reference." })),
|
|
@@ -189,21 +188,21 @@ const SubagentParamProperties = {
|
|
|
189
188
|
lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "Transcript tail lines; default 80." })),
|
|
190
189
|
topic: Type.Optional(Type.String()),
|
|
191
190
|
message: Type.Optional(Type.String({ description: "resume/steer guidance or project.open prompt." })),
|
|
192
|
-
mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto", "plan", "apply"], description: "steer delivery
|
|
191
|
+
mode: Type.Optional(Type.String({ enum: ["steer", "follow_up", "auto", "plan", "apply"], description: "steer delivery; worktree.cleanup plan/apply (reviewed planId)." })),
|
|
193
192
|
steeringRecovery: Type.Optional(Type.Boolean({ description: "steer: pause/revive after missed acknowledgment; default true in direct steer mode, forced false by extension RPC for exact ownership." })),
|
|
194
193
|
additional: Type.Optional(Type.Integer({ minimum: 1, description: "grant-spawn-budget: root interactive parent + native user confirmation only; total grants capped at original configured cap." })),
|
|
195
194
|
scope: Type.Optional(Type.String({ enum: ["session", "user", "project"], description: "watchdog.configure scope; default session, persistent only if explicit." })),
|
|
196
195
|
target: Type.Optional(Type.String({ enum: ["main", "children", "child"], description: "Watchdog target." })),
|
|
197
196
|
focus: Type.Optional(Type.Boolean({ description: "Focus inspector.open/project.open pane." })),
|
|
198
197
|
thinking: Type.Optional(Type.Unsafe({ anyOf: [{ type: "string" }, { type: "boolean" }], description: "watchdog.configure only: off/minimal/low/medium/high/xhigh/max, inherit, false=off; true invalid. Dispatch ignores this; use model suffix." })),
|
|
199
|
-
at: Type.Optional(Type.String({ description: "
|
|
200
|
-
every: Type.Optional(Type.String({ description: "
|
|
198
|
+
at: Type.Optional(Type.String({ description: "Delay/ISO or local HH:mm." })),
|
|
199
|
+
every: Type.Optional(Type.String({ description: "Duration or day/week." })),
|
|
201
200
|
sessionOnly: Type.Optional(Type.Boolean()),
|
|
202
201
|
quiet: Type.Optional(Type.Boolean()),
|
|
203
|
-
on: Type.Optional(Type.
|
|
204
|
-
timezone: Type.Optional(Type.String()),
|
|
202
|
+
on: Type.Optional(Type.Array(Type.String({ enum: ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] }), { minItems: 1, description: "Weekly." })),
|
|
203
|
+
timezone: Type.Optional(Type.String({ description: "IANA/UTC." })),
|
|
205
204
|
overlap: Type.Optional(Type.String({ enum: ["skip"] })),
|
|
206
|
-
catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed
|
|
205
|
+
catchUp: Type.Optional(Type.String({ enum: ["none", "latest"], description: "Missed; default latest." })),
|
|
207
206
|
missionId: Type.Optional(Type.String({ description: "Existing mission to attach to a workflow or schedule.create; read guide missions for lifecycle and retention." })),
|
|
208
207
|
mission: Type.Optional(Type.Unsafe({ ...MissionLaunchOverride, description: "false disables; true invalid. Object: exactly one non-empty title or summary; objective/labels optional; goal only true, requires budget.tokens." })),
|
|
209
208
|
missionUpdate: Type.Optional(Type.Unsafe({ ...MissionUpdateOverride, description: "Mission patch; read guide missions." })),
|
|
@@ -263,6 +262,7 @@ const SubagentParamProperties = {
|
|
|
263
262
|
description: "Child output path or false; relative workflow paths use managed artifact routing. Bind durable output here, not task prose; return outputReference/outputPathMapping/artifactPaths.",
|
|
264
263
|
})),
|
|
265
264
|
outputMode: Type.Optional(OutputModeOverride),
|
|
265
|
+
maxOutput: Type.Optional(Type.Object({ bytes: Type.Optional(Type.Integer({ minimum: 1 })), lines: Type.Optional(Type.Integer({ minimum: 1 })) }, { additionalProperties: false })),
|
|
266
266
|
skill: Type.Optional(SkillOverride),
|
|
267
267
|
model: Type.Optional(Type.String({ description: "Child model provider/id; bare id only if unique. Suffix :off/minimal/low/medium/high/xhigh/max overrides agent thinking default." })),
|
|
268
268
|
fast: Type.Optional(Type.Boolean({ description: "Native OpenAI-Codex priority tier; default false, may cost more/quota." })),
|
|
@@ -278,15 +278,30 @@ const SubagentParamProperties = {
|
|
|
278
278
|
})),
|
|
279
279
|
};
|
|
280
280
|
|
|
281
|
-
|
|
281
|
+
/** Full flat parameter shape accepted by RPC, slash, scheduled and workflow callers. */
|
|
282
|
+
export const SubagentFlatParams = Type.Object(SubagentParamProperties);
|
|
282
283
|
|
|
283
|
-
|
|
284
|
+
// Management/control fields go inside one opaque `options` object, so they are not sent on every request.
|
|
285
|
+
const { runId: _runId, maxRuntimeMs: _maxRuntimeMs, isolation: _isolation, ...ModelProperties } = SubagentParamProperties;
|
|
286
|
+
const { agent, task, workflow, args, async, model, cwd, worktree, output, action, id, message, ...SubagentOptionProperties } = ModelProperties;
|
|
287
|
+
|
|
288
|
+
export const SUBAGENT_OPTION_KEYS: readonly string[] = Object.keys(SubagentOptionProperties);
|
|
289
|
+
|
|
290
|
+
/** Values the model passes in `options`, checked with the same property schemas as flat callers. */
|
|
291
|
+
export const SubagentOptionParams = Type.Object(SubagentOptionProperties, { additionalProperties: false });
|
|
292
|
+
|
|
293
|
+
const ModelTopLevelProperties = {
|
|
294
|
+
agent, task, workflow, args, async, model, cwd, worktree, output, action, id, message,
|
|
295
|
+
options: Type.Optional(Type.Unsafe<Record<string, unknown>>({ type: "object", additionalProperties: true, description: "Every field not listed here, such as acceptance, timeoutMs, context, view and index; guide tool-reference/parameter-reference." })),
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
export const SubagentParams = keepTopLevelParameterDescriptions(Type.Object(ModelTopLevelProperties));
|
|
284
299
|
|
|
285
300
|
// Replaces workflow scripts when disabledFeatures lists "workflow-scripts". Kept small because every
|
|
286
301
|
// field is sent on every request; the executor validates step shapes and placeholders strictly.
|
|
287
302
|
const StructuredTask = { type: "object", properties: { agent: { type: "string", minLength: 1 }, task: { type: "string" } }, required: ["agent", "task"], additionalProperties: false };
|
|
288
303
|
const StructuredWorkflowProperties = {
|
|
289
|
-
action: Type.Optional(Type.String({ minLength: 1, description: "Management/control only; omit for execution. Discover actions with guide
|
|
304
|
+
action: Type.Optional(Type.String({ minLength: 1, description: "Management/control only; omit for execution. Discover actions with {action:\"guide\",options:{topic:\"tool-reference\"}}." })),
|
|
290
305
|
task: Type.Optional(Type.String({ description: "One-child task with agent, or the original request ({task}) with chain/tasks." })),
|
|
291
306
|
tasks: Type.Optional(Type.Unsafe({ type: "array", minItems: 1, items: StructuredTask, description: "Parallel children; results in order." })),
|
|
292
307
|
// Flattened step: {agent, task?, as?} or {parallel}; no object-shape union for provider converters.
|
|
@@ -301,7 +316,7 @@ const StructuredWorkflowProperties = {
|
|
|
301
316
|
export function createSubagentParamsSchema(disabled?: DisabledFeatureSurface): typeof SubagentParams {
|
|
302
317
|
if (!disabled || disabled.params.size === 0) return SubagentParams;
|
|
303
318
|
const structured = disabled.features.has("workflow-scripts");
|
|
304
|
-
const enabledProperties = Object.fromEntries(Object.entries(
|
|
319
|
+
const enabledProperties = Object.fromEntries(Object.entries(ModelTopLevelProperties).flatMap(([name, schema]) => {
|
|
305
320
|
if (disabled.params.has(name)) return [];
|
|
306
321
|
if (structured && name === "action") return [[name, StructuredWorkflowProperties.action]];
|
|
307
322
|
if (structured && name === "task") return [[name, StructuredWorkflowProperties.task], ["tasks", StructuredWorkflowProperties.tasks], ["chain", StructuredWorkflowProperties.chain]];
|
|
@@ -312,22 +327,11 @@ export function createSubagentParamsSchema(disabled?: DisabledFeatureSurface): t
|
|
|
312
327
|
}
|
|
313
328
|
|
|
314
329
|
const SubagentWaitParamsSchema = Type.Object({
|
|
315
|
-
id: Type.Optional(Type.String({
|
|
316
|
-
|
|
317
|
-
})),
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
})),
|
|
321
|
-
all: Type.Optional(Type.Boolean({
|
|
322
|
-
description: "Wait for ALL active runs to finish. Ordinary async subagent runs already notify this session natively; use all only when a same-turn result from tracked background work is truly needed. Default false: return when the first tracked run or provider item finishes or needs attention. Ignored when id targets a single run.",
|
|
323
|
-
})),
|
|
324
|
-
timeoutMs: Type.Optional(Type.Integer({
|
|
325
|
-
minimum: 1,
|
|
326
|
-
description: "Give up waiting after this many milliseconds (the runs keep going regardless). Ordinary async subagent runs already notify this session natively; use a wait timeout only when same-turn results are truly needed for provider, detached, or other background work without native notification. Defaults to config waitTool.defaultTimeoutMs, then 1800000 (30 minutes). Window expiry is a non-error active-work result.",
|
|
327
|
-
})),
|
|
328
|
-
stopOnAttention: Type.Optional(Type.Boolean({
|
|
329
|
-
description: "For a blocking wait that is truly needed, stop when a run needs attention by default. Set false to keep waiting through idle or long-thinking attention; supervisor/contact requests still stop the wait.",
|
|
330
|
-
})),
|
|
330
|
+
id: Type.Optional(Type.String({ description: "Run id or prefix." })),
|
|
331
|
+
nonBlocking: Type.Optional(Type.Boolean({ description: "Subscribe to id's wake and return immediately; requires id, not with all." })),
|
|
332
|
+
all: Type.Optional(Type.Boolean({ description: "Wait for all work active at call time." })),
|
|
333
|
+
timeoutMs: Type.Optional(Type.Integer({ minimum: 1, description: "Max wait; default waitTool.defaultTimeoutMs, then 30 min." })),
|
|
334
|
+
stopOnAttention: Type.Optional(Type.Boolean({ description: "false: keep waiting through idle or long-thinking attention." })),
|
|
331
335
|
});
|
|
332
336
|
|
|
333
337
|
export const SubagentWaitParams = keepTopLevelParameterDescriptions(SubagentWaitParamsSchema);
|
|
@@ -18,6 +18,10 @@ export const SUBAGENT_GUIDE_TOPICS = [
|
|
|
18
18
|
|
|
19
19
|
export type SubagentGuideTopic = (typeof SUBAGENT_GUIDE_TOPICS)[number];
|
|
20
20
|
|
|
21
|
+
// Guide output stays in the parent's history and is re-sent on every later turn, so docs-backed
|
|
22
|
+
// topics return a table of contents or one section, never a whole document.
|
|
23
|
+
const SUBAGENT_GUIDE_SECTION_MAX_CHARS = 8000;
|
|
24
|
+
|
|
21
25
|
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
22
26
|
|
|
23
27
|
// /council must work under `pi --no-skills`, which drops the package skills from context,
|
|
@@ -28,20 +32,96 @@ const COUNCIL_FILES = [
|
|
|
28
32
|
"skills/pi-subagents/references/execution-controls.md",
|
|
29
33
|
];
|
|
30
34
|
|
|
35
|
+
interface GuideSection {
|
|
36
|
+
address: string;
|
|
37
|
+
title: string;
|
|
38
|
+
level: number;
|
|
39
|
+
start: number;
|
|
40
|
+
end: number;
|
|
41
|
+
children: GuideSection[];
|
|
42
|
+
}
|
|
43
|
+
|
|
31
44
|
function isGuideTopic(value: string): value is SubagentGuideTopic {
|
|
32
45
|
return (SUBAGENT_GUIDE_TOPICS as readonly string[]).includes(value);
|
|
33
46
|
}
|
|
34
47
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
48
|
+
function headingSlug(title: string): string {
|
|
49
|
+
return title.toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").trim().replace(/\s/g, "-");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function parseSections(topic: string, lines: string[]): GuideSection[] {
|
|
53
|
+
const sections: GuideSection[] = [];
|
|
54
|
+
let fence: string | undefined;
|
|
55
|
+
lines.forEach((line, index) => {
|
|
56
|
+
const marker = /^\s*(```+|~~~+)/.exec(line)?.[1];
|
|
57
|
+
if (marker) {
|
|
58
|
+
if (!fence) fence = marker;
|
|
59
|
+
else if (marker.startsWith(fence)) fence = undefined;
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const heading = fence ? undefined : /^(#{2,6})\s+(.+?)\s*#*\s*$/.exec(line);
|
|
63
|
+
if (heading) sections.push({ address: "", title: heading[2]!, level: heading[1]!.length, start: index, end: lines.length, children: [] });
|
|
64
|
+
});
|
|
65
|
+
const used = new Set<string>();
|
|
66
|
+
const parents: GuideSection[] = [];
|
|
67
|
+
for (const [index, section] of sections.entries()) {
|
|
68
|
+
const next = sections.slice(index + 1).find((other) => other.level <= section.level);
|
|
69
|
+
if (next) section.end = next.start;
|
|
70
|
+
while (parents.length && parents.at(-1)!.level >= section.level) parents.pop();
|
|
71
|
+
const parent = parents.at(-1);
|
|
72
|
+
parent?.children.push(section);
|
|
73
|
+
let slug = headingSlug(section.title);
|
|
74
|
+
if (used.has(slug) && parent) slug = `${parent.address.slice(topic.length + 1)}-${slug}`;
|
|
75
|
+
for (let suffix = 2, base = slug; used.has(slug); suffix++) slug = `${base}-${suffix}`;
|
|
76
|
+
used.add(slug);
|
|
77
|
+
section.address = `${topic}/${slug}`;
|
|
78
|
+
parents.push(section);
|
|
38
79
|
}
|
|
39
|
-
|
|
80
|
+
return sections;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function tableOfContents(topic: string, sections: GuideSection[]): string {
|
|
84
|
+
const rows = sections.map((section) => `${" ".repeat(section.level - 2)}${section.address} — ${section.title}`);
|
|
85
|
+
return `Sections of guide topic '${topic}'. Read one with {action:"guide",options:{topic:"<section address>"}}:\n${rows.join("\n")}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function sectionText(lines: string[], section: GuideSection): string {
|
|
89
|
+
const text = lines.slice(section.start, section.end).join("\n").trim();
|
|
90
|
+
if (text.length <= SUBAGENT_GUIDE_SECTION_MAX_CHARS || !section.children.length) return text;
|
|
91
|
+
const intro = lines.slice(section.start, section.children[0]!.start).join("\n").trim();
|
|
92
|
+
return `${intro}\n\nSubsections (read one with {action:"guide",options:{topic:"<address>"}}):\n${section.children.map((child) => `${child.address} — ${child.title}`).join("\n")}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function readGuideFiles(topic: string, files: string[], root: string): string[] {
|
|
40
96
|
try {
|
|
41
|
-
|
|
42
|
-
return files.
|
|
97
|
+
// Windows checkouts can convert docs to CRLF; sections and their boundaries are defined on LF lines.
|
|
98
|
+
return files.map((file) => fs.readFileSync(path.join(root, file), "utf-8").replace(/\r\n/g, "\n"));
|
|
43
99
|
} catch (error) {
|
|
44
100
|
const message = error instanceof Error ? error.message : String(error);
|
|
45
101
|
throw new Error(`Failed to read packaged subagents guide '${topic}': ${message}`, { cause: error instanceof Error ? error : undefined });
|
|
46
102
|
}
|
|
47
103
|
}
|
|
104
|
+
|
|
105
|
+
/** Reads a guide topic. Docs-backed topics return their intro and table of contents; `topic/section` returns one section. */
|
|
106
|
+
export function readSubagentGuide(topic = "overview", root = packageRoot): string {
|
|
107
|
+
const separator = topic.indexOf("/");
|
|
108
|
+
const name = separator === -1 ? topic : topic.slice(0, separator);
|
|
109
|
+
const sectioned = isGuideTopic(name) && name !== "overview" && name !== "council";
|
|
110
|
+
if (!isGuideTopic(name) || (separator !== -1 && !sectioned)) {
|
|
111
|
+
return `Unknown subagents guide topic '${topic}'. Valid topics: ${SUBAGENT_GUIDE_TOPICS.join(", ")}. No files were changed.`;
|
|
112
|
+
}
|
|
113
|
+
if (!sectioned) {
|
|
114
|
+
const files = name === "overview" ? ["README.md"] : COUNCIL_FILES;
|
|
115
|
+
const contents = readGuideFiles(name, files, root);
|
|
116
|
+
return files.length === 1 ? contents[0]! : contents.map((content, index) => `<!-- ${files[index]} -->\n\n${content}`).join("\n\n");
|
|
117
|
+
}
|
|
118
|
+
const lines = readGuideFiles(name, [path.join("docs", `${name}.md`)], root)[0]!.split("\n");
|
|
119
|
+
const sections = parseSections(name, lines);
|
|
120
|
+
if (separator === -1) {
|
|
121
|
+
const intro = lines.slice(0, sections[0]?.start ?? lines.length).join("\n").trim();
|
|
122
|
+
return `${intro}\n\n${tableOfContents(name, sections)}`;
|
|
123
|
+
}
|
|
124
|
+
const section = sections.find((candidate) => candidate.address === topic);
|
|
125
|
+
if (!section) return `Unknown section '${topic}'. No files were changed.\n\n${tableOfContents(name, sections)}`;
|
|
126
|
+
return sectionText(lines, section);
|
|
127
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { Compile } from "typebox/compile";
|
|
3
|
+
import type { SubagentParamsLike } from "../runs/foreground/subagent-executor.ts";
|
|
4
|
+
import type { DisabledFeatureSurface } from "../shared/disabled-features.ts";
|
|
5
|
+
import { closestMatch } from "../shared/edit-distance.ts";
|
|
6
|
+
import { removedModelWorkflowFieldError } from "./public-execution.ts";
|
|
7
|
+
import { SUBAGENT_OPTION_KEYS, SubagentOptionParams, createSubagentParamsSchema } from "./schemas.ts";
|
|
8
|
+
|
|
9
|
+
const optionKeys = new Set(SUBAGENT_OPTION_KEYS);
|
|
10
|
+
const ALIAS_HINTS: Record<string, string> = { runId: "id (top-level)", maxRuntimeMs: "options.timeoutMs", isolation: "worktree (top-level)" };
|
|
11
|
+
const optionsValidator = Compile(SubagentOptionParams);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Lowers a model tool call's `options` into the flat params the executor reads.
|
|
15
|
+
* Management fields given at the top level keep working, as in the flat shape older sessions declared.
|
|
16
|
+
*/
|
|
17
|
+
export function flattenSubagentToolOptions(params: Record<string, unknown>, disabled?: DisabledFeatureSurface): SubagentParamsLike {
|
|
18
|
+
const removedTopLevel = removedModelWorkflowFieldError(params);
|
|
19
|
+
if (removedTopLevel) throw new Error(removedTopLevel);
|
|
20
|
+
const { options, ...topLevel } = params;
|
|
21
|
+
if (options === undefined) return topLevel;
|
|
22
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("subagent: options must be an object.");
|
|
23
|
+
const removedField = removedModelWorkflowFieldError(options);
|
|
24
|
+
if (removedField) throw new Error(removedField);
|
|
25
|
+
const entries = Object.entries(options);
|
|
26
|
+
const enabledKeys = SUBAGENT_OPTION_KEYS.filter((key) => !disabled?.params.has(key));
|
|
27
|
+
const unknown = entries.map(([key]) => key).filter((key) => !optionKeys.has(key));
|
|
28
|
+
if (unknown.length > 0) {
|
|
29
|
+
const fields = Object.keys(createSubagentParamsSchema(disabled).properties);
|
|
30
|
+
const hints = unknown.map((key) => {
|
|
31
|
+
if (Object.hasOwn(ALIAS_HINTS, key)) return `unknown options key '${key}'; use ${ALIAS_HINTS[key]}.`;
|
|
32
|
+
if (fields.includes(key)) return `'${key}' is a top-level field, not an option.`;
|
|
33
|
+
const suggestion = closestMatch(key, enabledKeys);
|
|
34
|
+
return `unknown options key '${key}'.${suggestion ? ` Did you mean '${suggestion}'?` : ""}`;
|
|
35
|
+
});
|
|
36
|
+
throw new Error(`subagent: ${hints.join(" ")} Valid options: ${enabledKeys.sort().join(", ")}.`);
|
|
37
|
+
}
|
|
38
|
+
const disabledKey = entries.find(([key]) => disabled?.params.has(key))?.[0];
|
|
39
|
+
if (disabledKey) throw new Error(`subagent option 'options.${disabledKey}' is disabled by config ${disabled!.params.get(disabledKey)}.`);
|
|
40
|
+
if (!optionsValidator.Check(options)) {
|
|
41
|
+
const errors = [...optionsValidator.Errors(options)].slice(0, 4).map((error) => `options${error.instancePath.replaceAll("/", ".")} ${error.message}`);
|
|
42
|
+
throw new Error(`subagent: ${errors.join("; ")}.`);
|
|
43
|
+
}
|
|
44
|
+
const conflicts = entries.filter(([key, value]) => topLevel[key] !== undefined && !isDeepStrictEqual(topLevel[key], value)).map(([key]) => `'${key}'`);
|
|
45
|
+
if (conflicts.length > 0) throw new Error(`subagent: ${conflicts.join(", ")} given both at the top level and in options with different values; give each once.`);
|
|
46
|
+
return { ...topLevel, ...options } as SubagentParamsLike;
|
|
47
|
+
}
|
|
@@ -2,6 +2,7 @@ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-w
|
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
|
|
4
4
|
import type { ToolActivationMode } from "../shared/types.ts";
|
|
5
|
+
import { registerPinnedTool } from "./declaration-pinning.ts";
|
|
5
6
|
|
|
6
7
|
interface ActivationDetails {
|
|
7
8
|
enabled?: string[];
|
|
@@ -124,12 +125,12 @@ export function registerSubagentToolActivation(
|
|
|
124
125
|
};
|
|
125
126
|
const advertised = await options.advertisedPrompt();
|
|
126
127
|
return {
|
|
127
|
-
content: [{ type: "text", text: `Enabled: subagent. If your tool list includes subagent (possibly prefixed), call
|
|
128
|
+
content: [{ type: "text", text: `Enabled: subagent. If your tool list includes subagent (possibly prefixed), call it now. 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
129
|
details: { enabled: [SUBAGENT_NAME] },
|
|
129
130
|
};
|
|
130
131
|
},
|
|
131
132
|
};
|
|
132
|
-
pi
|
|
133
|
+
registerPinnedTool(pi, loader);
|
|
133
134
|
|
|
134
135
|
// Decided at session start and tree navigation only; switching models keeps the session's tools.
|
|
135
136
|
let loaderSelected = true;
|
|
@@ -6,8 +6,6 @@ import { resolveDisabledFeatureSurface, type DisabledFeatureSurface, type Subage
|
|
|
6
6
|
|
|
7
7
|
const CUSTOM_TOOL_DESCRIPTION_FILE = "subagent-tool-description.md";
|
|
8
8
|
const CUSTOM_TOOL_DESCRIPTION_MAX_BYTES = 50 * 1024;
|
|
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.';
|
|
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.";
|
|
11
9
|
|
|
12
10
|
type FeatureText = (feature: SubagentSurfaceFeature, text: string, disabledText?: string) => string;
|
|
13
11
|
|
|
@@ -15,60 +13,58 @@ function featureText(disabled: DisabledFeatureSurface): FeatureText {
|
|
|
15
13
|
return (feature, text, disabledText = "") => disabled.features.has(feature) ? disabledText : text;
|
|
16
14
|
}
|
|
17
15
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
Model override: first call {action:"models"}; copy exact provider/id, not agent names. Thinking uses model suffix${on("watchdog", ", not watchdog-only thinking")}.
|
|
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.`;
|
|
36
|
-
|
|
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)}`;
|
|
16
|
+
// Part of every built-in description and appended to custom ones, so it is sent on every request.
|
|
17
|
+
export const SUBAGENT_SAFETY_GUIDANCE = `SAFETY-CRITICAL SUBAGENT GUIDANCE:
|
|
18
|
+
- Delegate only when the operator asked, directly or through applicable user/project instructions; size, complexity or risk alone is not authorization.
|
|
19
|
+
- Native async completion wakes this session: return control; do not sleep, poll or call bg_wait for it.
|
|
20
|
+
- One writer per cwd/worktree; isolate concurrent writers.
|
|
21
|
+
- After a launch or runtime failure, stop and report it; never silently switch to interactive_shell, pi -ne or another CLI.`;
|
|
22
|
+
|
|
23
|
+
const scriptCalls = "One child: {agent,task}. Independent parallel children: {workflow:\"parallel\",args:{tasks:[{agent,task},...]}}. Dependent multi-step work: exactly one top-level subagent workflow call with async:true; write one ```js workflow block in this reply, then call subagent({workflow:true}); children launch only inside it.";
|
|
24
|
+
const structuredCalls = "One child: {agent,task}. Parallel: tasks:[{agent,task},...]. In order: chain:[{agent,task?,as?} or {parallel:[{agent,task},...]}]; step tasks can use {task}, {previous} and {outputs.name}. Use exactly one top-level subagent chain or tasks call with async:true.";
|
|
25
|
+
|
|
26
|
+
const essentials = (on: FeatureText) => `${on("workflow-scripts", scriptCalls, structuredCalls)}
|
|
27
|
+
Management: {action,id?,options:{...}}; fields not in this schema go in options.
|
|
28
|
+
Launch agents by name and pass models as exact provider/id; an unknown agent or model returns the valid choices.
|
|
29
|
+
Details: guide workflows/recommended-orchestration-pattern (async, review, failure recovery), ${on("workflow-scripts", "guide workflows/scripted-workflows, ")}guide tool-reference/retained-children, guide tool-reference/external-cli-agent-profiles.
|
|
30
|
+
|
|
31
|
+
${SUBAGENT_SAFETY_GUIDANCE}`;
|
|
45
32
|
|
|
46
33
|
const managementDiscovery = (on: FeatureText) => [
|
|
47
34
|
["list/get/models/guide"],
|
|
48
35
|
[on("agent-management", "create/update/delete/eject/disable/enable/reset/refine")],
|
|
49
36
|
[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
|
|
37
|
+
[on("lane-management", "worktree.discard and reviewed worktree.cleanup")],
|
|
51
38
|
[`doctor${on("spawn-budget-grants", " and grant-spawn-budget")}`],
|
|
52
39
|
].map((group) => group.filter(Boolean).join(", ")).filter(Boolean).join("; ");
|
|
53
40
|
|
|
54
|
-
const
|
|
41
|
+
const scriptDetails = `• 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.
|
|
42
|
+
• workflow:'./path.js' (any value with '/') loads a file from request cwd; other strings name a resource, such as {workflow:'review',args:{task:'...'}}. agent/task exclude workflow; task excludes action; validate accepts workflow:true or a path without launching. Raw-script sandboxes add deeply frozen args that persist as evidence, so never include secrets; raw scripts cannot use runs.host. Granted commands/relative outputs use workflow cwd, never per-step cwd.
|
|
43
|
+
• 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.
|
|
44
|
+
`;
|
|
55
45
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
46
|
+
// Opt-in through toolDescriptionMode "full": the rarer rules the default leaves to guide sections.
|
|
47
|
+
const fullDetails = (on: FeatureText) => `DETAILS:
|
|
48
|
+
${on("workflow-scripts", scriptDetails)}• ${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 requires clean source, isolates each child and returns handoff artifacts; options.baseRef defaults to HEAD at allocation or a supported named ref, never full 40/64-character commit IDs or revision expressions.${on("usage-budgets", " usageBudget is shared across the workflow; already-running children are not stopped.")}
|
|
49
|
+
• Async follows asyncByDefault (normally true); async:false only to block the parent, not for final reviews/gates. Consume results at dependency barriers. bg_wait is for provider/detached work without native notification that needs a same-turn result.
|
|
50
|
+
• 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.
|
|
51
|
+
• Ordinary child subagents are not orchestrators; only configured fanout within depth/session limits. Use fresh-context read-only reviewers when independent review was requested. Oracle/advisor unknowns use supervisor dialogue; one-shot only when requested.
|
|
52
|
+
• 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 and may reject it. 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 the latest returned runId. Each distinct resume pass needs a new stable key; same-key reuse requires identical launch parameters.")}
|
|
53
|
+
• External CLI agents need an installed, authenticated CLI; preflight at launch decides, and passive PATH/PATHEXT/X_OK is not authentication/version/launch proof. They support native options only when their runner declares them: model, structured output, acceptance/agentContract, ${on("tool-budgets", "tool budget, ")}fast, fork context or skills/tools.
|
|
54
|
+
• Model override: copy exact provider/id, not agent names. Thinking uses model suffix${on("watchdog", ", not watchdog-only thinking")}.
|
|
55
|
+
• Missions auto-attach${on("missions", " unless options.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.
|
|
56
|
+
• Inspect asyncId/asyncDir (status.json, events.jsonl, logs) with status/debug.run; control with interrupt/stop/resume/steer. For local Pi children explicitly granted subagent_command, command.status/yield/cancel targets one exact toolCallId without interrupting the child.
|
|
57
|
+
• After a failure, report the exact failure, run/status and repo/cwd/worktree/branch/ref, and verify a clean worktree or capture the partial diff before a same-protocol retry. Governed-workflow fallback to foreground/CLI needs explicit owner approval, not Pi core's generic pi -ne hint.
|
|
59
58
|
• 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
59
|
|
|
61
|
-
const
|
|
60
|
+
const fullDescription = (on: FeatureText) => `${essentials(on)}\n\n${fullDetails(on)}`;
|
|
62
61
|
|
|
63
|
-
|
|
62
|
+
const allEnabled = featureText(resolveDisabledFeatureSurface({}));
|
|
64
63
|
|
|
65
|
-
export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION =
|
|
64
|
+
export const DEFAULT_SUBAGENT_TOOL_DESCRIPTION = essentials(allEnabled);
|
|
66
65
|
|
|
67
|
-
export const SUBAGENT_TOOL_PROMPT_SNIPPET = "
|
|
68
|
-
const STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET = "
|
|
69
|
-
export const SUBAGENT_TOOL_PROMPT_GUIDELINES = [
|
|
70
|
-
"Do not invoke subagents unless the operator requested delegation directly or through applicable instructions.",
|
|
71
|
-
];
|
|
66
|
+
export const SUBAGENT_TOOL_PROMPT_SNIPPET = "Delegate focused work to child agents; compose multi-child work in one workflow call.";
|
|
67
|
+
const STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET = "Delegate focused work to child agents; compose multi-child work in one chain or tasks call.";
|
|
72
68
|
|
|
73
69
|
export const COMPACT_SUBAGENT_TOOL_DESCRIPTION = DEFAULT_SUBAGENT_TOOL_DESCRIPTION;
|
|
74
70
|
|
|
@@ -90,17 +86,10 @@ export interface ToolDescriptionOptions {
|
|
|
90
86
|
disabledFeatures?: DisabledFeatureSurface;
|
|
91
87
|
}
|
|
92
88
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
promptGuidelines?: string[];
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export function buildSubagentToolPromptMetadata(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, disabledFeatures?: DisabledFeatureSurface): SubagentToolPromptMetadata {
|
|
89
|
+
// No promptGuidelines: the description carries the authorization rule, so it is stated once.
|
|
90
|
+
export function buildSubagentToolPromptMetadata(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, disabledFeatures?: DisabledFeatureSurface): { promptSnippet?: string } {
|
|
99
91
|
if (config.toolDescriptionMode !== undefined) return {};
|
|
100
|
-
return {
|
|
101
|
-
promptSnippet: disabledFeatures?.features.has("workflow-scripts") ? STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET : SUBAGENT_TOOL_PROMPT_SNIPPET,
|
|
102
|
-
promptGuidelines: SUBAGENT_TOOL_PROMPT_GUIDELINES,
|
|
103
|
-
};
|
|
92
|
+
return { promptSnippet: disabledFeatures?.features.has("workflow-scripts") ? STRUCTURED_SUBAGENT_TOOL_PROMPT_SNIPPET : SUBAGENT_TOOL_PROMPT_SNIPPET };
|
|
104
93
|
}
|
|
105
94
|
|
|
106
95
|
export function resolveToolDescriptionMode(config: Pick<ExtensionConfig, "toolDescriptionMode">, options?: ToolDescriptionOptions): ToolDescriptionMode {
|
|
@@ -179,32 +168,26 @@ function loadCustomToolDescription(options?: ToolDescriptionOptions): string | u
|
|
|
179
168
|
return undefined;
|
|
180
169
|
}
|
|
181
170
|
|
|
182
|
-
function withMandatorySafetyGuidance(description: string
|
|
171
|
+
function withMandatorySafetyGuidance(description: string): string {
|
|
183
172
|
const customDescription = description
|
|
184
173
|
.split(SUBAGENT_SAFETY_GUIDANCE)
|
|
185
|
-
.flatMap((part) => part.split(safety))
|
|
186
|
-
.flatMap((part) => part.split(SUBAGENT_FAILURE_RECOVERY_GUIDANCE))
|
|
187
174
|
.map((part) => part.trim())
|
|
188
175
|
.filter(Boolean)
|
|
189
176
|
.join("\n\n");
|
|
190
177
|
return customDescription
|
|
191
|
-
? `${customDescription}\n\n${
|
|
192
|
-
:
|
|
178
|
+
? `${customDescription}\n\n${SUBAGENT_SAFETY_GUIDANCE}`
|
|
179
|
+
: SUBAGENT_SAFETY_GUIDANCE;
|
|
193
180
|
}
|
|
194
181
|
|
|
195
182
|
export function buildSubagentToolDescription(config: Pick<ExtensionConfig, "toolDescriptionMode"> = {}, options?: ToolDescriptionOptions): string {
|
|
196
183
|
const on = options?.disabledFeatures ? featureText(options.disabledFeatures) : allEnabled;
|
|
197
|
-
if (config.toolDescriptionMode === undefined) return
|
|
184
|
+
if (config.toolDescriptionMode === undefined) return essentials(on);
|
|
198
185
|
const mode = resolveToolDescriptionMode(config, options);
|
|
199
|
-
|
|
200
|
-
if (mode === "
|
|
201
|
-
else if (mode === "custom") {
|
|
186
|
+
if (mode === "compact") return essentials(on);
|
|
187
|
+
if (mode === "custom") {
|
|
202
188
|
const custom = loadCustomToolDescription(options);
|
|
203
|
-
if (custom)
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
} else description = fullDescription(on);
|
|
209
|
-
return description;
|
|
189
|
+
if (custom) return withMandatorySafetyGuidance(custom);
|
|
190
|
+
warn(options, `${CUSTOM_TOOL_DESCRIPTION_FILE} was not found or valid for toolDescriptionMode "custom"; using full description.`);
|
|
191
|
+
}
|
|
192
|
+
return fullDescription(on);
|
|
210
193
|
}
|