@xzzpig/pi-subagents 0.20.0 → 0.22.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 (144) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/fork-supervisor-routing.md +77 -0
  13. package/docs/missions.md +34 -17
  14. package/docs/models.md +1 -1
  15. package/docs/observability.md +10 -5
  16. package/docs/tool-reference.md +117 -84
  17. package/docs/watchdog.md +8 -6
  18. package/docs/workflows.md +16 -7
  19. package/index.ts +5 -0
  20. package/package.json +6 -3
  21. package/prompts/council.md +1 -1
  22. package/skills/pi-subagents/SKILL.md +1 -1
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  24. package/skills/pi-subagents/references/execution-controls.md +16 -16
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  26. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  27. package/src/agents/advertised-agent-prompt.ts +9 -1
  28. package/src/agents/agent-management.ts +4 -0
  29. package/src/agents/agent-memory.ts +3 -3
  30. package/src/agents/agent-scope.ts +4 -0
  31. package/src/agents/agent-serializer.ts +8 -1
  32. package/src/agents/agents.ts +191 -145
  33. package/src/api/preflight.ts +8 -4
  34. package/src/api/supervisor-routing.ts +196 -0
  35. package/src/extension/config.ts +21 -2
  36. package/src/extension/context-injection.ts +6 -1
  37. package/src/extension/control-notices.ts +1 -9
  38. package/src/extension/declaration-pinning.ts +164 -0
  39. package/src/extension/doctor.ts +7 -10
  40. package/src/extension/fanout-child.ts +7 -8
  41. package/src/extension/index.ts +143 -134
  42. package/src/extension/reply-workflow-script.ts +20 -11
  43. package/src/extension/rpc.ts +11 -6
  44. package/src/extension/schemas.ts +34 -30
  45. package/src/extension/subagent-guide.ts +86 -6
  46. package/src/extension/subagent-options.ts +47 -0
  47. package/src/extension/tool-activation.ts +3 -2
  48. package/src/extension/tool-description.ts +51 -68
  49. package/src/inspectors/actions.ts +37 -11
  50. package/src/inspectors/plugins.ts +3 -2
  51. package/src/inspectors/tmux/actions.ts +204 -0
  52. package/src/inspectors/tmux/client.ts +85 -0
  53. package/src/inspectors/tmux/plugin.ts +21 -0
  54. package/src/integrations/herdr-status.ts +18 -49
  55. package/src/integrations/program-status.ts +215 -0
  56. package/src/intercom/fork-supervisor-routing.ts +533 -0
  57. package/src/intercom/native-supervisor-channel.ts +152 -13
  58. package/src/intercom/result-intercom.ts +3 -2
  59. package/src/intercom/supervisor-ui.ts +2 -174
  60. package/src/missions/store.ts +25 -5
  61. package/src/profiles/profiles.ts +24 -21
  62. package/src/runs/background/active-async-capacity.ts +58 -8
  63. package/src/runs/background/async-execution.ts +143 -38
  64. package/src/runs/background/async-job-tracker.ts +11 -4
  65. package/src/runs/background/async-resume.ts +5 -2
  66. package/src/runs/background/await-async-run.ts +14 -9
  67. package/src/runs/background/binary-bootstrap.ts +2 -1
  68. package/src/runs/background/calendar-schedule.ts +90 -0
  69. package/src/runs/background/chain-root-attachment.ts +9 -5
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +16 -2
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-child-launch.ts +1 -0
  79. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  80. package/src/runs/background/scheduled-runs.ts +256 -61
  81. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  82. package/src/runs/background/subagent-runner.ts +32 -12
  83. package/src/runs/background/subagent-wait.ts +38 -19
  84. package/src/runs/background/terminal-run-index.ts +46 -1
  85. package/src/runs/background/wait-completions.ts +1 -0
  86. package/src/runs/background/wait-tool.ts +33 -23
  87. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  88. package/src/runs/foreground/async-stop-action.ts +48 -22
  89. package/src/runs/foreground/execution.ts +94 -52
  90. package/src/runs/foreground/foreground-history.ts +1 -0
  91. package/src/runs/foreground/subagent-executor.ts +232 -77
  92. package/src/runs/shared/child-commands.ts +2 -1
  93. package/src/runs/shared/child-hooks.ts +4 -3
  94. package/src/runs/shared/child-launch.ts +3 -0
  95. package/src/runs/shared/child-session.ts +41 -24
  96. package/src/runs/shared/child-tool-plan.ts +13 -26
  97. package/src/runs/shared/dynamic-fanout.ts +1 -1
  98. package/src/runs/shared/fork-command-result.ts +10 -0
  99. package/src/runs/shared/herdr-placed-run.ts +5 -4
  100. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  101. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  102. package/src/runs/shared/model-resolution.ts +30 -1
  103. package/src/runs/shared/nested-events.ts +5 -0
  104. package/src/runs/shared/parallel-handoff.ts +56 -8
  105. package/src/runs/shared/parallel-utils.ts +2 -0
  106. package/src/runs/shared/partial-output.ts +48 -0
  107. package/src/runs/shared/runner-launcher.ts +25 -0
  108. package/src/runs/shared/single-output.ts +53 -0
  109. package/src/runs/shared/structured-output.ts +14 -7
  110. package/src/runs/shared/subagent-control.ts +3 -3
  111. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  112. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  113. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  114. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  115. package/src/runs/shared/worktree-lock.ts +29 -0
  116. package/src/runs/shared/worktree.ts +12 -1
  117. package/src/shared/atomic-json.ts +4 -2
  118. package/src/shared/edit-distance.ts +33 -0
  119. package/src/shared/file-lease.ts +74 -0
  120. package/src/shared/formatters.ts +1 -5
  121. package/src/shared/model-info.ts +22 -0
  122. package/src/shared/package-version.ts +17 -0
  123. package/src/shared/parent-wake.ts +79 -0
  124. package/src/shared/pruned-fork.ts +7 -1
  125. package/src/shared/runtime-module-path.ts +19 -0
  126. package/src/shared/settings-file-lease.ts +36 -0
  127. package/src/shared/types.ts +36 -2
  128. package/src/shared/utils.ts +8 -6
  129. package/src/slash/prompt-template-bridge.ts +21 -20
  130. package/src/slash/slash-commands.ts +3 -3
  131. package/src/slash/subagents-admin.ts +2 -1
  132. package/src/tui/fleet-native-transcript.ts +2 -0
  133. package/src/tui/fleet-transcript.ts +12 -3
  134. package/src/tui/fleet.ts +11 -8
  135. package/src/tui/render.ts +27 -19
  136. package/src/tui/subagent-messages.ts +305 -0
  137. package/src/watchdog/diff-tool.ts +2 -2
  138. package/src/watchdog/register-main.ts +2 -22
  139. package/src/watchdog/render.ts +2 -24
  140. package/src/watchdog/runtime.ts +6 -4
  141. package/src/watchdog/settings.ts +18 -13
  142. package/src/watchdog/tool-actions.ts +2 -2
  143. package/src/workflows/scripted-workflow.ts +20 -6
  144. package/src/workflows/workflow-resources.ts +11 -0
