@xzzpig/pi-subagents 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +32 -16
  4. package/docs/configuration.md +76 -9
  5. package/docs/extension-api.md +6 -5
  6. package/docs/missions.md +28 -14
  7. package/docs/models.md +8 -4
  8. package/docs/observability.md +10 -5
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +90 -88
  11. package/docs/workflows.md +171 -173
  12. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  13. package/package.json +6 -6
  14. package/prompts/review-loop.md +1 -1
  15. package/skills/council-mode/SKILL.md +1 -1
  16. package/skills/pi-subagents/SKILL.md +12 -5
  17. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
  18. package/skills/pi-subagents/references/execution-controls.md +68 -67
  19. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
  21. package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
  22. package/src/agents/advertised-agent-prompt.ts +21 -41
  23. package/src/agents/agent-management.ts +2 -2
  24. package/src/agents/agents.ts +66 -3
  25. package/src/api/preflight.ts +109 -63
  26. package/src/extension/config.ts +15 -4
  27. package/src/extension/control-notices.ts +3 -0
  28. package/src/extension/doctor.ts +1 -0
  29. package/src/extension/fanout-child.ts +12 -3
  30. package/src/extension/herdr-pi-bridge.ts +2 -0
  31. package/src/extension/index.ts +90 -174
  32. package/src/extension/public-execution.ts +72 -35
  33. package/src/extension/reply-workflow-script.ts +58 -0
  34. package/src/extension/rpc.ts +29 -10
  35. package/src/extension/schemas.ts +40 -135
  36. package/src/extension/tool-activation.ts +57 -108
  37. package/src/extension/tool-description.ts +62 -27
  38. package/src/extension/upgrade-notice.ts +40 -0
  39. package/src/integrations/herdr-status.ts +19 -3
  40. package/src/intercom/native-supervisor-channel.ts +4 -1
  41. package/src/missions/goal-driver.ts +44 -31
  42. package/src/missions/store.ts +10 -1
  43. package/src/profiles/profiles.ts +5 -2
  44. package/src/runs/background/async-execution.ts +146 -59
  45. package/src/runs/background/async-job-tracker.ts +66 -24
  46. package/src/runs/background/async-retention.ts +46 -16
  47. package/src/runs/background/await-async-run.ts +78 -0
  48. package/src/runs/background/chain-root-attachment.ts +4 -4
  49. package/src/runs/background/control-channel.ts +61 -2
  50. package/src/runs/background/notify.ts +5 -0
  51. package/src/runs/background/run-child-session.ts +17 -7
  52. package/src/runs/background/run-status.ts +6 -0
  53. package/src/runs/background/runner-aliases.ts +37 -6
  54. package/src/runs/background/runner-child-launch.ts +3 -0
  55. package/src/runs/background/scheduled-runs.ts +33 -18
  56. package/src/runs/background/stale-run-reconciler.ts +13 -2
  57. package/src/runs/background/subagent-runner.ts +58 -5
  58. package/src/runs/foreground/async-stop-action.ts +17 -3
  59. package/src/runs/foreground/command-action.ts +41 -0
  60. package/src/runs/foreground/execution.ts +145 -131
  61. package/src/runs/foreground/subagent-executor.ts +546 -296
  62. package/src/runs/shared/async-status-projection.ts +5 -0
  63. package/src/runs/shared/child-commands.ts +228 -0
  64. package/src/runs/shared/child-launch.ts +15 -2
  65. package/src/runs/shared/child-session.ts +184 -24
  66. package/src/runs/shared/child-tool-plan.ts +16 -4
  67. package/src/runs/shared/claude-code-adapter.ts +157 -2
  68. package/src/runs/shared/dynamic-fanout.ts +2 -2
  69. package/src/runs/shared/external-cli-preflight.ts +54 -6
  70. package/src/runs/shared/external-cli-runner.ts +5 -1
  71. package/src/runs/shared/mcp-config-sources.ts +2 -1
  72. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -11
  73. package/src/runs/shared/model-resolution.ts +38 -10
  74. package/src/runs/shared/model-scope.ts +28 -9
  75. package/src/runs/shared/nested-events.ts +55 -55
  76. package/src/runs/shared/parallel-utils.ts +4 -0
  77. package/src/runs/shared/pi-spawn.ts +7 -95
  78. package/src/runs/shared/run-history.ts +87 -0
  79. package/src/runs/shared/subagent-control.ts +32 -17
  80. package/src/runs/shared/subagent-prompt-runtime.ts +14 -6
  81. package/src/runs/shared/worktree.ts +1 -1
  82. package/src/shared/disabled-features.ts +123 -0
  83. package/src/shared/extension-context.ts +13 -0
  84. package/src/shared/model-info.ts +9 -0
  85. package/src/shared/required-child-extensions.ts +39 -5
  86. package/src/shared/settings.ts +1 -1
  87. package/src/shared/types.ts +27 -1
  88. package/src/slash/prompt-template-bridge.ts +2 -2
  89. package/src/slash/slash-commands.ts +10 -5
  90. package/src/slash/subagent-cost.ts +9 -5
  91. package/src/slash/subagents-admin.ts +24 -24
  92. package/src/tui/fleet-status.ts +14 -6
  93. package/src/tui/fleet.ts +14 -2
  94. package/src/tui/render.ts +117 -56
  95. package/src/tui/running-tone.ts +28 -0
  96. package/src/watchdog/diff-tool.ts +23 -9
  97. package/src/watchdog/register-child.ts +3 -3
  98. package/src/watchdog/register-main.ts +3 -3
  99. package/src/watchdog/review.ts +2 -2
  100. package/src/watchdog/turn-delta.ts +1 -1
  101. package/src/workflows/chat-progress.ts +2 -2
  102. package/src/workflows/scripted-workflow.ts +117 -37
  103. package/src/workflows/structured-workflow-scripts.ts +177 -0
  104. package/src/workflows/workflow-checklist.ts +6 -0
  105. package/src/workflows/workflow-receipt.ts +10 -4
  106. package/src/workflows/workflow-resources.ts +44 -16
  107. package/src/workflows/workflow-reuse.ts +120 -0
  108. package/src/workflows/workflow-revival.ts +123 -0
