@xzzpig/pi-subagents 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/docs/agents.md +15 -5
  3. package/docs/configuration.md +10 -0
  4. package/docs/extension-api.md +1 -1
  5. package/docs/missions.md +15 -1
  6. package/docs/models.md +6 -2
  7. package/docs/observability.md +8 -3
  8. package/docs/tool-reference.md +28 -3
  9. package/docs/workflows.md +2 -2
  10. package/package.json +1 -1
  11. package/src/agents/agents.ts +59 -3
  12. package/src/api/preflight.ts +42 -1
  13. package/src/extension/config.ts +4 -1
  14. package/src/extension/index.ts +23 -16
  15. package/src/extension/public-execution.ts +3 -0
  16. package/src/extension/reply-workflow-script.ts +1 -1
  17. package/src/extension/rpc.ts +1 -1
  18. package/src/extension/schemas.ts +5 -3
  19. package/src/extension/tool-description.ts +1 -1
  20. package/src/missions/goal-driver.ts +44 -31
  21. package/src/missions/store.ts +10 -1
  22. package/src/profiles/profiles.ts +5 -2
  23. package/src/runs/background/async-execution.ts +88 -6
  24. package/src/runs/background/async-job-tracker.ts +3 -2
  25. package/src/runs/background/await-async-run.ts +4 -2
  26. package/src/runs/background/control-channel.ts +43 -0
  27. package/src/runs/background/run-child-session.ts +13 -6
  28. package/src/runs/background/runner-aliases.ts +7 -4
  29. package/src/runs/background/scheduled-runs.ts +28 -13
  30. package/src/runs/background/stale-run-reconciler.ts +13 -2
  31. package/src/runs/background/subagent-runner.ts +43 -4
  32. package/src/runs/foreground/command-action.ts +41 -0
  33. package/src/runs/foreground/execution.ts +16 -7
  34. package/src/runs/foreground/subagent-executor.ts +63 -12
  35. package/src/runs/shared/child-commands.ts +228 -0
  36. package/src/runs/shared/child-session.ts +93 -19
  37. package/src/runs/shared/child-tool-plan.ts +1 -1
  38. package/src/runs/shared/claude-code-adapter.ts +157 -2
  39. package/src/runs/shared/dynamic-fanout.ts +1 -1
  40. package/src/runs/shared/external-cli-preflight.ts +54 -6
  41. package/src/runs/shared/external-cli-runner.ts +5 -1
  42. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -4
  43. package/src/runs/shared/model-resolution.ts +9 -1
  44. package/src/runs/shared/parallel-utils.ts +2 -0
  45. package/src/runs/shared/run-history.ts +87 -0
  46. package/src/runs/shared/subagent-control.ts +32 -17
  47. package/src/runs/shared/subagent-prompt-runtime.ts +12 -6
  48. package/src/shared/required-child-extensions.ts +39 -5
  49. package/src/shared/types.ts +6 -1
  50. package/src/slash/subagent-cost.ts +9 -5
  51. package/src/tui/render.ts +4 -4
  52. package/src/workflows/workflow-receipt.ts +2 -2
  53. package/src/workflows/workflow-resources.ts +7 -4
@@ -11,7 +11,9 @@ import * as fs from "node:fs";
11
11
  import * as path from "node:path";
12
12
  import { pathToFileURL } from "node:url";
13
13
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
14
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
14
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
15
+ import { CHILD_COMMAND_TOOL, createChildCommandRuntime } from "./child-commands.ts";
16
+ import { supervisorChannelDir } from "./child-tool-plan.ts";
15
17
  import { pinChildCacheRetention } from "../../shared/child-cache-retention.ts";
16
18
  import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
17
19
  import { resolvePackageSubpath } from "../background/runner-aliases.ts";