@@ -5,6 +5,7 @@ import { Type } from "typebox";
5
5
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
6
6
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
7
7
  import { createAtomicJsonWriter } from "../../shared/atomic-json.ts";
8
+ import { requireSuccessfulCommandResult } from "./fork-command-result.ts";
8
9
  import { watchAsyncControlInbox, requestAsyncCommand, type CommandRequest } from "../background/control-channel.ts";
9
10
 
10
11
  export const CHILD_COMMAND_TOOL = "subagent_command";
@@ -140,7 +141,7 @@ export function createChildCommandRuntime(channelDir: string) {
140
141
  const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
141
142
  job.snapshot.output = text(update);
142
143
  if (job.snapshot.state === "running") onUpdate?.(update);
143
- }, ctx)).then((result) => {
144
+ }, ctx)).then(requireSuccessfulCommandResult).then((result) => {
144
145
  job.snapshot.output = text(result);
145
146
  job.snapshot.state = "completed";
146
147
  const fullOutputPath = (result.details as { fullOutputPath?: string } | undefined)?.fullOutputPath;
@@ -3,7 +3,7 @@ import { listBackgroundWorkProviders } from "../../api/background-work.ts";
3
3
  import { ReadonlyDrainObservation } from "./readonly-drain-observation.ts";
4
4
  import registerFanoutChildSubagentExtension, { createChildSafeState } from "../../extension/fanout-child.ts";
5
5
  import registerSubagentFastModeExtension from "./fast-mode-extension.ts";
6
- import registerSubagentPromptRuntime from "./subagent-prompt-runtime.ts";
6
+ import registerSubagentPromptRuntime, { registerSubagentPromptBoundary } from "./subagent-prompt-runtime.ts";
7
7
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
8
8
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
9
9
  import type { ChildSessionLaunch } from "./child-session.ts";
@@ -164,11 +164,12 @@ function childHooks(config: ChildRuntimeConfig, capture?: OwnedCapture, holdFina
164
164
  registerSubagentPromptRuntime(pi, runtime, proof.observation);
165
165
  } },
166
166
  ];