@@ -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";
@@ -55,6 +57,8 @@ export interface ChildSessionLaunch {
55
57
  cwd: string;
56
58
  /** Resolved pane-native placement. Local launches omit this field. */
57
59
  machine?: HerdrMachineReference;
60
+ /** The launching session's project trust; undefined keeps Pi's default for hosts without trust. */
61
+ projectTrusted?: boolean;
58
62
  /** Process-local provider source owned by the invoking foreground parent. */
59
63
  parentProviderRegistry?: ParentProviderRegistry;
60
64
  /** Logical names resolved only by the remote ambient package. */
@@ -64,6 +68,8 @@ export interface ChildSessionLaunch {
64
68
  model?: string;
65
69
  /** Explicit tool allowlist; undefined keeps pi's defaults. */
66
70
  tools?: string[];
71
+ /** Tools of Pi's built-in MCP extension the child must declare to its model directly, with the `mcp:` selector that granted each; `tools` names them too. */
72
+ builtinMcpTools?: Array<{ name: string; selector: string }>;
67
73
  excludeTools?: string[];
68
74
  /** Extension files loaded for this child in addition to the inline hooks. */
69
75
  extensionPaths: string[];
@@ -107,12 +113,16 @@ export interface ChildSession {
107
113
  abort(): Promise<void>;
108
114
  /** Emits `session_shutdown` to the child's extensions and disposes the session; resolves once that shutdown work is done. */
109
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>;
110
118
  /** True while Pi still has steering or follow-up input that has not started a turn. */
111
119
  hasQueuedMessages?(): boolean;
112
120
  readonly messages: readonly AgentMessage[];
113
121
  readonly sessionFile: string | undefined;
114
122
  readonly sessionId: string;
115
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;
116
126
  readonly contextWindow?: number;
117
127
  readonly machineEvidence?: { machineId: string; initial?: HerdrRemoteGitStatus; final?: HerdrRemoteGitStatus };
118
128
  /** Event-updated pane-native status; reading it performs no network work. */
@@ -148,6 +158,8 @@ export interface DefaultChildSessionFactoryOptions {
148
158
  loadPiCodingAgent?: () => Promise<PiCodingAgentModule>;
149
159
  /** Upper bound on a disposed child's `session_shutdown` handlers before the session is dropped anyway. */
150
160
  shutdownTimeoutMs?: number;
161
+ /** Upper bound on the wait for selected built-in MCP tools to register after the session starts. */
162
+ builtinMcpToolWaitMs?: number;
151
163
  }
152
164
 
153
165
  type ModelRuntimeInstance = Awaited<ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]>>;
@@ -195,6 +207,30 @@ function prioritizeChildPromptRuntime<T extends { extensions: Array<{ path: stri
195
207
  return { ...result, extensions };
196
208
  }
197
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
+
198
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. */
199
235
  let loading: Promise<unknown> = Promise.resolve();
200
236
 
@@ -231,6 +267,53 @@ function restoreProcessEnv(saved: Array<[string, string | undefined]>): void {
231
267
  }
232
268
  }
233
269
 
270
+ /**
271
+ * Pi's built-in MCP extension registers server tools with the configured exposure, `codemode` by
272
+ * default, which the child's `tools` allowlist cannot declare. Registering the selected names as
273
+ * `direct` makes them model-declared and callable; `hidden` stays hidden. A name counts only when
274
+ * the tool's raw identity, its `<server>/<tool>` label, matches the granting selector: Pi can give
275
+ * the sanitized name of `srv/a.b` to `srv/a_b`. Every other tool the extension registers becomes
276
+ * `hidden`, so neither codemode nor `ctx.executeTool()` can call it, independent of the `tools`
277
+ * allowlist. The `builtin` entry loads
278
+ * through the explicit `builtin:mcp` path even with `noExtensions`, and `replaceable` lets an
279
+ * ambient MCP extension that registers `/mcp` replace it, as in the parent.
280
+ */
281
+ function selectedBuiltinMcpExtension(pi: PiCodingAgentModule, selections: ReadonlyArray<{ name: string; selector: string }>): ChildHookExtension & { builtin: true; replaceable: true } {
282
+ // Pi 0.99 export; the pinned SDK types predate it.
283
+ const createMcpExtension = (pi as { createMcpExtension?: () => (api: ExtensionAPI) => void | Promise<void> }).createMcpExtension;
284
+ if (typeof createMcpExtension !== "function") throw new Error(`Selected built-in MCP tools (${selections.map(({ name }) => name).join(", ")}) need a Pi version with built-in MCP.`);
285
+ const selectors = new Map(selections.map(({ name, selector }) => [name, selector]));
286
+ const granted = (tool: { name: string; label?: string; exposure?: string }) => {
287
+ const selector = selectors.get(tool.name);
288
+ if (selector === undefined || tool.exposure === "hidden" || tool.label === undefined) return false;
289
+ return selector.includes("/") ? tool.label === selector : tool.label.startsWith(`${selector}/`);
290
+ };
291
+ const mcp = createMcpExtension();
292
+ const factory = (api: ExtensionAPI) => mcp(new Proxy(api, {
293
+ get(target, prop) {
294
+ if (prop === "registerTool") {
295
+ return (tool: Parameters<ExtensionAPI["registerTool"]>[0] & { exposure?: string }) =>
296
+ target.registerTool({ ...tool, exposure: granted(tool) ? "direct" : "hidden" } as typeof tool);
297
+ }
298
+ const value = Reflect.get(target, prop, target);
299
+ return typeof value === "function" ? value.bind(target) : value;
300
+ },
301
+ }));
302
+ return { name: "mcp", factory, builtin: true, replaceable: true };
303
+ }
304
+
305
+ /** MCP connects after `session_start`, so the selected tools register some time after the session binds. */
306
+ async function missingBuiltinMcpTools(session: { getAllTools(): Array<{ name: string }>; getActiveToolNames(): string[] }, names: readonly string[], timeoutMs: number, stopped: () => boolean): Promise<string[]> {
307
+ const deadline = Date.now() + timeoutMs;
308
+ for (;;) {
309
+ const active = new Set(session.getActiveToolNames());
310
+ const direct = new Set(session.getAllTools().filter((tool) => (tool as { exposure?: string }).exposure === "direct").map(({ name }) => name));
311
+ const missing = names.filter((name) => !active.has(name) || !direct.has(name));
312
+ if (missing.length === 0 || stopped() || Date.now() >= deadline) return missing;
313
+ await new Promise((resolve) => setTimeout(resolve, 50));
314
+ }
315
+ }
316
+
234
317
  function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModule["DefaultResourceLoader"]>, modelRuntime: ModelRuntimeInstance, onError: ((error: ChildSessionExtensionError) => void) | undefined, requiredPaths: ReadonlySet<string>): { claimedProviderIds: Set<string>; registered: boolean } {
235
318
  const claimedProviderIds = new Set<string>();
236
319
  if (!("getExtensions" in loader) || typeof loader.getExtensions !== "function") return { claimedProviderIds, registered: false };
@@ -258,6 +341,25 @@ function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModu
258
341
  }
259
342
  }
