@xzzpig/pi-subagents 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +129 -0
- package/README.md +1 -1
- package/docs/agents.md +32 -16
- package/docs/configuration.md +76 -9
- package/docs/extension-api.md +6 -5
- package/docs/missions.md +28 -14
- package/docs/models.md +8 -4
- package/docs/observability.md +10 -5
- package/docs/standalone-background.md +1 -1
- package/docs/tool-reference.md +90 -88
- package/docs/workflows.md +171 -173
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +6 -6
- package/prompts/review-loop.md +1 -1
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +12 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
- package/skills/pi-subagents/references/execution-controls.md +68 -67
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-management.ts +2 -2
- package/src/agents/agents.ts +66 -3
- package/src/api/preflight.ts +109 -63
- package/src/extension/config.ts +15 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +1 -0
- package/src/extension/fanout-child.ts +12 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +90 -174
- package/src/extension/public-execution.ts +72 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +29 -10
- package/src/extension/schemas.ts +40 -135
- package/src/extension/tool-activation.ts +57 -108
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/native-supervisor-channel.ts +4 -1
- package/src/missions/goal-driver.ts +44 -31
- package/src/missions/store.ts +10 -1
- package/src/profiles/profiles.ts +5 -2
- package/src/runs/background/async-execution.ts +146 -59
- package/src/runs/background/async-job-tracker.ts +66 -24
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/await-async-run.ts +78 -0
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +61 -2
- package/src/runs/background/notify.ts +5 -0
- package/src/runs/background/run-child-session.ts +17 -7
- package/src/runs/background/run-status.ts +6 -0
- package/src/runs/background/runner-aliases.ts +37 -6
- package/src/runs/background/runner-child-launch.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +33 -18
- package/src/runs/background/stale-run-reconciler.ts +13 -2
- package/src/runs/background/subagent-runner.ts +58 -5
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/command-action.ts +41 -0
- package/src/runs/foreground/execution.ts +145 -131
- package/src/runs/foreground/subagent-executor.ts +546 -296
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/child-commands.ts +228 -0
- package/src/runs/shared/child-launch.ts +15 -2
- package/src/runs/shared/child-session.ts +184 -24
- package/src/runs/shared/child-tool-plan.ts +16 -4
- package/src/runs/shared/claude-code-adapter.ts +157 -2
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/external-cli-preflight.ts +54 -6
- package/src/runs/shared/external-cli-runner.ts +5 -1
- package/src/runs/shared/mcp-config-sources.ts +2 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -11
- package/src/runs/shared/model-resolution.ts +38 -10
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +55 -55
- package/src/runs/shared/parallel-utils.ts +4 -0
- package/src/runs/shared/pi-spawn.ts +7 -95
- package/src/runs/shared/run-history.ts +87 -0
- package/src/runs/shared/subagent-control.ts +32 -17
- package/src/runs/shared/subagent-prompt-runtime.ts +14 -6
- package/src/runs/shared/worktree.ts +1 -1
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/model-info.ts +9 -0
- package/src/shared/required-child-extensions.ts +39 -5
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +27 -1
- package/src/slash/prompt-template-bridge.ts +2 -2
- package/src/slash/slash-commands.ts +10 -5
- package/src/slash/subagent-cost.ts +9 -5
- package/src/slash/subagents-admin.ts +24 -24
- package/src/tui/fleet-status.ts +14 -6
- package/src/tui/fleet.ts +14 -2
- package/src/tui/render.ts +117 -56
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +23 -9
- package/src/watchdog/register-child.ts +3 -3
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +2 -2
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +117 -37
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-receipt.ts +10 -4
- package/src/workflows/workflow-resources.ts +44 -16
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
|
@@ -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 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
|
|
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. For local Pi children explicitly granted subagent_command, command.status/yield/cancel targets one exact toolCallId without interrupting the child. 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
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import packageJson from "../../package.json" with { type: "json" };
|
|
5
|
+
import { writeAtomicJson } from "../shared/atomic-json.ts";
|
|
6
|
+
import { getAgentDir } from "../shared/utils.ts";
|
|
7
|
+
|
|
8
|
+
// major.minor.patch as one comparable number; undefined for anything else.
|
|
9
|
+
const versionNumber = (version: unknown) => typeof version === "string" && /^\d+\.\d+\.\d+$/.test(version)
|
|
10
|
+
? version.split(".").reduce((total, part) => total * 1e6 + Number(part), 0)
|
|
11
|
+
: undefined;
|
|
12
|
+
|
|
13
|
+
export async function showUpgradeNotice(
|
|
14
|
+
ctx: { hasUI: boolean; ui: { notify(message: string, type: "info"): void } },
|
|
15
|
+
stateDir = path.join(getAgentDir(), "pi-subagents"),
|
|
16
|
+
changelogPath = fileURLToPath(new URL("../../CHANGELOG.md", import.meta.url)),
|
|
17
|
+
version = packageJson.version,
|
|
18
|
+
): Promise<void> {
|
|
19
|
+
if (!ctx.hasUI) return;
|
|
20
|
+
const statePath = path.join(stateDir, "last-seen-version.json");
|
|
21
|
+
const lastSeen = await fs.promises.readFile(statePath, "utf-8").then((raw) => JSON.parse(raw).version).catch(() => undefined);
|
|
22
|
+
const previous = versionNumber(lastSeen);
|
|
23
|
+
const current = versionNumber(version);
|
|
24
|
+
if (current === undefined || previous === current) return;
|
|
25
|
+
writeAtomicJson(statePath, { version });
|
|
26
|
+
if (previous === undefined || previous > current) return;
|
|
27
|
+
|
|
28
|
+
const bullets = (await fs.promises.readFile(changelogPath, "utf-8")).split(/^## /m).flatMap((section) => {
|
|
29
|
+
const released = versionNumber(/^\[([^\]]+)\]/.exec(section)?.[1]);
|
|
30
|
+
if (released === undefined || released <= previous || released > current) return [];
|
|
31
|
+
const highlights = section.split(/^### /m).find((part) => part.startsWith("Highlights")) ?? "";
|
|
32
|
+
return (highlights.match(/^- .*/gm) ?? []).map((bullet) => bullet.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim());
|
|
33
|
+
});
|
|
34
|
+
ctx.ui.notify([
|
|
35
|
+
`pi-subagents updated from ${lastSeen} to ${version}`,
|
|
36
|
+
...bullets.slice(0, 5),
|
|
37
|
+
...(bullets.length > 5 ? [`...and ${bullets.length - 5} more`] : []),
|
|
38
|
+
"Changelog: https://github.com/nicobailon/pi-subagents/blob/main/CHANGELOG.md",
|
|
39
|
+
].join("\n"), "info");
|
|
40
|
+
}
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
} from "../shared/types.ts";
|
|
6
6
|
import { previewDisplayText, sanitizeDisplayText } from "../shared/display-text.ts";
|
|
7
7
|
|
|
8
|
+
export const HERDR_FOREGROUND_CONTROL_CHANGED_EVENT = "pi-subagents:herdr:foreground-control-changed";
|
|
8
9
|
const DEFAULT_SOURCE = "pi-subagents:herdr";
|
|
9
10
|
const DEFAULT_TTL_MS = 120_000;
|
|
10
11
|
const DEFAULT_REFRESH_MS = 45_000;
|
|
@@ -29,6 +30,8 @@ export interface HerdrStatusRun {
|
|
|
29
30
|
id: string;
|
|
30
31
|
agent?: string;
|
|
31
32
|
agents?: string[];
|
|
33
|
+
/** A workflow owns busy state but is not itself a child agent. */
|
|
34
|
+
coordinator?: true;
|
|
32
35
|
/** Explicit launch/workflow label only; raw prompts never enter pane metadata. */
|
|
33
36
|
taskLabel?: string;
|
|
34
37
|
needsAttention?: boolean;
|
|
@@ -100,10 +103,17 @@ function workflowTaskLabel(data: Record<string, unknown>): string | undefined {
|
|
|
100
103
|
function startedRun(data: unknown): HerdrStatusRun | undefined {
|
|
101
104
|
if (!isRecord(data) || typeof data.id !== "string" || !data.id) return undefined;
|
|
102
105
|
const taskLabel = workflowTaskLabel(data);
|
|
106
|
+
// The workflow coordinator itself is not a running leaf: it starts with its
|
|
107
|
+
// own `agent: "workflow"` identity, but its actual leaves each publish their
|
|
108
|
+
// own start event separately. Counting the coordinator here would double it.
|
|
109
|
+
const isWorkflowCoordinator = data.mode === "workflow";
|
|
103
110
|
return {
|
|
104
111
|
id: data.id,
|
|
105
|
-
...(
|
|
106
|
-
...(
|
|
112
|
+
...(isWorkflowCoordinator ? { coordinator: true as const } : {}),
|
|
113
|
+
...(!isWorkflowCoordinator && typeof data.agent === "string" ? { agent: data.agent } : {}),
|
|
114
|
+
...(isWorkflowCoordinator
|
|
115
|
+
? { agents: [] }
|
|
116
|
+
: Array.isArray(data.agents) && data.agents.every((agent) => typeof agent === "string") ? { agents: data.agents as string[] } : {}),
|
|
107
117
|
...(taskLabel ? { taskLabel } : {}),
|
|
108
118
|
};
|
|
109
119
|
}
|
|
@@ -150,7 +160,10 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
|
|
|
150
160
|
let refreshTimer: ReturnType<typeof setInterval> | undefined;
|
|
151
161
|
|
|
152
162
|
const activeAgentNames = (): string[] => [...new Set([...runs.values()].flatMap((run) => run.agents?.length ? run.agents : run.agent ? [run.agent] : []))];
|
|
153
|
-
|
|
163
|
+
// Preserve the minimum count for ordinary runs with incomplete status;
|
|
164
|
+
// only an empty workflow coordinator contributes zero child agents.
|
|
165
|
+
const activeSubagentCount = (): number => [...runs.values()].reduce((total, run) =>
|
|
166
|
+
total + (run.coordinator && !run.agents?.length ? 0 : Math.max(1, run.agents?.length ?? (run.agent ? 1 : 0))), 0);
|
|
154
167
|
const activeTaskLabel = (): string | undefined => [...runs.values()].reverse().find((run) => run.taskLabel)?.taskLabel;
|
|
155
168
|
|
|
156
169
|
const label = (includeAttention = false): string => {
|
|
@@ -340,6 +353,9 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
|
|
|
340
353
|
};
|
|
341
354
|
|
|
342
355
|
if (enabled) {
|
|
356
|
+
subscribe(HERDR_FOREGROUND_CONTROL_CHANGED_EVENT, () => {
|
|
357
|
+
if (rootSession && options.getRuns) refresh();
|
|
358
|
+
});
|
|
343
359
|
subscribe(SUBAGENT_ASYNC_STARTED_EVENT, (data) => {
|
|
344
360
|
if (!rootSession) return;
|
|
345
361
|
const run = startedRun(data);
|
|
@@ -8,6 +8,7 @@ import type { ChildSupervisorMetadata } from "../runs/shared/child-runtime-confi
|
|
|
8
8
|
import { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type ControlEvent, type IntercomEventBus, type SubagentState } from "../shared/types.ts";
|
|
9
9
|
import { writeAtomicJson } from "../shared/atomic-json.ts";
|
|
10
10
|
import { shouldUseNativeFsWatch } from "../shared/watch-strategy.ts";
|
|
11
|
+
import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
|
|
11
12
|
import {
|
|
12
13
|
SUPERVISOR_REQUEST_MESSAGE_TYPE,
|
|
13
14
|
SUPERVISOR_REPLY_ENTRY_TYPE,
|
|
@@ -259,6 +260,7 @@ export function registerNativeSupervisorClient(pi: ExtensionAPI, metadata: Child
|
|
|
259
260
|
if (!metadata || hasTool(pi, "contact_supervisor")) return;
|
|
260
261
|
const tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {
|
|
261
262
|
name: "contact_supervisor",
|
|
263
|
+
...MODEL_ONLY_TOOL,
|
|
262
264
|
label: "Contact Supervisor",
|
|
263
265
|
description: "Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.",
|
|
264
266
|
parameters: ContactSupervisorParamsSchema,
|
|
@@ -585,6 +587,7 @@ function publicPendingRequests(pending: Map<string, PendingSupervisorRequest>):
|
|
|
585
587
|
function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver, discover: () => void, runState: (request: SupervisorRequest) => SubagentState): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
|
|
586
588
|
return {
|
|
587
589
|
name: NATIVE_SUPERVISOR_TOOL_NAME,
|
|
590
|
+
...MODEL_ONLY_TOOL,
|
|
588
591
|
label: "Subagent Supervisor",
|
|
589
592
|
description: "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
|
|
590
593
|
parameters: IntercomParamsSchema,
|
|
@@ -788,7 +791,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
788
791
|
if (poller) return;
|
|
789
792
|
poller = timers.setInterval(() => {
|
|
790
793
|
poll();
|
|
791
|
-
if (!useNativeWatcher() &&
|
|
794
|
+
if (!useNativeWatcher() && !hasTransportDemand()) {
|
|
792
795
|
if (poller) timers.clearInterval(poller);
|
|
793
796
|
poller = undefined;
|
|
794
797
|
}
|
|
@@ -31,7 +31,14 @@ function readLinkedRun(run: MissionRunLink): MissionRunLink {
|
|
|
31
31
|
if (!run.asyncDir) return run;
|
|
32
32
|
const statusPath = path.join(run.asyncDir, "status.json");
|
|
33
33
|
if (!fs.existsSync(statusPath)) return run;
|
|
34
|
-
|
|
34
|
+
let parsed: unknown;
|
|
35
|
+
try {
|
|
36
|
+
parsed = JSON.parse(fs.readFileSync(statusPath, "utf-8"));
|
|
37
|
+
} catch (error) {
|
|
38
|
+
throw new Error(`Failed to read linked run status '${statusPath}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
39
|
+
}
|
|
40
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`Linked run status '${statusPath}' must be an object`);
|
|
41
|
+
const status = parsed as Record<string, unknown>;
|
|
35
42
|
if (typeof status.state !== "string" || !status.state.trim()) throw new Error(`Linked run status '${statusPath}' is missing state`);
|
|
36
43
|
const tokens = tokenUsage(status.totalTokens)
|
|
37
44
|
?? (Array.isArray(status.steps)
|
|
@@ -123,42 +130,48 @@ export function collectGoalContinuationNotices(input: {
|
|
|
123
130
|
retainedChildren: RetainedChild[];
|
|
124
131
|
turnId: number;
|
|
125
132
|
now?: number;
|
|
133
|
+
onError?: (missionId: string, error: unknown) => void;
|
|
126
134
|
}): GoalContinuationNotice[] {
|
|
127
135
|
const notices: GoalContinuationNotice[] = [];
|
|
128
136
|
const seen = new Set<string>();
|
|
137
|
+
const onError = input.onError ?? ((missionId: string, error: unknown) => console.error("Failed to evaluate goal mission", missionId, error));
|
|
129
138
|
for (const listed of listMissions(input.location).records) {
|
|
130
139
|
if (listed.ownerSessionId !== input.ownerSessionId || !listed.goal || TERMINAL_MISSION_STATUSES.has(listed.status)) continue;
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
event: {
|
|
153
|
-
type: "needs_attention",
|
|
154
|
-
to: "needs_attention",
|
|
155
|
-
ts: input.now ?? Date.now(),
|
|
156
|
-
runId: `goal-${record.id}-turn-${input.turnId}`,
|
|
157
|
-
agent: "goal mission",
|
|
140
|
+
try {
|
|
141
|
+
let record = refreshGoalMission(input.location, readMission(input.location, listed.id));
|
|
142
|
+
if (!record.goal || record.goal.status !== "active" || !record.budget) continue;
|
|
143
|
+
if ((record.usage?.tokens ?? 0) >= record.budget.tokens) {
|
|
144
|
+
record = updateMission(input.location, record.id, { usage: record.usage ?? { tokens: 0 } });
|
|
145
|
+
if (record.goal?.status === "budget-exhausted") continue;
|
|
146
|
+
}
|
|
147
|
+
if (record.runs.some((run) => run.status && ACTIVE_RUN_STATUSES.has(run.status))) continue;
|
|
148
|
+
if (seen.has(record.id) || !record.budget) continue;
|
|
149
|
+
seen.add(record.id);
|
|
150
|
+
const budget = record.budget.tokens;
|
|
151
|
+
const used = record.usage?.tokens ?? 0;
|
|
152
|
+
const remaining = Math.max(0, budget - used);
|
|
153
|
+
const message = [
|
|
154
|
+
`Goal mission needs attention: ${bounded(record.title)}`,
|
|
155
|
+
`Mission: ${record.id}`,
|
|
156
|
+
`Remaining budget: ${remaining} tokens (${used}/${budget} used)`,
|
|
157
|
+
`Next ready action: ${nextReadyAction(input.location, record, input.retainedChildren)}`,
|
|
158
|
+
].join("\n");
|
|
159
|
+
notices.push({
|
|
160
|
+
missionId: record.id,
|
|
158
161
|
message,
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
+
event: {
|
|
163
|
+
type: "needs_attention",
|
|
164
|
+
to: "needs_attention",
|
|
165
|
+
ts: input.now ?? Date.now(),
|
|
166
|
+
runId: `goal-${record.id}-turn-${input.turnId}`,
|
|
167
|
+
agent: "goal mission",
|
|
168
|
+
message,
|
|
169
|
+
reason: "idle",
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
} catch (error) {
|
|
173
|
+
onError(listed.id, error);
|
|
174
|
+
}
|
|
162
175
|
}
|
|
163
176
|
return notices;
|
|
164
177
|
}
|
package/src/missions/store.ts
CHANGED
|
@@ -562,7 +562,16 @@ export function listGlobalMissions(globalIndexDir: string): GlobalMissionListRes
|
|
|
562
562
|
try {
|
|
563
563
|
const record = parseMissionRecord(JSON.parse(fs.readFileSync(entry.recordPath, "utf-8")), entry.recordPath);
|
|
564
564
|
if (record.id !== entry.missionId) throw new Error(`record id '${record.id}' does not match index id '${entry.missionId}'`);
|
|
565
|
-
|
|
565
|
+
const projection: MissionIndexEntry = {
|
|
566
|
+
...entry,
|
|
567
|
+
title: record.title,
|
|
568
|
+
status: record.status,
|
|
569
|
+
updatedAt: record.updatedAt,
|
|
570
|
+
};
|
|
571
|
+
delete projection.lastRunId;
|
|
572
|
+
const lastRunId = record.runs.at(-1)?.runId;
|
|
573
|
+
if (lastRunId) projection.lastRunId = lastRunId;
|
|
574
|
+
entries.push({ ...projection, stale: false });
|
|
566
575
|
} catch (error) {
|
|
567
576
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
568
577
|
try {
|
package/src/profiles/profiles.ts
CHANGED
|
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as os from "node:os";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
|
-
import { BUILTIN_AGENT_NAMES } from "../agents/agents.ts";
|
|
5
|
+
import { BUILTIN_AGENT_NAMES, validateOptionalMachine } from "../agents/agents.ts";
|
|
6
6
|
import { getPiSpawnCommand } from "../runs/shared/pi-spawn.ts";
|
|
7
7
|
import { findModelInfo, getSupportedThinkingLevels, splitKnownThinkingSuffix, toModelInfo } from "../shared/model-info.ts";
|
|
8
8
|
import { getAgentDir } from "../shared/utils.ts";
|
|
@@ -20,7 +20,7 @@ export type RecommendedRoleTier = "cheap" | "medium" | "strong";
|
|
|
20
20
|
interface ProfileAgentOverride {
|
|
21
21
|
model?: string;
|
|
22
22
|
thinking?: string | false;
|
|
23
|
-
machine?: string;
|
|
23
|
+
machine?: string | false;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
export interface SubagentProfileFile {
|
|
@@ -144,6 +144,9 @@ function validateSubagentProfile(filePath: string, parsed: Record<string, unknow
|
|
|
144
144
|
if (thinking !== undefined && thinking !== false && typeof thinking !== "string") {
|
|
145
145
|
throw new Error(`Profile '${filePath}' has invalid thinking for '${name}'; expected a string or false.`);
|
|
146
146
|
}
|
|
147
|
+
if (override.machine !== undefined && override.machine !== false) {
|
|
148
|
+
override.machine = validateOptionalMachine(override.machine, `Profile '${filePath}' has invalid machine for '${name}'`);
|
|
149
|
+
}
|
|
147
150
|
if ((override as Record<string, unknown>).fallbackModels !== undefined) throw new Error(`Profile '${filePath}' uses removed field fallbackModels for '${name}'; configure one model instead.`);
|
|
148
151
|
}
|
|
149
152
|
const disableBuiltins = (subagents as Record<string, unknown>).disableBuiltins;
|