@@ -111,12 +113,16 @@ export interface ChildSession {
111
113
  abort(): Promise<void>;
112
114
  /** Emits `session_shutdown` to the child's extensions and disposes the session; resolves once that shutdown work is done. */
113
115
  dispose(): Promise<void>;
116
+ /** Final settlement check for commands owned by this child; unfinished commands are cancelled and reject completion. */
117
+ finishCommands?(): Promise<void>;
114
118
  /** True while Pi still has steering or follow-up input that has not started a turn. */
115
119
  hasQueuedMessages?(): boolean;
116
120
  readonly messages: readonly AgentMessage[];
117
121
  readonly sessionFile: string | undefined;
118
122
  readonly sessionId: string;
119
123
  readonly modelId: string | undefined;
124
+ /** Live provider/id of the selected model when Pi marks it virtual (`api === "pi-virtual"`); assistant messages then name the dispatched physical model. */
125
+ readonly virtualModelId?: string;
120
126
  readonly contextWindow?: number;
121
127
  readonly machineEvidence?: { machineId: string; initial?: HerdrRemoteGitStatus; final?: HerdrRemoteGitStatus };
122
128
  /** Event-updated pane-native status; reading it performs no network work. */
@@ -201,6 +207,30 @@ function prioritizeChildPromptRuntime<T extends { extensions: Array<{ path: stri
201
207
  return { ...result, extensions };
202
208
  }
203
209
 
210
+ /** Ambient bash overrides keep their original backend and priority. */
211
+ function prioritizeChildCommandRuntime<T extends { extensions: Array<{ path: string; tools?: Map<string, unknown> }> }>(result: T): T {
212
+ const index = result.extensions.findIndex(({ path }) => path === "<inline:pi-subagents:commands>");
213
+ if (index < 0) return result;
214
+ if (result.extensions.some((extension, otherIndex) => otherIndex !== index && extension.tools?.has("bash"))) {
215
+ const extensions = result.extensions.filter((_, otherIndex) => otherIndex !== index);
216
+ if (!extensions.some((extension) => extension.tools?.has(CHILD_COMMAND_TOOL))) {
217
+ const commands = result.extensions[index]!;
218
+ const registered = commands.tools!.get(CHILD_COMMAND_TOOL) as { definition: ToolDefinition };
219
+ const reason = "Native command controls are unavailable with the active custom bash backend. Use that backend's own command controls.";
220
+ extensions.push({ ...commands, tools: new Map([[CHILD_COMMAND_TOOL, { ...registered, definition: {
221
+ ...registered.definition, description: reason,
222
+ execute: async () => { throw new Error(reason); },
223
+ } }]]) });
224
+ }
225
+ return { ...result, extensions };
226
+ }
227
+ if (index === 0) return result;
228
+ const extensions = [...result.extensions];
229
+ const [commands] = extensions.splice(index, 1);
230
+ extensions.unshift(commands!);
231
+ return { ...result, extensions };
232
+ }
233
+
204
234
  /** One launch at a time from env application through `session_start`, so parallel launches never observe each other's `processEnv` while their extensions load and start. */
205
235
  let loading: Promise<unknown> = Promise.resolve();
206
236
 
@@ -311,6 +341,25 @@ function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModu
311
341
  }
312
342
  }
313
343
  if (Array.isArray(runtime.pendingNativeProviderRegistrations)) runtime.pendingNativeProviderRegistrations = [];
344
+ // Pi core flushes pendingVirtualModelRegistrations when a session binds extensions
345
+ // (agent-session-services), but this factory resolves the requested model before that
346
+ // binding, so an extension-registered virtual model never resolves for the child. The
347
+ // structural cast keeps compiling against SDK versions that predate virtual models;
348
+ // there the queue is absent and the loop is a no-op.
349
+ const virtualModelRuntime = modelRuntime as ModelRuntimeInstance & { registerVirtualModel?: (definition: unknown) => void };
350
+ const virtualModelQueue = runtime as { pendingVirtualModelRegistrations?: Array<{ definition: unknown; extensionPath: string }> };
351
+ const pendingVirtualModelRegistrations = virtualModelQueue.pendingVirtualModelRegistrations ?? [];
352
+ for (const { definition, extensionPath } of pendingVirtualModelRegistrations) {
353
+ if (typeof virtualModelRuntime.registerVirtualModel !== "function") break;
354
+ try {
355
+ virtualModelRuntime.registerVirtualModel(definition);
356
+ registered = true;
357
+ } catch (error) {
358
+ onError?.({ extensionPath, event: "register_virtual_model", error });
359
+ if (requiredPaths.has(extensionPath)) throw new Error(`Required child extension virtual model registration failed for '${extensionPath}': ${error instanceof Error ? error.message : String(error)}`);
360
+ }
361
+ }
362
+ if (Array.isArray(virtualModelQueue.pendingVirtualModelRegistrations)) virtualModelQueue.pendingVirtualModelRegistrations = [];
314
363
  return { claimedProviderIds, registered };