260
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 = [];
261
363
  return { claimedProviderIds, registered };
262
364
  }
263
365
 
@@ -311,10 +413,14 @@ function isUnknownRecord(value: unknown): value is Record<string, unknown> {
311
413
  export function createDefaultChildSessionFactory(options: DefaultChildSessionFactoryOptions = {}): ChildSessionFactory {
312
414
  const loadPiCodingAgent = options.loadPiCodingAgent ?? loadHostPiCodingAgent;
313
415
  const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5_000;
416
+ const builtinMcpToolWaitMs = options.builtinMcpToolWaitMs ?? 10_000;
314
417
  let runtime: ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]> | undefined;
315
418
  const live = new Set<ChildSession>();
316
419
  /** Extension shutdowns still running for disposed children; `dispose()` waits for them. */
317
420
  const shutdowns = new Set<Promise<void>>();
421
+ /** Launches still waiting for their MCP tools; `dispose()` ends the wait and waits for their shutdown. */
422
+ const mcpWaits = new Set<Promise<void>>();
423
+ let disposals = 0;
318
424
  const sharedRuntime = async (pi: PiCodingAgentModule) => {
319
425
  runtime ??= pi.ModelRuntime.create().catch((error: unknown) => {
320
426
  runtime = undefined;
@@ -324,33 +430,72 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
324
430
  };
325
431
  return {
326
432
  async create(launch) {
433
+ const disposalsAtStart = disposals;
327
434
  const pi = await loadPiCodingAgent();
435
+ const builtinMcpTools = launch.builtinMcpTools ?? [];
436
+ const builtinMcp = builtinMcpTools.length ? selectedBuiltinMcpExtension(pi, builtinMcpTools) : undefined;
328
437
  const modelRuntime = launch.parentProviderRegistry
329
438
  ? await pi.ModelRuntime.create()
330
439
  : await sharedRuntime(pi);
331
440
  const agentDir = getAgentDir();
332
- const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir);
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;
446
+ const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir, { projectTrusted: launch.projectTrusted });
333
447
  // Foreground children share Pi's global theme with the parent, so reinitializing it
334
448
  // would overwrite the parent's active light/dark appearance. Detached runners have
335
449
  // no initialized theme and must initialize one for headless extension renderers.
336
450
  const themeKey = Symbol.for("@earendil-works/pi-coding-agent:theme");
337
451
  const themeInitialized = Boolean((globalThis as Record<symbol, unknown>)[themeKey]);
338
452
  if (!themeInitialized && typeof pi.initTheme === "function") pi.initTheme(settingsManager.getTheme());
453
+ // SDK sessions do not install Pi's CLI built-ins. Use the host's own
454
+ // codemode factory only when this child can select it; older Pi hosts
455
+ // without that factory retain the strict missing-tool diagnostic.
456
+ const createCodemodeExtension = (pi as PiCodingAgentModule & { createCodemodeExtension?: () => ChildHookExtension["factory"] }).createCodemodeExtension;
457
+ const codemode = typeof createCodemodeExtension === "function" &&
458
+ !launch.runtime.capabilityCeiling?.denyExtensions &&
459
+ (launch.tools === undefined || launch.tools.includes("codemode")) &&
460
+ !launch.excludeTools?.includes("codemode")
461
+ ? [{ name: "codemode", factory: createCodemodeExtension(), replaceable: true }]
462
+ : [];
339
463
  const loader = new pi.DefaultResourceLoader({
340
464
  cwd: launch.cwd,
341
465
  agentDir,
342
466
  settingsManager,
343
467
  noExtensions: !launch.ambientExtensions,
344
468
  noSkills: launch.noSkills,
469
+ // Pi merges skills from extensions' resources_discover without checking noSkills.
470
+ skillsOverride: launch.noSkills ? (base) => ({ ...base, skills: [] }) : undefined,
345
471
  noPromptTemplates: true,
346
472
  noThemes: true,
347
473
  noContextFiles: launch.noContextFiles,
348
- additionalExtensionPaths: launch.extensionPaths,
349
- extensionFactories: launch.hooks,
350
- extensionsOverride: prioritizeChildPromptRuntime,
474
+ additionalExtensionPaths: builtinMcp ? [...launch.extensionPaths, "builtin:mcp"] : launch.extensionPaths,
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)),
351
480
  ...(launch.systemPrompt !== undefined ? { systemPrompt: launch.systemPrompt } : {}),
352
481
  ...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
353
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
+ };
354
499
  const open = async () => {
355
500
  const requiredPaths = new Set((launch.requiredExtensions ?? []).map(({ path }) => path));
356
501
  const savedTransientEnv = captureProcessEnv(launch.transientProcessEnv);
@@ -401,14 +546,27 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
401
546
  // (registration and session_start); restore transient keys so an
402
547
  // in-process child cannot leak them into the host process.
403
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;
404
552
  try {
405
553
  await session.bindExtensions({
406
554
  mode: "print",
407
- 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
+ },
408
559
  });
409
560
  } catch (error) {
410
561
  session.dispose();
411
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("; ")}`);
412
570
  }
413
571
  return session;
414
572
  };
@@ -416,26 +574,26 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
416
574
  loading = opened;
417
575
  const session = await opened;
418
576
  let pending: Promise<void> | undefined;
419
- // pi's own hosts emit `session_shutdown` before disposing a session so the
420
- // extensions loaded into it (ambient extensions included) release their
421
- // watchers, servers, and timers. Do the same, then dispose.
422
- const shutdown = async (): Promise<void> => {
423
- try {
424
- const runner = session.extensionRunner;
425
- if (runner.hasHandlers("session_shutdown")) {
426
- await Promise.race([runner.emit({ type: "session_shutdown", reason: "quit" }), new Promise<void>((resolve) => setTimeout(resolve, shutdownTimeoutMs).unref?.())]);
427
- }
428
- } catch (error) {
429
- launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error });
430
- } finally {
431
- session.dispose();
432
- }
433
- };
577
+ const shutdown = () => shutdownSession(session);
578
+ // Outside the launch lock: MCP servers connect after `session_start` without reading the per-launch env.
579
+ if (builtinMcpTools.length) {
580
+ const disposed = () => disposals !== disposalsAtStart;
581
+ const ready = missingBuiltinMcpTools(session, builtinMcpTools.map(({ name }) => name), builtinMcpToolWaitMs, disposed).then(async (missing) => {
582
+ if (!missing.length && !disposed()) return;
583
+ await shutdown();
584
+ throw new Error(disposed()
585
+ ? "The child session factory was disposed while the child waited for its MCP tools."
586
+ : `Selected built-in MCP tools did not register in the child session: ${missing.join(", ")}. The MCP server may have failed to connect, or the name belongs to a different tool than the selector names; check it with /mcp.`);
587
+ });
588
+ mcpWaits.add(ready);
589
+ try { await ready; } finally { mcpWaits.delete(ready); }
590
+ }
434
591
  const child: ChildSession = {
435
592
  subscribe: (listener) => session.subscribe((event) => listener(event as unknown as ChildSessionEvent)),
436
593
  prompt: (text) => session.prompt(text),
437
- steer: (text) => session.steer(text),
438
- followUp: (text) => session.followUp(text),
594
+ ...(commands ? { finishCommands: () => commands.finish() } : {}),
595
+ steer: (text) => session.steer(text).then(() => undefined),
596
+ followUp: (text) => session.followUp(text).then(() => undefined),
439
597
  abort: () => session.abort(),
440
598
  hasQueuedMessages: () => session.agent?.hasQueuedMessages?.() === true,
441
599
  dispose: () => {
@@ -452,19 +610,21 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
452
610
  get sessionFile() { return session.sessionFile; },
453
611
  get sessionId() { return session.sessionId; },
454
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; },
455
614
  get contextWindow() { return session.model?.contextWindow; },
456
615
  };
457
616
  live.add(child);
458
617
  return child;
459
618
  },
460
619
  async dispose() {
620
+ disposals += 1;
461
621
  const children = [...live].filter((child) => !child.detached);
462
622
  for (const child of children) child.shutDown = true;
463
623
  await Promise.allSettled(children.map((child) => child.abort()));
464
624
  for (const child of children) {
465
625
  try { void child.dispose(); } catch { /* best effort */ }
466
626
  }
467
- await Promise.allSettled([...shutdowns]);
627
+ await Promise.allSettled([...shutdowns, ...mcpWaits]);
468
628
  if (live.size === 0) runtime = undefined;
469
629
  },
470
630
  };
@@ -9,6 +9,7 @@ import * as path from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
11
  import {
12
+ formatUnresolvedBuiltinMcpSelectors,
12
13
  formatUnresolvedMcpDirectToolSelectors,
13
14
  resolveMcpDirectToolResolution,
14
15
  type McpRuntimeSnapshotHost,
@@ -171,6 +172,8 @@ export interface ResolvePiLaunchToolPlanInput {
171
172
  * Non-core names remain allowed and are validated in the child's registry.
172
173
  */
173
174
  hostAvailableBuiltins?: readonly string[];
175
+ /** The parent's built-in MCP selections; the background runner has no host to resolve selectors against. */
176
+ builtinMcpTools?: ResolvedMcpDirectToolSelection[];
174
177
  }
175
178
 
176
179
  export interface PiLaunchToolPlan {
@@ -182,6 +185,8 @@ export interface PiLaunchToolPlan {
182
185
  resolvedMcpSelections: ResolvedMcpDirectToolSelection[];
183
186
  effectiveMcpSelections: ResolvedMcpDirectToolSelection[];
184
187
  effectiveMcpTools: string[];
188
+ /** Effective selections granted from Pi's built-in MCP; undefined when the selectors did not resolve against it. */
189
+ builtinMcpTools?: ResolvedMcpDirectToolSelection[];
185
190
  explicitToolAllowlist: boolean;
186
191
  internalTools: string[];
187
192
  effectiveToolAllowlist: string[];
@@ -353,7 +358,7 @@ export function resolvePiLaunchToolPlan(
353
358
  const ceilingFilteredBuiltinTools =
354
359
  input.tools === undefined
355
360
  ? allowedToolSet
356
- ? [...allowedToolSet]
361
+ ? [...allowedToolSet].filter((tool) => tool !== "subagent_command")
357
362
  : []
358
363
  : (input.requireReadTool &&
359
364
  requestedBuiltinTools.length > 0 &&
@@ -383,16 +388,21 @@ export function resolvePiLaunchToolPlan(
383
388
  );
384
389
  const mcpResolution = capabilityCeiling?.denyExtensions
385
390
  ? { selections: [], unresolvedSelectors: [] }
386
- : resolveMcpDirectToolResolution(input.mcpDirectTools, input.cwd, input.runtimeSnapshotHost);
391
+ : input.builtinMcpTools
392
+ // The runner applies the same ceilings again; filtering is idempotent.
393
+ ? { selections: input.builtinMcpTools, unresolvedSelectors: [], builtin: true as const }
394
+ : resolveMcpDirectToolResolution(input.mcpDirectTools, input.cwd, input.runtimeSnapshotHost);
387
395
  if (mcpResolution.runtimeServerNames?.length) {
388
396
  throw new Error(formatRuntimeSnapshotMcpServersError(input.agentName, mcpResolution.runtimeServerNames));
389
397
  }
390
398
  if (mcpResolution.unresolvedSelectors.length > 0) {
391
- throw new Error(formatUnresolvedMcpDirectToolSelectors(mcpResolution.unresolvedSelectors));
399
+ throw new Error(mcpResolution.builtin
400
+ ? formatUnresolvedBuiltinMcpSelectors(input.agentName, mcpResolution.unresolvedSelectors)
401
+ : formatUnresolvedMcpDirectToolSelectors(mcpResolution.unresolvedSelectors));
392
402
  }
393
403
  const resolvedMcpSelections = mcpResolution.selections;
394
404
  const resolvedMcpNames = new Set(resolvedMcpSelections.map((selection) => selection.name));
395
- const legacyMcpNameCounts = countLegacyUnderscoreMcpToolNames(resolvedMcpSelections);
405
+ const legacyMcpNameCounts = mcpResolution.builtin ? new Map<string, number>() : countLegacyUnderscoreMcpToolNames(resolvedMcpSelections);
396
406
  const effectiveMcpSelections = resolvedMcpSelections.filter(
397
407
  (selection) =>
398
408
  !allowedToolSet ||
@@ -402,6 +412,7 @@ export function resolvePiLaunchToolPlan(
402
412
  const effectiveMcpTools = effectiveMcpSelections.map(
403
413
  (selection) => selection.name,
404
414
  );
415
+ const builtinMcpTools = mcpResolution.builtin ? effectiveMcpSelections : undefined;
405
416
  const explicitToolAllowlist =
406
417
  input.tools !== undefined ||
407
418
  (input.mcpDirectTools?.length ?? 0) > 0 ||
@@ -538,6 +549,7 @@ export function resolvePiLaunchToolPlan(
538
549
  resolvedMcpSelections,
539
550
  effectiveMcpSelections,
540
551
  effectiveMcpTools,
552
+ builtinMcpTools,
541
553
  explicitToolAllowlist,
542
554
  internalTools,
543
555
  effectiveToolAllowlist,
@@ -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,8 +49,8 @@ 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",
53
- "structuredOutput", "structuredOutputSchema", "tools", "excludeTools", "allowNestedSubagents", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "mutationTools", "capabilityCeiling", "systemPrompt",
52
+ "runner", "outputName", "structured", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled", "waitToolDefaultTimeoutMs",
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
  ]);
56
56
  const DYNAMIC_COLLECT_KEYS = new Set(["as", "outputSchema"]);