@xzzpig/pi-subagents 0.16.0 → 0.18.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 (133) hide show
  1. package/CHANGELOG.md +164 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +17 -10
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/models.md +5 -3
  12. package/docs/observability.md +23 -13
  13. package/docs/standalone-background.md +4 -4
  14. package/docs/tool-reference.md +40 -19
  15. package/docs/watchdog.md +2 -0
  16. package/docs/workflows.md +57 -3
  17. package/inspector-runner.mjs +1 -1
  18. package/package.json +14 -8
  19. package/prompts/council.md +6 -3
  20. package/runner-peer-loader.mjs +4 -7
  21. package/runner-peer-preload.mjs +5 -7
  22. package/skills/pi-subagents/SKILL.md +1 -0
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  24. package/skills/pi-subagents/references/execution-controls.md +6 -4
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  26. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  27. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  28. package/src/agents/agent-eject.ts +3 -3
  29. package/src/agents/agent-management.ts +61 -52
  30. package/src/agents/agent-memory.ts +90 -3
  31. package/src/agents/agent-serializer.ts +4 -4
  32. package/src/agents/agents.ts +125 -51
  33. package/src/agents/global-npm-root.ts +58 -0
  34. package/src/agents/proactive-skills.ts +4 -1
  35. package/src/agents/runtime-agent-registry.ts +14 -11
  36. package/src/agents/skills.ts +42 -9
  37. package/src/api/delegation.ts +15 -0
  38. package/src/api/inspectors.ts +27 -0
  39. package/src/api/preflight.ts +60 -60
  40. package/src/extension/doctor.ts +9 -4
  41. package/src/extension/fanout-child.ts +8 -0
  42. package/src/extension/index.ts +101 -48
  43. package/src/extension/rpc.ts +10 -1
  44. package/src/extension/schemas.ts +12 -6
  45. package/src/extension/subagent-guide.ts +12 -4
  46. package/src/extension/tool-activation.ts +197 -0
  47. package/src/extension/tool-description.ts +1 -1
  48. package/src/inspectors/ghostty/plugin.ts +13 -1
  49. package/src/inspectors/plugins.ts +70 -3
  50. package/src/intercom/intercom-bridge.ts +2 -0
  51. package/src/intercom/native-supervisor-channel.ts +22 -15
  52. package/src/intercom/result-intercom.ts +4 -0
  53. package/src/runs/background/active-async-capacity.ts +3 -25
  54. package/src/runs/background/async-execution.ts +100 -140
  55. package/src/runs/background/async-job-tracker.ts +28 -34
  56. package/src/runs/background/async-resume.ts +16 -8
  57. package/src/runs/background/async-status.ts +2 -0
  58. package/src/runs/background/binary-bootstrap.ts +34 -6
  59. package/src/runs/background/fleet-view.ts +51 -7
  60. package/src/runs/background/notify.ts +93 -7
  61. package/src/runs/background/pid-namespace.ts +18 -0
  62. package/src/runs/background/process-terminal-candidate.ts +98 -0
  63. package/src/runs/background/process-terminal.ts +17 -96
  64. package/src/runs/background/result-watcher.ts +1 -1
  65. package/src/runs/background/retained-children.ts +3 -2
  66. package/src/runs/background/run-child-session.ts +16 -5
  67. package/src/runs/background/run-id-resolver.ts +10 -5
  68. package/src/runs/background/run-status.ts +10 -4
  69. package/src/runs/background/runner-aliases.ts +25 -15
  70. package/src/runs/background/runner-child-launch.ts +1 -2
  71. package/src/runs/background/runner-startup-failure.ts +56 -0
  72. package/src/runs/background/stale-run-reconciler.ts +19 -3
  73. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  74. package/src/runs/background/subagent-runner.ts +96 -287
  75. package/src/runs/background/wait-tool.ts +2 -0
  76. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  77. package/src/runs/foreground/execution.ts +217 -250
  78. package/src/runs/foreground/prompt-audit.ts +3 -9
  79. package/src/runs/foreground/subagent-executor.ts +377 -119
  80. package/src/runs/shared/acceptance.ts +167 -68
  81. package/src/runs/shared/capability-ceiling.ts +4 -1
  82. package/src/runs/shared/child-hooks.ts +1 -16
  83. package/src/runs/shared/child-launch.ts +22 -14
  84. package/src/runs/shared/child-runtime-config.ts +3 -0
  85. package/src/runs/shared/child-session.ts +52 -2
  86. package/src/runs/shared/child-tool-plan.ts +23 -113
  87. package/src/runs/shared/dynamic-fanout.ts +1 -1
  88. package/src/runs/shared/external-cli-runner.ts +3 -1
  89. package/src/runs/shared/external-job-bridge.ts +54 -0
  90. package/src/runs/shared/git-environment.ts +29 -0
  91. package/src/runs/shared/mcp-config-sources.ts +3 -0
  92. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  93. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  94. package/src/runs/shared/model-resolution.ts +6 -1
  95. package/src/runs/shared/nested-events.ts +67 -55
  96. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  97. package/src/runs/shared/parallel-utils.ts +2 -1
  98. package/src/runs/shared/pi-spawn.ts +92 -6
  99. package/src/runs/shared/single-output.ts +11 -2
  100. package/src/runs/shared/structured-output.ts +227 -7
  101. package/src/runs/shared/subagent-control.ts +2 -16
  102. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  103. package/src/runs/shared/tool-availability.ts +2 -2
  104. package/src/runs/shared/tool-budget.ts +21 -0
  105. package/src/runs/shared/usage-reconciliation.ts +73 -0
  106. package/src/runs/shared/worktree.ts +35 -8
  107. package/src/shared/child-session-name.ts +4 -2
  108. package/src/shared/fork-context.ts +11 -4
  109. package/src/shared/launch-contract.ts +1 -1
  110. package/src/shared/pruned-fork.ts +69 -56
  111. package/src/shared/types.ts +52 -16
  112. package/src/slash/delegation-adapters.ts +25 -1
  113. package/src/slash/prompt-template-bridge.ts +16 -1
  114. package/src/slash/prompt-workflows.ts +12 -1
  115. package/src/slash/slash-commands.ts +7 -241
  116. package/src/slash/subagent-cost.ts +313 -0
  117. package/src/slash/subagents-admin.ts +28 -29
  118. package/src/tui/fleet-status.ts +24 -2
  119. package/src/tui/fleet.ts +7 -4
  120. package/src/tui/render.ts +53 -19
  121. package/src/watchdog/diff-tool.ts +24 -3
  122. package/src/watchdog/permission-arbiter.ts +13 -15
  123. package/src/watchdog/register-child.ts +10 -2
  124. package/src/watchdog/review.ts +14 -14
  125. package/src/watchdog/runtime.ts +2 -1
  126. package/src/watchdog/turn-delta.ts +11 -5
  127. package/src/workflows/scripted-workflow.ts +109 -23
  128. package/src/workflows/workflow-child-summary.ts +4 -2
  129. package/src/workflows/workflow-settlement.ts +4 -1
  130. package/src/runs/shared/completion-evidence.ts +0 -89
  131. package/src/runs/shared/completion-guard.ts +0 -255
  132. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  133. package/src/runs/shared/task-intent.ts +0 -244