315
364
  }
316
365
 
@@ -389,6 +438,11 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
389
438
  ? await pi.ModelRuntime.create()
390
439
  : await sharedRuntime(pi);
391
440
  const agentDir = getAgentDir();
441
+ const commands = launch.runtime.runId && launch.runtime.agent && launch.runtime.childIndex !== undefined
442
+ && launch.tools?.includes("bash") && launch.tools.includes(CHILD_COMMAND_TOOL)
443
+ && !launch.excludeTools?.includes("bash") && !launch.excludeTools?.includes(CHILD_COMMAND_TOOL)
444
+ && typeof pi.createBashTool === "function"
445
+ ? createChildCommandRuntime(supervisorChannelDir(launch.runtime.runId, launch.runtime.agent, launch.runtime.childIndex)) : undefined;
392
446
  const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir, { projectTrusted: launch.projectTrusted });
393
447
  // Foreground children share Pi's global theme with the parent, so reinitializing it
394
448
  // would overwrite the parent's active light/dark appearance. Detached runners have
@@ -418,11 +472,30 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
418
472
  noThemes: true,
419
473
  noContextFiles: launch.noContextFiles,
420
474
  additionalExtensionPaths: builtinMcp ? [...launch.extensionPaths, "builtin:mcp"] : launch.extensionPaths,
421
- extensionFactories: [...launch.hooks, ...codemode, ...(builtinMcp ? [builtinMcp] : [])],
422
- extensionsOverride: prioritizeChildPromptRuntime,
475
+ extensionFactories: [...launch.hooks, ...(commands ? [{ name: "pi-subagents:commands", factory: (api: ExtensionAPI) => {
476
+ api.registerTool(commands.wrap(pi.createBashTool(launch.cwd, { commandPrefix: settingsManager.getShellCommandPrefix(), shellPath: settingsManager.getShellPath() }) as unknown as ToolDefinition));
477
+ api.registerTool(commands.tool());
478
+ } }] : []), ...codemode, ...(builtinMcp ? [builtinMcp] : [])],
479
+ extensionsOverride: (result) => prioritizeChildPromptRuntime(prioritizeChildCommandRuntime(result)),
423
480
  ...(launch.systemPrompt !== undefined ? { systemPrompt: launch.systemPrompt } : {}),
424
481
  ...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
425
482
  });
483
+ // pi's own hosts emit `session_shutdown` before disposing a session so the
484
+ // extensions loaded into it (ambient extensions included) release their
485
+ // watchers, servers, and timers. Do the same, then dispose.
486
+ const shutdownSession = async (session: Awaited<ReturnType<PiCodingAgentModule["createAgentSession"]>>["session"]): Promise<void> => {
487
+ try {
488
+ await commands?.shutdown();
489
+ const runner = session.extensionRunner;
490
+ if (runner.hasHandlers("session_shutdown")) {
491
+ await Promise.race([runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise<void>((resolve) => setTimeout(resolve, shutdownTimeoutMs).unref?.())]);
492
+ }
493
+ } catch (error) {
494
+ launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
495
+ } finally {
496
+ session.dispose();
497
+ }
498
+ };
426
499
  const open = async () => {
427
500
  const requiredPaths = new Set((launch.requiredExtensions ?? []).map(({ path }) => path));
428
501
  const savedTransientEnv = captureProcessEnv(launch.transientProcessEnv);
@@ -473,14 +546,27 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
473
546
  // (registration and session_start); restore transient keys so an
474
547
  // in-process child cannot leak them into the host process.
475
548
  restoreProcessEnv(savedTransientEnv);
549
+ // Pi reports handler failures through onError instead of throwing, so required startup failures must be collected here.
550
+ const requiredStartupErrors: string[] = [];
551
+ let binding = true;
476
552
  try {
477
553
  await session.bindExtensions({
478
554
  mode: "print",
479
- onError: (error) => launch.onExtensionError?.({ extensionPath: error.extensionPath, event: error.event, error: error.error }),
555
+ onError: (error) => {
556
+ if (binding && requiredPaths.has(error.extensionPath)) requiredStartupErrors.push(`${error.extensionPath} (${error.event}): ${error.error}`);
557
+ launch.onExtensionError?.({ extensionPath: error.extensionPath, event: error.event, error: error.error });
558
+ },
480
559
  });
481
560
  } catch (error) {
482
561
  session.dispose();
483
562
  throw error;
563
+ } finally {
564
+ binding = false;
565
+ }
566
+ if (requiredStartupErrors.length > 0) {
567
+ // Binding finished, so the other extensions' session_start handlers ran and may hold resources.
568
+ await shutdownSession(session);
569
+ throw new Error(`Required child extension failed during startup: ${requiredStartupErrors.join("; ")}`);
484
570
  }
485
571
  return session;
486
572
  };
