@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
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { sanitizeDisplayText, truncateDisplayText } from "../../shared/display-text.ts";
|
|
2
2
|
import { formatModelThinking } from "../../shared/formatters.ts";
|
|
3
|
+
import { childThinkingLevel, type ThinkingLevel } from "../../shared/model-info.ts";
|
|
3
4
|
import type { AsyncJobState, AsyncJobStep, HostStepFreshness, HostStepMonitorKind, HostStepNode, HostStepState, HostStepVerdict, NestedRunSummary, NestedStepSummary, SubagentRunMode, WorkflowGraphSnapshot, WorkflowPreflightLane, WorkflowPreflight } from "../../shared/types.ts";
|
|
4
5
|
import { HOST_STEP_MAX_COUNT, HOST_STEP_MAX_DETAIL_CHARS, HOST_STEP_MAX_LABEL_CHARS, HOST_STEP_MAX_PROVIDER_CHARS, HOST_STEP_MAX_REASON_CHARS, HOST_STEP_MAX_REF_CHARS, HOST_STEP_MAX_ROLE_CHARS, HOST_STEP_MAX_TARGET_CHARS, hostStepReportName, parseHostStepNode, validHostStepNodes } from "./host-step-status.ts";
|
|
5
6
|
import { workflowPreflightLaneForRuntimeKey } from "../../workflows/workflow-preflight.ts";
|
|
@@ -106,6 +107,8 @@ export interface AsyncStatusWorkflowRow {
|
|
|
106
107
|
kind?: HostStepMonitorKind;
|
|
107
108
|
context?: AsyncJobStep["context"];
|
|
108
109
|
modelThinking?: string;
|
|
110
|
+
/** Thinking level of the child a child row stands for. */
|
|
111
|
+
thinking?: ThinkingLevel;
|
|
109
112
|
activity?: string;
|
|
110
113
|
startedAt?: number;
|
|
111
114
|
endedAt?: number;
|
|
@@ -623,12 +626,14 @@ export function projectAsyncWorkflowRows(
|
|
|
623
626
|
|
|
624
627
|
function projectLoadedWorkflowRow(step: AsyncJobStep, index: number, preflight?: WorkflowPreflightLane): AsyncStatusWorkflowRow {
|
|
625
628
|
const modelThinking = formatModelThinking(step.model, step.thinking) || undefined;
|
|
629
|
+
const thinking = childThinkingLevel(step);
|
|
626
630
|
const activity = workflowStepActivity(step);
|
|
627
631
|
return {
|
|
628
632
|
name: workflowStepName(step, index),
|
|
629
633
|
state: step.status,
|
|
630
634
|
...(step.context ? { context: step.context } : {}),
|
|
631
635
|
...(modelThinking ? { modelThinking } : {}),
|
|
636
|
+
...(thinking ? { thinking } : {}),
|
|
632
637
|
...(activity ? { activity } : {}),
|
|
633
638
|
...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
|
|
634
639
|
...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { Type } from "typebox";
|
|
5
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
6
|
+
import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { createAtomicJsonWriter } from "../../shared/atomic-json.ts";
|
|
8
|
+
import { watchAsyncControlInbox, requestAsyncCommand, type CommandRequest } from "../background/control-channel.ts";
|
|
9
|
+
|
|
10
|
+
export const CHILD_COMMAND_TOOL = "subagent_command";
|
|
11
|
+
export type CommandOperation = "status" | "yield" | "cancel";
|
|
12
|
+
export interface ChildCommandSnapshot {
|
|
13
|
+
toolCallId: string;
|
|
14
|
+
state: "running" | "yielded" | "cancel_requested" | "completed" | "failed" | "cancelled";
|
|
15
|
+
startedAt: number;
|
|
16
|
+
endedAt?: number;
|
|
17
|
+
output: string;
|
|
18
|
+
fullOutputPath?: string;
|
|
19
|
+
}
|
|
20
|
+
interface CommandJob {
|
|
21
|
+
snapshot: ChildCommandSnapshot;
|
|
22
|
+
controller: AbortController;
|
|
23
|
+
yieldResult: () => void;
|
|
24
|
+
settled: Promise<void>;
|
|
25
|
+
yielded?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface ChildCommandState {
|
|
28
|
+
ownerId: string;
|
|
29
|
+
closed: boolean;
|
|
30
|
+
commands: ChildCommandSnapshot[];
|
|
31
|
+
}
|
|
32
|
+
const writeAtomicJson = createAtomicJsonWriter({ mode: 0o600 });
|
|
33
|
+
const MAX_OUTPUT_BYTES = 8 * 1024;
|
|
34
|
+
const RECENT_COMMANDS = 20;
|
|
35
|
+
|
|
36
|
+
function childCommandStatePath(channelDir: string): string {
|
|
37
|
+
return path.join(channelDir, "commands.json");
|
|
38
|
+
}
|
|
39
|
+
export function readChildCommandState(channelDir: string): ChildCommandState | undefined {
|
|
40
|
+
try { return JSON.parse(fs.readFileSync(childCommandStatePath(channelDir), "utf8")) as ChildCommandState; }
|
|
41
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
|
|
42
|
+
}
|
|
43
|
+
function active(job: CommandJob): boolean { return job.snapshot.endedAt === undefined; }
|
|
44
|
+
function text(result: AgentToolResult<unknown>): string {
|
|
45
|
+
return Buffer.from(result.content.filter((part) => part.type === "text").map((part) => part.text).join("\n")).subarray(-MAX_OUTPUT_BYTES).toString("utf8");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Owns command lifetimes, not shell execution. The supplied Pi tool still executes the command. */
|
|
49
|
+
export function createChildCommandRuntime(channelDir: string) {
|
|
50
|
+
const ownerId = randomUUID();
|
|
51
|
+
const jobs = new Map<string, CommandJob>();
|
|
52
|
+
const usedIds = new Set<string>();
|
|
53
|
+
let closed = false;
|
|
54
|
+
let disposeInbox: (() => void) | undefined;
|
|
55
|
+
const state = (): ChildCommandState => ({ ownerId, closed, commands: [...jobs.values()].map((job) => ({ ...job.snapshot })) });
|
|
56
|
+
const persist = () => writeAtomicJson(childCommandStatePath(channelDir), {
|
|
57
|
+
ownerId, closed,
|
|
58
|
+
commands: [...jobs.values()].map((job) => ({ ...job.snapshot, output: job.yielded ? job.snapshot.output : "" })),
|
|
59
|
+
});
|
|
60
|
+
const operate = (operation: CommandOperation, toolCallId?: string): ChildCommandState => {
|
|
61
|
+
if (operation === "status" && toolCallId === undefined) return state();
|
|
62
|
+
const job = toolCallId ? jobs.get(toolCallId) : undefined;
|
|
63
|
+
if (!job) throw new Error(`No retained command '${toolCallId ?? ""}' in this child session.`);
|
|
64
|
+
if (operation !== "status" && closed) throw new Error("Child command controller is closed.");
|
|
65
|
+
const before = job.snapshot.state;
|
|
66
|
+
if (active(job)) {
|
|
67
|
+
if (operation === "yield" && job.snapshot.state === "running") {
|
|
68
|
+
job.yielded = true;
|
|
69
|
+
job.snapshot.state = "yielded";
|
|
70
|
+
job.yieldResult();
|
|
71
|
+
} else if (operation === "cancel") {
|
|
72
|
+
job.snapshot.state = "cancel_requested";
|
|
73
|
+
job.controller.abort();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (job.snapshot.state !== before) persist();
|
|
77
|
+
return { ownerId, closed, commands: [{ ...job.snapshot }] };
|
|
78
|
+
};
|
|
79
|
+
const startInbox = () => {
|
|
80
|
+
if (disposeInbox) return;
|
|
81
|
+
disposeInbox = watchAsyncControlInbox(channelDir, {
|
|
82
|
+
onCommand(request) {
|
|
83
|
+
const replyPath = commandReplyPath(channelDir, request.id);
|
|
84
|
+
try {
|
|
85
|
+
if (request.ownerId !== ownerId) throw new Error("Command request belongs to another child session.");
|
|
86
|
+
if (Date.now() > request.deadlineAt) throw new Error("Command request expired before delivery.");
|
|
87
|
+
writeAtomicJson(replyPath, { state: operate(request.operation, request.toolCallId) });
|
|
88
|
+
} catch (error) {
|
|
89
|
+
writeAtomicJson(replyPath, { error: error instanceof Error ? error.message : String(error) });
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
};
|
|
94
|
+
const stop = async () => {
|
|
95
|
+
closed = true;
|
|
96
|
+
disposeInbox?.();
|
|
97
|
+
for (const job of jobs.values()) if (active(job)) {
|
|
98
|
+
job.snapshot.state = "cancel_requested";
|
|
99
|
+
job.controller.abort();
|
|
100
|
+
}
|
|
101
|
+
await Promise.all([...jobs.values()].map((job) => job.settled));
|
|
102
|
+
if (jobs.size) persist();
|
|
103
|
+
};
|
|
104
|
+
return {
|
|
105
|
+
state,
|
|
106
|
+
operate,
|
|
107
|
+
shutdown: stop,
|
|
108
|
+
async finish() {
|
|
109
|
+
const pending = [...jobs.values()].filter(active);
|
|
110
|
+
if (!pending.length) return;
|
|
111
|
+
await stop();
|
|
112
|
+
throw new Error(`Child finished with unfinished commands: ${pending.map((job) => job.snapshot.toolCallId).join(", ")}. Commands were cancelled; query or cancel background commands before finishing.`);
|
|
113
|
+
},
|
|
114
|
+
wrap(tool: ToolDefinition): ToolDefinition {
|
|
115
|
+
return {
|
|
116
|
+
...tool,
|
|
117
|
+
parameters: Type.Unsafe({ ...tool.parameters, properties: {
|
|
118
|
+
...(tool.parameters as { properties?: object }).properties,
|
|
119
|
+
yieldTimeMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 30_000, description: "Return a managed command handle after this wait; does not terminate the command. Omit to wait for completion." })),
|
|
120
|
+
} }),
|
|
121
|
+
description: `${tool.description}\nOptional yieldTimeMs returns a command handle without stopping execution. Use subagent_command to query or cancel it. Finish or cancel every command before completing the task.`,
|
|
122
|
+
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
123
|
+
if (closed) throw new Error("Child command controller is closed.");
|
|
124
|
+
if (usedIds.has(toolCallId)) throw new Error(`Command id '${toolCallId}' was already used in this child session.`);
|
|
125
|
+
usedIds.add(toolCallId);
|
|
126
|
+
const { yieldTimeMs, ...args } = params as Record<string, unknown>;
|
|
127
|
+
const controller = new AbortController();
|
|
128
|
+
const commandSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
129
|
+
let yieldResult!: () => void;
|
|
130
|
+
const yielded = new Promise<void>((resolve) => { yieldResult = resolve; });
|
|
131
|
+
const job: CommandJob = { snapshot: { toolCallId, state: "running", startedAt: Date.now(), output: "" }, controller, yieldResult, settled: Promise.resolve() };
|
|
132
|
+
// Keep active commands and a bounded recent history; never retain full outputs.
|
|
133
|
+
const completed = [...jobs].filter(([, candidate]) => !active(candidate));
|
|
134
|
+
for (const [id] of completed.slice(0, Math.max(0, completed.length - RECENT_COMMANDS + 1))) jobs.delete(id);
|
|
135
|
+
jobs.set(toolCallId, job);
|
|
136
|
+
persist();
|
|
137
|
+
startInbox();
|
|
138
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
139
|
+
if (typeof yieldTimeMs === "number") timer = setTimeout(() => operate("yield", toolCallId), yieldTimeMs);
|
|
140
|
+
const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
|
|
141
|
+
job.snapshot.output = text(update);
|
|
142
|
+
if (job.snapshot.state === "running") onUpdate?.(update);
|
|
143
|
+
}, ctx)).then((result) => {
|
|
144
|
+
job.snapshot.output = text(result);
|
|
145
|
+
job.snapshot.state = "completed";
|
|
146
|
+
const fullOutputPath = (result.details as { fullOutputPath?: string } | undefined)?.fullOutputPath;
|
|
147
|
+
if (fullOutputPath) job.snapshot.fullOutputPath = fullOutputPath;
|
|
148
|
+
return result;
|
|
149
|
+
}, (error: unknown) => {
|
|
150
|
+
job.snapshot.state = controller.signal.aborted ? "cancelled" : "failed";
|
|
151
|
+
job.snapshot.output = String(error).slice(-MAX_OUTPUT_BYTES);
|
|
152
|
+
throw error;
|
|
153
|
+
}).finally(() => {
|
|
154
|
+
if (timer) clearTimeout(timer);
|
|
155
|
+
job.snapshot.endedAt = Date.now();
|
|
156
|
+
persist();
|
|
157
|
+
});
|
|
158
|
+
job.settled = execution.then(() => {}, () => {});
|
|
159
|
+
const result = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => undefined)]);
|
|
160
|
+
if (result) return result.value;
|
|
161
|
+
return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.\n${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
},
|
|
165
|
+
tool(): ToolDefinition {
|
|
166
|
+
return {
|
|
167
|
+
name: CHILD_COMMAND_TOOL, label: "Child command",
|
|
168
|
+
description: "Inspect or cancel bash commands owned by this child. Cancellation stops only the selected command, not the agent. Check terminal state before finishing.",
|
|
169
|
+
parameters: Type.Object({ action: Type.String({ enum: ["status", "cancel"] }), toolCallId: Type.Optional(Type.String()), waitMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 30_000 })) }),
|
|
170
|
+
async execute(_id, params, signal) {
|
|
171
|
+
const { action, toolCallId, waitMs = 0 } = params as { action: "status" | "cancel"; toolCallId?: string; waitMs?: number };
|
|
172
|
+
operate(action, toolCallId);
|
|
173
|
+
const job = toolCallId ? jobs.get(toolCallId) : undefined;
|
|
174
|
+
if (job && active(job) && waitMs > 0) await waitForCommand(job.settled, waitMs, signal);
|
|
175
|
+
const snapshot = operate("status", toolCallId);
|
|
176
|
+
return { content: [{ type: "text", text: JSON.stringify(snapshot) }], details: snapshot };
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function waitForCommand(settled: Promise<void>, waitMs: number, signal?: AbortSignal): Promise<void> {
|
|
184
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
185
|
+
let abort!: () => void;
|
|
186
|
+
const wait = new Promise<void>((resolve, reject) => {
|
|
187
|
+
timer = setTimeout(resolve, waitMs);
|
|
188
|
+
abort = () => reject(new Error("Command wait aborted; command remains managed by the child."));
|
|
189
|
+
if (signal?.aborted) abort();
|
|
190
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
191
|
+
});
|
|
192
|
+
try { await Promise.race([settled, wait]); }
|
|
193
|
+
finally { clearTimeout(timer!); signal?.removeEventListener("abort", abort); }
|
|
194
|
+
}
|
|
195
|
+
function commandReplyPath(channelDir: string, id: string): string {
|
|
196
|
+
return path.join(channelDir, "command-replies", `${id}.json`);
|
|
197
|
+
}
|
|
198
|
+
export async function controlChildCommand(channelDir: string, operation: CommandOperation, toolCallId?: string, signal?: AbortSignal): Promise<ChildCommandState> {
|
|
199
|
+
const current = readChildCommandState(channelDir);
|
|
200
|
+
if (!current) throw new Error("No command controller is available for this child. Command controls require a local native Pi child with bash.");
|
|
201
|
+
if (current.closed) {
|
|
202
|
+
if (operation === "status") {
|
|
203
|
+
if (toolCallId === undefined) return current;
|
|
204
|
+
const command = current.commands.find((entry) => entry.toolCallId === toolCallId);
|
|
205
|
+
if (!command) throw new Error(`No retained command '${toolCallId}' in this child session.`);
|
|
206
|
+
return { ...current, commands: [command] };
|
|
207
|
+
}
|
|
208
|
+
throw new Error("Child command controller is closed.");
|
|
209
|
+
}
|
|
210
|
+
if (operation !== "status" && !toolCallId) throw new Error("An exact toolCallId is required; command controls never target the next command.");
|
|
211
|
+
const id = randomUUID();
|
|
212
|
+
const deadlineAt = Date.now() + 5_000;
|
|
213
|
+
const request: CommandRequest = { type: "command", id, ownerId: current.ownerId, operation, ...(toolCallId ? { toolCallId } : {}), deadlineAt };
|
|
214
|
+
requestAsyncCommand(channelDir, request);
|
|
215
|
+
const replyPath = commandReplyPath(channelDir, id);
|
|
216
|
+
try {
|
|
217
|
+
while (Date.now() < deadlineAt) {
|
|
218
|
+
if (signal?.aborted) throw new Error("Command control wait aborted; delivery may still be pending.");
|
|
219
|
+
try {
|
|
220
|
+
const reply = JSON.parse(fs.readFileSync(replyPath, "utf8")) as { state?: ChildCommandState; error?: string };
|
|
221
|
+
if (reply.error) throw new Error(reply.error);
|
|
222
|
+
if (reply.state) return reply.state;
|
|
223
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
224
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
225
|
+
}
|
|
226
|
+
throw new Error("Command control acknowledgement timed out. Inspect command status; cancellation is not confirmed.");
|
|
227
|
+
} finally { fs.rmSync(replyPath, { force: true }); }
|
|
228
|
+
}
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
type HerdrMachineReference,
|
|
18
18
|
} from "../../shared/types.ts";
|
|
19
19
|
import type { NestedPathEntry } from "./nested-path.ts";
|
|
20
|
-
import type
|
|
20
|
+
import { extensionOnlyMcpServers, type McpRuntimeSnapshotHost, type ResolvedMcpDirectToolSelection } from "./mcp-direct-tool-allowlist.ts";
|
|
21
21
|
import type { PermissionRules } from "./permissions.ts";
|
|
22
22
|
import type { StructuredOutputRuntime } from "./structured-output.ts";
|
|
23
23
|
import type { ChildToolDiagnostic } from "./tool-availability.ts";
|
|
@@ -86,6 +86,8 @@ export interface BuildInProcessChildLaunchInput {
|
|
|
86
86
|
requiredExtensions?: RequiredChildExtensionSnapshot;
|
|
87
87
|
systemPrompt?: string | null;
|
|
88
88
|
mcpDirectTools?: string[];
|
|
89
|
+
/** Selections the parent resolved against Pi's built-in MCP, carried to the runner. */
|
|
90
|
+
builtinMcpTools?: ResolvedMcpDirectToolSelection[];
|
|
89
91
|
extensionBindings?: ExtensionBindings;
|
|
90
92
|
cwd: string;
|
|
91
93
|
intercomSessionName?: string;
|
|
@@ -174,7 +176,9 @@ function inheritedCapabilityCeiling(inherited: InheritedChildRuntime | undefined
|
|
|
174
176
|
function childProcessEnv(input: BuildInProcessChildLaunchInput, toolPlan: PiLaunchToolPlan, sandboxEnv?: Record<string, string | undefined>): Record<string, string | undefined> {
|
|
175
177
|
const env: Record<string, string | undefined> = {};
|
|
176
178
|
env[PI_SUBAGENT_EXTENSION_BINDINGS_ENV] = encodeExtensionBindings(input.extensionBindings);
|
|
177
|
-
|
|
179
|
+
// Selectors resolved against Pi's built-in MCP never reach an adapter.
|
|
180
|
+
if (toolPlan.builtinMcpTools) env[MCP_DIRECT_TOOLS_ENV] = "__none__";
|
|
181
|
+
else if (!toolPlan.capabilityCeiling && input.mcpDirectTools?.length) env[MCP_DIRECT_TOOLS_ENV] = input.mcpDirectTools.join(",");
|
|
178
182
|
else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
|
|
179
183
|
env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
|
|
180
184
|
} else env[MCP_DIRECT_TOOLS_ENV] = "__none__";
|
|
@@ -211,6 +215,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
|
|
|
211
215
|
subagentOnlyExtensions: input.subagentOnlyExtensions,
|
|
212
216
|
requiredExtensions,
|
|
213
217
|
mcpDirectTools: input.mcpDirectTools,
|
|
218
|
+
builtinMcpTools: input.builtinMcpTools,
|
|
214
219
|
cwd: input.cwd,
|
|
215
220
|
requireReadTool: input.requireReadTool,
|
|
216
221
|
structuredOutput: Boolean(input.structuredOutput),
|
|
@@ -225,6 +230,12 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
|
|
|
225
230
|
permissionProfile: input.permissionProfile,
|
|
226
231
|
hostAvailableBuiltins: input.hostAvailableBuiltins,
|
|
227
232
|
});
|
|
233
|
+
// Foreground children load no ambient extensions, so an extension's registerMcpServer() never runs in them.
|
|
234
|
+
if (input.host === "parent" && input.runtimeSnapshotHost && toolPlan.builtinMcpTools?.length) {
|
|
235
|
+
// Pi treats a session without a trust decision as trusted.
|
|
236
|
+
const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false);
|
|
237
|
+
if (servers.length) throw new Error(`Agent '${input.childAgentName}' selects MCP tools from servers that extensions registered (${servers.join(", ")}). Only background children (async: true) load those extensions; run the agent in the background or add the server to the global mcp.json or a trusted project's .pi/mcp.json.`);
|
|
238
|
+
}
|
|
228
239
|
toolPlan.capabilityCeiling = intersectSubagentCapabilityCeilings(toolPlan.capabilityCeiling, agentCapabilityCeiling);
|
|
229
240
|
if (toolPlan.capabilityAudit && toolPlan.capabilityCeiling) {
|
|
230
241
|
toolPlan.capabilityAudit = { ...toolPlan.capabilityAudit, ceiling: toolPlan.capabilityCeiling };
|
|
@@ -334,10 +345,12 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
|
|
|
334
345
|
const session: Omit<ChildSessionLaunch, "onExtensionError"> = {
|
|
335
346
|
cwd: input.cwd,
|
|
336
347
|
...(input.machine ? { machine: input.machine } : {}),
|
|
348
|
+
...(input.projectTrusted !== undefined ? { projectTrusted: input.projectTrusted } : {}),
|
|
337
349
|
...(input.machine ? { remoteResources: { agent: input.childAgentName, ...(input.remoteSkillNames ? { skills: input.remoteSkillNames } : {}), ...(input.remoteReads !== undefined ? { reads: input.remoteReads } : {}), ...(toolPlan.explicitToolAllowlist ? { toolCeiling: [...toolPlan.effectiveToolAllowlist] } : toolPlan.capabilityCeiling?.allowedTools ? { toolCeiling: [...toolPlan.capabilityCeiling.allowedTools] } : {}) } } : {}),
|
|
338
350
|
storage: childStorage(input),
|
|
339
351
|
...(input.model ? { model: input.model } : {}),
|
|
340
352
|
...(toolPlan.explicitToolAllowlist ? { tools: toolPlan.effectiveToolAllowlist } : {}),
|
|
353
|
+
...(toolPlan.builtinMcpTools?.length ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
|
|
341
354
|
...(!toolPlan.explicitToolAllowlist && toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
|
|
342
355
|
extensionPaths,
|
|
343
356
|
requiredExtensions: toolPlan.requiredExtensions,
|