@@ -7,10 +7,15 @@
7
7
  * without the real runtime; the default implementation wraps
8
8
  * `createAgentSession` from a pi package module.
9
9
  */
10
+ import * as fs from "node:fs";
11
+ import * as path from "node:path";
12
+ import { pathToFileURL } from "node:url";
10
13
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
11
14
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
15
  import { pinChildCacheRetention } from "../../shared/child-cache-retention.ts";
13
- import { getAgentDir } from "../../shared/utils.ts";
16
+ import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
17
+ import { resolvePackageSubpath } from "../background/runner-aliases.ts";
18
+ import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "./pi-spawn.ts";
14
19
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
15
20
  import type { RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
16
21
  import type { HerdrMachineReference, HerdrRemoteGitStatus } from "../../shared/types.ts";
@@ -108,6 +113,7 @@ export interface ChildSession {
108
113
  readonly sessionFile: string | undefined;
109
114
  readonly sessionId: string;
110
115
  readonly modelId: string | undefined;
116
+ readonly contextWindow?: number;
111
117
  readonly machineEvidence?: { machineId: string; initial?: HerdrRemoteGitStatus; final?: HerdrRemoteGitStatus };
112
118
  /** Event-updated pane-native status; reading it performs no network work. */
113
119
  readonly placementSnapshot?: unknown;
@@ -255,12 +261,55 @@ function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModu
255
261
  return { claimedProviderIds, registered };
256
262
  }
257
263
 
264
+ /**
265
+ * Load the host-owned pi-coding-agent module by absolute package entry so a
266
+ * child cannot resolve an extension-owned copy. Root precedence is the running
267
+ * host, an explicit override, then the install tree. Once any root is selected,
268
+ * its manifest, package identity, entry, and import must all succeed; the bare
269
+ * specifier is used only when no root resolves.
270
+ */
271
+ export async function loadHostPiCodingAgent(): Promise<PiCodingAgentModule> {
272
+ const overrideRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]?.trim() || undefined;
273
+ const runningRoot = resolvePiPackageRoot();
274
+ const selectedOverride = runningRoot === undefined ? overrideRoot : undefined;
275
+ const root = runningRoot ?? selectedOverride ?? resolveInstalledPiPackageRoot();
276
+ if (root) {
277
+ const entry = fs.realpathSync(resolveHostPackageEntry(root, selectedOverride));
278
+ return import(pathToFileURL(entry).href);
279
+ }
280
+ return import(PI_CODING_AGENT_PACKAGE);
281
+ }
282
+
283
+ function resolveHostPackageEntry(root: string, overrideRoot: string | undefined): string {
284
+ const packageJson = path.join(root, "package.json");
285
+ const source = fs.readFileSync(packageJson, "utf8");
286
+ let parsed: unknown;
287
+ try {
288
+ parsed = JSON.parse(source);
289
+ } catch (error) {
290
+ throw new Error(`invalid host SDK manifest at ${packageJson}: malformed JSON`, { cause: error });
291
+ }
292
+ if (!isUnknownRecord(parsed)) throw new Error(`invalid host SDK manifest at ${packageJson}: expected a JSON object`);
293
+ const pkg = parsed;
294
+ if (pkg.name !== PI_CODING_AGENT_PACKAGE) {
295
+ const source = overrideRoot !== undefined ? ` (${PI_CODING_AGENT_PACKAGE_ROOT_ENV} override)` : "";
296
+ throw new Error(`refusing to load the host SDK from ${root}${source}: package.json name is "${String(pkg.name ?? "(none)")}", expected "${PI_CODING_AGENT_PACKAGE}"`);
297
+ }
298
+ const entry = resolvePackageSubpath(root, ".");
299
+ if (!entry) throw new Error(`host SDK manifest at ${packageJson} has no resolvable root export`);
300
+ return entry;
301
+ }
302
+
303
+ function isUnknownRecord(value: unknown): value is Record<string, unknown> {
304
+ return typeof value === "object" && value !== null && !Array.isArray(value);
305
+ }
306
+
258
307
  /**
259
308
  * Default factory: detached/background sessions retain the existing shared
260
309
  * runtime; each parent-bound foreground launch gets an isolated runtime.
261
310
  */