167
+ if (config.fast) hooks.push({ name: "pi-subagents:fast-mode", factory: (pi) => registerSubagentFastModeExtension(pi) });
168
+ if (config.fanoutChild) hooks.push({ name: "pi-subagents:fanout-child", factory: (pi) => registerFanoutChildSubagentExtension(pi, runtime) });
169
+ hooks.push({ name: "pi-subagents:prompt-boundary", factory: (pi) => registerSubagentPromptBoundary(pi, runtime) });
167
170
  if (proof) {
168
171
  proof.factories = hooks.map((hook) => hook.factory);
169
172
  promptProofs.set(hooks[0]!.factory, proof);
170
173
  }
171
- if (config.fast) hooks.push({ name: "pi-subagents:fast-mode", factory: (pi) => registerSubagentFastModeExtension(pi) });
172
- if (config.fanoutChild) hooks.push({ name: "pi-subagents:fanout-child", factory: (pi) => registerFanoutChildSubagentExtension(pi, runtime) });
173
174
  return hooks;
174
175
  }
@@ -67,6 +67,8 @@ export interface BuildInProcessChildLaunchInput {
67
67
  remoteSkillNames?: string[];
68
68
  remoteReads?: string[] | false;
69
69
  parentSessionId?: string;
70
+ /** The launching session's file; a new child session records it as its parent. */
71
+ parentSessionFile?: string;
70
72
  forkCacheKey?: string;
71
73
  sessionEnabled: boolean;
72
74
  sessionDir?: string;
@@ -348,6 +350,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
348
350
  ...(input.projectTrusted !== undefined ? { projectTrusted: input.projectTrusted } : {}),
349
351
  ...(input.machine ? { remoteResources: { agent: input.childAgentName, ...(input.remoteSkillNames ? { skills: input.remoteSkillNames } : {}), ...(input.remoteReads !== undefined ? { reads: input.remoteReads } : {}), ...(toolPlan.explicitToolAllowlist ? { toolCeiling: [...toolPlan.effectiveToolAllowlist] } : toolPlan.capabilityCeiling?.allowedTools ? { toolCeiling: [...toolPlan.capabilityCeiling.allowedTools] } : {}) } } : {}),
350
352
  storage: childStorage(input),
353
+ ...(input.parentSessionFile ? { parentSessionFile: input.parentSessionFile } : {}),
351
354
  ...(input.model ? { model: input.model } : {}),
352
355
  ...(toolPlan.explicitToolAllowlist ? { tools: toolPlan.effectiveToolAllowlist } : {}),
353
356
  ...(toolPlan.builtinMcpTools?.length ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
@@ -64,6 +64,8 @@ export interface ChildSessionLaunch {
64
64
  /** Logical names resolved only by the remote ambient package. */
65
65
  remoteResources?: { agent: string; skills?: string[]; toolCeiling?: string[]; reads?: string[] | false };
66
66
  storage: ChildSessionStorage;
67
+ /** The launching session's file, recorded as the new child session's `parentSession` header like Pi's forks. */
68
+ parentSessionFile?: string;
67
69
  /** Model reference as the agent config names it (`provider/id`, optionally `:thinking`). */
68
70
  model?: string;
69
71
  /** Explicit tool allowlist; undefined keeps pi's defaults. */
@@ -121,6 +123,8 @@ export interface ChildSession {
121
123
  readonly sessionFile: string | undefined;
122
124
  readonly sessionId: string;
123
125
  readonly modelId: string | undefined;
126
+ /** Provider id of the selected model when this child inherited that provider from the parent's registry instead of loading its extension. */
127
+ readonly inheritedProvider?: string;
124
128
  /** Live provider/id of the selected model when Pi marks it virtual (`api === "pi-virtual"`); assistant messages then name the dispatched physical model. */
125
129
  readonly virtualModelId?: string;
126
130
  readonly contextWindow?: number;
@@ -166,7 +170,8 @@ type ModelRuntimeInstance = Awaited<ReturnType<PiCodingAgentModule["ModelRuntime
166
170
 
167
171
  export type ParentProviderRegistry = Pick<ModelRuntimeInstance, "getRegisteredProviderIds" | "getRegisteredProviderConfig" | "getRegisteredNativeProvider">;
168
172
 
169
- function inheritParentProviders(modelRuntime: ModelRuntimeInstance, parentProviders: ParentProviderRegistry, claimedProviderIds: ReadonlySet<string>, onError: ((error: ChildSessionExtensionError) => void) | undefined): boolean {
173
+ /** Registers the parent's providers this child did not claim itself and returns their ids. */
174
+ function inheritParentProviders(modelRuntime: ModelRuntimeInstance, parentProviders: ParentProviderRegistry, claimedProviderIds: ReadonlySet<string>, onError: ((error: ChildSessionExtensionError) => void) | undefined): Set<string> {
170
175
  let providerIds: readonly string[];
171
176
  try {
172
177
  providerIds = parentProviders.getRegisteredProviderIds();
@@ -174,7 +179,7 @@ function inheritParentProviders(modelRuntime: ModelRuntimeInstance, parentProvid
174
179
  onError?.({ extensionPath: "<parent-providers>", event: "inherit_provider", error });
175
180
  throw new Error(`Failed to enumerate parent providers: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
176
181
  }
177
- let registered = false;
182
+ const inherited = new Set<string>();
178
183
  for (const providerId of new Set(providerIds)) {
179
184
  if (claimedProviderIds.has(providerId)) continue;
180
185
  try {
@@ -183,28 +188,26 @@ function inheritParentProviders(modelRuntime: ModelRuntimeInstance, parentProvid
183
188
  if (native) modelRuntime.registerNativeProvider(native);
184
189
  else if (config) modelRuntime.registerProvider(providerId, config);
185
190
  else throw new Error(`Parent provider '${providerId}' has no registered native provider or config.`);
186
- registered = true;
191
+ inherited.add(providerId);
187
192
  } catch (error) {
188
193
  onError?.({ extensionPath: `<parent-provider:${providerId}>`, event: "inherit_provider", error });
189
194
  throw new Error(`Failed to inherit parent provider '${providerId}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
190
195
  }
191
196
  }
192
- return registered;
197
+ return inherited;
193
198
  }
194
199
 
195
200
  const CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime>";
201
+ const CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
196
202
 
197
203
  /** The prompt runtime filters parent-only context before ambient extensions inspect
198
- * the child prompt. Other inline hooks keep their normal position after ambient
199
- * extensions, and ambient extension order stays unchanged. */
200
- function prioritizeChildPromptRuntime<T extends { extensions: Array<{ path: string }> }>(result: T): T {
201
- const index = result.extensions.findIndex(({ path }) => path === CHILD_PROMPT_RUNTIME_EXTENSION_PATH);
202
- if (index <= 0) return result;
203
- const extensions = [...result.extensions];
204
- const [promptRuntime] = extensions.splice(index, 1);
205
- if (!promptRuntime) return result;
206
- extensions.unshift(promptRuntime);
207
- return { ...result, extensions };
204
+ * the child prompt, and the boundary hook appends the child boundary after every
205
+ * extension has added its prompt sections. Every other extension keeps its order. */
206
+ function orderChildPromptHooks<T extends { extensions: Array<{ path: string }> }>(result: T): T {
207
+ const runtime = result.extensions.filter(({ path }) => path === CHILD_PROMPT_RUNTIME_EXTENSION_PATH);
208
+ const boundary = result.extensions.filter(({ path }) => path === CHILD_PROMPT_BOUNDARY_EXTENSION_PATH);
209
+ const others = result.extensions.filter(({ path }) => path !== CHILD_PROMPT_RUNTIME_EXTENSION_PATH && path !== CHILD_PROMPT_BOUNDARY_EXTENSION_PATH);
210
+ return { ...result, extensions: [...runtime, ...others, ...boundary] };
208
211
  }
209
212
 
210
213
  /** Ambient bash overrides keep their original backend and priority. */
@@ -272,7 +275,9 @@ function restoreProcessEnv(saved: Array<[string, string | undefined]>): void {
272
275
  * default, which the child's `tools` allowlist cannot declare. Registering the selected names as
273
276
  * `direct` makes them model-declared and callable; `hidden` stays hidden. A name counts only when
274
277
  * 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
278
+ * the sanitized name of `srv/a.b` to `srv/a_b`. The selector's server part may be the configured
279
+ * name or its `-`→`_` form, which Pi's namespace uses: Pi refuses two servers whose names differ
280
+ * only in `-` and `_`, so both forms name the same server. Every other tool the extension registers becomes
276
281
  * `hidden`, so neither codemode nor `ctx.executeTool()` can call it, independent of the `tools`
277
282
  * allowlist. The `builtin` entry loads
278
283
  * through the explicit `builtin:mcp` path even with `noExtensions`, and `replaceable` lets an
@@ -283,10 +288,16 @@ function selectedBuiltinMcpExtension(pi: PiCodingAgentModule, selections: Readon
283
288
  const createMcpExtension = (pi as { createMcpExtension?: () => (api: ExtensionAPI) => void | Promise<void> }).createMcpExtension;
284
289
  if (typeof createMcpExtension !== "function") throw new Error(`Selected built-in MCP tools (${selections.map(({ name }) => name).join(", ")}) need a Pi version with built-in MCP.`);
285
290
  const selectors = new Map(selections.map(({ name, selector }) => [name, selector]));
291
+ const split = (value: string) => {
292
+ const slash = value.indexOf("/");
293
+ return { server: (slash === -1 ? value : value.slice(0, slash)).replace(/-/g, "_"), tool: slash === -1 ? undefined : value.slice(slash + 1) };
294
+ };
286
295
  const granted = (tool: { name: string; label?: string; exposure?: string }) => {
287
296
  const selector = selectors.get(tool.name);
288
297
  if (selector === undefined || tool.exposure === "hidden" || tool.label === undefined) return false;
289
- return selector.includes("/") ? tool.label === selector : tool.label.startsWith(`${selector}/`);
298
+ const want = split(selector);
299
+ const have = split(tool.label);
300
+ return have.tool !== undefined && have.server === want.server && (want.tool === undefined || want.tool === have.tool);
290
301
  };
291
302
  const mcp = createMcpExtension();
292
303
  const factory = (api: ExtensionAPI) => mcp(new Proxy(api, {
@@ -476,7 +487,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
476
487
  api.registerTool(commands.wrap(pi.createBashTool(launch.cwd, { commandPrefix: settingsManager.getShellCommandPrefix(), shellPath: settingsManager.getShellPath() }) as unknown as ToolDefinition));
477
488
  api.registerTool(commands.tool());
478
489
  } }] : []), ...codemode, ...(builtinMcp ? [builtinMcp] : [])],
479
- extensionsOverride: (result) => prioritizeChildPromptRuntime(prioritizeChildCommandRuntime(result)),
490
+ extensionsOverride: (result) => orderChildPromptHooks(prioritizeChildCommandRuntime(result)),
480
491
  ...(launch.systemPrompt !== undefined ? { systemPrompt: launch.systemPrompt } : {}),
481
492
  ...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
482
493
  });
@@ -496,6 +507,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
496
507
  session.dispose();
497
508
  }
498
509
  };
510
+ let inheritedProviders = new Set<string>();
499
511
  const open = async () => {
500
512
  const requiredPaths = new Set((launch.requiredExtensions ?? []).map(({ path }) => path));
501
513
  const savedTransientEnv = captureProcessEnv(launch.transientProcessEnv);
@@ -506,10 +518,8 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
506
518
  ? loader.getExtensions().errors.filter(({ path }) => requiredPaths.has(path)) : [];
507
519
  if (loadErrors.length > 0) throw new Error(`Required child extension failed to load: ${loadErrors.map(({ path, error }) => `${path}: ${error}`).join("; ")}`);
508
520
  const queued = flushQueuedProviderRegistrations(loader, modelRuntime, launch.onExtensionError, requiredPaths);
509
- const inherited = launch.parentProviderRegistry
510
- ? inheritParentProviders(modelRuntime, launch.parentProviderRegistry, queued.claimedProviderIds, launch.onExtensionError)
511
- : false;
512
- if (queued.registered || inherited) {
521
+ if (launch.parentProviderRegistry) inheritedProviders = inheritParentProviders(modelRuntime, launch.parentProviderRegistry, queued.claimedProviderIds, launch.onExtensionError);
522
+ if (queued.registered || inheritedProviders.size > 0) {
513
523
  try {
514
524
  await modelRuntime.refresh({ allowNetwork: false });
515
525
  } catch (error) {
@@ -517,13 +527,19 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
517
527
  throw new Error(`Failed to refresh child providers: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
518
528
  }
519
529
  }
530
+ const newSessionOptions = launch.parentSessionFile ? { parentSession: launch.parentSessionFile } : undefined;
531
+ const newSessionFile = launch.storage.kind === "file" && !fs.existsSync(launch.storage.sessionFile);
520
532
  const sessionManager = launch.storage.kind === "file"
521
533
  ? pi.SessionManager.open(launch.storage.sessionFile, undefined, launch.cwd)
522
534
  : launch.storage.kind === "dir"
523
- ? pi.SessionManager.create(launch.cwd, launch.storage.sessionDir)
535
+ ? pi.SessionManager.create(launch.cwd, launch.storage.sessionDir, newSessionOptions)
524
536
  : launch.storage.kind === "memory"
525
- ? pi.SessionManager.inMemory(launch.cwd)
526
- : pi.SessionManager.create(launch.cwd);
537
+ ? pi.SessionManager.inMemory(launch.cwd, newSessionOptions)
538
+ : pi.SessionManager.create(launch.cwd, undefined, newSessionOptions);
539
+ // SessionManager.open takes no parent for a file it is about to create, so set it on the
540
+ // header Pi writes with the first assistant message. Forked and resumed files keep theirs.
541
+ const header = newSessionFile && launch.parentSessionFile ? sessionManager.getHeader() : null;
542
+ if (header) header.parentSession = launch.parentSessionFile;
527
543
  const resolvedModel = launch.model
528
544
  ? pi.resolveCliModel({ cliModel: launch.model, modelRuntime })
529
545
  : undefined;
@@ -610,6 +626,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
610
626
  get sessionFile() { return session.sessionFile; },
611
627
  get sessionId() { return session.sessionId; },
612
628
  get modelId() { return session.model ? `${session.model.provider}/${session.model.id}` : undefined; },
629
+ get inheritedProvider() { return session.model && inheritedProviders.has(session.model.provider) ? session.model.provider : undefined; },
613
630
  get virtualModelId() { return session.model?.api === "pi-virtual" ? `${session.model.provider}/${session.model.id}` : undefined; },
614
631
  get contextWindow() { return session.model?.contextWindow; },
615
632
  };
@@ -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 PROMPT_RUNTIME_EXTENSION_PATH = path.join(
38
- path.dirname(fileURLToPath(import.meta.url)),
39
- `subagent-prompt-runtime${path.extname(fileURLToPath(import.meta.url))}`,
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
- PROMPT_RUNTIME_EXTENSION_PATH,
58
- FANOUT_CHILD_EXTENSION_PATH,
59
- FAST_MODE_EXTENSION_PATH,
60
- ].map((extensionPath) => path.normalize(extensionPath)));
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 [FAST_MODE_EXTENSION_PATH];
119
+ return [resolveRuntimeModulePath(RUNTIME_EXTENSION_DIR, "fast-mode-extension")];
134
120
  }
135
121
 
136
122
  export interface ResolvePiLaunchToolPlanInput {
@@ -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
- PROMPT_RUNTIME_EXTENSION_PATH,
445
+ resolveRuntimeModulePath(RUNTIME_EXTENSION_DIR, "subagent-prompt-runtime"),
459
446
  ...fastModeExtensions,
460
- ...(fanoutAuthorized ? [FANOUT_CHILD_EXTENSION_PATH] : []),
447
+ ...(fanoutAuthorized ? [resolveRuntimeModulePath(FANOUT_CHILD_EXTENSION_DIR, "fanout-child")] : []),
461
448
  ...(effectivePermSystemExt ? [effectivePermSystemExt] : []),
462
449
  ...(sandboxExtension ? [sandboxExtension, SANDBOX_PROFILE_GUARD_EXTENSION_PATH] : []),
463
450
  ];
@@ -51,7 +51,7 @@ const RUNNER_DYNAMIC_PARALLEL_KEYS = new Set([
51
51
  ...DYNAMIC_PARALLEL_KEYS,
52
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
 
@@ -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.listeners.add((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
+ 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.frames) if (typeof frame.cursor === "number" && frame.cursor > this.#evidenceCursor) this.#frame(frame); input.bridge.listeners.add((frame) => 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
+ 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); }
@@ -174,10 +174,12 @@ function usesBuiltinMcp(host: McpRuntimeSnapshotHost | undefined): host is McpRu
174
174
 
175
175
  /**
176
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`
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`
179
180
  * before `a.b`), gets a suffix hashed from the raw server and tool (Pi's `createMcpToolName`), so
180
- * that suffixed name identifies the tool. The unsuffixed name may belong to another raw tool; the
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
181
183
  * child checks each granted tool's raw identity before it exposes the tool.
182
184
  */
183
185
  function resolveBuiltinMcpSelections(selectors: string[], tools: readonly McpHostToolInfo[]): McpDirectToolResolution {
@@ -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
 
@@ -262,6 +263,33 @@ function suggestAlternateProviderModel(
262
263
  return `${suggestion}${thinkingSuffix}`;
263
264
  }
264
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
+
265
293
  function resolveRequiredSubagentModelCandidate(
266
294
  model: string,
267
295
  availableModels: AvailableModelInfo[] | undefined,
@@ -270,8 +298,9 @@ function resolveRequiredSubagentModelCandidate(
270
298
  const resolved = resolveSubagentModelCandidate(model, availableModels, preferredProvider);
271
299
  if (resolved) return resolved;
272
300
  const suggestion = suggestAlternateProviderModel(model, availableModels);
301
+ const candidates = closestModelCandidates(model, availableModels).filter((candidate) => candidate !== suggestion);
273
302
  throw new Error(
274
- `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(", ")}.` : ""}`,
275
304
  );
276
305
  }
277
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);