@xzzpig/pi-subagents 0.15.1 → 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 (135) hide show
  1. package/CHANGELOG.md +178 -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 +19 -12
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/fork-extensions.md +23 -15
  12. package/docs/models.md +5 -3
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +4 -4
  15. package/docs/tool-reference.md +40 -19
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +57 -3
  18. package/inspector-runner.mjs +1 -1
  19. package/package.json +14 -8
  20. package/prompts/council.md +6 -3
  21. package/runner-peer-loader.mjs +4 -7
  22. package/runner-peer-preload.mjs +5 -7
  23. package/skills/pi-subagents/SKILL.md +1 -0
  24. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  25. package/skills/pi-subagents/references/execution-controls.md +6 -4
  26. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  27. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  28. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  29. package/src/agents/agent-eject.ts +3 -3
  30. package/src/agents/agent-management.ts +61 -52
  31. package/src/agents/agent-memory.ts +90 -3
  32. package/src/agents/agent-serializer.ts +4 -4
  33. package/src/agents/agents.ts +125 -51
  34. package/src/agents/global-npm-root.ts +58 -0
  35. package/src/agents/proactive-skills.ts +4 -1
  36. package/src/agents/runtime-agent-registry.ts +14 -11
  37. package/src/agents/skills.ts +42 -9
  38. package/src/api/delegation.ts +15 -0
  39. package/src/api/inspectors.ts +27 -0
  40. package/src/api/preflight.ts +60 -60
  41. package/src/extension/doctor.ts +9 -4
  42. package/src/extension/fanout-child.ts +8 -0
  43. package/src/extension/index.ts +101 -48
  44. package/src/extension/rpc.ts +10 -1
  45. package/src/extension/schemas.ts +12 -6
  46. package/src/extension/subagent-guide.ts +12 -4
  47. package/src/extension/tool-activation.ts +197 -0
  48. package/src/extension/tool-description.ts +1 -1
  49. package/src/inspectors/ghostty/plugin.ts +13 -1
  50. package/src/inspectors/plugins.ts +70 -3
  51. package/src/intercom/intercom-bridge.ts +2 -0
  52. package/src/intercom/native-supervisor-channel.ts +22 -15
  53. package/src/intercom/result-intercom.ts +4 -0
  54. package/src/runs/background/active-async-capacity.ts +3 -25
  55. package/src/runs/background/async-execution.ts +100 -140
  56. package/src/runs/background/async-job-tracker.ts +28 -34
  57. package/src/runs/background/async-resume.ts +16 -8
  58. package/src/runs/background/async-status.ts +2 -0
  59. package/src/runs/background/binary-bootstrap.ts +34 -6
  60. package/src/runs/background/fleet-view.ts +51 -7
  61. package/src/runs/background/notify.ts +93 -7
  62. package/src/runs/background/pid-namespace.ts +18 -0
  63. package/src/runs/background/process-terminal-candidate.ts +98 -0
  64. package/src/runs/background/process-terminal.ts +17 -96
  65. package/src/runs/background/result-watcher.ts +1 -1
  66. package/src/runs/background/retained-children.ts +3 -2
  67. package/src/runs/background/run-child-session.ts +16 -5
  68. package/src/runs/background/run-id-resolver.ts +10 -5
  69. package/src/runs/background/run-status.ts +10 -4
  70. package/src/runs/background/runner-aliases.ts +25 -15
  71. package/src/runs/background/runner-child-launch.ts +1 -2
  72. package/src/runs/background/runner-startup-failure.ts +56 -0
  73. package/src/runs/background/stale-run-reconciler.ts +19 -3
  74. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  75. package/src/runs/background/subagent-runner.ts +96 -287
  76. package/src/runs/background/wait-tool.ts +2 -0
  77. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  78. package/src/runs/foreground/execution.ts +217 -250
  79. package/src/runs/foreground/prompt-audit.ts +3 -9
  80. package/src/runs/foreground/subagent-executor.ts +377 -119
  81. package/src/runs/shared/acceptance.ts +167 -68
  82. package/src/runs/shared/capability-ceiling.ts +4 -1
  83. package/src/runs/shared/child-hooks.ts +1 -16
  84. package/src/runs/shared/child-launch.ts +22 -14
  85. package/src/runs/shared/child-runtime-config.ts +3 -0
  86. package/src/runs/shared/child-session.ts +52 -2
  87. package/src/runs/shared/child-tool-plan.ts +23 -113
  88. package/src/runs/shared/dynamic-fanout.ts +1 -1
  89. package/src/runs/shared/external-cli-runner.ts +3 -1
  90. package/src/runs/shared/external-job-bridge.ts +54 -0
  91. package/src/runs/shared/git-environment.ts +29 -0
  92. package/src/runs/shared/mcp-config-sources.ts +3 -0
  93. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  94. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  95. package/src/runs/shared/model-resolution.ts +6 -1
  96. package/src/runs/shared/nested-events.ts +67 -55
  97. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  98. package/src/runs/shared/parallel-utils.ts +2 -1
  99. package/src/runs/shared/pi-spawn.ts +92 -6
  100. package/src/runs/shared/profile-launch-env.ts +10 -2
  101. package/src/runs/shared/single-output.ts +11 -2
  102. package/src/runs/shared/structured-output.ts +227 -7
  103. package/src/runs/shared/subagent-control.ts +2 -16
  104. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  105. package/src/runs/shared/tool-availability.ts +2 -2
  106. package/src/runs/shared/tool-budget.ts +21 -0
  107. package/src/runs/shared/usage-reconciliation.ts +73 -0
  108. package/src/runs/shared/worktree.ts +35 -8
  109. package/src/shared/child-session-name.ts +4 -2
  110. package/src/shared/fork-context.ts +11 -4
  111. package/src/shared/launch-contract.ts +1 -1
  112. package/src/shared/pruned-fork.ts +69 -56
  113. package/src/shared/types.ts +52 -16
  114. package/src/slash/delegation-adapters.ts +25 -1
  115. package/src/slash/prompt-template-bridge.ts +16 -1
  116. package/src/slash/prompt-workflows.ts +12 -1
  117. package/src/slash/slash-commands.ts +7 -241
  118. package/src/slash/subagent-cost.ts +313 -0
  119. package/src/slash/subagents-admin.ts +28 -29
  120. package/src/tui/fleet-status.ts +24 -2
  121. package/src/tui/fleet.ts +7 -4
  122. package/src/tui/render.ts +53 -19
  123. package/src/watchdog/diff-tool.ts +24 -3
  124. package/src/watchdog/permission-arbiter.ts +13 -15
  125. package/src/watchdog/register-child.ts +10 -2
  126. package/src/watchdog/review.ts +14 -14
  127. package/src/watchdog/runtime.ts +2 -1
  128. package/src/watchdog/turn-delta.ts +11 -5
  129. package/src/workflows/scripted-workflow.ts +109 -23
  130. package/src/workflows/workflow-child-summary.ts +4 -2
  131. package/src/workflows/workflow-settlement.ts +4 -1
  132. package/src/runs/shared/completion-evidence.ts +0 -89
  133. package/src/runs/shared/completion-guard.ts +0 -255
  134. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  135. package/src/runs/shared/task-intent.ts +0 -244