262
311
  export function createDefaultChildSessionFactory(options: DefaultChildSessionFactoryOptions = {}): ChildSessionFactory {
263
- const loadPiCodingAgent = options.loadPiCodingAgent ?? (() => import("@earendil-works/pi-coding-agent"));
312
+ const loadPiCodingAgent = options.loadPiCodingAgent ?? loadHostPiCodingAgent;
264
313
  const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5_000;
265
314
  let runtime: ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]> | undefined;
266
315
  const live = new Set<ChildSession>();
@@ -403,6 +452,7 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
403
452
  get sessionFile() { return session.sessionFile; },
404
453
  get sessionId() { return session.sessionId; },
405
454
  get modelId() { return session.model ? `${session.model.provider}/${session.model.id}` : undefined; },
455
+ get contextWindow() { return session.model?.contextWindow; },
406
456
  };
407
457
  live.add(child);
408
458
  return child;
@@ -62,45 +62,10 @@ const SUBAGENT_RUNTIME_EXTENSION_PATHS = new Set([
62
62
  export function isSubagentRuntimeExtensionPath(extensionPath: string): boolean {
63
63
  return SUBAGENT_RUNTIME_EXTENSION_PATHS.has(path.normalize(extensionPath));
64
64
  }
65
- const FAST_MODE_ALLOWED_MODELS = new Set([
66
- "openai-codex/gpt-5.6-luna",
67
- "openai-codex/gpt-5.6-sol",
68
- ]);
69
- const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
70
65
  const PI_BUILTIN_TOOL_NAMES = new Set(["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"]);
71
- const REPOSITORY_INSPECTION_TOOLS = new Set(["read", "grep", "find", "ls", "bash", "powershell"]);
72
- const REVIEW_OR_SCOUT_AGENT_PATTERN = /\b(?:reviewer|scout)\b/i;
73
-
74
- export function isReviewOrScoutLaneAgent(agentName: string | undefined): boolean {
75
- return typeof agentName === "string" && REVIEW_OR_SCOUT_AGENT_PATTERN.test(agentName);
76
- }
77
-
78
- export function missingPermittedRepositoryInspectionTools(
79
- unavailableHostBuiltins: readonly string[],
80
- excludeTools: readonly string[] = [],
81
- ): string[] {
82
- const excluded = new Set(excludeTools);
83
- return unavailableHostBuiltins.filter((tool) => REPOSITORY_INSPECTION_TOOLS.has(tool) && !excluded.has(tool));
84
- }
85
-
86
- export function formatReviewLaneToolContractFailure(input: {
87
- agentName?: string;
88
- missingTools: readonly string[];
89
- requestedTools?: readonly string[];
90
- effectiveTools: readonly string[];
91
- ceilingSources?: readonly string[];
92
- excludeTools?: readonly string[];
93
- }): string {
94
- const subject = input.agentName ? `Agent '${input.agentName}'` : "Subagent";
95
- return [
96
- `${subject}: tool contract could not be satisfied; host runtime does not provide permitted required repository tools [${input.missingTools.join(", ")}].`,
97
- `Requested tool names: ${input.requestedTools ? `[${input.requestedTools.join(", ")}]` : "not explicitly specified"}; effective tool allowlist: [${input.effectiveTools.join(", ")}].`,
98
- ...(input.ceilingSources?.length ? [`Active capability ceiling sources: [${input.ceilingSources.join(", ")}].`] : []),
99
- ...(input.excludeTools?.length ? [`Explicit excludeTools: [${input.excludeTools.join(", ")}].`] : []),
100
- "This is a lane infrastructure failure, not a completed review/scout result.",
101
- ].join(" ");
102
- }
103
-
66
+ // Priority tier is an OpenAI-Codex request field; other providers reject or ignore it.
67
+ const FAST_MODE_PROVIDER_PREFIX = "openai-codex/";
68
+ const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
104
69
  export function deriveForkPromptCacheKey(parentSessionId: string | undefined): string | undefined {
105
70
  const parent = parentSessionId?.trim();
106
71
  if (!parent) return undefined;
@@ -160,9 +125,9 @@ function resolveFastModeExtension(input: Pick<ResolvePiLaunchToolPlanInput, "fas
160
125
  if (candidates.length === 0) {
161
126
  throw new Error(`fast mode requires an explicit supported native OpenAI-Codex model${input.agentName ? ` for agent '${input.agentName}'` : ""}.`);
162
127
  }
163
- const unsupported = candidates.filter((model) => !FAST_MODE_ALLOWED_MODELS.has(model));
128
+ const unsupported = candidates.filter((model) => !model.startsWith(FAST_MODE_PROVIDER_PREFIX));
164
129
  if (unsupported.length > 0) {
165
- throw new Error(`fast mode supports only ${[...FAST_MODE_ALLOWED_MODELS].join(", ")}; unsupported model${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
130
+ throw new Error(`fast mode supports only native ${FAST_MODE_PROVIDER_PREFIX}* models; unsupported model${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
166
131
  }
167
132
  return [FAST_MODE_EXTENSION_PATH];
168
133
  }
@@ -205,7 +170,8 @@ export interface ResolvePiLaunchToolPlanInput {
205
170
  * empty or ceiling-restricted allowlists are not a minimum-tool contract.
206
171
  * Non-core names remain allowed and are validated in the child's registry.
207
172
  */
208
- hostAvailableBuiltins?: readonly string[];}
173
+ hostAvailableBuiltins?: readonly string[];
174
+ }
209
175
 
210
176
  export interface PiLaunchToolPlan {
211
177
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
@@ -231,8 +197,6 @@ export interface PiLaunchToolPlan {
231
197
  capabilityAudit?: SubagentCapabilityAudit;
232
198
  /** Non-fatal launch warnings; they do not change behavior. */
233
199
  warnings: string[];
234
- /** Builtin tools the agent declared but the host runtime does not provide. */
235
- unavailableHostBuiltins: string[];
236
200
  }
237
201
 
238
202
  function extensionIdentifier(value: string): string {
@@ -361,32 +325,6 @@ export function resolvePermissionSystemExtension(): string | undefined {
361
325
  return undefined;
362
326
  }
363
327
 
364
- /**
365
- * Extract the names of builtin tools the host provides. Use this to pass
366
- * `hostAvailableBuiltins` to `resolvePiLaunchToolPlan` so child tool plans
367
- * intersect known core slots with what the host actually supports. Wrapped
368
- * core slots count regardless of source; host-specific builtins count too.
369
- *
370
- * Returns `undefined` when builtin tool discovery fails or yields nothing,
371
- * so callers skip the intersection (fail-safe to allowing all declared tools).
372
- * This handles test mocks without proper tool registration and hosts whose
373
- * getAllTools() throws before extensions load.
374
- */
375
- export function getHostBuiltinToolNames(pi: Pick<ExtensionAPI, "getAllTools">): string[] | undefined {
376
- try {
377
- const builtins = pi
378
- .getAllTools()
379
- .filter((tool) => {
380
- const source = (tool.sourceInfo as { source?: string } | undefined)?.source;
381
- return source === "builtin" || PI_BUILTIN_TOOL_NAMES.has(tool.name);
382
- })
383
- .map((tool) => tool.name);
384
- return builtins.length > 0 ? builtins : undefined;
385
- } catch {
386
- return undefined;
387
- }
388
- }
389
-
390
328
  export function resolvePiLaunchToolPlan(
391
329
  input: ResolvePiLaunchToolPlanInput,
392
330
  ): PiLaunchToolPlan {
@@ -402,21 +340,11 @@ export function resolvePiLaunchToolPlan(
402
340
  capabilityCeiling?.allowedTools === undefined
403
341
  ? undefined
404
342
  : new Set(capabilityCeiling.allowedTools);
405
- const hostAvailableSet =
406
- input.hostAvailableBuiltins === undefined
407
- ? undefined
408
- : new Set(input.hostAvailableBuiltins);
409
343
  const requestedBuiltinTools =
410
344
  input.tools?.filter(
411
345
  (tool) =>
412
346
  !(tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
413
347
  ) ?? [];
414
- if (input.requireReadTool && hostAvailableSet && !hostAvailableSet.has("read")) {
415
- const agentLabel = input.agentName ? ` for agent '${input.agentName}'` : "";
416
- throw new Error(
417
- `Host runtime does not provide required tool 'read'${agentLabel} for lazy skill loading.`,
418
- );
419
- }
420
348
  if (input.requireReadTool && allowedToolSet && !allowedToolSet.has("read")) {
421
349
  throw new Error(
422
350
  `Capability ceiling from ${capabilityCeiling?.sources.join(", ") || "unknown source"} excludes required tool 'read' for lazy skill loading.`,
@@ -434,12 +362,7 @@ export function resolvePiLaunchToolPlan(
434
362
  ? ["read", ...requestedBuiltinTools]
435
363
  : requestedBuiltinTools
436
364
  ).filter((tool) => !allowedToolSet || allowedToolSet.has(tool));
437
- const declaredBuiltinTools = hostAvailableSet
438
- ? ceilingFilteredBuiltinTools.filter((tool) => !PI_BUILTIN_TOOL_NAMES.has(tool) || hostAvailableSet.has(tool))
439
- : ceilingFilteredBuiltinTools;
440
- const unavailableHostBuiltins = hostAvailableSet
441
- ? ceilingFilteredBuiltinTools.filter((tool) => PI_BUILTIN_TOOL_NAMES.has(tool) && !hostAvailableSet.has(tool))
442
- : [];
365
+ const declaredBuiltinTools = ceilingFilteredBuiltinTools;
443
366
  const excludeTools = [...new Set((input.excludeTools ?? []).map((tool) => tool.trim()).filter(Boolean))];
444
367
  const excludedToolSet = new Set(excludeTools);
445
368
  const effectiveDeclaredBuiltinTools = declaredBuiltinTools.filter((tool) => !excludedToolSet.has(tool));
@@ -567,32 +490,6 @@ export function resolvePiLaunchToolPlan(
567
490
  ]),
568
491
  ]
569
492
  : undefined;
570
- const missingPermittedRepositoryTools = input.tools !== undefined
571
- ? missingPermittedRepositoryInspectionTools(unavailableHostBuiltins, excludeTools)
572
- : [];
573
- if (missingPermittedRepositoryTools.length > 0 && isReviewOrScoutLaneAgent(input.agentName)) {
574
- throw new Error(formatReviewLaneToolContractFailure({
575
- agentName: input.agentName,
576
- missingTools: missingPermittedRepositoryTools,
577
- requestedTools: requestedToolNames,
578
- effectiveTools: effectiveToolAllowlist,
579
- ceilingSources: capabilityCeiling?.sources,
580
- excludeTools,
581
- }));
582
- }
583
- // Host pruning also happens without a ceiling (and therefore without an
584
- // audit). Use the existing non-fatal launch warnings rather than inventing
585
- // a ceiling or treating the requested allowlist as a minimum requirement.
586
- if (unavailableHostBuiltins.length > 0) {
587
- const subject = input.agentName ? `Agent '${input.agentName}'` : "Subagent";
588
- warnings.push(
589
- `${subject}: host runtime tool availability omitted [${unavailableHostBuiltins.join(", ")}]. `
590
- + `Requested tool names: ${requestedToolNames ? `[${requestedToolNames.join(", ")}]` : "not explicitly specified"}; effective tool allowlist: [${effectiveToolAllowlist.join(", ")}]. `
591
- + (capabilityCeiling ? `Active capability ceiling sources: [${capabilityCeiling.sources.join(", ") || "unknown source"}]. ` : "")
592
- + (excludeTools.length > 0 ? `Explicit excludeTools: [${excludeTools.join(", ")}]. ` : "")
593
- + "This is a non-fatal tool-plan diagnostic, not verification of the child's runtime tool menu.",
594
- );
595
- }
596
493
  const capabilityAudit = capabilityCeiling
597
494
  ? ({
598
495
  ceiling: capabilityCeiling,
@@ -630,7 +527,6 @@ export function resolvePiLaunchToolPlan(
630
527
  capabilityCeilingAgentRestrictionSources(capabilityCeiling),
631
528
  }
632
529
  : {}),
633
- ...(unavailableHostBuiltins.length > 0 ? { unavailableHostBuiltins } : {}),
634
530
  } satisfies SubagentCapabilityAudit)
635
531
  : undefined;
636
532
  return {
@@ -654,7 +550,6 @@ export function resolvePiLaunchToolPlan(
654
550
  extensionArgs,
655
551
  disableAmbientExtensions,
656
552
  warnings,
657
- unavailableHostBuiltins,
658
553
  ...(capabilityAudit ? { capabilityAudit } : {}),
659
554
  };
660
555
  }
@@ -688,3 +583,18 @@ function legacyUnderscoreMcpToolName(selection: ResolvedMcpDirectToolSelection):
688
583
  const prefix = selection.name.slice(0, -suffix.length);
689
584
  return `${prefix.replace(/-/g, "_")}${suffix}`;
690
585
  }
586
+
587
+ export function getHostBuiltinToolNames(pi: Pick<ExtensionAPI, "getAllTools">): string[] | undefined {
588
+ try {
589
+ const builtins = pi
590
+ .getAllTools()
591
+ .filter((tool) => {
592
+ const source = (tool.sourceInfo as { source?: string } | undefined)?.source;
593
+ return source === "builtin" || PI_BUILTIN_TOOL_NAMES.has(tool.name);
594
+ })
595
+ .map((tool) => tool.name);
596
+ return builtins.length > 0 ? builtins : undefined;
597
+ } catch {
598
+ return undefined;
599
+ }
600
+ }
@@ -50,7 +50,7 @@ const DYNAMIC_PARALLEL_KEYS = new Set(["agent", "task", "phase", "label", "outpu
50
50
  const RUNNER_DYNAMIC_PARALLEL_KEYS = new Set([
51
51
  ...DYNAMIC_PARALLEL_KEYS,
52
52
  "outputName", "structured", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled", "waitToolDefaultTimeoutMs",
53
- "structuredOutput", "structuredOutputSchema", "tools", "excludeTools", "allowNestedSubagents", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "mutationTools", "capabilityCeiling", "completionGuard", "systemPrompt",
53
+ "structuredOutput", "structuredOutputSchema", "tools", "excludeTools", "allowNestedSubagents", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "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"]);
@@ -6,6 +6,7 @@ import { finished } from "node:stream/promises";
6
6
  import type { ExternalProcessStatus, ProcessTreeTerminal } from "../../shared/types.ts";
7
7
  import { createOwnedProcessTreeController, type OwnedProcessTreeController } from "../background/owned-process-tree.ts";
8
8
  import { omitExtensionBindingsEnv } from "./extension-bindings.ts";
9
+ import { omitGitRoutingEnv } from "./git-environment.ts";
9
10
  import {
10
11
  invalidateExternalCliPreflight,
11
12
  preflightExternalCli,
@@ -86,7 +87,8 @@ function narrowLimit(value: number | undefined, ceiling: number, label: string):
86
87
  }
87
88
 
88
89
  function externalEnvironment(allowlist: readonly string[] | undefined, values: Readonly<Record<string, string>> | undefined): NodeJS.ProcessEnv {
89
- if (!allowlist) return omitExtensionBindingsEnv(process.env);
90
+ // An adapter allowlist is a deliberate choice, so only the inherited default is filtered.
91
+ if (!allowlist) return omitGitRoutingEnv(omitExtensionBindingsEnv(process.env));
90
92
  const allowed = new Set(allowlist);
91
93
  const env: NodeJS.ProcessEnv = {};
92
94
  for (const key of allowed) {
@@ -3,6 +3,8 @@ import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
6
+ import { readStatus } from "../../shared/utils.ts";
7
+ import { isActiveAsyncState } from "../background/active-run-index.ts";
6
8
  import {
7
9
  ExternalJobProviderError,
8
10
  getExternalJobProvider,
@@ -19,6 +21,7 @@ export const EXTERNAL_JOB_BRIDGE_REQUEST_DIR = "external-job-requests";
19
21
  const EXTERNAL_JOB_BRIDGE_RESPONSE_DIR = "external-job-responses";
20
22
  const DEFAULT_OPERATION_TIMEOUT_MS = 120_000;
21
23
  const POLL_INTERVAL_MS = 50;
24
+ const CHILD_BRIDGE_SWEEP_INTERVAL_MS = 1_000;
22
25
  const MAX_REQUESTS_PER_SWEEP = 100;
23
26
 
24
27
  interface ExternalJobBridgeRequest {
@@ -309,6 +312,57 @@ function readClaimHandle(provider: string, claimDir: string): ExternalJobHandle
309
312
  }
310
313
  }
311
314
 
315
+ export function externalJobBridgeEligibility(steps: unknown): "required" | "not-required" | "unknown" {
316
+ if (!Array.isArray(steps)) return "unknown";
317
+ for (const step of steps) {
318
+ const runner = (step as { runner?: unknown } | null)?.runner;
319
+ if (runner === undefined) continue;
320
+ if (!runner || typeof runner !== "object" || Array.isArray(runner)) return "unknown";
321
+ const runnerType = (runner as { type?: unknown }).type;
322
+ if (typeof runnerType !== "string") return "unknown";
323
+ if (runnerType === "external-job") return "required";
324
+ if (runnerType !== "pi" && runnerType !== "external-cli") return "unknown";
325
+ }
326
+ return "not-required";
327
+ }
328
+
329
+ /** Services the bridges of external-job runs that a child session launched; only the root has an async job tracker. */
330
+ export function createChildExternalJobBridgeSweeper() {
331
+ const runs = new Map<string, string>();
332
+ let timer: ReturnType<typeof setInterval> | undefined;
333
+ const sweep = (): number => {
334
+ for (const [runId, asyncDir] of runs) {
335
+ try {
336
+ const status = readStatus(asyncDir);
337
+ // The launch status has no runner metadata until the runner starts, so re-check on every sweep.
338
+ if (externalJobBridgeEligibility(status?.steps) !== "not-required") serviceExternalJobBridgeRequests(asyncDir);
339
+ if (status && !isActiveAsyncState(status.state)) runs.delete(runId);
340
+ } catch (error) {
341
+ console.error(`Failed to service external-job bridge requests for '${asyncDir}':`, error);
342
+ }
343
+ }
344
+ if (runs.size === 0 && timer) {
345
+ clearInterval(timer);
346
+ timer = undefined;
347
+ }
348
+ return runs.size;
349
+ };
350
+ return {
351
+ track(runId: string, asyncDir: string): void {
352
+ runs.set(runId, asyncDir);
353
+ if (timer) return;
354
+ timer = setInterval(sweep, CHILD_BRIDGE_SWEEP_INTERVAL_MS);
355
+ timer.unref?.();
356
+ },
357
+ sweep,
358
+ dispose(): void {
359
+ runs.clear();
360
+ if (timer) clearInterval(timer);
361
+ timer = undefined;
362
+ },
363
+ };
364
+ }
365
+
312
366
  export function serviceExternalJobBridgeRequests(asyncDir: string): void {
313
367
  let files: string[];
314
368
  try {
@@ -0,0 +1,29 @@
1
+ const GIT_ROUTING_VARIABLES = new Set([
2
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
3
+ "GIT_COMMON_DIR",
4
+ "GIT_CONFIG",
5
+ "GIT_CONFIG_COUNT",
6
+ "GIT_CONFIG_PARAMETERS",
7
+ "GIT_DIR",
8
+ "GIT_GRAFT_FILE",
9
+ "GIT_IMPLICIT_WORK_TREE",
10
+ "GIT_INDEX_FILE",
11
+ "GIT_NAMESPACE",
12
+ "GIT_NO_REPLACE_OBJECTS",
13
+ "GIT_OBJECT_DIRECTORY",
14
+ "GIT_PREFIX",
15
+ "GIT_REPLACE_REF_BASE",
16
+ "GIT_SHALLOW_FILE",
17
+ "GIT_WORK_TREE",
18
+ ]);
19
+
20
+ function isGitRoutingVariable(name: string): boolean {
21
+ // Windows environment names are case-insensitive, and Git for Windows reads them that way.
22
+ const upper = name.toUpperCase();
23
+ return GIT_ROUTING_VARIABLES.has(upper) || /^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(upper);
24
+ }
25
+
26
+ /** Remove inherited values that can route Git commands away from the child cwd. */
27
+ export function omitGitRoutingEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
28
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !isGitRoutingVariable(name)));
29
+ }
@@ -3,6 +3,7 @@ import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { findConfiguredProjectRoot } from "../../agents/agents.ts";
5
5
  import { getAgentDir, getConfigDirName, getProjectConfigDir } from "../../shared/utils.ts";
6
+ import type { McpToolPrefix } from "./mcp-direct-tool-grant.ts";
6
7
 
7
8
  const PACKAGE_CONFIG_ROOT = "npm";
8
9
  const PACKAGE_GIT_ROOT = "git";
@@ -32,6 +33,8 @@ export interface McpServerDefinition {
32
33
  exposeResources?: boolean;
33
34
  includeTools?: string[];
34
35
  excludeTools?: string[];
36
+ /** Per-server override of the global `settings.toolPrefix`, matching the adapter. */
37
+ toolPrefix?: McpToolPrefix;
35
38
  protocolVersion?: string;
36
39
  directTools?: boolean | string[];
37
40
  httpTransport?: string;
@@ -301,7 +301,7 @@ function parseServerEntries(value: unknown): Record<string, ServerEntry> {
301
301
 
302
302
  function parseSettings(value: unknown): McpConfig["settings"] | undefined {
303
303
  if (!isRecord(value)) return undefined;
304
- const toolPrefix = value.toolPrefix === "server" || value.toolPrefix === "short" || value.toolPrefix === "none" ? value.toolPrefix : undefined;
304
+ const toolPrefix = value.toolPrefix === "server" || value.toolPrefix === "short" || value.toolPrefix === "none" || value.toolPrefix === "mcp" ? value.toolPrefix : undefined;
305
305
  const directTools = typeof value.directTools === "boolean" ? value.directTools : undefined;
306
306
  const settings: NonNullable<McpConfig["settings"]> = {
307
307
  ...(toolPrefix ? { toolPrefix } : {}),
@@ -1,11 +1,13 @@
1
1
  const BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
2
2
 
3
- export type McpToolPrefix = "server" | "none" | "short";
3
+ export type McpToolPrefix = "server" | "none" | "short" | "mcp";
4
4
 
5
5
  export interface McpGrantServerFacts {
6
6
  readonly exposeResources?: boolean;
7
7
  readonly includeTools?: readonly unknown[];
8
8
  readonly excludeTools?: readonly unknown[];
9
+ /** Per-server prefix override, matching the adapter's `ServerEntry.toolPrefix`. */
10
+ readonly toolPrefix?: unknown;
9
11
  }
10
12
 
11
13
  export interface McpGrantToolMetadata {
@@ -73,7 +75,6 @@ export function planMcpDirectToolGrant(input: McpDirectToolGrantInput): McpDirec
73
75
  const { servers: selectedServers, tools: selectedTools } = parseMcpDirectToolSelectors(selectors);
74
76
  const selections: ResolvedMcpDirectToolSelection[] = [];
75
77
  const seenNames = new Set<string>();
76
- const prefix = normalizeMcpToolPrefix(input.toolPrefix);
77
78
 
78
79
  for (const [serverName, server] of Object.entries(input.servers)) {
79
80
  const metadata = input.metadata[serverName];
@@ -83,6 +84,7 @@ export function planMcpDirectToolGrant(input: McpDirectToolGrantInput): McpDirec
83
84
  ? true
84
85
  : selectedTools.get(serverName);
85
86
  if (!toolFilter) continue;
87
+ const prefix = normalizeMcpToolPrefix(server.toolPrefix ?? input.toolPrefix);
86
88
 
87
89
  for (const tool of Array.isArray(metadata.tools) ? metadata.tools : []) {
88
90
  if (typeof tool?.name !== "string" || !tool.name) continue;
@@ -116,7 +118,7 @@ export function planMcpDirectToolGrant(input: McpDirectToolGrantInput): McpDirec
116
118
  }
117
119
 
118
120
  export function normalizeMcpToolPrefix(value: unknown): McpToolPrefix {
119
- return value === "none" || value === "short" || value === "server" ? value : "server";
121
+ return value === "none" || value === "short" || value === "mcp" || value === "server" ? value : "server";
120
122
  }
121
123
 
122
124
  export function formatUnresolvedMcpDirectToolSelectors(selectors: readonly string[]): string {
@@ -125,13 +127,26 @@ export function formatUnresolvedMcpDirectToolSelectors(selectors: readonly strin
125
127
 
126
128
  function getServerPrefix(serverName: string, mode: McpToolPrefix): string {
127
129
  if (mode === "none") return "";
128
- if (mode === "short") return serverName.replace(/-?mcp$/i, "") || "mcp";
129
- return serverName;
130
+ if (mode === "short") return sanitizeServerPrefix(serverName.replace(/-?mcp$/i, "")) || "mcp";
131
+ if (mode === "mcp") return `mcp__${sanitizeServerPrefix(serverName)}`;
132
+ return sanitizeServerPrefix(serverName);
133
+ }
134
+
135
+ /** Adapter parity: characters outside [A-Za-z0-9_-] become `_<code point in hex>_`. */
136
+ function sanitizeServerPrefix(serverName: string): string {
137
+ return Array.from(serverName, (char) => /^[A-Za-z0-9_-]$/.test(char) ? char : `_${char.codePointAt(0)!.toString(16)}_`).join("");
130
138
  }
131
139
 
132
140
  function formatToolName(toolName: string, serverName: string, prefix: McpToolPrefix): string {
133
141
  const serverPrefix = getServerPrefix(serverName, prefix);
134
- return serverPrefix ? `${serverPrefix}_${toolName}` : toolName;
142
+ const sanitized = toolName.replace(/\./g, "_");
143
+ // Some servers prefix their tool names with the server name (codegraph ->
144
+ // codegraph_explore). pi-mcp-adapter registers such a name unchanged, so
145
+ // keep the two sides in agreement instead of demanding codegraph_codegraph_explore.
146
+ if (serverPrefix && sanitized.startsWith(`${serverPrefix}_`) && sanitized.length > serverPrefix.length + 1) {
147
+ return sanitized;
148
+ }
149
+ return serverPrefix ? `${serverPrefix}_${sanitized}` : sanitized;
135
150
  }
136
151
 
137
152
  function isToolAllowed(
@@ -153,6 +168,7 @@ function toolNameCandidates(toolName: string, serverName: string, prefix: McpToo
153
168
  formatToolName(toolName, serverName, prefix),
154
169
  formatToolName(toolName, serverName, "server"),
155
170
  formatToolName(toolName, serverName, "short"),
171
+ formatToolName(toolName, serverName, "mcp"),
156
172
  formatToolName(toolName, serverName, "none"),
157
173
  ]);
158
174
  }
@@ -140,7 +140,12 @@ function resolveBaseModelCandidate(
140
140
  if (exactId) return exactId;
141
141
  }
142
142
 
143
- return fuzzyResolveModel(baseModel, availableModels, preferredProvider);
143
+ const fuzzy = fuzzyResolveModel(baseModel, availableModels, preferredProvider);
144
+ if (fuzzy || queryProvider === undefined) return fuzzy;
145
+ // Some catalogs (OpenRouter's `openrouter/auto-beta`) repeat the provider inside the id.
146
+ const queryId = normalizeModelSegment(baseModel);
147
+ const prefixedIdMatches = availableModels.filter((entry) => normalizeModelSegment(entry.id) === queryId && normalizeModelSegment(entry.provider) === queryProvider);
148
+ return prefixedIdMatches.length === 1 ? prefixedIdMatches[0]!.fullId : undefined;
144
149
  }
145
150
 
146
151
  /**