@xzzpig/pi-subagents 0.19.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 +214 -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 +86 -11
- package/docs/configuration.md +68 -7
- package/docs/extension-api.md +37 -12
- package/docs/fork-extensions.md +1 -0
- package/docs/missions.md +48 -17
- package/docs/models.md +7 -3
- package/docs/observability.md +18 -8
- package/docs/tool-reference.md +138 -80
- package/docs/watchdog.md +8 -6
- package/docs/workflows.md +18 -9
- 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 +224 -122
- package/src/api/preflight.ts +50 -5
- package/src/extension/config.ts +24 -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 +134 -145
- package/src/extension/public-execution.ts +3 -0
- package/src/extension/reply-workflow-script.ts +21 -12
- package/src/extension/rpc.ts +12 -7
- package/src/extension/schemas.ts +39 -33
- 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/goal-driver.ts +44 -31
- package/src/missions/store.ts +35 -6
- package/src/profiles/profiles.ts +29 -23
- package/src/runs/background/active-async-capacity.ts +58 -8
- package/src/runs/background/async-execution.ts +231 -44
- package/src/runs/background/async-job-tracker.ts +12 -4
- package/src/runs/background/async-resume.ts +5 -2
- package/src/runs/background/await-async-run.ts +18 -11
- 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/control-channel.ts +43 -0
- 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 +29 -8
- package/src/runs/background/run-id-resolver.ts +8 -5
- package/src/runs/background/run-status.ts +21 -16
- package/src/runs/background/runner-aliases.ts +7 -4
- 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 +282 -72
- package/src/runs/background/stale-run-reconciler.ts +13 -2
- package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
- package/src/runs/background/subagent-runner.ts +75 -16
- 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/command-action.ts +41 -0
- package/src/runs/foreground/execution.ts +109 -58
- package/src/runs/foreground/foreground-history.ts +1 -0
- package/src/runs/foreground/subagent-executor.ts +270 -89
- package/src/runs/shared/child-commands.ts +229 -0
- 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 +131 -40
- package/src/runs/shared/child-tool-plan.ts +14 -27
- 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/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 +8 -5
- package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
- package/src/runs/shared/model-resolution.ts +39 -2
- 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 +4 -0
- package/src/runs/shared/partial-output.ts +48 -0
- package/src/runs/shared/run-history.ts +87 -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 +33 -18
- package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
- 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/required-child-extensions.ts +39 -5
- package/src/shared/runtime-module-path.ts +19 -0
- package/src/shared/settings-file-lease.ts +36 -0
- package/src/shared/types.ts +42 -3
- package/src/shared/utils.ts +8 -6
- package/src/slash/slash-commands.ts +3 -3
- package/src/slash/subagent-cost.ts +9 -5
- 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 +28 -20
- 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-receipt.ts +2 -2
- package/src/workflows/workflow-resources.ts +18 -4
|
@@ -0,0 +1,229 @@
|
|
|
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 { requireSuccessfulCommandResult } from "./fork-command-result.ts";
|
|
9
|
+
import { watchAsyncControlInbox, requestAsyncCommand, type CommandRequest } from "../background/control-channel.ts";
|
|
10
|
+
|
|
11
|
+
export const CHILD_COMMAND_TOOL = "subagent_command";
|
|
12
|
+
export type CommandOperation = "status" | "yield" | "cancel";
|
|
13
|
+
export interface ChildCommandSnapshot {
|
|
14
|
+
toolCallId: string;
|
|
15
|
+
state: "running" | "yielded" | "cancel_requested" | "completed" | "failed" | "cancelled";
|
|
16
|
+
startedAt: number;
|
|
17
|
+
endedAt?: number;
|
|
18
|
+
output: string;
|
|
19
|
+
fullOutputPath?: string;
|
|
20
|
+
}
|
|
21
|
+
interface CommandJob {
|
|
22
|
+
snapshot: ChildCommandSnapshot;
|
|
23
|
+
controller: AbortController;
|
|
24
|
+
yieldResult: () => void;
|
|
25
|
+
settled: Promise<void>;
|
|
26
|
+
yielded?: boolean;
|
|
27
|
+
}
|
|
28
|
+
export interface ChildCommandState {
|
|
29
|
+
ownerId: string;
|
|
30
|
+
closed: boolean;
|
|
31
|
+
commands: ChildCommandSnapshot[];
|
|
32
|
+
}
|
|
33
|
+
const writeAtomicJson = createAtomicJsonWriter({ mode: 0o600 });
|
|
34
|
+
const MAX_OUTPUT_BYTES = 8 * 1024;
|
|
35
|
+
const RECENT_COMMANDS = 20;
|
|
36
|
+
|
|
37
|
+
function childCommandStatePath(channelDir: string): string {
|
|
38
|
+
return path.join(channelDir, "commands.json");
|
|
39
|
+
}
|
|
40
|
+
export function readChildCommandState(channelDir: string): ChildCommandState | undefined {
|
|
41
|
+
try { return JSON.parse(fs.readFileSync(childCommandStatePath(channelDir), "utf8")) as ChildCommandState; }
|
|
42
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
|
|
43
|
+
}
|
|
44
|
+
function active(job: CommandJob): boolean { return job.snapshot.endedAt === undefined; }
|
|
45
|
+
function text(result: AgentToolResult<unknown>): string {
|
|
46
|
+
return Buffer.from(result.content.filter((part) => part.type === "text").map((part) => part.text).join("\n")).subarray(-MAX_OUTPUT_BYTES).toString("utf8");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Owns command lifetimes, not shell execution. The supplied Pi tool still executes the command. */
|
|
50
|
+
export function createChildCommandRuntime(channelDir: string) {
|
|
51
|
+
const ownerId = randomUUID();
|
|
52
|
+
const jobs = new Map<string, CommandJob>();
|
|
53
|
+
const usedIds = new Set<string>();
|
|
54
|
+
let closed = false;
|
|
55
|
+
let disposeInbox: (() => void) | undefined;
|
|
56
|
+
const state = (): ChildCommandState => ({ ownerId, closed, commands: [...jobs.values()].map((job) => ({ ...job.snapshot })) });
|
|
57
|
+
const persist = () => writeAtomicJson(childCommandStatePath(channelDir), {
|
|
58
|
+
ownerId, closed,
|
|
59
|
+
commands: [...jobs.values()].map((job) => ({ ...job.snapshot, output: job.yielded ? job.snapshot.output : "" })),
|
|
60
|
+
});
|
|
61
|
+
const operate = (operation: CommandOperation, toolCallId?: string): ChildCommandState => {
|
|
62
|
+
if (operation === "status" && toolCallId === undefined) return state();
|
|
63
|
+
const job = toolCallId ? jobs.get(toolCallId) : undefined;
|
|
64
|
+
if (!job) throw new Error(`No retained command '${toolCallId ?? ""}' in this child session.`);
|
|
65
|
+
if (operation !== "status" && closed) throw new Error("Child command controller is closed.");
|
|
66
|
+
const before = job.snapshot.state;
|
|
67
|
+
if (active(job)) {
|
|
68
|
+
if (operation === "yield" && job.snapshot.state === "running") {
|
|
69
|
+
job.yielded = true;
|
|
70
|
+
job.snapshot.state = "yielded";
|
|
71
|
+
job.yieldResult();
|
|
72
|
+
} else if (operation === "cancel") {
|
|
73
|
+
job.snapshot.state = "cancel_requested";
|
|
74
|
+
job.controller.abort();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (job.snapshot.state !== before) persist();
|
|
78
|
+
return { ownerId, closed, commands: [{ ...job.snapshot }] };
|
|
79
|
+
};
|
|
80
|
+
const startInbox = () => {
|
|
81
|
+
if (disposeInbox) return;
|
|
82
|
+
disposeInbox = watchAsyncControlInbox(channelDir, {
|
|
83
|
+
onCommand(request) {
|
|
84
|
+
const replyPath = commandReplyPath(channelDir, request.id);
|
|
85
|
+
try {
|
|
86
|
+
if (request.ownerId !== ownerId) throw new Error("Command request belongs to another child session.");
|
|
87
|
+
if (Date.now() > request.deadlineAt) throw new Error("Command request expired before delivery.");
|
|
88
|
+
writeAtomicJson(replyPath, { state: operate(request.operation, request.toolCallId) });
|
|
89
|
+
} catch (error) {
|
|
90
|
+
writeAtomicJson(replyPath, { error: error instanceof Error ? error.message : String(error) });
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
const stop = async () => {
|
|
96
|
+
closed = true;
|
|
97
|
+
disposeInbox?.();
|
|
98
|
+
for (const job of jobs.values()) if (active(job)) {
|
|
99
|
+
job.snapshot.state = "cancel_requested";
|
|
100
|
+
job.controller.abort();
|
|
101
|
+
}
|
|
102
|
+
await Promise.all([...jobs.values()].map((job) => job.settled));
|
|
103
|
+
if (jobs.size) persist();
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
state,
|
|
107
|
+
operate,
|
|
108
|
+
shutdown: stop,
|
|
109
|
+
async finish() {
|
|
110
|
+
const pending = [...jobs.values()].filter(active);
|
|
111
|
+
if (!pending.length) return;
|
|
112
|
+
await stop();
|
|
113
|
+
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.`);
|
|
114
|
+
},
|
|
115
|
+
wrap(tool: ToolDefinition): ToolDefinition {
|
|
116
|
+
return {
|
|
117
|
+
...tool,
|
|
118
|
+
parameters: Type.Unsafe({ ...tool.parameters, properties: {
|
|
119
|
+
...(tool.parameters as { properties?: object }).properties,
|
|
120
|
+
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." })),
|
|
121
|
+
} }),
|
|
122
|
+
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.`,
|
|
123
|
+
async execute(toolCallId, params, signal, onUpdate, ctx) {
|
|
124
|
+
if (closed) throw new Error("Child command controller is closed.");
|
|
125
|
+
if (usedIds.has(toolCallId)) throw new Error(`Command id '${toolCallId}' was already used in this child session.`);
|
|
126
|
+
usedIds.add(toolCallId);
|
|
127
|
+
const { yieldTimeMs, ...args } = params as Record<string, unknown>;
|
|
128
|
+
const controller = new AbortController();
|
|
129
|
+
const commandSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
130
|
+
let yieldResult!: () => void;
|
|
131
|
+
const yielded = new Promise<void>((resolve) => { yieldResult = resolve; });
|
|
132
|
+
const job: CommandJob = { snapshot: { toolCallId, state: "running", startedAt: Date.now(), output: "" }, controller, yieldResult, settled: Promise.resolve() };
|
|
133
|
+
// Keep active commands and a bounded recent history; never retain full outputs.
|
|
134
|
+
const completed = [...jobs].filter(([, candidate]) => !active(candidate));
|
|
135
|
+
for (const [id] of completed.slice(0, Math.max(0, completed.length - RECENT_COMMANDS + 1))) jobs.delete(id);
|
|
136
|
+
jobs.set(toolCallId, job);
|
|
137
|
+
persist();
|
|
138
|
+
startInbox();
|
|
139
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
140
|
+
if (typeof yieldTimeMs === "number") timer = setTimeout(() => operate("yield", toolCallId), yieldTimeMs);
|
|
141
|
+
const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
|
|
142
|
+
job.snapshot.output = text(update);
|
|
143
|
+
if (job.snapshot.state === "running") onUpdate?.(update);
|
|
144
|
+
}, ctx)).then(requireSuccessfulCommandResult).then((result) => {
|
|
145
|
+
job.snapshot.output = text(result);
|
|
146
|
+
job.snapshot.state = "completed";
|
|
147
|
+
const fullOutputPath = (result.details as { fullOutputPath?: string } | undefined)?.fullOutputPath;
|
|
148
|
+
if (fullOutputPath) job.snapshot.fullOutputPath = fullOutputPath;
|
|
149
|
+
return result;
|
|
150
|
+
}, (error: unknown) => {
|
|
151
|
+
job.snapshot.state = controller.signal.aborted ? "cancelled" : "failed";
|
|
152
|
+
job.snapshot.output = String(error).slice(-MAX_OUTPUT_BYTES);
|
|
153
|
+
throw error;
|
|
154
|
+
}).finally(() => {
|
|
155
|
+
if (timer) clearTimeout(timer);
|
|
156
|
+
job.snapshot.endedAt = Date.now();
|
|
157
|
+
persist();
|
|
158
|
+
});
|
|
159
|
+
job.settled = execution.then(() => {}, () => {});
|
|
160
|
+
const result = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => undefined)]);
|
|
161
|
+
if (result) return result.value;
|
|
162
|
+
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 } } };
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
},
|
|
166
|
+
tool(): ToolDefinition {
|
|
167
|
+
return {
|
|
168
|
+
name: CHILD_COMMAND_TOOL, label: "Child command",
|
|
169
|
+
description: "Inspect or cancel bash commands owned by this child. Cancellation stops only the selected command, not the agent. Check terminal state before finishing.",
|
|
170
|
+
parameters: Type.Object({ action: Type.String({ enum: ["status", "cancel"] }), toolCallId: Type.Optional(Type.String()), waitMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 30_000 })) }),
|
|
171
|
+
async execute(_id, params, signal) {
|
|
172
|
+
const { action, toolCallId, waitMs = 0 } = params as { action: "status" | "cancel"; toolCallId?: string; waitMs?: number };
|
|
173
|
+
operate(action, toolCallId);
|
|
174
|
+
const job = toolCallId ? jobs.get(toolCallId) : undefined;
|
|
175
|
+
if (job && active(job) && waitMs > 0) await waitForCommand(job.settled, waitMs, signal);
|
|
176
|
+
const snapshot = operate("status", toolCallId);
|
|
177
|
+
return { content: [{ type: "text", text: JSON.stringify(snapshot) }], details: snapshot };
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function waitForCommand(settled: Promise<void>, waitMs: number, signal?: AbortSignal): Promise<void> {
|
|
185
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
186
|
+
let abort!: () => void;
|
|
187
|
+
const wait = new Promise<void>((resolve, reject) => {
|
|
188
|
+
timer = setTimeout(resolve, waitMs);
|
|
189
|
+
abort = () => reject(new Error("Command wait aborted; command remains managed by the child."));
|
|
190
|
+
if (signal?.aborted) abort();
|
|
191
|
+
else signal?.addEventListener("abort", abort, { once: true });
|
|
192
|
+
});
|
|
193
|
+
try { await Promise.race([settled, wait]); }
|
|
194
|
+
finally { clearTimeout(timer!); signal?.removeEventListener("abort", abort); }
|
|
195
|
+
}
|
|
196
|
+
function commandReplyPath(channelDir: string, id: string): string {
|
|
197
|
+
return path.join(channelDir, "command-replies", `${id}.json`);
|
|
198
|
+
}
|
|
199
|
+
export async function controlChildCommand(channelDir: string, operation: CommandOperation, toolCallId?: string, signal?: AbortSignal): Promise<ChildCommandState> {
|
|
200
|
+
const current = readChildCommandState(channelDir);
|
|
201
|
+
if (!current) throw new Error("No command controller is available for this child. Command controls require a local native Pi child with bash.");
|
|
202
|
+
if (current.closed) {
|
|
203
|
+
if (operation === "status") {
|
|
204
|
+
if (toolCallId === undefined) return current;
|
|
205
|
+
const command = current.commands.find((entry) => entry.toolCallId === toolCallId);
|
|
206
|
+
if (!command) throw new Error(`No retained command '${toolCallId}' in this child session.`);
|
|
207
|
+
return { ...current, commands: [command] };
|
|
208
|
+
}
|
|
209
|
+
throw new Error("Child command controller is closed.");
|
|
210
|
+
}
|
|
211
|
+
if (operation !== "status" && !toolCallId) throw new Error("An exact toolCallId is required; command controls never target the next command.");
|
|
212
|
+
const id = randomUUID();
|
|
213
|
+
const deadlineAt = Date.now() + 5_000;
|
|
214
|
+
const request: CommandRequest = { type: "command", id, ownerId: current.ownerId, operation, ...(toolCallId ? { toolCallId } : {}), deadlineAt };
|
|
215
|
+
requestAsyncCommand(channelDir, request);
|
|
216
|
+
const replyPath = commandReplyPath(channelDir, id);
|
|
217
|
+
try {
|
|
218
|
+
while (Date.now() < deadlineAt) {
|
|
219
|
+
if (signal?.aborted) throw new Error("Command control wait aborted; delivery may still be pending.");
|
|
220
|
+
try {
|
|
221
|
+
const reply = JSON.parse(fs.readFileSync(replyPath, "utf8")) as { state?: ChildCommandState; error?: string };
|
|
222
|
+
if (reply.error) throw new Error(reply.error);
|
|
223
|
+
if (reply.state) return reply.state;
|
|
224
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
225
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
226
|
+
}
|
|
227
|
+
throw new Error("Command control acknowledgement timed out. Inspect command status; cancellation is not confirmed.");
|
|
228
|
+
} finally { fs.rmSync(replyPath, { force: true }); }
|
|
229
|
+
}
|
|
@@ -3,7 +3,7 @@ import { listBackgroundWorkProviders } from "../../api/background-work.ts";
|
|
|
3
3
|
import { ReadonlyDrainObservation } from "./readonly-drain-observation.ts";
|
|
4
4
|
import registerFanoutChildSubagentExtension, { createChildSafeState } from "../../extension/fanout-child.ts";
|
|
5
5
|
import registerSubagentFastModeExtension from "./fast-mode-extension.ts";
|
|
6
|
-
import registerSubagentPromptRuntime from "./subagent-prompt-runtime.ts";
|
|
6
|
+
import registerSubagentPromptRuntime, { registerSubagentPromptBoundary } from "./subagent-prompt-runtime.ts";
|
|
7
7
|
import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
|
|
8
8
|
import type { ChildToolDiagnostic } from "./tool-availability.ts";
|
|
9
9
|
import type { ChildSessionLaunch } from "./child-session.ts";
|
|
@@ -164,11 +164,12 @@ function childHooks(config: ChildRuntimeConfig, capture?: OwnedCapture, holdFina
|
|
|
164
164
|
registerSubagentPromptRuntime(pi, runtime, proof.observation);
|
|
165
165
|
} },
|
|
166
166
|
];
|
|
167
|
+
if (config.fast) hooks.push({ name: "pi-subagents:fast-mode", factory: (pi) => registerSubagentFastModeExtension(pi) });
|
|
168
|
+
if (config.fanoutChild) hooks.push({ name: "pi-subagents:fanout-child", factory: (pi) => registerFanoutChildSubagentExtension(pi, runtime) });
|
|
169
|
+
hooks.push({ name: "pi-subagents:prompt-boundary", factory: (pi) => registerSubagentPromptBoundary(pi, runtime) });
|
|
167
170
|
if (proof) {
|
|
168
171
|
proof.factories = hooks.map((hook) => hook.factory);
|
|
169
172
|
promptProofs.set(hooks[0]!.factory, proof);
|
|
170
173
|
}
|
|
171
|
-
if (config.fast) hooks.push({ name: "pi-subagents:fast-mode", factory: (pi) => registerSubagentFastModeExtension(pi) });
|
|
172
|
-
if (config.fanoutChild) hooks.push({ name: "pi-subagents:fanout-child", factory: (pi) => registerFanoutChildSubagentExtension(pi, runtime) });
|
|
173
174
|
return hooks;
|
|
174
175
|
}
|
|
@@ -67,6 +67,8 @@ export interface BuildInProcessChildLaunchInput {
|
|
|
67
67
|
remoteSkillNames?: string[];
|
|
68
68
|
remoteReads?: string[] | false;
|
|
69
69
|
parentSessionId?: string;
|
|
70
|
+
/** The launching session's file; a new child session records it as its parent. */
|
|
71
|
+
parentSessionFile?: string;
|
|
70
72
|
forkCacheKey?: string;
|
|
71
73
|
sessionEnabled: boolean;
|
|
72
74
|
sessionDir?: string;
|
|
@@ -348,6 +350,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
|
|
|
348
350
|
...(input.projectTrusted !== undefined ? { projectTrusted: input.projectTrusted } : {}),
|
|
349
351
|
...(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] } : {}) } } : {}),
|
|
350
352
|
storage: childStorage(input),
|
|
353
|
+
...(input.parentSessionFile ? { parentSessionFile: input.parentSessionFile } : {}),
|
|
351
354
|
...(input.model ? { model: input.model } : {}),
|
|
352
355
|
...(toolPlan.explicitToolAllowlist ? { tools: toolPlan.effectiveToolAllowlist } : {}),
|
|
353
356
|
...(toolPlan.builtinMcpTools?.length ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
|
|
@@ -11,7 +11,9 @@ import * as fs from "node:fs";
|
|
|
11
11
|
import * as path from "node:path";
|
|
12
12
|
import { pathToFileURL } from "node:url";
|
|
13
13
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
14
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
|
+
import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
import { CHILD_COMMAND_TOOL, createChildCommandRuntime } from "./child-commands.ts";
|
|
16
|
+
import { supervisorChannelDir } from "./child-tool-plan.ts";
|
|
15
17
|
import { pinChildCacheRetention } from "../../shared/child-cache-retention.ts";
|
|
16
18
|
import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
|
|
17
19
|
import { resolvePackageSubpath } from "../background/runner-aliases.ts";
|
|
@@ -62,6 +64,8 @@ export interface ChildSessionLaunch {
|
|
|
62
64
|
/** Logical names resolved only by the remote ambient package. */
|
|
63
65
|
remoteResources?: { agent: string; skills?: string[]; toolCeiling?: string[]; reads?: string[] | false };
|
|
64
66
|
storage: ChildSessionStorage;
|
|
67
|
+
/** The launching session's file, recorded as the new child session's `parentSession` header like Pi's forks. */
|
|
68
|
+
parentSessionFile?: string;
|
|
65
69
|
/** Model reference as the agent config names it (`provider/id`, optionally `:thinking`). */
|
|
66
70
|
model?: string;
|
|
67
71
|
/** Explicit tool allowlist; undefined keeps pi's defaults. */
|
|
@@ -111,12 +115,18 @@ export interface ChildSession {
|
|
|
111
115
|
abort(): Promise<void>;
|
|
112
116
|
/** Emits `session_shutdown` to the child's extensions and disposes the session; resolves once that shutdown work is done. */
|
|
113
117
|
dispose(): Promise<void>;
|
|
118
|
+
/** Final settlement check for commands owned by this child; unfinished commands are cancelled and reject completion. */
|
|
119
|
+
finishCommands?(): Promise<void>;
|
|
114
120
|
/** True while Pi still has steering or follow-up input that has not started a turn. */
|
|
115
121
|
hasQueuedMessages?(): boolean;
|
|
116
122
|
readonly messages: readonly AgentMessage[];
|
|
117
123
|
readonly sessionFile: string | undefined;
|
|
118
124
|
readonly sessionId: string;
|
|
119
125
|
readonly modelId: string | undefined;
|
|
126
|
+
/** Provider id of the selected model when this child inherited that provider from the parent's registry instead of loading its extension. */
|
|
127
|
+
readonly inheritedProvider?: string;
|
|
128
|
+
/** Live provider/id of the selected model when Pi marks it virtual (`api === "pi-virtual"`); assistant messages then name the dispatched physical model. */
|
|
129
|
+
readonly virtualModelId?: string;
|
|
120
130
|
readonly contextWindow?: number;
|
|
121
131
|
readonly machineEvidence?: { machineId: string; initial?: HerdrRemoteGitStatus; final?: HerdrRemoteGitStatus };
|
|
122
132
|
/** Event-updated pane-native status; reading it performs no network work. */
|
|
@@ -160,7 +170,8 @@ type ModelRuntimeInstance = Awaited<ReturnType<PiCodingAgentModule["ModelRuntime
|
|
|
160
170
|
|
|
161
171
|
export type ParentProviderRegistry = Pick<ModelRuntimeInstance, "getRegisteredProviderIds" | "getRegisteredProviderConfig" | "getRegisteredNativeProvider">;
|
|
162
172
|
|
|
163
|
-
|
|
173
|
+
/** Registers the parent's providers this child did not claim itself and returns their ids. */
|
|
174
|
+
function inheritParentProviders(modelRuntime: ModelRuntimeInstance, parentProviders: ParentProviderRegistry, claimedProviderIds: ReadonlySet<string>, onError: ((error: ChildSessionExtensionError) => void) | undefined): Set<string> {
|
|
164
175
|
let providerIds: readonly string[];
|
|
165
176
|
try {
|
|
166
177
|
providerIds = parentProviders.getRegisteredProviderIds();
|
|
@@ -168,7 +179,7 @@ function inheritParentProviders(modelRuntime: ModelRuntimeInstance, parentProvid
|
|
|
168
179
|
onError?.({ extensionPath: "<parent-providers>", event: "inherit_provider", error });
|
|
169
180
|
throw new Error(`Failed to enumerate parent providers: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
170
181
|
}
|
|
171
|
-
|
|
182
|
+
const inherited = new Set<string>();
|
|
172
183
|
for (const providerId of new Set(providerIds)) {
|
|
173
184
|
if (claimedProviderIds.has(providerId)) continue;
|
|
174
185
|
try {
|
|
@@ -177,27 +188,49 @@ function inheritParentProviders(modelRuntime: ModelRuntimeInstance, parentProvid
|
|
|
177
188
|
if (native) modelRuntime.registerNativeProvider(native);
|
|
178
189
|
else if (config) modelRuntime.registerProvider(providerId, config);
|
|
179
190
|
else throw new Error(`Parent provider '${providerId}' has no registered native provider or config.`);
|
|
180
|
-
|
|
191
|
+
inherited.add(providerId);
|
|
181
192
|
} catch (error) {
|
|
182
193
|
onError?.({ extensionPath: `<parent-provider:${providerId}>`, event: "inherit_provider", error });
|
|
183
194
|
throw new Error(`Failed to inherit parent provider '${providerId}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
184
195
|
}
|
|
185
196
|
}
|
|
186
|
-
return
|
|
197
|
+
return inherited;
|
|
187
198
|
}
|
|
188
199
|
|
|
189
200
|
const CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime>";
|
|
201
|
+
const CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
|
|
190
202
|
|
|
191
203
|
/** The prompt runtime filters parent-only context before ambient extensions inspect
|
|
192
|
-
* the child prompt
|
|
193
|
-
*
|
|
194
|
-
function
|
|
195
|
-
const
|
|
196
|
-
|
|
204
|
+
* the child prompt, and the boundary hook appends the child boundary after every
|
|
205
|
+
* extension has added its prompt sections. Every other extension keeps its order. */
|
|
206
|
+
function orderChildPromptHooks<T extends { extensions: Array<{ path: string }> }>(result: T): T {
|
|
207
|
+
const runtime = result.extensions.filter(({ path }) => path === CHILD_PROMPT_RUNTIME_EXTENSION_PATH);
|
|
208
|
+
const boundary = result.extensions.filter(({ path }) => path === CHILD_PROMPT_BOUNDARY_EXTENSION_PATH);
|
|
209
|
+
const others = result.extensions.filter(({ path }) => path !== CHILD_PROMPT_RUNTIME_EXTENSION_PATH && path !== CHILD_PROMPT_BOUNDARY_EXTENSION_PATH);
|
|
210
|
+
return { ...result, extensions: [...runtime, ...others, ...boundary] };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Ambient bash overrides keep their original backend and priority. */
|
|
214
|
+
function prioritizeChildCommandRuntime<T extends { extensions: Array<{ path: string; tools?: Map<string, unknown> }> }>(result: T): T {
|
|
215
|
+
const index = result.extensions.findIndex(({ path }) => path === "<inline:pi-subagents:commands>");
|
|
216
|
+
if (index < 0) return result;
|
|
217
|
+
if (result.extensions.some((extension, otherIndex) => otherIndex !== index && extension.tools?.has("bash"))) {
|
|
218
|
+
const extensions = result.extensions.filter((_, otherIndex) => otherIndex !== index);
|
|
219
|
+
if (!extensions.some((extension) => extension.tools?.has(CHILD_COMMAND_TOOL))) {
|
|
220
|
+
const commands = result.extensions[index]!;
|
|
221
|
+
const registered = commands.tools!.get(CHILD_COMMAND_TOOL) as { definition: ToolDefinition };
|
|
222
|
+
const reason = "Native command controls are unavailable with the active custom bash backend. Use that backend's own command controls.";
|
|
223
|
+
extensions.push({ ...commands, tools: new Map([[CHILD_COMMAND_TOOL, { ...registered, definition: {
|
|
224
|
+
...registered.definition, description: reason,
|
|
225
|
+
execute: async () => { throw new Error(reason); },
|
|
226
|
+
} }]]) });
|
|
227
|
+
}
|
|
228
|
+
return { ...result, extensions };
|
|
229
|
+
}
|
|
230
|
+
if (index === 0) return result;
|
|
197
231
|
const extensions = [...result.extensions];
|
|
198
|
-
const [
|
|
199
|
-
|
|
200
|
-
extensions.unshift(promptRuntime);
|
|
232
|
+
const [commands] = extensions.splice(index, 1);
|
|
233
|
+
extensions.unshift(commands!);
|
|
201
234
|
return { ...result, extensions };
|
|
202
235
|
}
|
|
203
236
|
|
|
@@ -242,7 +275,9 @@ function restoreProcessEnv(saved: Array<[string, string | undefined]>): void {
|
|
|
242
275
|
* default, which the child's `tools` allowlist cannot declare. Registering the selected names as
|
|
243
276
|
* `direct` makes them model-declared and callable; `hidden` stays hidden. A name counts only when
|
|
244
277
|
* the tool's raw identity, its `<server>/<tool>` label, matches the granting selector: Pi can give
|
|
245
|
-
* the sanitized name of `srv/a.b` to `srv/a_b`.
|
|
278
|
+
* the sanitized name of `srv/a.b` to `srv/a_b`. The selector's server part may be the configured
|
|
279
|
+
* name or its `-`→`_` form, which Pi's namespace uses: Pi refuses two servers whose names differ
|
|
280
|
+
* only in `-` and `_`, so both forms name the same server. Every other tool the extension registers becomes
|
|
246
281
|
* `hidden`, so neither codemode nor `ctx.executeTool()` can call it, independent of the `tools`
|
|
247
282
|
* allowlist. The `builtin` entry loads
|
|
248
283
|
* through the explicit `builtin:mcp` path even with `noExtensions`, and `replaceable` lets an
|
|
@@ -253,10 +288,16 @@ function selectedBuiltinMcpExtension(pi: PiCodingAgentModule, selections: Readon
|
|
|
253
288
|
const createMcpExtension = (pi as { createMcpExtension?: () => (api: ExtensionAPI) => void | Promise<void> }).createMcpExtension;
|
|
254
289
|
if (typeof createMcpExtension !== "function") throw new Error(`Selected built-in MCP tools (${selections.map(({ name }) => name).join(", ")}) need a Pi version with built-in MCP.`);
|
|
255
290
|
const selectors = new Map(selections.map(({ name, selector }) => [name, selector]));
|
|
291
|
+
const split = (value: string) => {
|
|
292
|
+
const slash = value.indexOf("/");
|
|
293
|
+
return { server: (slash === -1 ? value : value.slice(0, slash)).replace(/-/g, "_"), tool: slash === -1 ? undefined : value.slice(slash + 1) };
|
|
294
|
+
};
|
|
256
295
|
const granted = (tool: { name: string; label?: string; exposure?: string }) => {
|
|
257
296
|
const selector = selectors.get(tool.name);
|
|
258
297
|
if (selector === undefined || tool.exposure === "hidden" || tool.label === undefined) return false;
|
|
259
|
-
|
|
298
|
+
const want = split(selector);
|
|
299
|
+
const have = split(tool.label);
|
|
300
|
+
return have.tool !== undefined && have.server === want.server && (want.tool === undefined || want.tool === have.tool);
|
|
260
301
|
};
|
|
261
302
|
const mcp = createMcpExtension();
|
|
262
303
|
const factory = (api: ExtensionAPI) => mcp(new Proxy(api, {
|
|
@@ -311,6 +352,25 @@ function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModu
|
|
|
311
352
|
}
|
|
312
353
|
}
|
|
313
354
|
if (Array.isArray(runtime.pendingNativeProviderRegistrations)) runtime.pendingNativeProviderRegistrations = [];
|
|
355
|
+
// Pi core flushes pendingVirtualModelRegistrations when a session binds extensions
|
|
356
|
+
// (agent-session-services), but this factory resolves the requested model before that
|
|
357
|
+
// binding, so an extension-registered virtual model never resolves for the child. The
|
|
358
|
+
// structural cast keeps compiling against SDK versions that predate virtual models;
|
|
359
|
+
// there the queue is absent and the loop is a no-op.
|
|
360
|
+
const virtualModelRuntime = modelRuntime as ModelRuntimeInstance & { registerVirtualModel?: (definition: unknown) => void };
|
|
361
|
+
const virtualModelQueue = runtime as { pendingVirtualModelRegistrations?: Array<{ definition: unknown; extensionPath: string }> };
|
|
362
|
+
const pendingVirtualModelRegistrations = virtualModelQueue.pendingVirtualModelRegistrations ?? [];
|
|
363
|
+
for (const { definition, extensionPath } of pendingVirtualModelRegistrations) {
|
|
364
|
+
if (typeof virtualModelRuntime.registerVirtualModel !== "function") break;
|
|
365
|
+
try {
|
|
366
|
+
virtualModelRuntime.registerVirtualModel(definition);
|
|
367
|
+
registered = true;
|
|
368
|
+
} catch (error) {
|
|
369
|
+
onError?.({ extensionPath, event: "register_virtual_model", error });
|
|
370
|
+
if (requiredPaths.has(extensionPath)) throw new Error(`Required child extension virtual model registration failed for '${extensionPath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (Array.isArray(virtualModelQueue.pendingVirtualModelRegistrations)) virtualModelQueue.pendingVirtualModelRegistrations = [];
|
|
314
374
|
return { claimedProviderIds, registered };
|
|
315
375
|
}
|
|
316
376
|
|
|
@@ -389,6 +449,11 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
389
449
|
? await pi.ModelRuntime.create()
|
|
390
450
|
: await sharedRuntime(pi);
|
|
391
451
|
const agentDir = getAgentDir();
|
|
452
|
+
const commands = launch.runtime.runId && launch.runtime.agent && launch.runtime.childIndex !== undefined
|
|
453
|
+
&& launch.tools?.includes("bash") && launch.tools.includes(CHILD_COMMAND_TOOL)
|
|
454
|
+
&& !launch.excludeTools?.includes("bash") && !launch.excludeTools?.includes(CHILD_COMMAND_TOOL)
|
|
455
|
+
&& typeof pi.createBashTool === "function"
|
|
456
|
+
? createChildCommandRuntime(supervisorChannelDir(launch.runtime.runId, launch.runtime.agent, launch.runtime.childIndex)) : undefined;
|
|
392
457
|
const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir, { projectTrusted: launch.projectTrusted });
|
|
393
458
|
// Foreground children share Pi's global theme with the parent, so reinitializing it
|
|
394
459
|
// would overwrite the parent's active light/dark appearance. Detached runners have
|
|
@@ -418,11 +483,31 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
418
483
|
noThemes: true,
|
|
419
484
|
noContextFiles: launch.noContextFiles,
|
|
420
485
|
additionalExtensionPaths: builtinMcp ? [...launch.extensionPaths, "builtin:mcp"] : launch.extensionPaths,
|
|
421
|
-
extensionFactories: [...launch.hooks, ...
|
|
422
|
-
|
|
486
|
+
extensionFactories: [...launch.hooks, ...(commands ? [{ name: "pi-subagents:commands", factory: (api: ExtensionAPI) => {
|
|
487
|
+
api.registerTool(commands.wrap(pi.createBashTool(launch.cwd, { commandPrefix: settingsManager.getShellCommandPrefix(), shellPath: settingsManager.getShellPath() }) as unknown as ToolDefinition));
|
|
488
|
+
api.registerTool(commands.tool());
|
|
489
|
+
} }] : []), ...codemode, ...(builtinMcp ? [builtinMcp] : [])],
|
|
490
|
+
extensionsOverride: (result) => orderChildPromptHooks(prioritizeChildCommandRuntime(result)),
|
|
423
491
|
...(launch.systemPrompt !== undefined ? { systemPrompt: launch.systemPrompt } : {}),
|
|
424
492
|
...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
|
|
425
493
|
});
|
|
494
|
+
// pi's own hosts emit `session_shutdown` before disposing a session so the
|
|
495
|
+
// extensions loaded into it (ambient extensions included) release their
|
|
496
|
+
// watchers, servers, and timers. Do the same, then dispose.
|
|
497
|
+
const shutdownSession = async (session: Awaited<ReturnType<PiCodingAgentModule["createAgentSession"]>>["session"]): Promise<void> => {
|
|
498
|
+
try {
|
|
499
|
+
await commands?.shutdown();
|
|
500
|
+
const runner = session.extensionRunner;
|
|
501
|
+
if (runner.hasHandlers("session_shutdown")) {
|
|
502
|
+
await Promise.race([runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise<void>((resolve) => setTimeout(resolve, shutdownTimeoutMs).unref?.())]);
|
|
503
|
+
}
|
|
504
|
+
} catch (error) {
|
|
505
|
+
launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
|
|
506
|
+
} finally {
|
|
507
|
+
session.dispose();
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
let inheritedProviders = new Set<string>();
|
|
426
511
|
const open = async () => {
|
|
427
512
|
const requiredPaths = new Set((launch.requiredExtensions ?? []).map(({ path }) => path));
|
|
428
513
|
const savedTransientEnv = captureProcessEnv(launch.transientProcessEnv);
|
|
@@ -433,10 +518,8 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
433
518
|
? loader.getExtensions().errors.filter(({ path }) => requiredPaths.has(path)) : [];
|
|
434
519
|
if (loadErrors.length > 0) throw new Error(`Required child extension failed to load: ${loadErrors.map(({ path, error }) => `${path}: ${error}`).join("; ")}`);
|
|
435
520
|
const queued = flushQueuedProviderRegistrations(loader, modelRuntime, launch.onExtensionError, requiredPaths);
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
: false;
|
|
439
|
-
if (queued.registered || inherited) {
|
|
521
|
+
if (launch.parentProviderRegistry) inheritedProviders = inheritParentProviders(modelRuntime, launch.parentProviderRegistry, queued.claimedProviderIds, launch.onExtensionError);
|
|
522
|
+
if (queued.registered || inheritedProviders.size > 0) {
|
|
440
523
|
try {
|
|
441
524
|
await modelRuntime.refresh({ allowNetwork: false });
|
|
442
525
|
} catch (error) {
|
|
@@ -444,13 +527,19 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
444
527
|
throw new Error(`Failed to refresh child providers: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
445
528
|
}
|
|
446
529
|
}
|
|
530
|
+
const newSessionOptions = launch.parentSessionFile ? { parentSession: launch.parentSessionFile } : undefined;
|
|
531
|
+
const newSessionFile = launch.storage.kind === "file" && !fs.existsSync(launch.storage.sessionFile);
|
|
447
532
|
const sessionManager = launch.storage.kind === "file"
|
|
448
533
|
? pi.SessionManager.open(launch.storage.sessionFile, undefined, launch.cwd)
|
|
449
534
|
: launch.storage.kind === "dir"
|
|
450
|
-
? pi.SessionManager.create(launch.cwd, launch.storage.sessionDir)
|
|
535
|
+
? pi.SessionManager.create(launch.cwd, launch.storage.sessionDir, newSessionOptions)
|
|
451
536
|
: launch.storage.kind === "memory"
|
|
452
|
-
? pi.SessionManager.inMemory(launch.cwd)
|
|
453
|
-
: pi.SessionManager.create(launch.cwd);
|
|
537
|
+
? pi.SessionManager.inMemory(launch.cwd, newSessionOptions)
|
|
538
|
+
: pi.SessionManager.create(launch.cwd, undefined, newSessionOptions);
|
|
539
|
+
// SessionManager.open takes no parent for a file it is about to create, so set it on the
|
|
540
|
+
// header Pi writes with the first assistant message. Forked and resumed files keep theirs.
|
|
541
|
+
const header = newSessionFile && launch.parentSessionFile ? sessionManager.getHeader() : null;
|
|
542
|
+
if (header) header.parentSession = launch.parentSessionFile;
|
|
454
543
|
const resolvedModel = launch.model
|
|
455
544
|
? pi.resolveCliModel({ cliModel: launch.model, modelRuntime })
|
|
456
545
|
: undefined;
|
|
@@ -473,14 +562,27 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
473
562
|
// (registration and session_start); restore transient keys so an
|
|
474
563
|
// in-process child cannot leak them into the host process.
|
|
475
564
|
restoreProcessEnv(savedTransientEnv);
|
|
565
|
+
// Pi reports handler failures through onError instead of throwing, so required startup failures must be collected here.
|
|
566
|
+
const requiredStartupErrors: string[] = [];
|
|
567
|
+
let binding = true;
|
|
476
568
|
try {
|
|
477
569
|
await session.bindExtensions({
|
|
478
570
|
mode: "print",
|
|
479
|
-
onError: (error) =>
|
|
571
|
+
onError: (error) => {
|
|
572
|
+
if (binding && requiredPaths.has(error.extensionPath)) requiredStartupErrors.push(`${error.extensionPath} (${error.event}): ${error.error}`);
|
|
573
|
+
launch.onExtensionError?.({ extensionPath: error.extensionPath, event: error.event, error: error.error });
|
|
574
|
+
},
|
|
480
575
|
});
|
|
481
576
|
} catch (error) {
|
|
482
577
|
session.dispose();
|
|
483
578
|
throw error;
|
|
579
|
+
} finally {
|
|
580
|
+
binding = false;
|
|
581
|
+
}
|
|
582
|
+
if (requiredStartupErrors.length > 0) {
|
|
583
|
+
// Binding finished, so the other extensions' session_start handlers ran and may hold resources.
|
|
584
|
+
await shutdownSession(session);
|
|
585
|
+
throw new Error(`Required child extension failed during startup: ${requiredStartupErrors.join("; ")}`);
|
|
484
586
|
}
|
|
485
587
|
return session;
|
|
486
588
|
};
|
|
@@ -488,21 +590,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
488
590
|
loading = opened;
|
|
489
591
|
const session = await opened;
|
|
490
592
|
let pending: Promise<void> | undefined;
|
|
491
|
-
|
|
492
|
-
// extensions loaded into it (ambient extensions included) release their
|
|
493
|
-
// watchers, servers, and timers. Do the same, then dispose.
|
|
494
|
-
const shutdown = async (): Promise<void> => {
|
|
495
|
-
try {
|
|
496
|
-
const runner = session.extensionRunner;
|
|
497
|
-
if (runner.hasHandlers("session_shutdown")) {
|
|
498
|
-
await Promise.race([runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise<void>((resolve) => setTimeout(resolve, shutdownTimeoutMs).unref?.())]);
|
|
499
|
-
}
|
|
500
|
-
} catch (error) {
|
|
501
|
-
launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
|
|
502
|
-
} finally {
|
|
503
|
-
session.dispose();
|
|
504
|
-
}
|
|
505
|
-
};
|
|
593
|
+
const shutdown = () => shutdownSession(session);
|
|
506
594
|
// Outside the launch lock: MCP servers connect after `session_start` without reading the per-launch env.
|
|
507
595
|
if (builtinMcpTools.length) {
|
|
508
596
|
const disposed = () => disposals !== disposalsAtStart;
|
|
@@ -519,6 +607,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
519
607
|
const child: ChildSession = {
|
|
520
608
|
subscribe: (listener) => session.subscribe((event) => listener(event as unknown as ChildSessionEvent)),
|
|
521
609
|
prompt: (text) => session.prompt(text),
|
|
610
|
+
...(commands ? { finishCommands: () => commands.finish() } : {}),
|
|
522
611
|
steer: (text) => session.steer(text).then(() => undefined),
|
|
523
612
|
followUp: (text) => session.followUp(text).then(() => undefined),
|
|
524
613
|
abort: () => session.abort(),
|
|
@@ -537,6 +626,8 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
537
626
|
get sessionFile() { return session.sessionFile; },
|
|
538
627
|
get sessionId() { return session.sessionId; },
|
|
539
628
|
get modelId() { return session.model ? `${session.model.provider}/${session.model.id}` : undefined; },
|
|
629
|
+
get inheritedProvider() { return session.model && inheritedProviders.has(session.model.provider) ? session.model.provider : undefined; },
|
|
630
|
+
get virtualModelId() { return session.model?.api === "pi-virtual" ? `${session.model.provider}/${session.model.id}` : undefined; },
|
|
540
631
|
get contextWindow() { return session.model?.contextWindow; },
|
|
541
632
|
};
|
|
542
633
|
live.add(child);
|