pi-subagents 0.83.1 → 0.85.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 +79 -0
- package/bundle/agents.js +3 -3
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/{chunk-5YIITCPD.js → chunk-3UZ5FVVJ.js} +322 -110
- package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
- package/bundle/{chunk-YXFJVCOL.js → chunk-CS4O36CZ.js} +11 -156
- package/bundle/{chunk-AHIFYGR3.js → chunk-DV2NCNPR.js} +22 -11
- package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
- package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
- package/bundle/{chunk-MABL3FUM.js → chunk-HFTBF7SG.js} +2 -1
- package/bundle/chunk-HXRB42AF.js +108 -0
- package/bundle/{chunk-UFL7IYCW.js → chunk-IQIWF2VX.js} +190 -1177
- package/bundle/{chunk-NPIYWVOD.js → chunk-JNXT3MPI.js} +15 -6
- package/bundle/{chunk-C7JMPU5F.js → chunk-JO67XSKD.js} +59 -27
- package/bundle/{chunk-UUP372DR.js → chunk-JWYG26RE.js} +223 -93
- package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
- package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
- package/bundle/{chunk-VLFZIN6D.js → chunk-KZ34KQQH.js} +9 -6
- package/bundle/{chunk-ZVOAMTUQ.js → chunk-L2ENOFVZ.js} +76 -58
- package/bundle/{chunk-RNIZLSEA.js → chunk-LGMILZNE.js} +323 -18
- package/bundle/{chunk-UYK5MZWE.js → chunk-LTPH2DXH.js} +247 -153
- package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
- package/bundle/{chunk-IPGZMQXV.js → chunk-O7CPL6H4.js} +183 -28
- package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
- package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
- package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
- package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
- package/bundle/{chunk-QP5ZWNIS.js → chunk-RV5OGHLO.js} +6 -3
- package/bundle/chunk-T5V5BRCL.js +1067 -0
- package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
- package/bundle/{chunk-F5DBXJ2G.js → chunk-WOVMHDES.js} +234 -182
- package/bundle/control-channel.js +2 -2
- package/bundle/index.js +1 -1
- package/bundle/intercom-bridge.js +2 -2
- package/bundle/preflight.js +8 -8
- package/bundle/project-panes.js +3 -3
- package/docs/agents.md +17 -2
- package/docs/configuration.md +2 -2
- package/docs/extension-api.md +16 -1
- package/docs/workflows.md +30 -2
- package/package.json +1 -1
- package/src/agents/agent-management.js +27 -11
- package/src/agents/agent-memory.d.ts +1 -4
- package/src/agents/agent-memory.js +1 -4
- package/src/agents/agents.d.ts +1 -3
- package/src/agents/agents.js +7 -6
- package/src/agents/frontmatter.js +1 -8
- package/src/agents/global-npm-root.d.ts +1 -0
- package/src/agents/global-npm-root.js +11 -3
- package/src/agents/skills.d.ts +0 -3
- package/src/agents/skills.js +0 -3
- package/src/extension/config.js +7 -1
- package/src/extension/herdr-pi-bridge.js +10 -2
- package/src/extension/index.d.ts +0 -13
- package/src/extension/index.js +43 -32
- package/src/extension/public-execution.d.ts +1 -0
- package/src/extension/public-execution.js +4 -0
- package/src/extension/reply-workflow-script.js +24 -4
- package/src/extension/schemas.d.ts +8 -3
- package/src/extension/schemas.js +5 -3
- package/src/extension/session-switch.d.ts +25 -0
- package/src/extension/session-switch.js +138 -0
- package/src/extension/subagent-guide.d.ts +1 -1
- package/src/extension/subagent-guide.js +1 -1
- package/src/extension/subagent-launch-tool.d.ts +25 -0
- package/src/extension/subagent-launch-tool.js +48 -0
- package/src/extension/tool-activation.js +25 -11
- package/src/extension/tool-description.js +6 -0
- package/src/inspectors/herdr/actions.d.ts +0 -1
- package/src/inspectors/herdr/actions.js +0 -1
- package/src/inspectors/session-roots-codec.d.ts +0 -1
- package/src/inspectors/session-roots-codec.js +0 -1
- package/src/inspectors/tmux/actions.d.ts +0 -1
- package/src/inspectors/tmux/actions.js +0 -1
- package/src/integrations/herdr-status.js +3 -8
- package/src/intercom/native-supervisor-channel.js +65 -9
- package/src/runs/background/async-execution.d.ts +8 -9
- package/src/runs/background/async-execution.js +77 -27
- package/src/runs/background/async-job-tracker.js +12 -0
- package/src/runs/background/async-resume.d.ts +2 -1
- package/src/runs/background/async-resume.js +112 -39
- package/src/runs/background/async-retention.d.ts +1 -0
- package/src/runs/background/async-retention.js +22 -11
- package/src/runs/background/auto-drain.js +2 -1
- package/src/runs/background/boot-id.d.ts +1 -3
- package/src/runs/background/boot-id.js +1 -3
- package/src/runs/background/completion-batcher.d.ts +3 -4
- package/src/runs/background/completion-batcher.js +2 -3
- package/src/runs/background/control-channel.d.ts +0 -6
- package/src/runs/background/control-channel.js +0 -6
- package/src/runs/background/fleet-view.js +2 -3
- package/src/runs/background/notify.d.ts +0 -2
- package/src/runs/background/notify.js +0 -2
- package/src/runs/background/result-watcher.d.ts +1 -0
- package/src/runs/background/result-watcher.js +59 -29
- package/src/runs/background/resume-guidance.js +4 -2
- package/src/runs/background/retained-children.js +2 -1
- package/src/runs/background/run-child-session.d.ts +2 -1
- package/src/runs/background/run-child-session.js +10 -2
- package/src/runs/background/run-status.js +4 -3
- package/src/runs/background/scheduled-runs.d.ts +3 -1
- package/src/runs/background/scheduled-runs.js +13 -16
- package/src/runs/background/subagent-runner.d.ts +2 -4
- package/src/runs/background/subagent-runner.js +10 -6
- package/src/runs/background/subagent-wait.js +12 -15
- package/src/runs/background/wait-config.d.ts +2 -0
- package/src/runs/background/wait-config.js +17 -3
- package/src/runs/background/wait-tool.js +4 -2
- package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
- package/src/runs/background/workflow-terminal-proof.js +0 -1
- package/src/runs/foreground/execution.d.ts +0 -3
- package/src/runs/foreground/execution.js +17 -9
- package/src/runs/foreground/subagent-executor.d.ts +3 -2
- package/src/runs/foreground/subagent-executor.js +112 -26
- package/src/runs/shared/child-commands.js +15 -2
- package/src/runs/shared/child-hooks.d.ts +1 -7
- package/src/runs/shared/child-hooks.js +13 -5
- package/src/runs/shared/child-launch.js +6 -2
- package/src/runs/shared/child-runtime-config.d.ts +0 -1
- package/src/runs/shared/child-session.d.ts +3 -1
- package/src/runs/shared/child-session.js +22 -2
- package/src/runs/shared/child-tool-plan.d.ts +0 -1
- package/src/runs/shared/child-tool-plan.js +0 -1
- package/src/runs/shared/claude-code-adapter.js +11 -0
- package/src/runs/shared/external-cli-runner.js +26 -6
- package/src/runs/shared/herdr-connection.js +2 -1
- package/src/runs/shared/herdr-pane-host.d.ts +2 -2
- package/src/runs/shared/herdr-pane-host.js +17 -1
- package/src/runs/shared/herdr-placed-run.js +48 -22
- package/src/runs/shared/lane-metadata.d.ts +0 -1
- package/src/runs/shared/lane-metadata.js +0 -1
- package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
- package/src/runs/shared/model-resolution-diagnostic.d.ts +11 -1
- package/src/runs/shared/model-resolution-diagnostic.js +25 -0
- package/src/runs/shared/model-resolution.d.ts +2 -2
- package/src/runs/shared/model-resolution.js +7 -1
- package/src/runs/shared/model-scope.d.ts +1 -5
- package/src/runs/shared/model-scope.js +1 -5
- package/src/runs/shared/mutation-evidence.d.ts +1 -1
- package/src/runs/shared/mutation-evidence.js +52 -7
- package/src/runs/shared/nested-events.d.ts +1 -0
- package/src/runs/shared/nested-events.js +1 -1
- package/src/runs/shared/parallel-utils.d.ts +2 -1
- package/src/runs/shared/permissions.js +5 -3
- package/src/runs/shared/placement-host.d.ts +5 -1
- package/src/runs/shared/rex-pane-host.d.ts +0 -1
- package/src/runs/shared/rex-pane-host.js +0 -2
- package/src/runs/shared/run-launch-folder.d.ts +12 -0
- package/src/runs/shared/run-launch-folder.js +21 -0
- package/src/runs/shared/runner-launcher.d.ts +12 -1
- package/src/runs/shared/runner-launcher.js +16 -0
- package/src/runs/shared/single-output.d.ts +3 -3
- package/src/runs/shared/single-output.js +5 -3
- package/src/runs/shared/structured-output.d.ts +8 -0
- package/src/runs/shared/structured-output.js +30 -2
- package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
- package/src/runs/shared/subagent-prompt-runtime.js +4 -2
- package/src/runs/shared/tool-timeout.js +2 -1
- package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
- package/src/runs/shared/worktree-cleanup-plan.js +0 -1
- package/src/runs/shared/worktree.d.ts +3 -0
- package/src/runs/shared/worktree.js +20 -0
- package/src/shared/capacity-resilient-json.d.ts +1 -1
- package/src/shared/child-cache-retention.d.ts +1 -2
- package/src/shared/child-cache-retention.js +1 -2
- package/src/shared/fleet-transcript-reader.d.ts +51 -0
- package/src/shared/fleet-transcript-reader.js +333 -0
- package/src/shared/formatters.d.ts +0 -18
- package/src/shared/formatters.js +0 -18
- package/src/shared/session-succession.d.ts +16 -1
- package/src/shared/session-succession.js +41 -2
- package/src/shared/session-warnings.d.ts +7 -0
- package/src/shared/session-warnings.js +26 -0
- package/src/shared/settings.d.ts +0 -23
- package/src/shared/settings.js +3 -35
- package/src/shared/types.d.ts +28 -11
- package/src/shared/types.js +0 -12
- package/src/shared/utils.d.ts +0 -14
- package/src/shared/utils.js +0 -22
- package/src/shared/wait-tool-name.d.ts +8 -0
- package/src/shared/wait-tool-name.js +13 -0
- package/src/slash/slash-commands.js +2 -1
- package/src/slash/subagent-cost.d.ts +3 -2
- package/src/slash/subagent-cost.js +22 -3
- package/src/slash/subagents-admin.js +0 -1
- package/src/tui/fleet-status.d.ts +0 -5
- package/src/tui/fleet-status.js +4 -24
- package/src/tui/fleet-transcript.d.ts +1 -44
- package/src/tui/fleet-transcript.js +1 -327
- package/src/tui/fleet.js +6 -4
- package/src/tui/render.d.ts +0 -9
- package/src/tui/render.js +81 -47
- package/src/tui/subagent-messages.js +3 -2
- package/src/watchdog/register-child.d.ts +2 -3
- package/src/watchdog/register-child.js +2 -3
- package/src/watchdog/turn-delta.js +2 -1
- package/src/workflows/scripted-workflow.js +243 -20
- package/src/workflows/workflow-launch-record.d.ts +15 -6
- package/src/workflows/workflow-launch-record.js +30 -12
- package/src/workflows/workflow-resume-claim.js +2 -2
- package/src/workflows/workflow-resume.d.ts +1 -1
- package/src/workflows/workflow-resume.js +11 -8
- package/src/workflows/workflow-script-worker.d.ts +13 -0
- package/src/workflows/workflow-script-worker.js +79 -0
- package/workflow-script-process.cjs +36 -0
- package/workflow-script-worker.cjs +453 -176
|
@@ -15,7 +15,9 @@ const MAX_PARSER_LINE_BYTES = 256 * 1024;
|
|
|
15
15
|
const MAX_PARSER_STREAM_BYTES = 32 * 1024 * 1024;
|
|
16
16
|
const MAX_PARSER_OUTPUT_BYTES = 1024 * 1024;
|
|
17
17
|
const MAX_OVERSIZED_LINE_PREFIX_BYTES = 512;
|
|
18
|
-
|
|
18
|
+
// A skipped line keeps only its prefix in memory, and the stream limit still bounds the run.
|
|
19
|
+
// Claude Code puts a read image's base64 in its tool-result line twice.
|
|
20
|
+
const MAX_SKIPPABLE_LINE_BYTES = 8 * 1024 * 1024;
|
|
19
21
|
const PARSER_PROGRESS_INTERVAL_MS = 100;
|
|
20
22
|
export function buildExternalCliPrompt(systemInstructions, task) {
|
|
21
23
|
return `<System instructions>\n${systemInstructions.trim()}\n\n<Task>\n${task}`;
|
|
@@ -196,6 +198,22 @@ export function runExternalCli(input) {
|
|
|
196
198
|
let processTree;
|
|
197
199
|
let processPid;
|
|
198
200
|
let termination;
|
|
201
|
+
// A throwing onProcess fails the run only after the process is stopped and temp paths are removed.
|
|
202
|
+
let callbackFailed = false;
|
|
203
|
+
let callbackError;
|
|
204
|
+
const notifyProcess = (status) => {
|
|
205
|
+
try {
|
|
206
|
+
input.onProcess?.(status);
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (callbackFailed)
|
|
210
|
+
return;
|
|
211
|
+
callbackFailed = true;
|
|
212
|
+
callbackError = error;
|
|
213
|
+
if (!settled && processTree && processPid !== undefined)
|
|
214
|
+
termination ??= terminateExternalProcessTree(processPid, processTree);
|
|
215
|
+
}
|
|
216
|
+
};
|
|
199
217
|
const flushProgress = () => {
|
|
200
218
|
if (!latestProgress)
|
|
201
219
|
return;
|
|
@@ -217,7 +235,7 @@ export function runExternalCli(input) {
|
|
|
217
235
|
progressTimer.unref?.();
|
|
218
236
|
};
|
|
219
237
|
const terminate = (reason) => {
|
|
220
|
-
if (settled || timedOut || stopped || parserError)
|
|
238
|
+
if (settled || timedOut || stopped || parserError || callbackFailed)
|
|
221
239
|
return;
|
|
222
240
|
timedOut = reason === "timeout";
|
|
223
241
|
stopped = reason === "stop";
|
|
@@ -323,7 +341,7 @@ export function runExternalCli(input) {
|
|
|
323
341
|
stderrPath,
|
|
324
342
|
...(input.finalOutputPath ? { finalOutputPath: input.finalOutputPath } : {}),
|
|
325
343
|
};
|
|
326
|
-
|
|
344
|
+
notifyProcess(initialProcess);
|
|
327
345
|
child.stdout.on("data", (chunk) => {
|
|
328
346
|
parseChunk(chunk);
|
|
329
347
|
writeBoundedLog(child.stdout, stdoutStream, chunk, stdoutLog, limits.stdoutLogBytes);
|
|
@@ -380,7 +398,7 @@ export function runExternalCli(input) {
|
|
|
380
398
|
...(stdoutLog.total > stdoutLog.bytes ? { stdoutTruncated: true } : {}),
|
|
381
399
|
...(stderrLog.total > stderrLog.bytes ? { stderrTruncated: true } : {}),
|
|
382
400
|
};
|
|
383
|
-
|
|
401
|
+
notifyProcess(externalProcess);
|
|
384
402
|
const stderr = stderrTail.text().trim();
|
|
385
403
|
const parserFailure = parserError?.message ?? (parserTerminal?.state === "failed" ? parserTerminal.error ?? "External CLI parser reported terminal failure." : undefined);
|
|
386
404
|
const treeFailure = process.platform !== "win32" && treeProof?.state === "unknown"
|
|
@@ -415,11 +433,13 @@ export function runExternalCli(input) {
|
|
|
415
433
|
reject(cleanupError);
|
|
416
434
|
return;
|
|
417
435
|
}
|
|
418
|
-
if (
|
|
436
|
+
if (callbackFailed)
|
|
437
|
+
reject(callbackError);
|
|
438
|
+
else if (streamFailure?.status === "rejected")
|
|
419
439
|
reject(streamFailure.reason);
|
|
420
440
|
else
|
|
421
441
|
resolve(result);
|
|
422
|
-
})();
|
|
442
|
+
})().catch(reject);
|
|
423
443
|
});
|
|
424
444
|
});
|
|
425
445
|
}
|
|
@@ -238,7 +238,8 @@ function openSshSockets(machine, options) {
|
|
|
238
238
|
if (!path.posix.isAbsolute(remotePath))
|
|
239
239
|
throw new Error("Remote socket path must be absolute.");
|
|
240
240
|
const local = path.join(dir, `${name}.sock`);
|
|
241
|
-
|
|
241
|
+
// Some sshd policies drop sessions that run no command (`ssh -N`). The remote command reads the open stdin pipe, so it ends on EOF when the connection closes; a non-tty `sleep` would outlive the forwarder.
|
|
242
|
+
const child = spawn(options.sshBin ?? "ssh", [...herdrSshArgs(options.env), "-o", "StreamLocalBindUnlink=yes", "-L", `${local}:${remotePath}`, machine.target, remoteShellCommand("exec cat >/dev/null")], { env: hardenedSshEnv(options.env), stdio: ["pipe", "ignore", "ignore"], windowsHide: true });
|
|
242
243
|
children.add(child);
|
|
243
244
|
const stop = async () => { await terminateChild(child); children.delete(child); try {
|
|
244
245
|
fs.rmSync(local, { force: true });
|
|
@@ -2,7 +2,7 @@ import type { HerdrMachineReference, PlacementMachineReference } from "../../sha
|
|
|
2
2
|
import { type HerdrForwardedConnection, type HerdrRpcClient } from "./herdr-connection.ts";
|
|
3
3
|
import type { HerdrRunIdentity } from "./herdr-placed-run.ts";
|
|
4
4
|
import { PlacedRunOwner, type PlacedBridgeManifest } from "./placed-run-owner.ts";
|
|
5
|
-
import { type PlacementAgentKind, type PlacementBridgeIdentity, type PlacementEvidenceProof, type PlacementOwnedPane, type PlacementReconnectCheck, type PlacementRunState, type PlacementStartOptions } from "./placement-host.ts";
|
|
5
|
+
import { type PlacementAgentKind, type PlacementBridgeIdentity, type PlacementEvidenceProof, type PlacementOwnedPane, type PlacementPromptOptions, type PlacementReconnectCheck, type PlacementRunState, type PlacementStartOptions } from "./placement-host.ts";
|
|
6
6
|
export interface HerdrPaneCandidate {
|
|
7
7
|
endpoint: {
|
|
8
8
|
session: string | null;
|
|
@@ -43,7 +43,7 @@ export declare const herdrPaneHost: {
|
|
|
43
43
|
owned: PlacementOwnedPane;
|
|
44
44
|
terminalId: string;
|
|
45
45
|
}>;
|
|
46
|
-
prompt(connection: HerdrForwardedConnection, identity: HerdrRunIdentity, text: string): Promise<void>;
|
|
46
|
+
prompt(connection: HerdrForwardedConnection, identity: HerdrRunIdentity, text: string, options?: PlacementPromptOptions): Promise<void>;
|
|
47
47
|
subscribe(connection: HerdrForwardedConnection, paneId: string, listener: (event: unknown) => void, onDisconnect: (error: Error) => void): Promise<() => void>;
|
|
48
48
|
paneEvent(event: unknown, fallback: PlacementRunState): {
|
|
49
49
|
terminalId: unknown;
|
|
@@ -104,7 +104,23 @@ export const herdrPaneHost = {
|
|
|
104
104
|
connect(machine) { return connectHerdrMachine(asHerdrMachine(machine)); },
|
|
105
105
|
sessionOf(connection) { return connection.endpoint.session; },
|
|
106
106
|
async launch(connection, machine, runId, runtimeDir, request, onPane, options) { const owned = await provisionHerdrOwnedPane(connection, asHerdrMachine(machine), runId, runtimeDir, request.environment); await onPane(owned); const { terminalId } = await startHerdrAgent(connection, owned, request.kind, request.name, request.args, options); return { owned, terminalId }; },
|
|
107
|
-
async prompt(connection, identity, text
|
|
107
|
+
async prompt(connection, identity, text, options = {}) {
|
|
108
|
+
// Herdr registers a started agent's name asynchronously, so a prompt right after start can be refused; a refused prompt was not delivered.
|
|
109
|
+
const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 5_000), pollMs = options.pollMs ?? 100;
|
|
110
|
+
for (;;) {
|
|
111
|
+
try {
|
|
112
|
+
await connection.client.call("agent.prompt", { target: identity.agentName, text });
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
if (!(error instanceof Error) || !error.message.includes("is not an active named agent") || clock.now() >= deadline)
|
|
117
|
+
throw error;
|
|
118
|
+
await clock.wait(Math.min(pollMs, deadline - clock.now()));
|
|
119
|
+
if (options.stopped?.())
|
|
120
|
+
throw new Error("Remote Pi prompt was not sent because the run was stopped.", { cause: error });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
},
|
|
108
124
|
subscribe(connection, paneId, listener, onDisconnect) { return connection.client.subscribe(herdrStatusSubscriptions(paneId), listener, onDisconnect); },
|
|
109
125
|
paneEvent(event, fallback) { const data = event && typeof event === "object" ? event.data : undefined; return data ? { terminalId: data.terminal_id, paneId: data.pane_id, state: herdrRunState(data.agent_status, fallback) } : undefined; },
|
|
110
126
|
async panes(connection) { return { endpoint: connection.endpoint, agents: snapshotAgents(parseHerdrSessionSnapshot(await connection.client.call("session.snapshot"))) }; },
|
|
@@ -7,6 +7,7 @@ import { herdrPaneHost, HerdrPlacedRunOwner } from "./herdr-pane-host.js";
|
|
|
7
7
|
import { encodeHerdrPiFrame, HERDR_PI_MODE_ENV, HERDR_PI_PROTOCOL, HERDR_PI_RUN_ENV, HERDR_PI_RUNTIME_DIR_ENV, HerdrPiFrameDecoder, validateHerdrPiRunId } from "./herdr-pi-protocol.js";
|
|
8
8
|
import { discoverPlacedBridgeManifest } from "./placed-run-owner.js";
|
|
9
9
|
import { RexPlacedRunOwner } from "./rex-pane-host.js";
|
|
10
|
+
import { ensureSupervisorChannelDir } from "../../intercom/native-supervisor-channel.js";
|
|
10
11
|
import { isRexLocalMachine } from "./rex-machine.js";
|
|
11
12
|
import { PLACED_RESTORE_UNSUPPORTED } from "./herdr-machine.js";
|
|
12
13
|
/** The pane half comes from the host; the bridge half (run, package, protocol, native session, evidence cursor) is host-neutral. */
|
|
@@ -136,21 +137,35 @@ export class HerdrPiSession {
|
|
|
136
137
|
#reconnectFactory;
|
|
137
138
|
#reconnectFailure;
|
|
138
139
|
#replyTimer;
|
|
140
|
+
#repliesInFlight = new Set();
|
|
139
141
|
supervisorDir;
|
|
140
142
|
runtime;
|
|
141
143
|
owner;
|
|
142
144
|
constructor(owner, bridgeForward, bridge, requestedTools, model, runtime, initialGit) { this.owner = owner; this.bridgeForward = bridgeForward; this.bridge = bridge; this.requestedTools = requestedTools; this.model = model; this.runtime = runtime; this.supervisorDir = runtime.supervisorChannelDir; this.#initialGit = initialGit; bridge.adopt((frame) => this.#frame(frame)); if (this.supervisorDir) {
|
|
143
|
-
this.#replyTimer = setInterval(() =>
|
|
144
|
-
const file = path.join(replies, name);
|
|
145
|
-
try {
|
|
146
|
-
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
147
|
-
if (typeof value.message === "string" && typeof value.requestId === "string")
|
|
148
|
-
void this.#operation("supervisor-reply", value.message, value.requestId, typeof value.error === "string" ? value.error : undefined).then(() => fs.rmSync(file, { force: true }));
|
|
149
|
-
}
|
|
150
|
-
catch { }
|
|
151
|
-
} }, 50);
|
|
145
|
+
this.#replyTimer = setInterval(() => this.#deliverSupervisorReplies(this.supervisorDir), 50);
|
|
152
146
|
this.#replyTimer.unref?.();
|
|
153
147
|
} }
|
|
148
|
+
// Runs on a timer, where a throw or an unhandled rejection exits Pi. A reply that can't be read or delivered stays
|
|
149
|
+
// on disk for the next tick, once its earlier delivery has settled; a lost transport reaches the session through the
|
|
150
|
+
// bridge failure.
|
|
151
|
+
#deliverSupervisorReplies(supervisorDir) { const replies = path.join(supervisorDir, "replies"); let names; try {
|
|
152
|
+
names = fs.existsSync(replies) ? fs.readdirSync(replies) : [];
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
return;
|
|
156
|
+
} for (const name of names) {
|
|
157
|
+
const file = path.join(replies, name);
|
|
158
|
+
if (this.#repliesInFlight.has(file))
|
|
159
|
+
continue;
|
|
160
|
+
try {
|
|
161
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
162
|
+
if (typeof value.message === "string" && typeof value.requestId === "string") {
|
|
163
|
+
this.#repliesInFlight.add(file);
|
|
164
|
+
void this.#operation("supervisor-reply", value.message, value.requestId, typeof value.error === "string" ? value.error : undefined).then(() => fs.rmSync(file, { force: true })).catch(() => { }).finally(() => this.#repliesInFlight.delete(file));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
catch { }
|
|
168
|
+
} }
|
|
154
169
|
get host() { return this.owner.host; }
|
|
155
170
|
get identity() { return this.owner.identity; }
|
|
156
171
|
set identity(value) { this.owner.identity = value; }
|
|
@@ -218,23 +233,34 @@ export class HerdrPiSession {
|
|
|
218
233
|
for (const listener of this.#listeners)
|
|
219
234
|
listener({ type: "agent_settled" });
|
|
220
235
|
} }
|
|
221
|
-
#relaySupervisor(frame) {
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
236
|
+
#relaySupervisor(frame) {
|
|
237
|
+
if (!this.supervisorDir || typeof frame.requestId !== "string")
|
|
238
|
+
return;
|
|
239
|
+
const reason = frame.reason;
|
|
240
|
+
if (reason !== "need_decision" && reason !== "interview_request" && reason !== "progress_update")
|
|
241
|
+
return;
|
|
242
|
+
const createdAt = Date.now();
|
|
243
|
+
const file = path.join(this.supervisorDir, "requests", `${path.basename(frame.requestId)}.json`);
|
|
244
|
+
const request = { type: "subagent.supervisor.request", id: frame.requestId, createdAt, ...(reason !== "progress_update" ? { expiresAt: createdAt + 10 * 60_000 } : {}), reason, message: typeof frame.message === "string" ? frame.message : "", ...(frame.interview && typeof frame.interview === "object" ? { interview: frame.interview } : {}), expectsReply: reason !== "progress_update", runId: this.runtime.runId ?? this.identity.runId, agent: this.runtime.agent ?? "remote", childIndex: this.runtime.childIndex ?? 0, orchestratorSessionId: this.runtime.orchestratorSessionId };
|
|
245
|
+
// The parent's stale-channel cleanup removes an idle channel's empty directories after a minute.
|
|
246
|
+
ensureSupervisorChannelDir(this.supervisorDir);
|
|
247
|
+
try {
|
|
248
|
+
fs.writeFileSync(file, JSON.stringify(request), { mode: 0o600, flag: "wx" });
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
if (error.code !== "EEXIST")
|
|
252
|
+
throw error;
|
|
253
|
+
const existing = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
254
|
+
if (existing.id !== frame.requestId || existing.reason !== reason)
|
|
255
|
+
throw new Error("Supervisor relay identity changed during replay.");
|
|
256
|
+
}
|
|
257
|
+
if (reason === "progress_update")
|
|
258
|
+
this.bridge.supervisorDelivered(frame.requestId);
|
|
225
259
|
}
|
|
226
|
-
catch (error) {
|
|
227
|
-
if (error.code !== "EEXIST")
|
|
228
|
-
throw error;
|
|
229
|
-
const existing = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
230
|
-
if (existing.id !== frame.requestId || existing.reason !== reason)
|
|
231
|
-
throw new Error("Supervisor relay identity changed during replay.");
|
|
232
|
-
} if (reason === "progress_update")
|
|
233
|
-
this.bridge.supervisorDelivered(frame.requestId); }
|
|
234
260
|
async #operation(operation, text, supervisorId, supervisorError) { const requestId = `${++this.#sequence}_${randomBytes(5).toString("hex")}`; let completion = Promise.resolve(); if (operation === "prompt")
|
|
235
261
|
completion = new Promise((resolve, reject) => this.#operations.set(requestId, { resolve, reject, accepted: false, settled: false })); try {
|
|
236
262
|
await Promise.race([this.bridge.prepare(requestId, operation, text, supervisorId, supervisorError), this.bridge.failure]);
|
|
237
|
-
await this.host.prompt(this.connection, this.identity, `/pi-subagents-bridge ${requestId}
|
|
263
|
+
await this.host.prompt(this.connection, this.identity, `/pi-subagents-bridge ${requestId}`, operation === "abort" ? {} : { stopped: () => this.#aborted || this.#disposed });
|
|
238
264
|
await completion;
|
|
239
265
|
}
|
|
240
266
|
catch (error) {
|
|
@@ -8,7 +8,6 @@ export declare const WORKFLOW_LANE_OUTPUT_PATHS_MAX = 10;
|
|
|
8
8
|
export declare const WORKTREE_STATUS_PATH_MAX_BYTES = 4096;
|
|
9
9
|
export declare const WORKTREE_STATUS_BRANCH_MAX_BYTES = 256;
|
|
10
10
|
export declare const WORKTREE_STATUS_NAMING_LABEL_MAX_BYTES = 256;
|
|
11
|
-
/** Normalize and validate launch-declared lane metadata. */
|
|
12
11
|
export declare function normalizeWorkflowLaneMetadata(value: unknown, label?: string): WorkflowLaneMetadata | undefined;
|
|
13
12
|
export declare function assertWorkflowLaneKey(lane: WorkflowLaneMetadata | undefined, workflowKey: string | undefined, label?: string): void;
|
|
14
13
|
export interface WorktreeStatusReference {
|
|
@@ -43,7 +43,6 @@ function boundedStringArray(value, label, maxItems, maxBytes) {
|
|
|
43
43
|
return boundedNonEmptyString(entry, `${label}[${index}]`, maxBytes);
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
|
-
/** Normalize and validate launch-declared lane metadata. */
|
|
47
46
|
export function normalizeWorkflowLaneMetadata(value, label = "lane") {
|
|
48
47
|
if (value === undefined)
|
|
49
48
|
return undefined;
|
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
const BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
|
|
2
2
|
export function normalizeMcpDirectToolSelectors(selectors) {
|
|
3
|
-
return [...new Set((selectors ?? []).map(
|
|
3
|
+
return [...new Set((selectors ?? []).map(trimTrailingSlashes).filter(Boolean))];
|
|
4
|
+
}
|
|
5
|
+
/** A `/+$/` replace rescans the selector from every index when the string ends in anything else. */
|
|
6
|
+
function trimTrailingSlashes(selector) {
|
|
7
|
+
let end = selector.length;
|
|
8
|
+
while (end > 0 && selector[end - 1] === "/")
|
|
9
|
+
end -= 1;
|
|
10
|
+
return selector.slice(0, end);
|
|
4
11
|
}
|
|
5
12
|
export function parseMcpDirectToolSelectors(selectors) {
|
|
6
13
|
const servers = new Set();
|
|
@@ -2,7 +2,6 @@ export interface ChildModelResolutionDiagnostic {
|
|
|
2
2
|
agent?: string;
|
|
3
3
|
model?: string;
|
|
4
4
|
host?: "parent" | "runner";
|
|
5
|
-
/** The launch's resolved capability ceiling, when one is active. */
|
|
6
5
|
capabilityCeiling?: {
|
|
7
6
|
denyExtensions: boolean;
|
|
8
7
|
sources?: readonly string[];
|
|
@@ -31,3 +30,14 @@ export declare function formatChildModelResolutionDiagnostic(diagnostic: ChildMo
|
|
|
31
30
|
export declare function formatInheritedProviderDiagnostic(diagnostic: ChildModelResolutionDiagnostic & {
|
|
32
31
|
provider: string;
|
|
33
32
|
}): string;
|
|
33
|
+
/**
|
|
34
|
+
* Explain a background child that failed before any successful response on a
|
|
35
|
+
* provider a parent extension registered, when that extension did not load in
|
|
36
|
+
* the child. A parent extension can register a provider under a built-in id,
|
|
37
|
+
* so the model still resolves in the child, through the built-in provider
|
|
38
|
+
* rather than the parent's. Whether that caused this failure is unknown here,
|
|
39
|
+
* hence the conditional wording.
|
|
40
|
+
*/
|
|
41
|
+
export declare function formatMissingParentProviderDiagnostic(diagnostic: ChildModelResolutionDiagnostic & {
|
|
42
|
+
provider: string;
|
|
43
|
+
}): string;
|
|
@@ -89,3 +89,28 @@ export function formatInheritedProviderDiagnostic(diagnostic) {
|
|
|
89
89
|
`If ${provider} depends on those hooks, run this agent with \`async: true\` (a background child loads the ambient extensions unless the agent sets \`extensions\`), or load the extension for this agent with \`subagentOnlyExtensions\` or \`extensions\` in the agent frontmatter.`,
|
|
90
90
|
].join("\n");
|
|
91
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* Explain a background child that failed before any successful response on a
|
|
94
|
+
* provider a parent extension registered, when that extension did not load in
|
|
95
|
+
* the child. A parent extension can register a provider under a built-in id,
|
|
96
|
+
* so the model still resolves in the child, through the built-in provider
|
|
97
|
+
* rather than the parent's. Whether that caused this failure is unknown here,
|
|
98
|
+
* hence the conditional wording.
|
|
99
|
+
*/
|
|
100
|
+
export function formatMissingParentProviderDiagnostic(diagnostic) {
|
|
101
|
+
const subject = diagnostic.agent ? `Agent '${diagnostic.agent}'` : "Subagent";
|
|
102
|
+
const model = diagnostic.model ? `'${diagnostic.model}'` : "this model";
|
|
103
|
+
const provider = `'${diagnostic.provider}'`;
|
|
104
|
+
const facts = `${subject} ran as a background child without the ambient extensions. In the parent, provider ${provider} for ${model} is registered by an extension that did not load in this child, so the child sent its requests without that extension's provider, through the built-in provider of the same id if there is one.`;
|
|
105
|
+
if (capabilityCeilingDeniesExtensions(diagnostic)) {
|
|
106
|
+
return [
|
|
107
|
+
facts,
|
|
108
|
+
`${denyExtensionsClause(diagnostic)}, so that extension cannot load for this child: listed \`subagentOnlyExtensions\` or \`extensions\` entries are suppressed, and leaving \`extensions\` unset does not enable ambient loading.`,
|
|
109
|
+
`If ${provider} depends on that extension, relax the capability ceiling to allow extensions, or use a model whose provider does not.`,
|
|
110
|
+
].join("\n");
|
|
111
|
+
}
|
|
112
|
+
return [
|
|
113
|
+
facts,
|
|
114
|
+
`If ${provider} depends on that extension, list it in \`subagentOnlyExtensions\` or \`extensions\` in the agent frontmatter, leave \`extensions\` unset so the child loads the ambient extensions, or register it from the host with \`registerRequiredChildExtensions\` so it loads for every launch.`,
|
|
115
|
+
].join("\n");
|
|
116
|
+
}
|
|
@@ -12,7 +12,6 @@ export { splitThinkingSuffix };
|
|
|
12
12
|
* to, so the virtual selection's provider/id is compared exactly with the launch candidate instead.
|
|
13
13
|
*/
|
|
14
14
|
export declare function formatSubagentModelVerificationError(expectedModel: string, observedModel: string, availableModels: AvailableModelInfo[] | undefined, modelResponseAliases?: Record<string, string[]>, observedVirtualModel?: string): string | undefined;
|
|
15
|
-
/** Sentinel model value requesting that a subagent inherit the parent session's model. */
|
|
16
15
|
export declare const INHERIT_MODEL = "inherit";
|
|
17
16
|
/** Minimal shape of the parent session's in-memory model (`ctx.model`). */
|
|
18
17
|
export interface ParentModel {
|
|
@@ -56,6 +55,8 @@ export declare function fuzzyResolveModel(baseModel: string, availableModels: Av
|
|
|
56
55
|
* query.
|
|
57
56
|
*/
|
|
58
57
|
export declare function resolveModelCandidate(model: string | undefined, availableModels: AvailableModelInfo[] | undefined, preferredProvider?: string): string | undefined;
|
|
58
|
+
/** A configured pin that launch refuses because the registry cannot resolve it. An empty registry checks nothing. */
|
|
59
|
+
export declare function isUnavailableSubagentModel(model: string | undefined, availableModels: AvailableModelInfo[] | undefined, preferredProvider?: string): boolean;
|
|
59
60
|
export interface ResolveSubagentModelOverrideOptions {
|
|
60
61
|
/** When set with `enforce: true`, out-of-scope models are rejected. */
|
|
61
62
|
scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
|
|
@@ -90,7 +91,6 @@ export interface ResolveModelSelectionOptions {
|
|
|
90
91
|
onWarn?: (violation: ModelScopeViolation) => void;
|
|
91
92
|
/** The primary model came from the running parent session, not configuration. */
|
|
92
93
|
primaryModelFromParent?: boolean;
|
|
93
|
-
/** How the model was selected. */
|
|
94
94
|
origin?: ModelOrigin;
|
|
95
95
|
}
|
|
96
96
|
export declare function resolveModelOrigin(input: {
|
|
@@ -31,7 +31,6 @@ export function formatSubagentModelVerificationError(expectedModel, observedMode
|
|
|
31
31
|
}
|
|
32
32
|
return `model_verification_failed: native Pi child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'. If you have independently verified this response ID identifies the requested model, declare the exact mapping in modelResponseAliases in ~/.pi/agent/extensions/subagent/config.json (see docs/configuration.md#modelresponsealiases). Use the resolved provider/model ID without its thinking suffix as the key. This leaves the outgoing request unchanged. Configuration changes affect new independent native runs; resumed native runs retain their launch-time declaration. External CLI adapters do not use this setting.`;
|
|
33
33
|
}
|
|
34
|
-
/** Sentinel model value requesting that a subagent inherit the parent session's model. */
|
|
35
34
|
export const INHERIT_MODEL = "inherit";
|
|
36
35
|
export function normalizeParentModel(model) {
|
|
37
36
|
if (!model || typeof model !== "object")
|
|
@@ -257,6 +256,13 @@ function closestModelCandidates(model, availableModels) {
|
|
|
257
256
|
.slice(0, MAX_MODEL_CANDIDATES)
|
|
258
257
|
.map((entry) => `${entry.fullId}${thinkingSuffix}`);
|
|
259
258
|
}
|
|
259
|
+
/** A configured pin that launch refuses because the registry cannot resolve it. An empty registry checks nothing. */
|
|
260
|
+
export function isUnavailableSubagentModel(model, availableModels, preferredProvider) {
|
|
261
|
+
const trimmed = model?.trim();
|
|
262
|
+
if (!trimmed || trimmed === INHERIT_MODEL || !availableModels?.length)
|
|
263
|
+
return false;
|
|
264
|
+
return resolveSubagentModelCandidate(trimmed, availableModels, preferredProvider) === undefined;
|
|
265
|
+
}
|
|
260
266
|
function resolveRequiredSubagentModelCandidate(model, availableModels, preferredProvider) {
|
|
261
267
|
const resolved = resolveSubagentModelCandidate(model, availableModels, preferredProvider);
|
|
262
268
|
if (resolved)
|
|
@@ -8,9 +8,6 @@
|
|
|
8
8
|
* inherited from agent frontmatter / `defaultModel` / the parent session only
|
|
9
9
|
* emits a warning so existing configurations keep working. Optional strict
|
|
10
10
|
* enforcement makes inherited models hard errors too.
|
|
11
|
-
*
|
|
12
|
-
* The decision logic ({@link checkModelScope}) is a pure function of its
|
|
13
|
-
* inputs so it can be unit-tested without touching the filesystem or config.
|
|
14
11
|
*/
|
|
15
12
|
export interface ModelScopeRule {
|
|
16
13
|
enforce?: boolean;
|
|
@@ -60,8 +57,7 @@ export declare function resolveModelScopesForAgent(config: ModelScopeConfig | un
|
|
|
60
57
|
} | undefined, scopedModelIds?: readonly string[]): ResolvedModelScope[];
|
|
61
58
|
/**
|
|
62
59
|
* Validate and normalize a raw `subagents.modelScope` value from settings.
|
|
63
|
-
* Throws a descriptive error for malformed configs
|
|
64
|
-
* settings-parsing style). Returns `undefined` when the field is absent.
|
|
60
|
+
* Throws a descriptive error for malformed configs. Returns `undefined` when the field is absent.
|
|
65
61
|
*/
|
|
66
62
|
export declare function parseModelScopeConfig(value: unknown, meta: {
|
|
67
63
|
filePath: string;
|
|
@@ -8,9 +8,6 @@
|
|
|
8
8
|
* inherited from agent frontmatter / `defaultModel` / the parent session only
|
|
9
9
|
* emits a warning so existing configurations keep working. Optional strict
|
|
10
10
|
* enforcement makes inherited models hard errors too.
|
|
11
|
-
*
|
|
12
|
-
* The decision logic ({@link checkModelScope}) is a pure function of its
|
|
13
|
-
* inputs so it can be unit-tested without touching the filesystem or config.
|
|
14
11
|
*/
|
|
15
12
|
import { splitKnownThinkingSuffix } from "../../shared/model-info.js";
|
|
16
13
|
export const SCOPED_PATTERN = "scoped";
|
|
@@ -140,8 +137,7 @@ export function resolveModelScopesForAgent(config, agentName, parentModel, scope
|
|
|
140
137
|
}
|
|
141
138
|
/**
|
|
142
139
|
* Validate and normalize a raw `subagents.modelScope` value from settings.
|
|
143
|
-
* Throws a descriptive error for malformed configs
|
|
144
|
-
* settings-parsing style). Returns `undefined` when the field is absent.
|
|
140
|
+
* Throws a descriptive error for malformed configs. Returns `undefined` when the field is absent.
|
|
145
141
|
*/
|
|
146
142
|
export function parseModelScopeConfig(value, meta) {
|
|
147
143
|
if (value === undefined)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ArtifactPaths, TimeoutRecoveryProjection, TimeoutRecoverySummary, TrackedMutationEvidence, TrackedMutationSnapshot } from "../../shared/types.ts";
|
|
2
2
|
export declare function snapshotTrackedMutations(cwd: string): TrackedMutationSnapshot;
|
|
3
|
-
export declare function collectTrackedMutationEvidence(snapshot: TrackedMutationSnapshot, cwd?: string): TrackedMutationEvidence
|
|
3
|
+
export declare function collectTrackedMutationEvidence(snapshot: TrackedMutationSnapshot, cwd?: string): Promise<TrackedMutationEvidence>;
|
|
4
4
|
/** Keep status and completion details to bounded routing evidence, not raw output or effects. */
|
|
5
5
|
export declare function projectTimeoutRecovery(value: unknown): TimeoutRecoveryProjection | undefined;
|
|
6
6
|
/** Render only the bounded recovery route needed by a parent/operator. */
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { execFileSync } from "node:child_process";
|
|
1
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
4
|
import * as os from "node:os";
|
|
5
5
|
import * as path from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
6
7
|
const MAX_TRACKED_PATHS = 500;
|
|
7
8
|
const MAX_HASH_BYTES = 1024 * 1024;
|
|
8
9
|
const MAX_TIMEOUT_FILES = 20;
|
|
@@ -13,6 +14,32 @@ function gitArguments(args) {
|
|
|
13
14
|
function gitOutput(cwd, args, maxBuffer = MAX_HASH_BYTES) {
|
|
14
15
|
return execFileSync("git", gitArguments(args), { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"], maxBuffer, windowsHide: true });
|
|
15
16
|
}
|
|
17
|
+
const execFileAsync = promisify(execFile);
|
|
18
|
+
/** The collection path runs while sibling children settle, so git runs off the event loop. */
|
|
19
|
+
async function gitOutputAsync(cwd, args) {
|
|
20
|
+
return (await execFileAsync("git", gitArguments(args), { cwd, encoding: "utf-8", maxBuffer: MAX_HASH_BYTES, windowsHide: true })).stdout;
|
|
21
|
+
}
|
|
22
|
+
/** Yields to the event loop every 2 MiB so hashing a large diff does not stall other work. */
|
|
23
|
+
async function hashFileAsync(diffPath) {
|
|
24
|
+
const hash = createHash("sha256");
|
|
25
|
+
const fd = fs.openSync(diffPath, "r");
|
|
26
|
+
try {
|
|
27
|
+
const buffer = Buffer.alloc(64 * 1024);
|
|
28
|
+
let chunks = 0;
|
|
29
|
+
for (;;) {
|
|
30
|
+
const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null);
|
|
31
|
+
if (bytesRead === 0)
|
|
32
|
+
break;
|
|
33
|
+
hash.update(bytesRead === buffer.length ? buffer : buffer.subarray(0, bytesRead));
|
|
34
|
+
if (++chunks % 32 === 0)
|
|
35
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
fs.closeSync(fd);
|
|
40
|
+
}
|
|
41
|
+
return hash.digest("hex");
|
|
42
|
+
}
|
|
16
43
|
function splitNul(output) {
|
|
17
44
|
return output.split("\0").filter((part) => part.length > 0);
|
|
18
45
|
}
|
|
@@ -41,8 +68,9 @@ function hashLargeDiff(cwd, relativePath) {
|
|
|
41
68
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
42
69
|
}
|
|
43
70
|
}
|
|
44
|
-
|
|
45
|
-
|
|
71
|
+
const CHANGED_FILES_ARGS = ["diff", "--no-ext-diff", "--name-only", "-z", "HEAD", "--"];
|
|
72
|
+
function changedTrackedFiles(nameOnlyOutput) {
|
|
73
|
+
const paths = splitNul(nameOnlyOutput);
|
|
46
74
|
return { paths: paths.slice(0, MAX_TRACKED_PATHS), truncated: paths.length > MAX_TRACKED_PATHS };
|
|
47
75
|
}
|
|
48
76
|
function fingerprintPath(cwd, relativePath) {
|
|
@@ -61,7 +89,7 @@ function sameFingerprint(left, right) {
|
|
|
61
89
|
}
|
|
62
90
|
export function snapshotTrackedMutations(cwd) {
|
|
63
91
|
try {
|
|
64
|
-
const changed =
|
|
92
|
+
const changed = changedTrackedFiles(gitOutput(cwd, CHANGED_FILES_ARGS));
|
|
65
93
|
const fingerprints = {};
|
|
66
94
|
for (const file of changed.paths)
|
|
67
95
|
fingerprints[file] = fingerprintPath(cwd, file);
|
|
@@ -71,12 +99,29 @@ export function snapshotTrackedMutations(cwd) {
|
|
|
71
99
|
return { source: "tracked-files", trackedOnly: true, cwd, dirtyFiles: [], fingerprints: {}, unavailable: error instanceof Error ? error.message : String(error) };
|
|
72
100
|
}
|
|
73
101
|
}
|
|
74
|
-
|
|
102
|
+
async function fingerprintPathAsync(cwd, relativePath) {
|
|
103
|
+
try {
|
|
104
|
+
const diff = await gitOutputAsync(cwd, ["diff", "--no-ext-diff", "--binary", "HEAD", "--", relativePath]);
|
|
105
|
+
return { kind: "diff", digest: createHash("sha256").update(diff).digest("hex") };
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-mutation-evidence-"));
|
|
109
|
+
try {
|
|
110
|
+
const diffPath = path.join(tempDir, "diff.bin");
|
|
111
|
+
await gitOutputAsync(cwd, ["diff", "--no-ext-diff", "--binary", `--output=${diffPath}`, "HEAD", "--", relativePath]);
|
|
112
|
+
return { kind: "diff", digest: await hashFileAsync(diffPath) };
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export async function collectTrackedMutationEvidence(snapshot, cwd = snapshot.cwd) {
|
|
75
120
|
if (snapshot.unavailable) {
|
|
76
121
|
return { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: false, unavailable: snapshot.unavailable };
|
|
77
122
|
}
|
|
78
123
|
try {
|
|
79
|
-
const current =
|
|
124
|
+
const current = changedTrackedFiles(await gitOutputAsync(cwd, CHANGED_FILES_ARGS));
|
|
80
125
|
const startDirty = new Set(snapshot.dirtyFiles);
|
|
81
126
|
const candidates = new Set([...snapshot.dirtyFiles, ...current.paths]);
|
|
82
127
|
const changedFiles = [];
|
|
@@ -86,7 +131,7 @@ export function collectTrackedMutationEvidence(snapshot, cwd = snapshot.cwd) {
|
|
|
86
131
|
changedFiles.push(file);
|
|
87
132
|
continue;
|
|
88
133
|
}
|
|
89
|
-
if (!sameFingerprint(snapshot.fingerprints[file],
|
|
134
|
+
if (!sameFingerprint(snapshot.fingerprints[file], await fingerprintPathAsync(cwd, file)))
|
|
90
135
|
changedFiles.push(file);
|
|
91
136
|
}
|
|
92
137
|
changedFiles.sort();
|
|
@@ -87,6 +87,7 @@ export interface NestedRunResolutionScope {
|
|
|
87
87
|
parentStepIndex?: number;
|
|
88
88
|
};
|
|
89
89
|
}
|
|
90
|
+
export declare function collectNestedRuns(children: NestedRunSummary[] | undefined, output?: NestedRunSummary[]): NestedRunSummary[];
|
|
90
91
|
export declare function findNestedRunMatchesById(id: string, options?: {
|
|
91
92
|
prefix?: boolean;
|
|
92
93
|
scope?: NestedRunResolutionScope;
|
|
@@ -564,7 +564,7 @@ export function retainNestedLookupRoute(state, route, sessionId) {
|
|
|
564
564
|
}
|
|
565
565
|
state.retainedNestedLookupRoutes.routes.set(route.rootRunId, route);
|
|
566
566
|
}
|
|
567
|
-
function collectNestedRuns(children, output = []) {
|
|
567
|
+
export function collectNestedRuns(children, output = []) {
|
|
568
568
|
for (const child of children ?? []) {
|
|
569
569
|
output.push(child);
|
|
570
570
|
collectNestedRuns(child.children, output);
|
|
@@ -22,7 +22,6 @@ export interface RunnerSubagentStep {
|
|
|
22
22
|
requestId: string;
|
|
23
23
|
requestDigest: string;
|
|
24
24
|
};
|
|
25
|
-
/** Resolved launch context for this child. */
|
|
26
25
|
context?: "fresh" | "fork";
|
|
27
26
|
importAsyncRoot?: {
|
|
28
27
|
runId: string;
|
|
@@ -55,6 +54,8 @@ export interface RunnerSubagentStep {
|
|
|
55
54
|
}>;
|
|
56
55
|
modelResponseAliases?: Record<string, string[]>;
|
|
57
56
|
tools?: string[];
|
|
57
|
+
/** Provider of `model` that a parent extension registers; set only when this child loads no ambient extensions. */
|
|
58
|
+
parentExtensionProvider?: string;
|
|
58
59
|
excludeTools?: string[];
|
|
59
60
|
allowNestedSubagents?: boolean;
|
|
60
61
|
/** Resolved selected-agent policy for launches made by this child. */
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
-
|
|
3
|
+
import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
|
|
4
|
+
const COORDINATION_TOOLS = new Set(["contact_supervisor", "intercom", "structured_output"]);
|
|
5
|
+
const isInternalTool = (tool) => COORDINATION_TOOLS.has(tool) || tool === waitToolName();
|
|
4
6
|
const DECISIONS = new Set(["allow", "ask", "deny"]);
|
|
5
7
|
const MAX_POLICY_BYTES = 16 * 1024;
|
|
6
8
|
const MAX_PREVIEW_BYTES = 2048;
|
|
@@ -20,7 +22,7 @@ export function validatePermissionRules(value, label) {
|
|
|
20
22
|
throw new Error(`${label} contains an empty tool name.`);
|
|
21
23
|
if (tool === "bash")
|
|
22
24
|
throw new Error(`${label}.bash is unsupported; pi-subagents leaves bash policy to pi-guard.`);
|
|
23
|
-
if (
|
|
25
|
+
if (isInternalTool(tool) || tool === DEFAULT_WAIT_TOOL_NAME)
|
|
24
26
|
throw new Error(`${label}.${tool} is reserved for child coordination and cannot be gated.`);
|
|
25
27
|
if (!DECISIONS.has(decision))
|
|
26
28
|
throw new Error(`${label}.${tool} must be allow, ask, or deny.`);
|
|
@@ -47,7 +49,7 @@ export function resolvePermissionRules(globalConfig, agentRules) {
|
|
|
47
49
|
return Object.keys(merged).length ? merged : undefined;
|
|
48
50
|
}
|
|
49
51
|
export function permissionDecision(rules, toolName) {
|
|
50
|
-
if (toolName === "bash" ||
|
|
52
|
+
if (toolName === "bash" || isInternalTool(toolName))
|
|
51
53
|
return "allow";
|
|
52
54
|
return rules?.[toolName] ?? "allow";
|
|
53
55
|
}
|
|
@@ -39,6 +39,10 @@ export interface PlacementStartOptions {
|
|
|
39
39
|
wait(ms: number): Promise<void>;
|
|
40
40
|
};
|
|
41
41
|
}
|
|
42
|
+
/** `stopped` ends a pending prompt retry once the run is aborted or disposed, so a refused prompt is never sent after that. */
|
|
43
|
+
export interface PlacementPromptOptions extends PlacementStartOptions {
|
|
44
|
+
stopped?: () => boolean;
|
|
45
|
+
}
|
|
42
46
|
/** What to start in a new pane; the pane is created in the machine's cwd with this environment. */
|
|
43
47
|
export interface PlacementLaunchRequest {
|
|
44
48
|
kind: PlacementAgentKind;
|
|
@@ -81,7 +85,7 @@ export interface PlacementPaneHost<C extends PlacementSockets = PlacementSockets
|
|
|
81
85
|
owned: PlacementOwnedPane;
|
|
82
86
|
terminalId: string;
|
|
83
87
|
}>;
|
|
84
|
-
prompt(connection: C, identity: HerdrRunIdentity, text: string): Promise<void>;
|
|
88
|
+
prompt(connection: C, identity: HerdrRunIdentity, text: string, options?: PlacementPromptOptions): Promise<void>;
|
|
85
89
|
subscribe(connection: C, paneId: string, listener: (event: unknown) => void, onDisconnect: (error: Error) => void): Promise<() => void>;
|
|
86
90
|
paneEvent(event: unknown, fallback: PlacementRunState): {
|
|
87
91
|
terminalId: unknown;
|
|
@@ -51,7 +51,6 @@ export declare const rexPaneHost: {
|
|
|
51
51
|
reconcile: typeof reconcileRexPlacedRun;
|
|
52
52
|
closeOwnedPane: typeof closeOwnedRexPane;
|
|
53
53
|
};
|
|
54
|
-
/** The placed-run owner bound to Rex and the pane machine's access. */
|
|
55
54
|
export declare class RexPlacedRunOwner extends PlacedRunOwner<RexConnection, RexMachineReference> {
|
|
56
55
|
private constructor();
|
|
57
56
|
/** A Rex SSH owner's machine carries the resolved remote cwd, and its host reconnects only to the session recorded here. */
|