@@ -488,21 +574,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
488
574
  loading = opened;
489
575
  const session = await opened;
490
576
  let pending: Promise<void> | undefined;
491
- // pi's own hosts emit `session_shutdown` before disposing a session so the
492
- // extensions loaded into it (ambient extensions included) release their
493
- // watchers, servers, and timers. Do the same, then dispose.
494
- const shutdown = async (): Promise<void> => {
495
- try {
496
- const runner = session.extensionRunner;
497
- if (runner.hasHandlers("session_shutdown")) {
498
- await Promise.race([runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise<void>((resolve) => setTimeout(resolve, shutdownTimeoutMs).unref?.())]);
499
- }
500
- } catch (error) {
501
- launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
502
- } finally {
503
- session.dispose();
504
- }
505
- };
577
+ const shutdown = () => shutdownSession(session);
506
578
  // Outside the launch lock: MCP servers connect after `session_start` without reading the per-launch env.
507
579
  if (builtinMcpTools.length) {
508
580
  const disposed = () => disposals !== disposalsAtStart;
@@ -519,6 +591,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
519
591
  const child: ChildSession = {
520
592
  subscribe: (listener) => session.subscribe((event) => listener(event as unknown as ChildSessionEvent)),
521
593
  prompt: (text) => session.prompt(text),
594
+ ...(commands ? { finishCommands: () => commands.finish() } : {}),
522
595
  steer: (text) => session.steer(text).then(() => undefined),
523
596
  followUp: (text) => session.followUp(text).then(() => undefined),
524
597
  abort: () => session.abort(),
@@ -537,6 +610,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
537
610
  get sessionFile() { return session.sessionFile; },
538
611
  get sessionId() { return session.sessionId; },
539
612
  get modelId() { return session.model ? `${session.model.provider}/${session.model.id}` : undefined; },
613
+ get virtualModelId() { return session.model?.api === "pi-virtual" ? `${session.model.provider}/${session.model.id}` : undefined; },
540
614
  get contextWindow() { return session.model?.contextWindow; },
541
615
  };
542
616
  live.add(child);
@@ -358,7 +358,7 @@ export function resolvePiLaunchToolPlan(
358
358
  const ceilingFilteredBuiltinTools =
359
359
  input.tools === undefined
360
360
  ? allowedToolSet
361
- ? [...allowedToolSet]
361
+ ? [...allowedToolSet].filter((tool) => tool !== "subagent_command")
362
362
  : []
363
363
  : (input.requireReadTool &&
364
364
  requestedBuiltinTools.length > 0 &&
@@ -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,7 +49,7 @@ 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
54
  "systemPromptMode", "thinking", "requestedModel", "sessionFile", "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "parentSessionId", "requiredExtensions", "launchResolvedExtensions", "requestedCwd", "machineEnv",
55
55
  ]);
@@ -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
- function resolveBinary(command: string, env: NodeJS.ProcessEnv): string {
44
- if (path.isAbsolute(command) || command.includes(path.sep)) {
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
- const extensions = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""];
50
- for (const directory of (env.PATH ?? "").split(path.delimiter)) {
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
- return fs.realpathSync(candidate);
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 result = spawnSync(binaryPath, [...args], {
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(preflight?.binaryPath ?? input.command, input.args ?? [], {
336
+ const child = spawn(launch.command, launch.args, {
333
337
  cwd: input.cwd,
334
338
  env,
335
339
  stdio: ["pipe", "pipe", "pipe"],
@@ -173,8 +173,9 @@ 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 invalid characters replaced by `_`,
177
- * in the namespace `mcp__<server>`. An overlong name, or one an earlier tool already took (`a_b`
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 server
178
+ * and tool. An overlong name, or one an earlier tool already took (`a_b`
178
179
  * before `a.b`), gets a suffix hashed from the raw server and tool (Pi's `createMcpToolName`), so
179
180
  * that suffixed name identifies the tool. The unsuffixed name may belong to another raw tool; the
180
181
  * child checks each granted tool's raw identity before it exposes the tool.
@@ -185,7 +186,7 @@ function resolveBuiltinMcpSelections(selectors: string[], tools: readonly McpHos
185
186
  for (const selector of selectors) {
186
187
  const slash = selector.indexOf("/");
187
188
  const server = slash === -1 ? selector : selector.slice(0, slash);
188
- const inServer = tools.filter((tool) => tool.namespace?.name === `mcp__${server}`);
189
+ const inServer = tools.filter((tool) => tool.namespace?.name === `mcp__${server.replace(/-/g, "_")}`);
189
190
  const toolName = slash === -1 ? undefined : builtinMcpToolNames(server, selector.slice(slash + 1)).find((name) => inServer.some((tool) => tool.name === name));
190
191
  const matches = inServer.filter((tool) => tool.exposure !== "hidden" && (slash === -1 || tool.name === toolName));
191
192
  if (matches.length === 0) unresolvedSelectors.push(selector);
@@ -198,7 +199,7 @@ function resolveBuiltinMcpSelections(selectors: string[], tools: readonly McpHos
198
199
 
199
200
  /** The names Pi's `createMcpToolName` can give a raw tool, the hash-suffixed one first. */
200
201
  function builtinMcpToolNames(server: string, tool: string): string[] {
201
- const name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_-]/g, "_");
202
+ const name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, "_");
202
203
  const hash = createHash("sha256").update(`${server}\0${tool}`).digest("hex").slice(0, 8);
203
204
  const suffixed = `${name.slice(0, 64 - hash.length - 1)}_${hash}`;
204
205
  return name.length <= 64 ? [suffixed, name] : [suffixed];
@@ -10,15 +10,23 @@ export interface ModelSelectionEvidence {
10
10
 
11
11
  export { splitThinkingSuffix };
12
12
 
13
- /** Aliases apply only to the resolved launch candidate (without its thinking suffix) and the exact raw response ID. */
13
+ /**
14
+ * Aliases apply only to the resolved launch candidate (without its thinking suffix) and the exact raw response ID.
15
+ * When the child's live selection is a Pi virtual model, assistant messages name the physical model it dispatched
16
+ * to, so the virtual selection's provider/id is compared exactly with the launch candidate instead.
17
+ */
14
18
  export function formatSubagentModelVerificationError(
15
19
  expectedModel: string,
16
20
  observedModel: string,
17
21
  availableModels: AvailableModelInfo[] | undefined,
18
22
  modelResponseAliases?: Record<string, string[]>,
23
+ observedVirtualModel?: string,
19
24
  ): string | undefined {
20
25
  if (!availableModels || availableModels.length === 0) return undefined;
21
26
  const expectedBase = splitThinkingSuffix(expectedModel).baseModel;
27
+ if (observedVirtualModel !== undefined) {
28
+ 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.`;
29
+ }
22
30
  if (modelResponseAliases && Object.hasOwn(modelResponseAliases, expectedBase)
23
31
  && modelResponseAliases[expectedBase]?.includes(observedModel)) return undefined;
24
32
  const observedBase = splitThinkingSuffix(observedModel).baseModel;
@@ -44,6 +44,8 @@ export interface RunnerSubagentStep {
44
44
  contextLimit?: number;
45
45
  fast?: boolean;
46
46
  thinking?: string;
47
+ /** Trailing Claude Code argv for an explicit model/thinking request. */
48
+ claudeCodeOverrideArgs?: string[];
47
49
  thinkingCeiling?: import("../../shared/model-info.ts").ThinkingLevel;
48
50
  requestedModel?: string;
49
51
  /** The primary model is inherited from the parent session and should not be verified against the child-reported active registry model. */