@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
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
} from "../../shared/types.ts";
|
|
23
23
|
import { THINKING_LEVELS } from "../../shared/model-info.ts";
|
|
24
24
|
import { getAgentDir } from "../../shared/utils.ts";
|
|
25
|
+
import { resolveRuntimeModulePath, RUNTIME_MODULE_EXTENSIONS } from "../../shared/runtime-module-path.ts";
|
|
25
26
|
import type { PermissionRules } from "./permissions.ts";
|
|
26
27
|
import { resolveProfileExtensions } from "./profile-extensions.ts";
|
|
27
28
|
import { snapshotRequiredChildExtensions, type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
|
|
@@ -34,30 +35,15 @@ import {
|
|
|
34
35
|
} from "./capability-ceiling.ts";
|
|
35
36
|
|
|
36
37
|
const MAX_LAUNCH_RESOLVED_EXTENSION_IDS = 32;
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
);
|
|
41
|
-
const FANOUT_CHILD_EXTENSION_PATH = path.join(
|
|
42
|
-
path.dirname(fileURLToPath(import.meta.url)),
|
|
43
|
-
"..",
|
|
44
|
-
"..",
|
|
45
|
-
"extension",
|
|
46
|
-
`fanout-child${path.extname(fileURLToPath(import.meta.url))}`,
|
|
47
|
-
);
|
|
48
|
-
const FAST_MODE_EXTENSION_PATH = path.join(
|
|
49
|
-
path.dirname(fileURLToPath(import.meta.url)),
|
|
50
|
-
`fast-mode-extension${path.extname(fileURLToPath(import.meta.url))}`,
|
|
51
|
-
);
|
|
52
|
-
const SANDBOX_PROFILE_GUARD_EXTENSION_PATH = path.join(
|
|
53
|
-
path.dirname(fileURLToPath(import.meta.url)),
|
|
54
|
-
"sandbox-profile-guard.ts",
|
|
55
|
-
);
|
|
38
|
+
const RUNTIME_EXTENSION_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
39
|
+
const FANOUT_CHILD_EXTENSION_DIR = path.join(RUNTIME_EXTENSION_DIR, "..", "..", "extension");
|
|
40
|
+
|
|
41
|
+
const SANDBOX_PROFILE_GUARD_EXTENSION_PATH = path.join(RUNTIME_EXTENSION_DIR, "sandbox-profile-guard.ts");
|
|
56
42
|
const SUBAGENT_RUNTIME_EXTENSION_PATHS = new Set([
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
].map((
|
|
43
|
+
path.join(RUNTIME_EXTENSION_DIR, "subagent-prompt-runtime"),
|
|
44
|
+
path.join(RUNTIME_EXTENSION_DIR, "fast-mode-extension"),
|
|
45
|
+
path.join(FANOUT_CHILD_EXTENSION_DIR, "fanout-child"),
|
|
46
|
+
].flatMap((base) => RUNTIME_MODULE_EXTENSIONS.map((extension) => path.normalize(`${base}${extension}`))));
|
|
61
47
|
|
|
62
48
|
/** True for the extension files pi-subagents itself installs in child sessions. */
|
|
63
49
|
export function isSubagentRuntimeExtensionPath(extensionPath: string): boolean {
|
|
@@ -130,7 +116,7 @@ function resolveFastModeExtension(input: Pick<ResolvePiLaunchToolPlanInput, "fas
|
|
|
130
116
|
if (unsupported.length > 0) {
|
|
131
117
|
throw new Error(`fast mode supports only native ${FAST_MODE_PROVIDER_PREFIX}* models; unsupported model${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
|
|
132
118
|
}
|
|
133
|
-
return [
|
|
119
|
+
return [resolveRuntimeModulePath(RUNTIME_EXTENSION_DIR, "fast-mode-extension")];
|
|
134
120
|
}
|
|
135
121
|
|
|
136
122
|
export interface ResolvePiLaunchToolPlanInput {
|
|
@@ -358,7 +344,7 @@ export function resolvePiLaunchToolPlan(
|
|
|
358
344
|
const ceilingFilteredBuiltinTools =
|
|
359
345
|
input.tools === undefined
|
|
360
346
|
? allowedToolSet
|
|
361
|
-
? [...allowedToolSet]
|
|
347
|
+
? [...allowedToolSet].filter((tool) => tool !== "subagent_command")
|
|
362
348
|
: []
|
|
363
349
|
: (input.requireReadTool &&
|
|
364
350
|
requestedBuiltinTools.length > 0 &&
|
|
@@ -454,10 +440,11 @@ export function resolvePiLaunchToolPlan(
|
|
|
454
440
|
});
|
|
455
441
|
if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode requires a child runtime extension, but this launch denies extensions.");
|
|
456
442
|
const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, agentName: input.agentName });
|
|
443
|
+
// Resolved per launch: an in-place package update can swap a sibling's .ts for .js.
|
|
457
444
|
const runtimeExtensions = [
|
|
458
|
-
|
|
445
|
+
resolveRuntimeModulePath(RUNTIME_EXTENSION_DIR, "subagent-prompt-runtime"),
|
|
459
446
|
...fastModeExtensions,
|
|
460
|
-
...(fanoutAuthorized ? [
|
|
447
|
+
...(fanoutAuthorized ? [resolveRuntimeModulePath(FANOUT_CHILD_EXTENSION_DIR, "fanout-child")] : []),
|
|
461
448
|
...(effectivePermSystemExt ? [effectivePermSystemExt] : []),
|
|
462
449
|
...(sandboxExtension ? [sandboxExtension, SANDBOX_PROFILE_GUARD_EXTENSION_PATH] : []),
|
|
463
450
|
];
|
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import { parseExternalCliJsonlEvent, type ExternalCliParser, type ExternalCliParserProgress, type ExternalCliParserTerminal } from "./external-cli-runner.ts";
|
|
2
2
|
import type { ExternalCliPreflightSpec } from "./external-cli-preflight.ts";
|
|
3
|
+
import { splitKnownThinkingSuffix, THINKING_LEVELS, type ThinkingLevel } from "../../shared/model-info.ts";
|
|
4
|
+
import { assertThinkingWithinCeiling } from "../../shared/thinking-ceiling.ts";
|
|
5
|
+
import { checkModelScope, type ResolvedModelScope } from "./model-scope.ts";
|
|
3
6
|
|
|
4
7
|
const MAX_EVENT_TYPE_LENGTH = 128;
|
|
5
8
|
const MAX_ERROR_LENGTH = 4_096;
|
|
6
9
|
|
|
7
10
|
export const CLAUDE_CODE_ADAPTER_ID = "claude-code" as const;
|
|
8
11
|
export const CLAUDE_CODE_WRITER_ADAPTER_ID = "claude-code-writer" as const;
|
|
12
|
+
|
|
13
|
+
/** True for the two code-owned adapters that launch the Claude Code CLI. */
|
|
14
|
+
export function isClaudeCodeAdapterId(value: unknown): value is typeof CLAUDE_CODE_ADAPTER_ID | typeof CLAUDE_CODE_WRITER_ADAPTER_ID {
|
|
15
|
+
return value === CLAUDE_CODE_ADAPTER_ID || value === CLAUDE_CODE_WRITER_ADAPTER_ID;
|
|
16
|
+
}
|
|
9
17
|
export const CLAUDE_CODE_WRITER_TOOLS = "Read,Write,Edit,Glob,Grep" as const;
|
|
10
18
|
export const CLAUDE_CODE_ENV_ALLOWLIST = [
|
|
11
19
|
"PATH",
|
|
@@ -42,6 +50,146 @@ export const CLAUDE_CODE_ENV_ALLOWLIST = [
|
|
|
42
50
|
"SSL_CERT_DIR",
|
|
43
51
|
] as const;
|
|
44
52
|
|
|
53
|
+
/**
|
|
54
|
+
* Claude Code exposes a five-value `--effort` scale. Pi's thinking vocabulary is
|
|
55
|
+
* wider, so the extra levels collapse onto the nearest supported value and `off`
|
|
56
|
+
* means "pass no flag at all".
|
|
57
|
+
*/
|
|
58
|
+
const CLAUDE_CODE_EFFORT_BY_THINKING: Record<ThinkingLevel, string | undefined> = {
|
|
59
|
+
off: undefined,
|
|
60
|
+
minimal: "low",
|
|
61
|
+
low: "low",
|
|
62
|
+
medium: "medium",
|
|
63
|
+
high: "high",
|
|
64
|
+
xhigh: "xhigh",
|
|
65
|
+
max: "max",
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Claude Code model ids: aliases, `claude-*` ids, and Bedrock/Vertex prefixes.
|
|
70
|
+
* `:` stays legal because Bedrock inference profiles and ARNs contain it, so the
|
|
71
|
+
* thinking suffix is split off before this pattern is applied rather than
|
|
72
|
+
* excluded by it.
|
|
73
|
+
*/
|
|
74
|
+
const CLAUDE_CODE_MODEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
|
|
75
|
+
|
|
76
|
+
const INVALID_CLAUDE_CODE_MODEL = "expected an alias such as \"opus\" or a model id such as \"claude-opus-5.5\"";
|
|
77
|
+
|
|
78
|
+
export interface ClaudeCodeOverride {
|
|
79
|
+
/** Tokens appended after the adapter's fixed argv. */
|
|
80
|
+
args: string[];
|
|
81
|
+
/** Model id the launch pins, when it pins one. */
|
|
82
|
+
model?: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The agent-config fields that can pin a model, structurally typed to avoid importing them. */
|
|
86
|
+
export interface ClaudeCodeAgentModel {
|
|
87
|
+
model?: string | false;
|
|
88
|
+
modelSource?: { type?: string; model?: string };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The model an agent pins for itself. `subagents.defaultModel` is a Pi child
|
|
93
|
+
* model, so it is a default for Pi children only and never becomes `--model`.
|
|
94
|
+
*/
|
|
95
|
+
function agentPinnedModel(agent: ClaudeCodeAgentModel | undefined): string | undefined {
|
|
96
|
+
const model = typeof agent?.model === "string" ? agent.model : undefined;
|
|
97
|
+
if (!model) return undefined;
|
|
98
|
+
if (agent?.modelSource?.type === "subagents.defaultModel" && agent.modelSource.model === model) return undefined;
|
|
99
|
+
return model;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A launch that asks only for a level keeps the agent's pinned model, so
|
|
104
|
+
* `model: ":high"` means the same thing as frontmatter `thinking: high`.
|
|
105
|
+
*/
|
|
106
|
+
function combineClaudeCodeModel(launch: string | undefined, pinned: string | undefined): string | undefined {
|
|
107
|
+
if (launch === undefined) return pinned;
|
|
108
|
+
const { baseModel, thinkingSuffix } = splitKnownThinkingSuffix(launch);
|
|
109
|
+
if (baseModel) return launch;
|
|
110
|
+
if (!launch) return launch;
|
|
111
|
+
// An empty base means the request was a bare level: run it on the agent's model.
|
|
112
|
+
const pinnedBase = pinned ? splitKnownThinkingSuffix(pinned).baseModel : "";
|
|
113
|
+
return pinnedBase && thinkingSuffix ? `${pinnedBase}${thinkingSuffix}` : launch;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Resolve an explicit model and thinking level for a code-owned Claude Code
|
|
118
|
+
* adapter. Returns undefined when neither was requested, so the CLI falls back
|
|
119
|
+
* to its own configured default.
|
|
120
|
+
*
|
|
121
|
+
* The level travels as the same `:level` suffix Pi children use:
|
|
122
|
+
* `model: "claude-opus-5.5:high"` pins the model and the effort, and a bare
|
|
123
|
+
* `model: ":high"` takes the effort alone on the agent's own model. A suffix
|
|
124
|
+
* wins over the frontmatter `thinking` value, which is the precedence Pi
|
|
125
|
+
* children already use.
|
|
126
|
+
*
|
|
127
|
+
* Values are validated here because this module owns the adapter's argv: every
|
|
128
|
+
* returned token is passed as its own argv element, and an unusable value is a
|
|
129
|
+
* rejected launch rather than a silently different model. The ceiling is checked
|
|
130
|
+
* against the requested level, not against the effort it maps to.
|
|
131
|
+
*/
|
|
132
|
+
export function resolveClaudeCodeOverride(input: {
|
|
133
|
+
model?: string;
|
|
134
|
+
agent?: ClaudeCodeAgentModel;
|
|
135
|
+
thinking?: string;
|
|
136
|
+
thinkingCeiling?: ThinkingLevel;
|
|
137
|
+
agentName?: string;
|
|
138
|
+
runId?: string;
|
|
139
|
+
}): ClaudeCodeOverride | undefined {
|
|
140
|
+
const args: string[] = [];
|
|
141
|
+
let model: string | undefined;
|
|
142
|
+
let level: string | undefined;
|
|
143
|
+
const launchModel = input.model === undefined ? undefined : input.model.trim();
|
|
144
|
+
const requested = combineClaudeCodeModel(launchModel, agentPinnedModel(input.agent));
|
|
145
|
+
if (requested !== undefined) {
|
|
146
|
+
const { baseModel, thinkingSuffix } = splitKnownThinkingSuffix(requested);
|
|
147
|
+
level = thinkingSuffix ? thinkingSuffix.slice(1) : undefined;
|
|
148
|
+
if (baseModel) {
|
|
149
|
+
if (!CLAUDE_CODE_MODEL_PATTERN.test(baseModel)) throw new Error(`Invalid Claude Code model ${JSON.stringify(requested)}; ${INVALID_CLAUDE_CODE_MODEL}.`);
|
|
150
|
+
model = baseModel;
|
|
151
|
+
args.push("--model", baseModel);
|
|
152
|
+
} else if (!level) {
|
|
153
|
+
throw new Error(`Invalid Claude Code model ${JSON.stringify(requested)}; ${INVALID_CLAUDE_CODE_MODEL}.`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (!level && input.thinking !== undefined) {
|
|
157
|
+
const thinking = input.thinking.trim();
|
|
158
|
+
if (!(THINKING_LEVELS as readonly string[]).includes(thinking)) {
|
|
159
|
+
throw new Error(`Invalid thinking level ${JSON.stringify(input.thinking)}; expected one of ${THINKING_LEVELS.join(", ")}.`);
|
|
160
|
+
}
|
|
161
|
+
level = thinking;
|
|
162
|
+
}
|
|
163
|
+
if (level) {
|
|
164
|
+
// A level can arrive without a model, so it goes to the shared check as the
|
|
165
|
+
// suffix form that check already understands.
|
|
166
|
+
assertThinkingWithinCeiling({ model: `:${level}`, ceiling: input.thinkingCeiling, agent: input.agentName, runId: input.runId });
|
|
167
|
+
const effort = CLAUDE_CODE_EFFORT_BY_THINKING[level as ThinkingLevel];
|
|
168
|
+
if (effort) args.push("--effort", effort);
|
|
169
|
+
}
|
|
170
|
+
if (args.length === 0) return undefined;
|
|
171
|
+
return { args, ...(model ? { model } : {}) };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* A Claude Code launch pins a model the Pi registry does not know, so an enforced
|
|
176
|
+
* model scope can only be honored by checking the id the CLI will actually run.
|
|
177
|
+
* A launch that pins nothing cannot be checked at all, and an enforced scope must
|
|
178
|
+
* not be bypassed by staying silent.
|
|
179
|
+
*/
|
|
180
|
+
export function assertClaudeCodeModelScope(input: { scopes: readonly ResolvedModelScope[]; model?: string; agent: string; runId?: string }): void {
|
|
181
|
+
const enforced = input.scopes.filter((scope) => scope.enforce === true);
|
|
182
|
+
if (enforced.length === 0) return;
|
|
183
|
+
if (!input.model) {
|
|
184
|
+
const subject = input.runId ? `agent '${input.agent}' run '${input.runId}'` : `agent '${input.agent}'`;
|
|
185
|
+
throw new Error(`${subject} does not name a Claude Code model, so it cannot be checked against an enforced subagent model scope (modelScope). Name the model on the launch, or in the agent's frontmatter, or turn enforcement off.`);
|
|
186
|
+
}
|
|
187
|
+
for (const scope of enforced) {
|
|
188
|
+
const violation = checkModelScope(input.model, scope, "explicit");
|
|
189
|
+
if (violation) throw new Error(violation.message);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
45
193
|
function terminalError(event: Record<string, unknown>): string {
|
|
46
194
|
for (const value of [event.error, event.result]) {
|
|
47
195
|
if (typeof value === "string" && value.trim()) return value.trim().slice(0, MAX_ERROR_LENGTH);
|
|
@@ -82,6 +230,8 @@ export function resolveClaudeCodeLaunch(input: {
|
|
|
82
230
|
command: string;
|
|
83
231
|
/** Test-only executable prefix for a fake Claude Code process. */
|
|
84
232
|
commandPrefixArgs?: readonly string[];
|
|
233
|
+
/** Trailing argv for an explicit model/thinking request, built by resolveClaudeCodeOverride. */
|
|
234
|
+
overrideArgs?: readonly string[];
|
|
85
235
|
}): {
|
|
86
236
|
command: string;
|
|
87
237
|
args: string[];
|
|
@@ -108,6 +258,9 @@ export function resolveClaudeCodeLaunch(input: {
|
|
|
108
258
|
"--no-session-persistence",
|
|
109
259
|
"--disable-slash-commands",
|
|
110
260
|
"--no-chrome",
|
|
261
|
+
// Session options go last: preflight builds versionArgs/helpArgs from `prefix`
|
|
262
|
+
// only, so these tokens never reach the --version/--help probes.
|
|
263
|
+
...(input.overrideArgs ?? []),
|
|
111
264
|
];
|
|
112
265
|
return {
|
|
113
266
|
command: input.command,
|
|
@@ -120,8 +273,10 @@ export function resolveClaudeCodeLaunch(input: {
|
|
|
120
273
|
validate(result) {
|
|
121
274
|
// Claude Code now publishes both semver (`2.1.259 (Claude Code)`) and
|
|
122
275
|
// calendar/platform (`2026.4.24 macos-arm64 (2026-04-27)`) versions.
|
|
123
|
-
// The launch flags are validated from --help below, so only require a
|
|
124
|
-
// recognizable release identifier here rather than one display format.
|
|
276
|
+
// The fixed launch flags are validated from --help below, so only require a
|
|
277
|
+
// recognizable release identifier here rather than one display format. The
|
|
278
|
+
// per-launch --model/--effort tokens are not part of this probe; a CLI that
|
|
279
|
+
// does not know them reports that itself on the launch.
|
|
125
280
|
if (!/^(?:\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)? \(Claude Code\)|\d{4}\.\d{1,2}\.\d{1,2} [A-Za-z0-9._-]+ \(\d{4}-\d{2}-\d{2}\))$/.test(result.version)) throw new Error(`Unsupported Claude Code version response: ${JSON.stringify(result.version)}.`);
|
|
126
281
|
for (const required of ["Claude Code - starts an interactive session", "--print", "--input-format", "stream-json", "--verbose", "--permission-mode", writer ? "acceptEdits" : "plan", "--tools", "--strict-mcp-config", "--mcp-config", "--setting-sources", "--no-session-persistence", "--disable-slash-commands", "--no-chrome"]) {
|
|
127
282
|
if (!result.help.includes(required)) throw new Error(`Claude Code help does not document required option ${JSON.stringify(required)}.`);
|
|
@@ -49,9 +49,9 @@ const DYNAMIC_EXPAND_FROM_KEYS = new Set(["output", "path"]);
|
|
|
49
49
|
const DYNAMIC_PARALLEL_KEYS = new Set(["agent", "task", "phase", "label", "outputSchema", "cwd", "machine", "output", "outputMode", "reads", "progress", "skill", "model", "fast", "toolBudget", "acceptance", "agentContract", "gateOn"]);
|
|
50
50
|
const RUNNER_DYNAMIC_PARALLEL_KEYS = new Set([
|
|
51
51
|
...DYNAMIC_PARALLEL_KEYS,
|
|
52
|
-
"outputName", "structured", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled", "waitToolDefaultTimeoutMs",
|
|
52
|
+
"runner", "outputName", "structured", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled", "waitToolDefaultTimeoutMs",
|
|
53
53
|
"structuredOutput", "structuredOutputSchema", "tools", "excludeTools", "allowNestedSubagents", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "builtinMcpTools", "mutationTools", "capabilityCeiling", "systemPrompt",
|
|
54
|
-
"systemPromptMode", "thinking", "requestedModel", "sessionFile", "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "parentSessionId", "requiredExtensions", "launchResolvedExtensions", "requestedCwd", "machineEnv",
|
|
54
|
+
"systemPromptMode", "thinking", "requestedModel", "sessionFile", "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "parentSessionId", "parentSessionFile", "requiredExtensions", "launchResolvedExtensions", "requestedCwd", "machineEnv",
|
|
55
55
|
]);
|
|
56
56
|
const DYNAMIC_COLLECT_KEYS = new Set(["as", "outputSchema"]);
|
|
57
57
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
|
+
import { resolveNodeExecutable } from "../../shared/node-executable.ts";
|
|
4
5
|
|
|
5
6
|
const MAX_PROBE_OUTPUT_BYTES = 256 * 1024;
|
|
6
7
|
const MAX_PROBE_TIMEOUT_MS = 5_000;
|
|
@@ -40,20 +41,28 @@ export type ExternalCliBinaryAvailability =
|
|
|
40
41
|
| { available: true }
|
|
41
42
|
| { available: false; unavailableReason: string };
|
|
42
43
|
|
|
43
|
-
|
|
44
|
-
|
|
44
|
+
const BATCH_FILE = /\.(cmd|bat)$/i;
|
|
45
|
+
|
|
46
|
+
function resolveBinary(command: string, env: NodeJS.ProcessEnv, platform: NodeJS.Platform = process.platform): string {
|
|
47
|
+
const windows = platform === "win32";
|
|
48
|
+
if (path.isAbsolute(command) || command.includes(path.sep) || (windows && command.includes("/"))) {
|
|
45
49
|
const resolved = path.resolve(command);
|
|
46
50
|
fs.accessSync(resolved, fs.constants.X_OK);
|
|
47
51
|
return resolved;
|
|
48
52
|
}
|
|
49
|
-
|
|
50
|
-
|
|
53
|
+
// Windows environment names are case-insensitive, and a copied process.env keeps its spelling (often `Path`).
|
|
54
|
+
const read = (name: string) => windows ? Object.entries(env).find(([key]) => key.toUpperCase() === name)?.[1] : env[name];
|
|
55
|
+
const pathExt = windows ? (read("PATHEXT") ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [];
|
|
56
|
+
const named = pathExt.some((extension) => command.toLowerCase().endsWith(extension.toLowerCase()));
|
|
57
|
+
const extensions = windows ? (named ? ["", ...pathExt] : pathExt) : [""];
|
|
58
|
+
for (const directory of (read("PATH") ?? "").split(path.delimiter)) {
|
|
51
59
|
if (!directory) continue;
|
|
52
60
|
for (const extension of extensions) {
|
|
53
61
|
const candidate = path.join(directory, `${command}${extension}`);
|
|
54
62
|
try {
|
|
55
63
|
fs.accessSync(candidate, fs.constants.X_OK);
|
|
56
|
-
|
|
64
|
+
// A batch shim resolves its target from its own directory (%dp0%), so keep the path it was found at.
|
|
65
|
+
return windows && BATCH_FILE.test(candidate) ? candidate : fs.realpathSync(candidate);
|
|
57
66
|
} catch {}
|
|
58
67
|
}
|
|
59
68
|
}
|
|
@@ -71,8 +80,47 @@ export function resolveExternalCliBinaryAvailability(command: string, env: NodeJ
|
|
|
71
80
|
}
|
|
72
81
|
}
|
|
73
82
|
|
|
83
|
+
// npm's cmd-shim output for a `#!/usr/bin/env node` bin, with CRLF normalized; the target path sits between the two parts.
|
|
84
|
+
const NPM_NODE_SHIM_HEAD = '@ECHO off\nGOTO start\n:find_dp0\nSET dp0=%~dp0\nEXIT /b\n:start\nSETLOCAL\nCALL :find_dp0\n\nIF EXIST "%dp0%\\node.exe" (\n SET "_prog=%dp0%\\node.exe"\n) ELSE (\n SET "_prog=node"\n SET PATHEXT=%PATHEXT:;.JS;=;%\n)\n\nendLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\';
|
|
85
|
+
const NPM_NODE_SHIM_TAIL = '" %*\n';
|
|
86
|
+
|
|
87
|
+
export interface ExternalCliSpawn {
|
|
88
|
+
command: string;
|
|
89
|
+
args: readonly string[];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Node refuses to spawn `.cmd`/`.bat` files without a shell (CVE-2024-27980), and a shell would expand
|
|
94
|
+
* `%` and `!` inside operator- and project-controlled arguments. On Windows, an npm Node shim is launched
|
|
95
|
+
* by running Node on its script directly; every other batch wrapper is rejected.
|
|
96
|
+
*/
|
|
97
|
+
export function resolveExternalCliSpawn(command: string, args: readonly string[], env: NodeJS.ProcessEnv, platform: NodeJS.Platform = process.platform): ExternalCliSpawn {
|
|
98
|
+
const unchanged = { command, args };
|
|
99
|
+
if (platform !== "win32") return unchanged;
|
|
100
|
+
let resolved: string;
|
|
101
|
+
try {
|
|
102
|
+
resolved = resolveBinary(command, env, platform);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (BATCH_FILE.test(command)) throw error;
|
|
105
|
+
return unchanged;
|
|
106
|
+
}
|
|
107
|
+
if (!BATCH_FILE.test(resolved)) return unchanged;
|
|
108
|
+
const shim = fs.readFileSync(resolved, "utf-8").replace(/\r\n/g, "\n");
|
|
109
|
+
const target = /\.cmd$/i.test(resolved) && shim.startsWith(NPM_NODE_SHIM_HEAD) && shim.endsWith(NPM_NODE_SHIM_TAIL)
|
|
110
|
+
? shim.slice(NPM_NODE_SHIM_HEAD.length, shim.length - NPM_NODE_SHIM_TAIL.length)
|
|
111
|
+
: "";
|
|
112
|
+
const directory = path.dirname(resolved);
|
|
113
|
+
const script = path.resolve(directory, target.split("\\").join(path.sep));
|
|
114
|
+
if (!target || /^\\|["%:/\n]/.test(target) || !fs.statSync(script, { throwIfNoEntry: false })?.isFile()) {
|
|
115
|
+
throw new Error(`External CLI '${resolved}' is a batch wrapper that cannot run without a shell. On Windows, only npm-generated Node shims and .exe files can launch.`);
|
|
116
|
+
}
|
|
117
|
+
const bundledNode = path.join(directory, "node.exe");
|
|
118
|
+
return { command: fs.existsSync(bundledNode) ? bundledNode : resolveNodeExecutable(), args: [script, ...args] };
|
|
119
|
+
}
|
|
120
|
+
|
|
74
121
|
function probeWithTimeout(binaryPath: string, args: readonly string[], env: NodeJS.ProcessEnv, label: string, timeoutMs: number, cwd?: string): string {
|
|
75
|
-
const
|
|
122
|
+
const launch = resolveExternalCliSpawn(binaryPath, args, env);
|
|
123
|
+
const result = spawnSync(launch.command, launch.args, {
|
|
76
124
|
cwd,
|
|
77
125
|
env,
|
|
78
126
|
encoding: "utf-8",
|
|
@@ -10,8 +10,10 @@ import { omitGitRoutingEnv } from "./git-environment.ts";
|
|
|
10
10
|
import {
|
|
11
11
|
invalidateExternalCliPreflight,
|
|
12
12
|
preflightExternalCli,
|
|
13
|
+
resolveExternalCliSpawn,
|
|
13
14
|
type ExternalCliPreflightResult,
|
|
14
15
|
type ExternalCliPreflightSpec,
|
|
16
|
+
type ExternalCliSpawn,
|
|
15
17
|
} from "./external-cli-preflight.ts";
|
|
16
18
|
|
|
17
19
|
const MAX_OUTPUT_TAIL_BYTES = 64 * 1024;
|
|
@@ -198,6 +200,7 @@ export function runExternalCli(input: {
|
|
|
198
200
|
};
|
|
199
201
|
const env = externalEnvironment(input.environment?.allowlist, input.environment?.values);
|
|
200
202
|
let preflight: ExternalCliPreflightResult | undefined;
|
|
203
|
+
let launch: ExternalCliSpawn;
|
|
201
204
|
try {
|
|
202
205
|
for (const directory of input.temporaryDirectories ?? []) {
|
|
203
206
|
fs.mkdirSync(directory, { mode: 0o700 });
|
|
@@ -210,6 +213,7 @@ export function runExternalCli(input: {
|
|
|
210
213
|
finally { fs.closeSync(promptDescriptor); }
|
|
211
214
|
}
|
|
212
215
|
if (input.preflight) preflight = preflightExternalCli(input.command, input.preflight, env, input.cwd);
|
|
216
|
+
launch = resolveExternalCliSpawn(preflight?.binaryPath ?? input.command, input.args ?? [], env);
|
|
213
217
|
} catch (error) {
|
|
214
218
|
const endedAt = Date.now();
|
|
215
219
|
const externalProcess = { startedAt, endedAt, durationMs: endedAt - startedAt, exitCode: 1, processSignal: null, stdoutPath, stderrPath, ...(input.finalOutputPath ? { finalOutputPath: input.finalOutputPath } : {}) } satisfies ExternalProcessStatus;
|
|
@@ -329,7 +333,7 @@ export function runExternalCli(input: {
|
|
|
329
333
|
}
|
|
330
334
|
appendPendingLine(chunk.subarray(start));
|
|
331
335
|
};
|
|
332
|
-
const child = spawn(
|
|
336
|
+
const child = spawn(launch.command, launch.args, {
|
|
333
337
|
cwd: input.cwd,
|
|
334
338
|
env,
|
|
335
339
|
stdio: ["pipe", "pipe", "pipe"],
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
2
|
+
|
|
3
|
+
/** Pi 1 reports shell failures as results; the command controller owns a rejected failure path. */
|
|
4
|
+
export function requireSuccessfulCommandResult<T extends AgentToolResult<unknown>>(result: T): T {
|
|
5
|
+
if ((result as T & { isError?: boolean }).isError === true) {
|
|
6
|
+
const message = result.content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
|
|
7
|
+
throw new Error(message || "Command failed.");
|
|
8
|
+
}
|
|
9
|
+
return result;
|
|
10
|
+
}
|
|
@@ -167,10 +167,11 @@ export class HerdrPlacedRunOwner {
|
|
|
167
167
|
|
|
168
168
|
export class BridgeChannel {
|
|
169
169
|
readonly socket: net.Socket; readonly decoder = new HerdrPiFrameDecoder(); readonly listeners = new Set<(frame: HerdrPiFrame) => void>(); readonly waiters = new Map<string, { resolve(frame: HerdrPiFrame): void; reject(error: Error): void }>(); readonly runId: string; readonly frames: HerdrPiFrame[] = [];
|
|
170
|
-
readonly failure: Promise<never>; #rejectFailure!: (error: Error) => void; #failed = false;
|
|
171
|
-
constructor(socketPath: string, runId: string) { this.runId = runId; this.failure = new Promise<never>((_resolve, reject) => { this.#rejectFailure = reject; }); this.failure.catch(() => {}); this.socket = net.createConnection(socketPath); this.socket.on("data", (chunk: Buffer) => { try { for (const frame of this.decoder.push(chunk)) { if (frame.runId !== runId) throw new Error("Bridge run identity mismatch."); this.frames.push(frame); if (this.frames.length > 1024) throw new Error("Bridge replay queue exceeded its bound."); const key = typeof frame.requestId === "string" ? `${frame.type}:${frame.requestId}` : ""; const waiter = this.waiters.get(key); if (waiter) { this.waiters.delete(key); waiter.resolve(frame); } for (const listener of this.listeners) listener(frame); } } catch (error) { this.fail(error as Error); } }); this.socket.on("error", (error) => this.fail(error)); this.socket.on("close", () => { if (!this.#failed) this.fail(new Error("Remote Pi bridge connection was lost; task state is unknown.")); }); }
|
|
170
|
+
readonly failure: Promise<never>; #rejectFailure!: (error: Error) => void; #failed = false; #adopted = false;
|
|
171
|
+
constructor(socketPath: string, runId: string) { this.runId = runId; this.failure = new Promise<never>((_resolve, reject) => { this.#rejectFailure = reject; }); this.failure.catch(() => {}); this.socket = net.createConnection(socketPath); this.socket.on("data", (chunk: Buffer) => { try { for (const frame of this.decoder.push(chunk)) { if (frame.runId !== runId) throw new Error("Bridge run identity mismatch."); if (!this.#adopted) { this.frames.push(frame); if (this.frames.length > 1024) throw new Error("Bridge replay queue exceeded its bound."); } const key = typeof frame.requestId === "string" ? `${frame.type}:${frame.requestId}` : ""; const waiter = this.waiters.get(key); if (waiter) { this.waiters.delete(key); waiter.resolve(frame); } for (const listener of this.listeners) listener(frame); } } catch (error) { this.fail(error as Error); } }); this.socket.on("error", (error) => this.fail(error)); this.socket.on("close", () => { if (!this.#failed) this.fail(new Error("Remote Pi bridge connection was lost; task state is unknown.")); }); }
|
|
172
172
|
fail(error: Error) { if (this.#failed) return; this.#failed = true; this.#rejectFailure(error); for (const waiter of this.waiters.values()) waiter.reject(error); this.waiters.clear(); }
|
|
173
173
|
get failed() { return this.#failed; }
|
|
174
|
+
adopt(listener: (frame: HerdrPiFrame) => void): HerdrPiFrame[] { this.#adopted = true; this.listeners.add(listener); return this.frames.splice(0); }
|
|
174
175
|
wait(type: string, requestId: string): Promise<HerdrPiFrame> { return new Promise((resolve, reject) => this.waiters.set(`${type}:${requestId}`, { resolve, reject })); }
|
|
175
176
|
configure(resources: { agent: string; skills?: string[]; toolCeiling?: string[]; reads?: string[] | false }) { const requestId = `cfg_${randomBytes(6).toString("hex")}`; const waiting = this.wait("configured", requestId); this.socket.write(encodeHerdrPiFrame({ protocol: HERDR_PI_PROTOCOL, runId: this.runId, type: "configure", requestId, resources })); return waiting; }
|
|
176
177
|
supervisorDelivered(requestId: string) { this.socket.write(encodeHerdrPiFrame({ protocol: HERDR_PI_PROTOCOL, runId: this.runId, type: "supervisor-delivered", requestId })); }
|
|
@@ -196,13 +197,13 @@ export class HerdrPiSession implements ChildSession {
|
|
|
196
197
|
readonly #operations = new Map<string, { resolve(): void; reject(error: Error): void; accepted: boolean; settled: boolean }>();
|
|
197
198
|
#snapshot: HerdrRunSnapshot; bridgeForward: { close(): Promise<void> }; bridge: BridgeChannel; readonly requestedTools: string[] | undefined; readonly model: string | undefined; #evidenceCursor = 0; #reconnecting?: Promise<void>; #reconnectFactory?: () => Promise<void>; #reconnectFailure?: Error;
|
|
198
199
|
#replyTimer?: NodeJS.Timeout; readonly supervisorDir: string | undefined; readonly runtime: ChildRuntimeConfig; readonly owner: HerdrPlacedRunOwner;
|
|
199
|
-
constructor(owner: HerdrPlacedRunOwner, bridgeForward: { close(): Promise<void> }, bridge: BridgeChannel, requestedTools: string[] | undefined, model: string | undefined, runtime: ChildRuntimeConfig, initialGit?: HerdrRemoteGitStatus) { this.owner = owner; this.bridgeForward = bridgeForward; this.bridge = bridge; this.requestedTools = requestedTools; this.model = model; this.runtime = runtime; this.supervisorDir = runtime.supervisorChannelDir; this.#snapshot = { connection: "connected", state: "ready", identity: owner.identity, revision: 0 }; this.#initialGit = initialGit; bridge.
|
|
200
|
+
constructor(owner: HerdrPlacedRunOwner, bridgeForward: { close(): Promise<void> }, bridge: BridgeChannel, requestedTools: string[] | undefined, model: string | undefined, runtime: ChildRuntimeConfig, initialGit?: HerdrRemoteGitStatus) { this.owner = owner; this.bridgeForward = bridgeForward; this.bridge = bridge; this.requestedTools = requestedTools; this.model = model; this.runtime = runtime; this.supervisorDir = runtime.supervisorChannelDir; this.#snapshot = { connection: "connected", state: "ready", identity: owner.identity, revision: 0 }; this.#initialGit = initialGit; bridge.adopt((frame) => this.#frame(frame)); if (this.supervisorDir) { this.#replyTimer = setInterval(() => { const replies = path.join(this.supervisorDir!, "replies"); for (const name of fs.existsSync(replies) ? fs.readdirSync(replies) : []) { const file = path.join(replies, name); try { const value = JSON.parse(fs.readFileSync(file, "utf8")) as { message?: unknown; requestId?: unknown }; if (typeof value.message === "string" && typeof value.requestId === "string") void this.#operation("supervisor-reply", value.message, value.requestId).then(() => fs.rmSync(file, { force: true })); } catch {} } }, 50); this.#replyTimer.unref?.(); } }
|
|
200
201
|
get identity(): HerdrRunIdentity { return this.owner.identity!; } set identity(value: HerdrRunIdentity) { this.owner.identity = value; }
|
|
201
202
|
get connection(): HerdrForwardedConnection { return this.owner.connection; } set connection(value: HerdrForwardedConnection) { this.owner.connection = value; }
|
|
202
203
|
armReconnect(factory: () => Promise<void>) { this.#reconnectFactory = factory; const observed = this.bridge; observed.failure.catch(() => { if (this.bridge === observed) void this.reconnect(); }); }
|
|
203
204
|
get evidenceCursor() { return this.#evidenceCursor; }
|
|
204
205
|
async reconnect() { if (this.#disposed || !this.#reconnectFactory || this.#reconnectFailure) return; this.#snapshot = { ...this.#snapshot, connection: "unknown", state: "unknown", revision: this.#snapshot.revision + 1 }; this.#reconnecting ??= this.#reconnectFactory().catch((error) => { const unknown = this.#reconnectFailure = new Error(`Remote Pi reconciliation failed; task state is unknown: ${error instanceof Error ? error.message : String(error)}`); for (const operation of this.#operations.values()) if (!operation.settled) { operation.settled = true; operation.reject(unknown); } }).finally(() => { this.#reconnecting = undefined; }); await this.#reconnecting; }
|
|
205
|
-
async replaceTransport(input: { connection: HerdrForwardedConnection; bridgeForward: { close(): Promise<void> }; bridge: BridgeChannel; unsubscribe: () => void; paneId: string; cursor: number; state: HerdrRunSnapshot["state"] }) { if (this.#disposed) { input.unsubscribe(); input.bridge.close(); await input.bridgeForward.close(); await input.connection.close(); return; } const old = { bridgeForward: this.bridgeForward, bridge: this.bridge }; this.bridgeForward = input.bridgeForward; this.bridge = input.bridge; this.identity = { ...this.identity, paneId: input.paneId }; this.#reconnectFailure = undefined; for (const frame of input.bridge.
|
|
206
|
+
async replaceTransport(input: { connection: HerdrForwardedConnection; bridgeForward: { close(): Promise<void> }; bridge: BridgeChannel; unsubscribe: () => void; paneId: string; cursor: number; state: HerdrRunSnapshot["state"] }) { if (this.#disposed) { input.unsubscribe(); input.bridge.close(); await input.bridgeForward.close(); await input.connection.close(); return; } const old = { bridgeForward: this.bridgeForward, bridge: this.bridge }; this.bridgeForward = input.bridgeForward; this.bridge = input.bridge; this.identity = { ...this.identity, paneId: input.paneId }; this.#reconnectFailure = undefined; for (const frame of input.bridge.adopt((frame) => this.#frame(frame))) if (typeof frame.cursor === "number" && frame.cursor > this.#evidenceCursor) this.#frame(frame); for (const operation of this.#operations.values()) if (!operation.accepted && !operation.settled) { operation.settled = true; operation.reject(new Error("Remote operation was not accepted before transport loss; task state is unknown.")); } this.#evidenceCursor = Math.max(this.#evidenceCursor, input.cursor); this.#snapshot = { connection: "connected", state: input.state, identity: this.identity, revision: this.#snapshot.revision + 1 }; const ownerReplacement = this.owner.replaceConnection({ connection: input.connection, unsubscribe: input.unsubscribe, paneId: input.paneId, state: input.state }); old.bridge.close(); await old.bridgeForward.close(); await ownerReplacement; if (this.#disposed) { await this.owner.cleanup(this.#aborted); return; } this.armReconnect(this.#reconnectFactory!); }
|
|
206
207
|
observeHerdr(value: unknown) { const data = value && typeof value === "object" ? (value as { data?: Record<string, unknown> }).data : undefined; if (!data || (data.terminal_id !== this.identity.terminalId && data.pane_id !== this.identity.paneId)) return; this.#snapshot = { ...this.#snapshot, revision: this.#snapshot.revision + 1, state: herdrRunState(data.agent_status, this.#snapshot.state) }; }
|
|
207
208
|
#frame(frame: HerdrPiFrame) { if (typeof frame.cursor === "number") { if (frame.cursor <= this.#evidenceCursor) return; this.#evidenceCursor = frame.cursor; } if (frame.nativeSessionId !== this.identity.nativeSessionId) { this.bridge.fail(new Error("Remote Pi native session identity changed.")); void this.connection.close(); return; } if (frame.type === "accepted" && typeof frame.requestId === "string") { const operation = this.#operations.get(frame.requestId); if (operation) operation.accepted = true; } if (frame.type === "supervisor-request" && this.supervisorDir && typeof frame.requestId === "string") this.#relaySupervisor(frame); if (frame.type === "event" && frame.event && typeof frame.event === "object") { const event = frame.event as ChildSessionEvent; const message = event.message as AgentMessage | undefined; if (event.type === "message_end" && message) this.#messages.push(message); for (const listener of this.#listeners) listener(event); } if (frame.type === "settled" && typeof frame.requestId === "string") { if (frame.finalAssistant && typeof frame.finalAssistant === "object") { const message = frame.finalAssistant as AgentMessage; if (!this.#messages.includes(message)) this.#messages.push(message); } if (frame.finalGit && typeof frame.finalGit === "object") this.#finalGit = frame.finalGit as HerdrRemoteGitStatus; const operation = this.#operations.get(frame.requestId); if (operation && !operation.settled) { operation.accepted = true; operation.settled = true; frame.idle === true && frame.pending === false ? operation.resolve() : operation.reject(new Error("Remote Pi did not settle with an empty native queue.")); } for (const listener of this.#listeners) listener({ type: "agent_settled" }); } }
|
|
208
209
|
#relaySupervisor(frame: HerdrPiFrame) { if (!this.supervisorDir || typeof frame.requestId !== "string") return; const reason = frame.reason; if (reason !== "need_decision" && reason !== "interview_request" && reason !== "progress_update") return; const createdAt = Date.now(); const file = path.join(this.supervisorDir, "requests", `${path.basename(frame.requestId)}.json`); 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 }; try { fs.writeFileSync(file, JSON.stringify(request), { mode: 0o600, flag: "wx" }); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; const existing = JSON.parse(fs.readFileSync(file, "utf8")) as { id?: unknown; reason?: unknown }; if (existing.id !== frame.requestId || existing.reason !== reason) throw new Error("Supervisor relay identity changed during replay."); } if (reason === "progress_update") this.bridge.supervisorDelivered(frame.requestId); }
|
|
@@ -173,10 +173,13 @@ function usesBuiltinMcp(host: McpRuntimeSnapshotHost | undefined): host is McpRu
|
|
|
173
173
|
}
|
|
174
174
|
|
|
175
175
|
/**
|
|
176
|
-
* Pi names built-in MCP tools `mcp__<server>__<tool>` with
|
|
177
|
-
* in the namespace `mcp__<server
|
|
176
|
+
* Pi names built-in MCP tools `mcp__<server>__<tool>` with everything but `[A-Za-z0-9_]` replaced
|
|
177
|
+
* by `_`, in the namespace `mcp__<server>` with `-` replaced by `_`. Selectors name the raw tool;
|
|
178
|
+
* the server part may be the configured name or its `-`→`_` form, since Pi refuses two servers
|
|
179
|
+
* whose names differ only in `-` and `_`. An overlong name, or one an earlier tool already took (`a_b`
|
|
178
180
|
* before `a.b`), gets a suffix hashed from the raw server and tool (Pi's `createMcpToolName`), so
|
|
179
|
-
* that suffixed name identifies the tool
|
|
181
|
+
* that suffixed name identifies the tool, and only the configured server name selects it. The
|
|
182
|
+
* unsuffixed name may belong to another raw tool; the
|
|
180
183
|
* child checks each granted tool's raw identity before it exposes the tool.
|
|
181
184
|
*/
|
|
182
185
|
function resolveBuiltinMcpSelections(selectors: string[], tools: readonly McpHostToolInfo[]): McpDirectToolResolution {
|
|
@@ -185,7 +188,7 @@ function resolveBuiltinMcpSelections(selectors: string[], tools: readonly McpHos
|
|
|
185
188
|
for (const selector of selectors) {
|
|
186
189
|
const slash = selector.indexOf("/");
|
|
187
190
|
const server = slash === -1 ? selector : selector.slice(0, slash);
|
|
188
|
-
const inServer = tools.filter((tool) => tool.namespace?.name === `mcp__${server}`);
|
|
191
|
+
const inServer = tools.filter((tool) => tool.namespace?.name === `mcp__${server.replace(/-/g, "_")}`);
|
|
189
192
|
const toolName = slash === -1 ? undefined : builtinMcpToolNames(server, selector.slice(slash + 1)).find((name) => inServer.some((tool) => tool.name === name));
|
|
190
193
|
const matches = inServer.filter((tool) => tool.exposure !== "hidden" && (slash === -1 || tool.name === toolName));
|
|
191
194
|
if (matches.length === 0) unresolvedSelectors.push(selector);
|
|
@@ -198,7 +201,7 @@ function resolveBuiltinMcpSelections(selectors: string[], tools: readonly McpHos
|
|
|
198
201
|
|
|
199
202
|
/** The names Pi's `createMcpToolName` can give a raw tool, the hash-suffixed one first. */
|
|
200
203
|
function builtinMcpToolNames(server: string, tool: string): string[] {
|
|
201
|
-
const name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_
|
|
204
|
+
const name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, "_");
|
|
202
205
|
const hash = createHash("sha256").update(`${server}\0${tool}`).digest("hex").slice(0, 8);
|
|
203
206
|
const suffixed = `${name.slice(0, 64 - hash.length - 1)}_${hash}`;
|
|
204
207
|
return name.length <= 64 ? [suffixed, name] : [suffixed];
|
|
@@ -74,3 +74,28 @@ export function formatChildModelResolutionDiagnostic(diagnostic: ChildModelResol
|
|
|
74
74
|
`If ${model} is served by a provider extension, that extension is not loaded for this child: list it in \`subagentOnlyExtensions\` or \`extensions\` in the agent frontmatter, or leave \`extensions\` unset so the child loads the ambient extensions.`,
|
|
75
75
|
].join("\n");
|
|
76
76
|
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Explain a local foreground child that failed before any successful response
|
|
80
|
+
* on a provider it inherited from the parent's registry. The child got the
|
|
81
|
+
* provider but not the parent extension that registered it, so a provider that
|
|
82
|
+
* depends on that extension's session hooks can reject the child's requests.
|
|
83
|
+
* Whether this provider does is unknown here, hence the conditional wording.
|
|
84
|
+
*/
|
|
85
|
+
export function formatInheritedProviderDiagnostic(diagnostic: ChildModelResolutionDiagnostic & { provider: string }): string {
|
|
86
|
+
const subject = diagnostic.agent ? `Agent '${diagnostic.agent}'` : "Subagent";
|
|
87
|
+
const model = diagnostic.model ? `'${diagnostic.model}'` : "this model";
|
|
88
|
+
const provider = `'${diagnostic.provider}'`;
|
|
89
|
+
const facts = `${subject} ran as a foreground child, which never loads the parent's ambient extensions. Provider ${provider} for ${model} was registered by a parent extension; the child inherited the provider but not that extension's session hooks.`;
|
|
90
|
+
if (capabilityCeilingDeniesExtensions(diagnostic)) {
|
|
91
|
+
return [
|
|
92
|
+
facts,
|
|
93
|
+
`${denyExtensionsClause(diagnostic)}, so that extension cannot load for this child: \`async: true\` does not help either, and listed \`subagentOnlyExtensions\` or \`extensions\` entries are suppressed.`,
|
|
94
|
+
`If ${provider} depends on those hooks, relax the capability ceiling to allow extensions, or use a model whose provider does not.`,
|
|
95
|
+
].join("\n");
|
|
96
|
+
}
|
|
97
|
+
return [
|
|
98
|
+
facts,
|
|
99
|
+
`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.`,
|
|
100
|
+
].join("\n");
|
|
101
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { splitKnownThinkingSuffix as splitThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
|
|
2
2
|
import { checkModelScope, SCOPED_PATTERN, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
|
|
3
|
+
import { editDistance } from "../../shared/edit-distance.ts";
|
|
3
4
|
|
|
4
5
|
export type { AvailableModelInfo };
|
|
5
6
|
|
|
@@ -10,15 +11,23 @@ export interface ModelSelectionEvidence {
|
|
|
10
11
|
|
|
11
12
|
export { splitThinkingSuffix };
|
|
12
13
|
|
|
13
|
-
/**
|
|
14
|
+
/**
|
|
15
|
+
* Aliases apply only to the resolved launch candidate (without its thinking suffix) and the exact raw response ID.
|
|
16
|
+
* When the child's live selection is a Pi virtual model, assistant messages name the physical model it dispatched
|
|
17
|
+
* to, so the virtual selection's provider/id is compared exactly with the launch candidate instead.
|
|
18
|
+
*/
|
|
14
19
|
export function formatSubagentModelVerificationError(
|
|
15
20
|
expectedModel: string,
|
|
16
21
|
observedModel: string,
|
|
17
22
|
availableModels: AvailableModelInfo[] | undefined,
|
|
18
23
|
modelResponseAliases?: Record<string, string[]>,
|
|
24
|
+
observedVirtualModel?: string,
|
|
19
25
|
): string | undefined {
|
|
20
26
|
if (!availableModels || availableModels.length === 0) return undefined;
|
|
21
27
|
const expectedBase = splitThinkingSuffix(expectedModel).baseModel;
|
|
28
|
+
if (observedVirtualModel !== undefined) {
|
|
29
|
+
return observedVirtualModel === expectedBase ? undefined : `model_verification_failed: native Pi child selected virtual model '${observedVirtualModel}', but the launch candidate was '${expectedModel}'. modelResponseAliases does not apply to a virtual-model selection.`;
|
|
30
|
+
}
|
|
22
31
|
if (modelResponseAliases && Object.hasOwn(modelResponseAliases, expectedBase)
|
|
23
32
|
&& modelResponseAliases[expectedBase]?.includes(observedModel)) return undefined;
|
|
24
33
|
const observedBase = splitThinkingSuffix(observedModel).baseModel;
|
|
@@ -254,6 +263,33 @@ function suggestAlternateProviderModel(
|
|
|
254
263
|
return `${suggestion}${thinkingSuffix}`;
|
|
255
264
|
}
|
|
256
265
|
|
|
266
|
+
const MAX_MODEL_CANDIDATES = 5;
|
|
267
|
+
|
|
268
|
+
/** Exact registry ids for an unresolved request: the same id under any provider first, then near spellings. */
|
|
269
|
+
function closestModelCandidates(model: string, availableModels: AvailableModelInfo[] | undefined): string[] {
|
|
270
|
+
if (!availableModels || availableModels.length === 0) return [];
|
|
271
|
+
const { baseModel, thinkingSuffix } = splitThinkingSuffix(model);
|
|
272
|
+
const { queryProvider, queryIdRaw } = splitQualifiedModelQuery(baseModel, availableModels);
|
|
273
|
+
const queryId = normalizeModelSegment(queryIdRaw);
|
|
274
|
+
const queryIdNoDate = stripTrailingDateStamp(queryId);
|
|
275
|
+
return availableModels
|
|
276
|
+
.map((entry) => {
|
|
277
|
+
const id = normalizeModelSegment(entry.id);
|
|
278
|
+
const distance = editDistance(queryId, id);
|
|
279
|
+
return {
|
|
280
|
+
fullId: entry.fullId,
|
|
281
|
+
sameId: id === queryId || stripTrailingDateStamp(id) === queryIdNoDate,
|
|
282
|
+
sameProvider: normalizeModelSegment(entry.provider) === queryProvider,
|
|
283
|
+
distance,
|
|
284
|
+
close: distance <= Math.max(2, Math.floor(id.length / 3)),
|
|
285
|
+
};
|
|
286
|
+
})
|
|
287
|
+
.filter((entry) => entry.sameId || entry.close)
|
|
288
|
+
.sort((left, right) => Number(right.sameId) - Number(left.sameId) || left.distance - right.distance || Number(right.sameProvider) - Number(left.sameProvider) || left.fullId.localeCompare(right.fullId))
|
|
289
|
+
.slice(0, MAX_MODEL_CANDIDATES)
|
|
290
|
+
.map((entry) => `${entry.fullId}${thinkingSuffix}`);
|
|
291
|
+
}
|
|
292
|
+
|
|
257
293
|
function resolveRequiredSubagentModelCandidate(
|
|
258
294
|
model: string,
|
|
259
295
|
availableModels: AvailableModelInfo[] | undefined,
|
|
@@ -262,8 +298,9 @@ function resolveRequiredSubagentModelCandidate(
|
|
|
262
298
|
const resolved = resolveSubagentModelCandidate(model, availableModels, preferredProvider);
|
|
263
299
|
if (resolved) return resolved;
|
|
264
300
|
const suggestion = suggestAlternateProviderModel(model, availableModels);
|
|
301
|
+
const candidates = closestModelCandidates(model, availableModels).filter((candidate) => candidate !== suggestion);
|
|
265
302
|
throw new Error(
|
|
266
|
-
`Unknown subagent model '${model}' in the active Pi model registry.${suggestion ? ` Did you mean '${suggestion}'?` : ""}`,
|
|
303
|
+
`Unknown subagent model '${model}' in the active Pi model registry.${suggestion ? ` Did you mean '${suggestion}'?` : ""}${candidates.length ? ` Closest registry models: ${candidates.join(", ")}.` : ""}`,
|
|
267
304
|
);
|
|
268
305
|
}
|
|
269
306
|
|
|
@@ -189,6 +189,11 @@ export function inheritedNestedParentAddressOf(runtime: { nestedParent?: { paren
|
|
|
189
189
|
};
|
|
190
190
|
}
|
|
191
191
|
|
|
192
|
+
/** The owner's reply when its foreground map has no route for a nested run; interrupt matches it exactly. */
|
|
193
|
+
export function nestedRunNotActiveMessage(runId: string): string {
|
|
194
|
+
return `Nested run ${runId} is not active in this fanout child.`;
|
|
195
|
+
}
|
|
196
|
+
|
|
192
197
|
export function resolveNestedAsyncDir(rootRunId: string, run: NestedRunSummary): string | undefined {
|
|
193
198
|
if (!run.asyncDir) return undefined;
|
|
194
199
|
const resolved = path.resolve(run.asyncDir);
|