@@ -27,6 +27,7 @@ import { parseThinkingLevel, type ThinkingLevel } from "../shared/thinking-ceili
27
27
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
28
28
  import { validatePermissionProfileName } from "../shared/permission-profile.ts";
29
29
  import { assertJsonSchemaObject } from "../runs/shared/structured-output.ts";
30
+ import { normalizeCapabilityCeilingAllowedAgents } from "../runs/shared/capability-ceiling.ts";
30
31
 
31
32
  export type AgentScope = "user" | "project" | "both";
32
33
 
@@ -76,11 +77,11 @@ export interface BuiltinAgentOverrideBase {
76
77
  tools?: string[];
77
78
  excludeTools?: string[];
78
79
  allowNestedSubagents?: boolean;
80
+ allowedAgents?: string[];
79
81
  mcpDirectTools?: string[];
80
82
  extensions?: string[];
81
83
  subagentOnlyExtensions?: string[];
82
84
  mutationTools?: string[];
83
- completionGuard?: boolean;
84
85
  toolBudget?: ToolBudgetConfig;
85
86
  sandbox?: string;
86
87
  permissionProfile?: string;
@@ -108,10 +109,10 @@ interface BuiltinAgentOverrideConfig {
108
109
  tools?: string[] | false | "inherit";
109
110
  excludeTools?: string[] | false;
110
111
  allowNestedSubagents?: boolean;
112
+ allowedAgents?: string[] | false;
111
113
  extensions?: string[] | false;
112
114
  subagentOnlyExtensions?: string[] | false;
113
115
  mutationTools?: string[] | false;
114
- completionGuard?: boolean;
115
116
  toolBudget?: ToolBudgetConfig | false;
116
117
  sandbox?: string;
117
118
  permissionProfile?: string;
@@ -147,6 +148,7 @@ export interface AgentConfig {
147
148
  tools?: string[];
148
149
  excludeTools?: string[];
149
150
  allowNestedSubagents?: boolean;
151
+ allowedAgents?: string[];
150
152
  mcpDirectTools?: string[];
151
153
  model?: string;
152
154
  modelProvider?: string;
@@ -180,7 +182,6 @@ export interface AgentConfig {
180
182
  injectToContext?: boolean;
181
183
  interactive?: boolean;
182
184
  maxSubagentDepth?: number;
183
- completionGuard?: boolean;
184
185
  toolBudget?: ToolBudgetConfig;
185
186
  sandbox?: string;
186
187
  permissionProfile?: string;
@@ -212,6 +213,7 @@ interface SubagentSettings {
212
213
  defaultThinking?: string;
213
214
  maxThinking?: ThinkingLevel;
214
215
  defaultExtensions?: string[];
216
+ defaultSubagentOnlyExtensions?: string[];
215
217
  disableBuiltins?: boolean;
216
218
  disableThinking?: boolean;
217
219
  modelScope?: ModelScopeConfig;
@@ -516,7 +518,7 @@ function getGlobalNpmRoot(): string | null {
516
518
  }
517
519
 
518
520
  try {
519
- cachedGlobalNpmRoot = fs.realpathSync(execSync("npm root -g", { encoding: "utf-8", timeout: 5000, windowsHide: true }).trim());
521
+ cachedGlobalNpmRoot = fs.realpathSync(execSync("npm root -g", { encoding: "utf-8", timeout: 5000, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }).trim());
520
522
  return cachedGlobalNpmRoot;
521
523
  } catch {
522
524
  cachedGlobalNpmRoot = "";
@@ -626,7 +628,7 @@ function collectSettingsPackageRoots(settingsFile: string, baseDir: string): str
626
628
  return roots;
627
629
  }
628
630
 
629
- function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean } = { includeUser: true, includeProject: true }): PackageSubagentPaths {
631
+ function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean; globalNpmRoot?: string | null } = { includeUser: true, includeProject: true }): PackageSubagentPaths {
630
632
  const agentDir = getAgentDir();
631
633
  const projectRoot = findConfiguredProjectRoot(cwd) ?? cwd;
632
634
  const packageRoots: Array<{ root: string; scope: PackageScope }> = [
@@ -661,7 +663,7 @@ function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolea
661
663
  }
662
664
 
663
665
  if (options.includeUser) {
664
- const globalRoot = getGlobalNpmRoot();
666
+ const globalRoot = options.globalNpmRoot === undefined ? getGlobalNpmRoot() : options.globalNpmRoot;
665
667
  if (globalRoot) {
666
668
  packageRoots.push(...collectPackageRootsFromNodeModules(globalRoot, watchPaths).map((root) => ({ root, scope: "user" as const })));
667
669
  }
@@ -809,11 +811,11 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
809
811
  ...(agent.tools ? { tools: [...agent.tools] } : {}),
810
812
  ...(agent.excludeTools ? { excludeTools: [...agent.excludeTools] } : {}),
811
813
  ...(agent.allowNestedSubagents !== undefined ? { allowNestedSubagents: agent.allowNestedSubagents } : {}),
814
+ ...(agent.allowedAgents !== undefined ? { allowedAgents: [...agent.allowedAgents] } : {}),
812
815
  ...(agent.mcpDirectTools ? { mcpDirectTools: [...agent.mcpDirectTools] } : {}),
813
816
  ...(!agent.extensionsFromDefault && agent.extensions ? { extensions: [...agent.extensions] } : {}),
814
817
  ...(agent.subagentOnlyExtensions ? { subagentOnlyExtensions: [...agent.subagentOnlyExtensions] } : {}),
815
818
  ...(agent.mutationTools ? { mutationTools: [...agent.mutationTools] } : {}),
816
- ...(agent.completionGuard !== undefined ? { completionGuard: agent.completionGuard } : {}),
817
819
  ...(agent.toolBudget !== undefined ? { toolBudget: agent.toolBudget } : {}),
818
820
  ...(agent.sandbox !== undefined ? { sandbox: agent.sandbox } : {}),
819
821
  ...(agent.permissionProfile !== undefined ? { permissionProfile: agent.permissionProfile } : {}),
@@ -843,10 +845,10 @@ function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentO
843
845
  ...(override.tools !== undefined ? { tools: Array.isArray(override.tools) ? [...override.tools] : override.tools } : {}),
844
846
  ...(override.excludeTools !== undefined ? { excludeTools: override.excludeTools === false ? false : [...override.excludeTools] } : {}),
845
847
  ...(override.allowNestedSubagents !== undefined ? { allowNestedSubagents: override.allowNestedSubagents } : {}),
848
+ ...(override.allowedAgents !== undefined ? { allowedAgents: override.allowedAgents === false ? false : [...override.allowedAgents] } : {}),
846
849
  ...(override.extensions !== undefined ? { extensions: override.extensions === false ? false : [...override.extensions] } : {}),
847
850
  ...(override.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: override.subagentOnlyExtensions === false ? false : [...override.subagentOnlyExtensions] } : {}),
848
851
  ...(override.mutationTools !== undefined ? { mutationTools: override.mutationTools === false ? false : [...override.mutationTools] } : {}),
849
- ...(override.completionGuard !== undefined ? { completionGuard: override.completionGuard } : {}),
850
852
  ...(override.toolBudget !== undefined ? { toolBudget: override.toolBudget === false ? false : { ...override.toolBudget, ...(Array.isArray(override.toolBudget.block) ? { block: [...override.toolBudget.block] } : {}) } } : {}),
851
853
  ...(override.sandbox !== undefined ? { sandbox: override.sandbox } : {}),
852
854
  ...(override.permissionProfile !== undefined ? { permissionProfile: override.permissionProfile } : {}),
@@ -878,7 +880,7 @@ function findProjectRootCandidates(cwd: string): string[] {
878
880
  }
879
881
  }
880
882
 
881
- function findNearestGitRoot(cwd: string): string | null {
883
+ export function findNearestGitRoot(cwd: string): string | null {
882
884
  let currentDir = cwd;
883
885
  while (true) {
884
886
  if (fs.existsSync(path.join(currentDir, ".git"))) return currentDir;
@@ -1117,13 +1119,6 @@ function parseBuiltinOverrideEntry(
1117
1119
  }
1118
1120
  }
1119
1121
 
1120
- if ("completionGuard" in input) {
1121
- if (typeof input.completionGuard === "boolean") {
1122
- override.completionGuard = input.completionGuard;
1123
- } else {
1124
- throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'completionGuard'; expected a boolean.`);
1125
- }
1126
- }
1127
1122
 
1128
1123
  if ("toolBudget" in input) {
1129
1124
  if (input.toolBudget === false) {
@@ -1175,6 +1170,8 @@ function parseBuiltinOverrideEntry(
1175
1170
  if (typeof input.allowNestedSubagents === "boolean") override.allowNestedSubagents = input.allowNestedSubagents;
1176
1171
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'allowNestedSubagents'; expected a boolean.`);
1177
1172
  }
1173
+ const allowedAgents = parseOverrideStringArrayOrFalse(input.allowedAgents, { filePath, name, field: "allowedAgents" });
1174
+ if (allowedAgents !== undefined) override.allowedAgents = allowedAgents === false ? false : normalizeCapabilityCeilingAllowedAgents(allowedAgents);
1178
1175
 
1179
1176
  const extensions = parseOverrideStringArrayOrFalse(input.extensions, { filePath, name, field: "extensions" });
1180
1177
  if (extensions !== undefined) override.extensions = extensions;
@@ -1259,6 +1256,14 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
1259
1256
  }
1260
1257
  injectAgents = subagentsObject.injectAgents.map((item) => item.trim());
1261
1258
  }
1259
+ let defaultSubagentOnlyExtensions: string[] | undefined;
1260
+ if ("defaultSubagentOnlyExtensions" in subagentsObject) {
1261
+ if (!Array.isArray(subagentsObject.defaultSubagentOnlyExtensions)
1262
+ || subagentsObject.defaultSubagentOnlyExtensions.some((item) => typeof item !== "string" || !item.trim())) {
1263
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'defaultSubagentOnlyExtensions'; expected an array of non-empty strings.`);
1264
+ }
1265
+ defaultSubagentOnlyExtensions = subagentsObject.defaultSubagentOnlyExtensions.map((item) => item.trim());
1266
+ }
1262
1267
  let agentScanDirs: string[] | undefined;
1263
1268
  if ("agentScanDirs" in subagentsObject) {
1264
1269
  if (!Array.isArray(subagentsObject.agentScanDirs)
@@ -1289,6 +1294,7 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
1289
1294
  ...(defaultThinking !== undefined ? { defaultThinking } : {}),
1290
1295
  ...(maxThinking !== undefined ? { maxThinking } : {}),
1291
1296
  ...(defaultExtensions !== undefined ? { defaultExtensions } : {}),
1297
+ ...(defaultSubagentOnlyExtensions !== undefined ? { defaultSubagentOnlyExtensions } : {}),
1292
1298
  ...(agentScanDirs !== undefined ? { agentScanDirs } : {}),
1293
1299
  ...(agentExcludeDirs !== undefined ? { agentExcludeDirs } : {}),
1294
1300
  ...(disableBuiltins !== undefined ? { disableBuiltins } : {}),
@@ -1425,16 +1431,40 @@ function applySubagentDefaultExtensions(agents: AgentConfig[], defaultExtensions
1425
1431
  });
1426
1432
  }
1427
1433
 
1434
+ function resolveSubagentDefaultSubagentOnlyExtensions(
1435
+ userSettings: SubagentSettings,
1436
+ projectSettings: SubagentSettings,
1437
+ projectSettingsPath: string | null,
1438
+ ): string[] | undefined {
1439
+ if (projectSettingsPath && projectSettings.defaultSubagentOnlyExtensions !== undefined) return projectSettings.defaultSubagentOnlyExtensions;
1440
+ return userSettings.defaultSubagentOnlyExtensions;
1441
+ }
1442
+
1443
+ function applySubagentDefaultSubagentOnlyExtensions(agents: AgentConfig[], defaultSubagentOnlyExtensions: string[] | undefined): AgentConfig[] {
1444
+ if (defaultSubagentOnlyExtensions === undefined) return agents;
1445
+ return agents.map((agent) => {
1446
+ if (agent.subagentOnlyExtensions !== undefined) return agent;
1447
+ const next = { ...agent, subagentOnlyExtensions: [...defaultSubagentOnlyExtensions] };
1448
+ const frontmatterFields = agentFrontmatterFields.get(agent);
1449
+ if (frontmatterFields) agentFrontmatterFields.set(next, frontmatterFields);
1450
+ return next;
1451
+ });
1452
+ }
1453
+
1428
1454
  function applySubagentDefaults(
1429
1455
  agents: AgentConfig[],
1430
1456
  defaultModel: AgentModelSourceInfo | undefined,
1431
1457
  defaultProvider: string | undefined,
1432
1458
  defaultThinking: string | undefined,
1433
1459
  defaultExtensions: string[] | undefined,
1460
+ defaultSubagentOnlyExtensions: string[] | undefined,
1434
1461
  ): AgentConfig[] {
1435
- return applySubagentDefaultExtensions(
1436
- applySubagentDefaultThinking(applySubagentDefaultModel(agents, defaultModel, defaultProvider), defaultThinking),
1437
- defaultExtensions,
1462
+ return applySubagentDefaultSubagentOnlyExtensions(
1463
+ applySubagentDefaultExtensions(
1464
+ applySubagentDefaultThinking(applySubagentDefaultModel(agents, defaultModel, defaultProvider), defaultThinking),
1465
+ defaultExtensions,
1466
+ ),
1467
+ defaultSubagentOnlyExtensions,
1438
1468
  );
1439
1469
  }
1440
1470
 
@@ -1496,10 +1526,10 @@ function applyBuiltinOverride(
1496
1526
  if (override.tools !== undefined) applyToolsOverride(next, override.tools);
1497
1527
  if (override.excludeTools !== undefined) { if (override.excludeTools === false) delete next.excludeTools; else next.excludeTools = [...override.excludeTools]; }
1498
1528
  if (override.allowNestedSubagents !== undefined) next.allowNestedSubagents = override.allowNestedSubagents;
1529
+ if (override.allowedAgents !== undefined) { if (override.allowedAgents === false) delete next.allowedAgents; else next.allowedAgents = [...override.allowedAgents]; }
1499
1530
  if (override.extensions !== undefined) { if (override.extensions === false) delete next.extensions; else next.extensions = [...override.extensions]; }
1500
1531
  if (override.subagentOnlyExtensions !== undefined) { if (override.subagentOnlyExtensions === false) delete next.subagentOnlyExtensions; else next.subagentOnlyExtensions = [...override.subagentOnlyExtensions]; }
1501
1532
  if (override.mutationTools !== undefined) { if (override.mutationTools === false) delete next.mutationTools; else next.mutationTools = [...override.mutationTools]; }
1502
- if (override.completionGuard !== undefined) next.completionGuard = override.completionGuard;
1503
1533
  if (override.toolBudget !== undefined) { if (override.toolBudget === false) delete next.toolBudget; else next.toolBudget = override.toolBudget; }
1504
1534
  if (override.sandbox !== undefined) next.sandbox = override.sandbox;
1505
1535
  if (override.permissionProfile !== undefined) next.permissionProfile = override.permissionProfile;
@@ -1602,9 +1632,48 @@ function applyCustomAgentOverrides(
1602
1632
  });
1603
1633
  }
1604
1634
 
1635
+ export interface RuntimeAgentSettingsContext {
1636
+ cwd: string;
1637
+ scope: AgentScope;
1638
+ preferredModelProvider?: string;
1639
+ }
1640
+
1641
+ function runtimeAgentOverrides(settings: SubagentSettings): SubagentSettings {
1642
+ const overrides: Record<string, BuiltinAgentOverrideConfig> = {};
1643
+ for (const [name, override] of Object.entries(settings.overrides)) {
1644
+ const narrowed: BuiltinAgentOverrideConfig = {};
1645
+ if (override.model !== undefined) narrowed.model = override.model;
1646
+ if (override.defaultProvider !== undefined) narrowed.defaultProvider = override.defaultProvider;
1647
+ if (override.fast !== undefined) narrowed.fast = override.fast;
1648
+ if (override.thinking !== undefined) narrowed.thinking = override.thinking;
1649
+ if (Object.keys(narrowed).length > 0) overrides[name] = narrowed;
1650
+ }
1651
+ return { ...settings, overrides };
1652
+ }
1653
+
1654
+ /**
1655
+ * Runtime-registered agents keep their extension-owned definition (prompt,
1656
+ * tools, context, budgets, and every other launch field) but follow the same
1657
+ * model-tier settings as every other agent: `subagents.defaultModel`,
1658
+ * `defaultProvider`, `defaultThinking`, and the `model`, `defaultProvider`,
1659
+ * `fast`, and `thinking` fields of `agentOverrides.<name>`, user then project,
1660
+ * provider-scoped overrides included. Other override fields are ignored for
1661
+ * runtime agents. A definition `model` still wins over `defaultModel`.
1662
+ */
1663
+ export function applyRuntimeAgentSettings(agents: AgentConfig[], context: RuntimeAgentSettingsContext): AgentConfig[] {
1664
+ if (agents.length === 0) return agents;
1665
+ const sources = getAgentDiscoverySources(context.cwd, context.preferredModelProvider);
1666
+ const { user, project } = settingsForScope(sources, context.scope);
1667
+ const defaultProvider = resolveSubagentDefaultProvider(user, project, sources.projectSettingsPath);
1668
+ const defaultModel = resolveSubagentDefaultModel(user, project, sources.userSettingsPath, sources.projectSettingsPath, defaultProvider);
1669
+ const defaultThinking = resolveSubagentDefaultThinking(user, project, sources.projectSettingsPath);
1670
+ const withDefaults = applySubagentDefaultThinking(applySubagentDefaultModel(agents, defaultModel, defaultProvider), defaultThinking);
1671
+ return applyCustomAgentOverrides(withDefaults, runtimeAgentOverrides(user), runtimeAgentOverrides(project), sources.userSettingsPath, sources.projectSettingsPath);
1672
+ }
1673
+
1605
1674
  export function buildBuiltinOverrideConfig(
1606
1675
  base: BuiltinAgentOverrideBase,
1607
- draft: Pick<AgentConfig, "model" | "modelProvider" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "allowNestedSubagents" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "mutationTools" | "completionGuard" | "toolBudget" | "sandbox" | "permissionProfile"> & Partial<Pick<AgentConfig, "description" | "machine" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
1676
+ draft: Pick<AgentConfig, "model" | "modelProvider" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "allowNestedSubagents" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "mutationTools" | "toolBudget" | "sandbox" | "permissionProfile"> & Partial<Pick<AgentConfig, "description" | "machine" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
1608
1677
  ): BuiltinAgentOverrideConfig | undefined {
1609
1678
  const override: BuiltinAgentOverrideConfig = {};
1610
1679
  if (draft.machine !== base.machine) override.machine = draft.machine ?? false;
@@ -1640,9 +1709,6 @@ export function buildBuiltinOverrideConfig(
1640
1709
  override.subagentOnlyExtensions = draft.subagentOnlyExtensions ? [...draft.subagentOnlyExtensions] : false;
1641
1710
  }
1642
1711
  if (!arraysEqual(draft.mutationTools, base.mutationTools)) override.mutationTools = draft.mutationTools ? [...draft.mutationTools] : false;
1643
- if ((draft.completionGuard !== false) !== (base.completionGuard !== false)) {
1644
- override.completionGuard = draft.completionGuard !== false;
1645
- }
1646
1712
  if (JSON.stringify(draft.toolBudget) !== JSON.stringify(base.toolBudget)) override.toolBudget = draft.toolBudget ?? false;
1647
1713
  if (draft.sandbox !== undefined && draft.sandbox !== base.sandbox) override.sandbox = draft.sandbox;
1648
1714
  if (draft.permissionProfile !== undefined && draft.permissionProfile !== base.permissionProfile) override.permissionProfile = draft.permissionProfile;
@@ -2006,7 +2072,7 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
2006
2072
 
2007
2073
  function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
2008
2074
  if (runner?.type !== "external-cli" && runner?.type !== "external-job") return;
2009
- const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission-profile", "permission", "permissions"]
2075
+ const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "allowedAgents", "model", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission-profile", "permission", "permissions"]
2010
2076
  .filter((field) => frontmatter[field] !== undefined);
2011
2077
  if (unsupported.length > 0) {
2012
2078
  throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
@@ -2095,6 +2161,8 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2095
2161
  const tools = parsedTools.tools ?? [];
2096
2162
  const mcpDirectTools = parsedTools.mcpDirectTools ?? [];
2097
2163
  const excludeTools = parseFrontmatterList(frontmatter.excludeTools);
2164
+ const parsedAllowedAgents = parseFrontmatterList(frontmatter.allowedAgents);
2165
+ const allowedAgents = parsedAllowedAgents === undefined ? undefined : normalizeCapabilityCeilingAllowedAgents(parsedAllowedAgents);
2098
2166
  const defaultReads = parseFrontmatterList(frontmatter.defaultReads);
2099
2167
  const aliases = normalizeAgentAliases(parseFrontmatterList(frontmatter.aliases ?? frontmatter.alias), runtimeName);
2100
2168
  const profileError = validateCodeOwnedProfileRunner({ name: runtimeName, localName, aliases, runner });
@@ -2207,11 +2275,6 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2207
2275
  assertJsonSchemaObject(parsed, `Agent '${localName}' outputSchema`);
2208
2276
  outputSchema = parsed;
2209
2277
  }
2210
- const completionGuard = frontmatter.completionGuard === "false"
2211
- ? false
2212
- : frontmatter.completionGuard === "true"
2213
- ? true
2214
- : undefined;
2215
2278
 
2216
2279
  const maxSubagentDepth = Number.isInteger(parsedMaxSubagentDepth) && parsedMaxSubagentDepth >= 0
2217
2280
  ? parsedMaxSubagentDepth
@@ -2232,6 +2295,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2232
2295
  ...(rawTools !== undefined ? { tools } : {}),
2233
2296
  ...(excludeTools !== undefined ? { excludeTools } : {}),
2234
2297
  ...(allowNestedSubagents !== undefined ? { allowNestedSubagents } : {}),
2298
+ ...(allowedAgents !== undefined ? { allowedAgents } : {}),
2235
2299
  ...(mcpDirectTools.length > 0 ? { mcpDirectTools } : {}),
2236
2300
  ...(frontmatter.model !== undefined ? { model: frontmatter.model } : {}),
2237
2301
  ...(fast !== undefined ? { fast } : {}),
@@ -2264,7 +2328,6 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2264
2328
  injectToContext: frontmatter.injectToContext === "true",
2265
2329
  interactive: frontmatter.interactive === "true",
2266
2330
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
2267
- ...(completionGuard !== undefined ? { completionGuard } : {}),
2268
2331
  ...(toolBudget !== undefined ? { toolBudget } : {}),
2269
2332
  ...(sandbox !== undefined ? { sandbox } : {}),
2270
2333
  ...(permissionProfile !== undefined ? { permissionProfile } : {}),
@@ -2465,6 +2528,7 @@ export interface AgentDiscoveryAllResult {
2465
2528
  package: AgentConfig[];
2466
2529
  user: AgentConfig[];
2467
2530
  project: AgentConfig[];
2531
+ cwd: string;
2468
2532
  agentDiagnostics?: AgentDiscoveryDiagnostic[];
2469
2533
  injectAgents?: string[];
2470
2534
  chains: ChainConfig[];
@@ -2489,6 +2553,11 @@ export interface AgentDiscoverySnapshot {
2489
2553
  all: AgentDiscoveryAllResult;
2490
2554
  }
2491
2555
 
2556
+ /** Undefined uses synchronous npm lookup; null skips global npm discovery. */
2557
+ export interface AgentDiscoveryOptions {
2558
+ globalNpmRoot?: string | null;
2559
+ }
2560
+
2492
2561
  interface LoadedAgentDirectory {
2493
2562
  dir: string;
2494
2563
  inspection: AgentDefinitionInspection;
@@ -2591,10 +2660,11 @@ function discoveryFingerprint(sources: AgentDiscoverySources): string {
2591
2660
  .join("\n");
2592
2661
  }
2593
2662
 
2594
- function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined): string {
2663
+ function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined, globalNpmRoot?: string | null): string {
2595
2664
  return JSON.stringify([
2596
2665
  path.resolve(cwd),
2597
2666
  preferredModelProvider ?? null,
2667
+ globalNpmRoot === undefined ? ["default"] : ["override", globalNpmRoot],
2598
2668
  getProjectConfigDir(path.resolve(cwd)),
2599
2669
  getAgentDir(),
2600
2670
  os.homedir(),
@@ -2623,7 +2693,7 @@ function packageEntryIncluded(scope: AgentScope, packageScopes: PackageSubagentP
2623
2693
  return packageScopes.has(scope);
2624
2694
  }
2625
2695
 
2626
- function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string): AgentDiscoverySources {
2696
+ function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string, globalNpmRoot?: string | null): AgentDiscoverySources {
2627
2697
  const effectiveCwd = path.resolve(cwd);
2628
2698
  const userDirOld = path.join(getAgentDir(), "agents");
2629
2699
  const userDirNew = path.join(os.homedir(), ".agents");
@@ -2632,7 +2702,7 @@ function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string
2632
2702
  const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(effectiveCwd);
2633
2703
  const userSettingsPath = getUserAgentSettingsPath();
2634
2704
  const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
2635
- const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd);
2705
+ const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: true, includeProject: true, globalNpmRoot });
2636
2706
  const exclusionRoots = agentExclusionRoots(userSettingsPath, projectSettingsPath);
2637
2707
  const isExcluded = agentExclusions(exclusionRoots);
2638
2708
  const userScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(userSettingsPath), isExcluded);
@@ -2718,8 +2788,8 @@ function ensureDiscoveryChains(sources: AgentDiscoverySources): void {
2718
2788
  sources.watchPaths = [...new Set([...sources.watchPaths, ...watchPaths])];
2719
2789
  }
2720
2790
 
2721
- function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false): AgentDiscoverySources {
2722
- const key = discoveryCacheKey(cwd, preferredModelProvider);
2791
+ function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false, globalNpmRoot?: string | null): AgentDiscoverySources {
2792
+ const key = discoveryCacheKey(cwd, preferredModelProvider, globalNpmRoot);
2723
2793
  const cached = agentDiscoveryCache.get(key);
2724
2794
  if (cached && cached.fingerprint === discoveryFingerprint(cached.sources)) {
2725
2795
  if (includeChains) {
@@ -2728,7 +2798,7 @@ function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string,
2728
2798
  }
2729
2799
  return cached.sources;
2730
2800
  }
2731
- const sources = buildAgentDiscoverySources(cwd, preferredModelProvider);
2801
+ const sources = buildAgentDiscoverySources(cwd, preferredModelProvider, globalNpmRoot);
2732
2802
  const entry = { sources, fingerprint: discoveryFingerprint(sources) };
2733
2803
  agentDiscoveryCache.set(key, entry);
2734
2804
  if (includeChains) {
@@ -2781,7 +2851,8 @@ function configuredAgentsForScope(sources: AgentDiscoverySources, scope: AgentSc
2781
2851
  const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, sources.projectSettingsPath);
2782
2852
  const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, sources.projectSettingsPath);
2783
2853
  const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, sources.projectSettingsPath);
2784
- const applyDefaults = (agents: AgentConfig[]): AgentConfig[] => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions);
2854
+ const defaultSubagentOnlyExtensions = resolveSubagentDefaultSubagentOnlyExtensions(userSettings, projectSettings, sources.projectSettingsPath);
2855
+ const applyDefaults = (agents: AgentConfig[]): AgentConfig[] => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions, defaultSubagentOnlyExtensions);
2785
2856
  const builtin = applyBuiltinOverrides(applyDefaults(sources.builtinLoaded.agents), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
2786
2857
  const user = applyCustomAgentOverrides(
2787
2858
  applyDefaults(scope === "project" ? [] : sources.userLoaded.flatMap((loaded) => loaded.loaded.agents)),
@@ -2901,6 +2972,7 @@ function buildAllDiscovery(sources: AgentDiscoverySources, includeChains: boolea
2901
2972
  ],
2902
2973
  chains,
2903
2974
  chainDiagnostics: [...packageChainDiagnostics, ...(sources.userChains?.diagnostics ?? []), ...projectChainDiagnostics],
2975
+ cwd: sources.cwd,
2904
2976
  userDir: sources.userDir,
2905
2977
  projectDir: sources.projectAgentsDir,
2906
2978
  userChainDir: sources.userChainDir,
@@ -2916,14 +2988,14 @@ export function discoverAgentSnapshot(
2916
2988
  cwd: string,
2917
2989
  scope: AgentScope,
2918
2990
  preferredModelProvider?: string,
2919
- options: { includeChains?: boolean } = {},
2991
+ options: AgentDiscoveryOptions & { includeChains?: boolean } = {},
2920
2992
  ): AgentDiscoverySnapshot {
2921
2993
  const includeChains = options.includeChains !== false;
2922
- const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains);
2994
+ const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains, options.globalNpmRoot);
2923
2995
  return { effective: buildEffectiveDiscovery(sources, scope), all: buildAllDiscovery(sources, includeChains, scope) };
2924
2996
  }
2925
2997
 
2926
- function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelProvider?: string): AgentDiscoveryResult {
2998
+ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryResult {
2927
2999
  const effectiveCwd = path.resolve(cwd);
2928
3000
  const userDirOld = path.join(getAgentDir(), "agents");
2929
3001
  const userDirNew = path.join(os.homedir(), ".agents");
@@ -2937,15 +3009,17 @@ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelPr
2937
3009
  const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
2938
3010
  const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, projectSettingsPath);
2939
3011
  const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
3012
+ const defaultSubagentOnlyExtensions = resolveSubagentDefaultSubagentOnlyExtensions(userSettings, projectSettings, projectSettingsPath);
2940
3013
  const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
2941
3014
  const injectAgents = projectSettings.injectAgents !== undefined
2942
3015
  ? projectSettings.injectAgents
2943
3016
  : userSettings.injectAgents;
2944
- const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: scope !== "project", includeProject: scope !== "user" });
3017
+ const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: scope !== "project", includeProject: scope !== "user", globalNpmRoot: options.globalNpmRoot });
2945
3018
  const isExcluded = agentExclusions(agentExclusionRoots(userSettingsPath, projectSettingsPath));
2946
3019
  const directories: AgentDefinitionDirectoryReport[] = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
2947
3020
  const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
2948
- const builtinAgents = applyBuiltinOverrides(applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
3021
+ const applyDefaults = (agents: AgentConfig[]): AgentConfig[] => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions, defaultSubagentOnlyExtensions);
3022
+ const builtinAgents = applyBuiltinOverrides(applyDefaults(builtinLoaded.agents), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2949
3023
  const userScanDirs = settingsAgentScanDirs(userSettings.agentScanDirs ?? [], isExcluded);
2950
3024
  const projectScanDirs = settingsAgentScanDirs(projectSettings.agentScanDirs ?? [], isExcluded);
2951
3025
  const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].filter((dir) => !isExcluded(dir)).map((dir, discoveryPriority) => {
@@ -2953,7 +3027,7 @@ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelPr
2953
3027
  directories.push(reportAgentDefinitionDirectory("user", dir, inspection));
2954
3028
  return loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection);
2955
3029
  });
2956
- const userAgents = applyCustomAgentOverrides(applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
3030
+ const userAgents = applyCustomAgentOverrides(applyDefaults(userLoaded.flatMap((loaded) => loaded.agents)), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2957
3031
  const projectInspections = scope === "user" ? new Map<string, AgentDefinitionInspection>() : new Map(projectCandidateDirs.filter((dir) => !isExcluded(dir)).map((dir) => [dir, inspectAgentDefinitionDirectory(dir, undefined, isExcluded)]));
2958
3032
  if (scope !== "user") for (const [dir, inspection] of projectInspections) directories.push(reportAgentDefinitionDirectory("project", dir, inspection));
2959
3033
  const projectLoaded = scope === "user" ? [] : [...projectScanDirs.dirs, ...projectAgentDirs].filter((dir) => !isExcluded(dir)).map((dir, discoveryPriority) => {
@@ -2961,7 +3035,7 @@ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelPr
2961
3035
  if (!projectInspections.has(dir)) directories.push(reportAgentDefinitionDirectory("project", dir, inspection));
2962
3036
  return loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection);
2963
3037
  });
2964
- const projectAgents = applyCustomAgentOverrides(applySubagentDefaults(projectLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
3038
+ const projectAgents = applyCustomAgentOverrides(applyDefaults(projectLoaded.flatMap((loaded) => loaded.agents)), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2965
3039
  const packageLoaded = packageSubagentPaths.agents.filter((entry) => !isExcluded(entry.dir)).map((entry, index) => {
2966
3040
  const inspection = inspectAgentDefinitionDirectory(entry.dir, undefined, isExcluded);
2967
3041
  directories.push(reportAgentDefinitionDirectory("package", entry.dir, inspection));
@@ -2969,18 +3043,18 @@ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelPr
2969
3043
  });
2970
3044
  const packageMap = new Map<string, AgentConfig>();
2971
3045
  for (const loaded of packageLoaded) for (const agent of loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
2972
- const packageAgents = applyCustomAgentOverrides(applySubagentDefaults(Array.from(packageMap.values()), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
3046
+ const packageAgents = applyCustomAgentOverrides(applyDefaults(Array.from(packageMap.values())), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2973
3047
  const agents = applySubagentMaxThinking(mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents).filter((agent) => agent.disabled !== true), maxThinking);
2974
3048
  const agentDiagnostics = [...builtinLoaded.diagnostics, ...userLoaded.flatMap((loaded) => loaded.diagnostics), ...projectLoaded.flatMap((loaded) => loaded.diagnostics), ...packageLoaded.flatMap((loaded) => loaded.diagnostics)];
2975
3049
  return { agents, agentDiagnostics, projectAgentsDir, cwd: effectiveCwd, scope, directories, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}), ...(maxThinking !== undefined ? { maxThinking } : {}) };
2976
3050
  }
2977
3051
 
2978
- export function discoverAgents(cwd: string, scope: AgentScope, preferredModelProvider?: string): AgentDiscoveryResult {
2979
- if (scope !== "both") return discoverAgentsUncached(cwd, scope, preferredModelProvider);
2980
- const sources = getAgentDiscoverySources(cwd, preferredModelProvider);
3052
+ export function discoverAgents(cwd: string, scope: AgentScope, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryResult {
3053
+ if (scope !== "both") return discoverAgentsUncached(cwd, scope, preferredModelProvider, options);
3054
+ const sources = getAgentDiscoverySources(cwd, preferredModelProvider, false, options.globalNpmRoot);
2981
3055
  return buildEffectiveDiscovery(sources, scope);
2982
3056
  }
2983
3057
 
2984
- export function discoverAgentsAll(cwd: string, preferredModelProvider?: string): AgentDiscoveryAllResult {
2985
- return discoverAgentSnapshot(cwd, "both", preferredModelProvider).all;
3058
+ export function discoverAgentsAll(cwd: string, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryAllResult {
3059
+ return discoverAgentSnapshot(cwd, "both", preferredModelProvider, options).all;
2986
3060
  }
@@ -0,0 +1,58 @@
1
+ import { exec, execFile } from "node:child_process";
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ /** Optional global package discovery; a failure never prevents local discovery. */
6
+ export async function resolveGlobalNpmRoot(options: {
7
+ env?: NodeJS.ProcessEnv;
8
+ platform?: NodeJS.Platform;
9
+ timeoutMs?: number;
10
+ } = {}): Promise<string | null> {
11
+ const env = options.env ?? process.env;
12
+ const offline = env.PI_OFFLINE?.toLowerCase();
13
+ if (offline === "1" || offline === "true" || offline === "yes") return null;
14
+
15
+ if ((options.platform ?? process.platform) === "win32" && env.APPDATA) {
16
+ const appDataRoot = path.join(env.APPDATA, "npm", "node_modules");
17
+ try {
18
+ if ((await fs.stat(appDataRoot)).isDirectory()) return await fs.realpath(appDataRoot);
19
+ } catch {
20
+ // Invalid APPDATA roots fall back to npm (including disappearing directories).
21
+ }
22
+ }
23
+
24
+ const timeoutMs = options.timeoutMs ?? 5000;
25
+ const output = await new Promise<string | null>((resolve) => {
26
+ let settled = false;
27
+ const finish = (value: string | null) => {
28
+ if (settled) return;
29
+ settled = true;
30
+ clearTimeout(timer);
31
+ resolve(value);
32
+ };
33
+ const commandOptions = {
34
+ encoding: "utf8",
35
+ timeout: timeoutMs,
36
+ windowsHide: true,
37
+ env,
38
+ maxBuffer: 64 * 1024,
39
+ } as const;
40
+ // POSIX npm is executable directly: killing a shell would leave npm running.
41
+ // Windows npm.cmd requires a shell, matching the existing command behavior.
42
+ const callback = (error: Error | null, stdout: string) => finish(error ? null : stdout.trim());
43
+ const child = (options.platform ?? process.platform) === "win32"
44
+ ? exec("npm root -g", commandOptions, callback)
45
+ : execFile("npm", ["root", "-g"], commandOptions, callback);
46
+ // Resolve at the deadline even if inherited pipes hold the callback open.
47
+ const timer = setTimeout(() => {
48
+ child.kill();
49
+ finish(null);
50
+ }, timeoutMs);
51
+ });
52
+ if (!output) return null;
53
+ try {
54
+ return await fs.realpath(output);
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
@@ -27,6 +27,7 @@ export interface ProactiveSkillSubagentRecommendation {
27
27
  export interface AvailableSkill {
28
28
  name: string;
29
29
  description?: string;
30
+ disableModelInvocation?: boolean;
30
31
  }
31
32
 
32
33
  function positiveInteger(value: unknown): number | undefined {
@@ -140,7 +141,9 @@ export function recommendProactiveSkillSubagents(input: {
140
141
  }
141
142
 
142
143
  return [...counts.entries()]
143
- .filter(([skill, sources]) => sources.size >= config.minReferences && (!availableByName || availableByName.has(skill)))
144
+ // Hidden skills (disable-model-invocation: true) are user-only and must
145
+ // never surface in model-facing proactive recommendations.
146
+ .filter(([skill, sources]) => sources.size >= config.minReferences && (!availableByName || availableByName.has(skill)) && availableByName?.get(skill)?.disableModelInvocation !== true)
144
147
  .map(([skill, sources]) => {
145
148
  const description = availableByName?.get(skill)?.description;
146
149
  return {
@@ -5,7 +5,7 @@ import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
5
5
  import { validatePermissionRules, type PermissionRules } from "../runs/shared/permissions.ts";
6
6
  import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
7
7
  import { BUILTIN_AGENT_NAMES } from "./builtin-names.ts";
8
- import type { AgentConfig, AgentDefaultContext, AgentDiscoveryDiagnostic } from "./agents.ts";
8
+ import { applyRuntimeAgentSettings, type AgentConfig, type AgentDefaultContext, type AgentDiscoveryDiagnostic, type RuntimeAgentSettingsContext } from "./agents.ts";
9
9
  import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
10
10
  import { validatePermissionProfileName } from "../shared/permission-profile.ts";
11
11
 
@@ -51,7 +51,6 @@ export interface RuntimeAgentDefinition {
51
51
  injectToContext?: boolean;
52
52
  interactive?: boolean;
53
53
  maxSubagentDepth?: number;
54
- completionGuard?: boolean;
55
54
  toolBudget?: ToolBudgetConfig;
56
55
  sandbox?: string;
57
56
  permissionProfile?: string;
@@ -208,7 +207,7 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
208
207
  "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "defaultContext", "defaultAsync", "defaultTimeoutMs",
209
208
  "defaultToolTimeoutMs", "defaultAcceptance", "acceptanceRole", "runner", "machine", "skills", "skillPath",
210
209
  "extensions", "subagentOnlyExtensions", "mutationTools", "output", "outputMode", "defaultReads", "defaultProgress", "injectToContext", "interactive",
211
- "maxSubagentDepth", "completionGuard", "toolBudget", "sandbox", "permissionProfile", "permissions",
210
+ "maxSubagentDepth", "toolBudget", "sandbox", "permissionProfile", "permissions",
212
211
  ]);
213
212
  const unknown = Object.keys(definition).filter((key) => !supported.has(key));
214
213
  if (unknown.length > 0) throw new Error(`Runtime agent definition has unknown fields: ${unknown.join(", ")}.`);
@@ -249,7 +248,6 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
249
248
  const injectToContext = validateBoolean(definition.injectToContext, "Runtime agent definition injectToContext");
250
249
  const interactive = validateBoolean(definition.interactive, "Runtime agent definition interactive");
251
250
  const maxSubagentDepth = validatePositiveInteger(definition.maxSubagentDepth, "Runtime agent definition maxSubagentDepth");
252
- const completionGuard = validateBoolean(definition.completionGuard, "Runtime agent definition completionGuard");
253
251
  const toolBudget = validateToolBudget(definition.toolBudget);
254
252
  const sandbox = definition.sandbox === undefined
255
253
  ? undefined
@@ -298,7 +296,6 @@ function validateDefinition(value: unknown): RuntimeAgentDefinition {
298
296
  ...(injectToContext !== undefined ? { injectToContext } : {}),
299
297
  ...(interactive !== undefined ? { interactive } : {}),
300
298
  ...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
301
- ...(completionGuard !== undefined ? { completionGuard } : {}),
302
299
  ...(toolBudget !== undefined ? { toolBudget } : {}),
303
300
  ...(sandbox !== undefined ? { sandbox } : {}),
304
301
  ...(permissionProfile !== undefined ? { permissionProfile } : {}),
@@ -383,7 +380,6 @@ function toAgentConfig(name: string, definition: RuntimeAgentDefinition): AgentC
383
380
  ...(definition.injectToContext !== undefined ? { injectToContext: definition.injectToContext } : {}),
384
381
  ...(definition.interactive !== undefined ? { interactive: definition.interactive } : {}),
385
382
  ...(definition.maxSubagentDepth !== undefined ? { maxSubagentDepth: definition.maxSubagentDepth } : {}),
386
- ...(definition.completionGuard !== undefined ? { completionGuard: definition.completionGuard } : {}),
387
383
  ...(definition.toolBudget !== undefined ? { toolBudget: definition.toolBudget } : {}),
388
384
  ...(definition.sandbox !== undefined ? { sandbox: definition.sandbox } : {}),
389
385
  ...(definition.permissionProfile !== undefined ? { permissionProfile: definition.permissionProfile } : {}),
@@ -445,10 +441,17 @@ function assertNoConfiguredCollision(configuredAgents: readonly AgentConfig[], r
445
441
  }
446
442
  }
447
443
 
448
- export function mergeRuntimeAgents<T extends { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[] }>(pi: RuntimeAgentOwner, discovered: T, configuredAgents: readonly AgentConfig[] = discovered.agents): T {
449
- const runtimeAgents = listRuntimeAgentConfigs(pi).filter((agent) => agent.disabled !== true);
450
- if (runtimeAgents.length === 0) return discovered;
451
- assertNoIdentityCollisions(runtimeAgents, "Runtime agent registration");
452
- assertNoConfiguredCollision(configuredAgents, runtimeAgents);
444
+ /**
445
+ * Append registered runtime agents to a discovery result. With `settings`, the
446
+ * runtime agents also receive the subagent model-tier settings that apply in
447
+ * that discovery context (see `applyRuntimeAgentSettings`); without it they
448
+ * carry only their registered definition.
449
+ */
450
+ export function mergeRuntimeAgents<T extends { agents: AgentConfig[]; agentDiagnostics?: AgentDiscoveryDiagnostic[] }>(pi: RuntimeAgentOwner, discovered: T, configuredAgents: readonly AgentConfig[] = discovered.agents, settings?: RuntimeAgentSettingsContext): T {
451
+ const registered = listRuntimeAgentConfigs(pi).filter((agent) => agent.disabled !== true);
452
+ if (registered.length === 0) return discovered;
453
+ assertNoIdentityCollisions(registered, "Runtime agent registration");
454
+ assertNoConfiguredCollision(configuredAgents, registered);
455
+ const runtimeAgents = settings ? applyRuntimeAgentSettings(registered, settings) : registered;
453
456
  return { ...discovered, agents: [...discovered.agents, ...runtimeAgents] };
454
457
  }