@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -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 +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  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 +29 -8
  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-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -8,13 +8,18 @@ import { parse as parseYaml } from "yaml";
8
8
  import * as os from "node:os";
9
9
  import * as path from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
- import type { AcceptanceInput, AcceptanceRole, AgentRunnerConfig, JsonSchemaObject, OutputMode, ToolBudgetConfig } from "../shared/types.ts";
11
+ import { createAtomicJsonWriter } from "../shared/atomic-json.ts";
12
+ import { resolveSettingsWriteTarget, withSettingsFileLease } from "../shared/settings-file-lease.ts";
13
+ import { RUNNER_LAUNCHER_NAME_PATTERN, RUNNER_LAUNCHER_NAME_RULE, type AcceptanceInput, type AcceptanceRole, type AgentRunnerConfig, type JsonSchemaObject, type OutputMode, type ToolBudgetConfig } from "../shared/types.ts";
12
14
  import { CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL, isCodeOwnedExternalCliAdapterId, parseExternalCliCapabilityNarrowing, validateCodeOwnedProfileRunner } from "../runs/shared/external-cli-contract.ts";
15
+ import { isClaudeCodeAdapterId } from "../runs/shared/claude-code-adapter.ts";
13
16
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
14
17
  import { expandHomePath } from "../shared/settings.ts";
15
18
  import { KNOWN_FIELDS } from "./agent-serializer.ts";
16
19
  import { parseChain, parseJsonChain } from "./chain-serializer.ts";
17
20
  import { mergeAgentsForScope } from "./agent-selection.ts";
21
+ import { projectScopeRequiresTrustMessage } from "./agent-scope.ts";
22
+ import { closestMatch } from "../shared/edit-distance.ts";
18
23
  import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.ts";
19
24
  import { buildRuntimeName, parsePackageName } from "./identity.ts";
20
25
  import { parseModelScopeConfig, type ModelScopeConfig } from "../runs/shared/model-scope.ts";
@@ -189,6 +194,8 @@ export interface AgentConfig {
189
194
  permissions?: PermissionRules;
190
195
  memory?: AgentMemoryConfig;
191
196
  machine?: string;
197
+ /** Name of a user-configured `runnerLaunchers` entry that wraps this agent's background runner. */
198
+ launcher?: string;
192
199
  disabled?: boolean;
193
200
  extraFields?: Record<string, string>;
194
201
  override?: BuiltinAgentOverrideInfo;
@@ -322,10 +329,13 @@ export interface UnknownAgentDiagnosticContext {
322
329
  scope: AgentScope;
323
330
  directories: readonly AgentDefinitionDirectoryReport[];
324
331
  agents: readonly AgentConfig[];
332
+ disabledAgents?: readonly string[];
325
333
  }
326
334
 
327
335
  export interface AgentDiscoveryResult {
328
336
  agents: AgentConfig[];
337
+ /** Names that resolved to a disabled definition, which discovery leaves out of `agents`. */
338
+ disabledAgents?: string[];
329
339
  agentDiagnostics?: AgentDiscoveryDiagnostic[];
330
340
  projectAgentsDir: string | null;
331
341
  cwd: string;
@@ -337,15 +347,36 @@ export interface AgentDiscoveryResult {
337
347
  }
338
348
 
339
349
  /** Create formatter input from the exact discovery operation used for resolution. */
340
- export function unknownAgentDiagnosticContext(discovered: Pick<AgentDiscoveryResult, "cwd" | "scope" | "directories" | "agents">): UnknownAgentDiagnosticContext {
350
+ export function unknownAgentDiagnosticContext(discovered: Pick<AgentDiscoveryResult, "cwd" | "scope" | "directories" | "agents" | "disabledAgents">): UnknownAgentDiagnosticContext {
341
351
  return {
342
352
  cwd: discovered.cwd,
343
353
  scope: discovered.scope,
344
354
  directories: discovered.directories,
345
355
  agents: discovered.agents,
356
+ ...(discovered.disabledAgents?.length ? { disabledAgents: discovered.disabledAgents } : {}),
346
357
  };
347
358
  }
348
359
 
360
+ const MAX_LISTED_AGENTS = 30;
361
+ const MAX_LISTED_DESCRIPTION_CHARS = 80;
362
+
363
+ /** One line per agent the caller can launch instead, so a wrong name needs no separate list call. */
364
+ export function formatAvailableAgentLines(agents: readonly AgentConfig[]): string[] {
365
+ const sorted = [...agents].sort((left, right) => left.name.localeCompare(right.name) || left.source.localeCompare(right.source));
366
+ const lines = sorted.slice(0, MAX_LISTED_AGENTS).map((agent) => {
367
+ const description = agent.description.replace(/\s+/gu, " ").trim();
368
+ const short = description.length > MAX_LISTED_DESCRIPTION_CHARS ? `${description.slice(0, MAX_LISTED_DESCRIPTION_CHARS - 1).trimEnd()}…` : description;
369
+ return `- ${agent.name} (${agent.source})${short ? ` — ${short}` : ""}`;
370
+ });
371
+ if (sorted.length > MAX_LISTED_AGENTS) lines.push(`+${sorted.length - MAX_LISTED_AGENTS} more; {action:"list"}`);
372
+ return lines.length ? lines : ["- (none)"];
373
+ }
374
+
375
+ /** The closest agent name or alias when `name` looks like a typo of one. */
376
+ export function suggestAgentName(name: string, agents: readonly AgentConfig[]): string | undefined {
377
+ return closestMatch(name.trim(), new Set(agents.flatMap((agent) => [agent.name, ...(agent.localName ? [agent.localName] : []), ...(agent.aliases ?? [])])));
378
+ }
379
+
349
380
  /** Render local discovery evidence without exposing filesystem error details. */
350
381
  export function formatUnknownAgentError(name: string, context: UnknownAgentDiagnosticContext, prefix = "Unknown agent"): string {
351
382
  const directories = context.directories.map((directory) => {
@@ -356,16 +387,15 @@ export function formatUnknownAgentError(name: string, context: UnknownAgentDiagn
356
387
  : directory.state;
357
388
  return `- ${directory.source}: ${directory.path} (${state})`;
358
389
  });
359
- const agents = [...context.agents]
360
- .sort((left, right) => left.name.localeCompare(right.name) || left.source.localeCompare(right.source))
361
- .map((agent) => `- ${agent.name} (${agent.source})`);
390
+ const disabled = context.disabledAgents?.includes(name.trim()) === true;
391
+ const suggestion = disabled ? undefined : suggestAgentName(name, context.agents);
362
392
  return [
363
- `${prefix}: ${name}`,
393
+ disabled ? `${prefix}: ${name} is disabled by a settings override.` : `${prefix}: ${name}${suggestion ? `. Did you mean '${suggestion}'?` : ""}`,
364
394
  `Effective cwd: ${path.resolve(context.cwd)}`,
365
395
  "Consulted agent-definition directories:",
366
396
  ...(directories.length ? directories : ["- (none)"]),
367
- "Discovered agents:",
368
- ...(agents.length ? agents : ["- (none)"]),
397
+ "Available agents:",
398
+ ...formatAvailableAgentLines(context.agents),
369
399
  ].join("\n");
370
400
  }
371
401
 
@@ -629,13 +659,10 @@ function collectSettingsPackageRoots(settingsFile: string, baseDir: string): str
629
659
  return roots;
630
660
  }
631
661
 
632
- function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean; globalNpmRoot?: string | null } = { includeUser: true, includeProject: true }): PackageSubagentPaths {
662
+ function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean; globalNpmRoot?: string | null; projectTrusted?: boolean }): PackageSubagentPaths {
633
663
  const agentDir = getAgentDir();
634
- const projectRoot = findConfiguredProjectRoot(cwd) ?? cwd;
635
- const packageRoots: Array<{ root: string; scope: PackageScope }> = [
636
- { root: projectRoot, scope: "root" },
637
- ];
638
- const watchPaths: string[] = [path.join(projectRoot, "package.json")];
664
+ const packageRoots: Array<{ root: string; scope: PackageScope }> = [];
665
+ const watchPaths: string[] = [];
639
666
  const settingsErrors: Partial<Record<PackageSettingsScope, Error>> = {};
640
667
  const collectScopedSettingsRoots = (scope: PackageSettingsScope, settingsFile: string, baseDir: string): string[] => {
641
668
  try {
@@ -650,11 +677,17 @@ function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolea
650
677
  return [];
651
678
  }
652
679
  };
653
- if (options.includeProject) {
654
- const projectConfigDir = getProjectConfigDir(projectRoot);
655
- const nodeModulesDir = path.join(projectConfigDir, "npm", "node_modules");
656
- packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "project" as const })));
657
- packageRoots.push(...collectScopedSettingsRoots("project", path.join(projectConfigDir, "settings.json"), projectConfigDir).map((root) => ({ root, scope: "project" as const })));
680
+ // Resolving the project root reads project settings, which an untrusted project does not supply.
681
+ if (options.projectTrusted !== false) {
682
+ const projectRoot = findConfiguredProjectRoot(cwd) ?? cwd;
683
+ packageRoots.push({ root: projectRoot, scope: "root" });
684
+ watchPaths.push(path.join(projectRoot, "package.json"));
685
+ if (options.includeProject) {
686
+ const projectConfigDir = getProjectConfigDir(projectRoot);
687
+ const nodeModulesDir = path.join(projectConfigDir, "npm", "node_modules");
688
+ packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "project" as const })));
689
+ packageRoots.push(...collectScopedSettingsRoots("project", path.join(projectConfigDir, "settings.json"), projectConfigDir).map((root) => ({ root, scope: "project" as const })));
690
+ }
658
691
  }
659
692
 
660
693
  if (options.includeUser) {
@@ -969,7 +1002,32 @@ function readSettingsFileStrict(filePath: string): Record<string, unknown> {
969
1002
 
970
1003
  function writeSettingsFile(filePath: string, settings: Record<string, unknown>): void {
971
1004
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
972
- fs.writeFileSync(filePath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
1005
+ const targetPath = resolveSettingsWriteTarget(filePath);
1006
+ let existingMode: number | undefined;
1007
+ try {
1008
+ existingMode = fs.statSync(targetPath).mode & 0o7777;
1009
+ } catch (error) {
1010
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
1011
+ }
1012
+ if (existingMode !== undefined) fs.accessSync(targetPath, fs.constants.W_OK);
1013
+
1014
+ const tempMode = existingMode === undefined ? undefined : existingMode | 0o200;
1015
+ // Reuse the atomic temp/rename path while retaining settings' newline and existing mode.
1016
+ const writeAtomicSettings = createAtomicJsonWriter({
1017
+ mode: tempMode,
1018
+ fs: {
1019
+ mkdirSync: fs.mkdirSync,
1020
+ writeFileSync: (tempPath, data, options) => {
1021
+ return fs.writeFileSync(tempPath, `${data}\n`, options);
1022
+ },
1023
+ renameSync: (sourcePath, destinationPath) => {
1024
+ if (existingMode !== undefined) fs.chmodSync(sourcePath, existingMode);
1025
+ fs.renameSync(sourcePath, destinationPath);
1026
+ },
1027
+ rmSync: fs.rmSync,
1028
+ },
1029
+ });
1030
+ writeAtomicSettings(targetPath, settings);
973
1031
  }
974
1032
 
975
1033
  function parseOverrideStringArrayOrFalse(
@@ -1004,7 +1062,7 @@ function parseToolsOverride(
1004
1062
  throw new Error(`Builtin override '${meta.name}' in '${meta.filePath}' has invalid 'tools'; expected an array of strings, "inherit", or false.`);
1005
1063
  }
1006
1064
 
1007
- function validateOptionalMachine(value: unknown, label: string): string | undefined {
1065
+ export function validateOptionalMachine(value: unknown, label: string): string | undefined {
1008
1066
  if (value === undefined || value === false) return undefined;
1009
1067
  if (typeof value !== "string" || !value.trim()) throw new Error(label + " must be a non-empty string or false.");
1010
1068
  const machine = value.trim();
@@ -1026,6 +1084,9 @@ function parseBuiltinOverrideEntry(
1026
1084
  if (Object.hasOwn(input, "fallbackModels")) {
1027
1085
  throw new Error(`Builtin override '${name}' in '${filePath}' uses removed field 'fallbackModels'; configure one model instead.`);
1028
1086
  }
1087
+ if (Object.hasOwn(input, "launcher")) {
1088
+ throw new Error(`Builtin override '${name}' in '${filePath}' sets 'launcher', which settings overrides do not support; set 'launcher' in a user agent file instead.`);
1089
+ }
1029
1090
  const override: BuiltinAgentOverrideConfig = {};
1030
1091
 
1031
1092
  if ("description" in input) {
@@ -1643,6 +1704,7 @@ export interface RuntimeAgentSettingsContext {
1643
1704
  cwd: string;
1644
1705
  scope: AgentScope;
1645
1706
  preferredModelProvider?: string;
1707
+ projectTrusted?: boolean;
1646
1708
  }
1647
1709
 
1648
1710
  function runtimeAgentOverrides(settings: SubagentSettings): SubagentSettings {
@@ -1669,7 +1731,7 @@ function runtimeAgentOverrides(settings: SubagentSettings): SubagentSettings {
1669
1731
  */
1670
1732
  export function applyRuntimeAgentSettings(agents: AgentConfig[], context: RuntimeAgentSettingsContext): AgentConfig[] {
1671
1733
  if (agents.length === 0) return agents;
1672
- const sources = getAgentDiscoverySources(context.cwd, context.preferredModelProvider);
1734
+ const sources = getAgentDiscoverySources(context.cwd, context.preferredModelProvider, false, undefined, context.projectTrusted !== false);
1673
1735
  const { user, project } = settingsForScope(sources, context.scope);
1674
1736
  const defaultProvider = resolveSubagentDefaultProvider(user, project, sources.projectSettingsPath);
1675
1737
  const defaultModel = resolveSubagentDefaultModel(user, project, sources.userSettingsPath, sources.projectSettingsPath, defaultProvider);
@@ -1732,19 +1794,21 @@ export function saveBuiltinAgentOverride(
1732
1794
  const filePath = scope === "project" ? getProjectAgentSettingsPath(cwd) : getUserAgentSettingsPath();
1733
1795
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1734
1796
 
1735
- const settings = readSettingsFileStrict(filePath);
1736
- const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
1737
- ? { ...(settings.subagents as Record<string, unknown>) }
1738
- : {};
1739
- const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
1740
- ? { ...(subagents.agentOverrides as Record<string, unknown>) }
1741
- : {};
1742
-
1743
- agentOverrides[name] = cloneOverrideValue(override);
1744
- subagents.agentOverrides = agentOverrides;
1745
- settings.subagents = subagents;
1746
- writeSettingsFile(filePath, settings);
1747
- return filePath;
1797
+ return withSettingsFileLease(filePath, () => {
1798
+ const settings = readSettingsFileStrict(filePath);
1799
+ const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
1800
+ ? { ...(settings.subagents as Record<string, unknown>) }
1801
+ : {};
1802
+ const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
1803
+ ? { ...(subagents.agentOverrides as Record<string, unknown>) }
1804
+ : {};
1805
+
1806
+ agentOverrides[name] = cloneOverrideValue(override);
1807
+ subagents.agentOverrides = agentOverrides;
1808
+ settings.subagents = subagents;
1809
+ writeSettingsFile(filePath, settings);
1810
+ return filePath;
1811
+ });
1748
1812
  }
1749
1813
 
1750
1814
  export function removeBuiltinAgentOverride(cwd: string, name: string, scope: "user" | "project", options?: { preserveMachine?: boolean }): { path: string; removed: boolean; machinePreserved: boolean } {
@@ -1752,28 +1816,30 @@ export function removeBuiltinAgentOverride(cwd: string, name: string, scope: "us
1752
1816
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1753
1817
  if (!fs.existsSync(filePath)) return { path: filePath, removed: false, machinePreserved: false };
1754
1818
 
1755
- const settings = readSettingsFileStrict(filePath);
1756
- const subagents = settings.subagents;
1757
- if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false, machinePreserved: false };
1758
- const nextSubagents = { ...(subagents as Record<string, unknown>) };
1759
- const agentOverrides = nextSubagents.agentOverrides;
1760
- if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false, machinePreserved: false };
1819
+ return withSettingsFileLease(filePath, () => {
1820
+ const settings = readSettingsFileStrict(filePath);
1821
+ const subagents = settings.subagents;
1822
+ if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false, machinePreserved: false };
1823
+ const nextSubagents = { ...(subagents as Record<string, unknown>) };
1824
+ const agentOverrides = nextSubagents.agentOverrides;
1825
+ if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false, machinePreserved: false };
1761
1826
 
1762
- const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1763
- const current = nextOverrides[name];
1764
- if (!Object.prototype.hasOwnProperty.call(nextOverrides, name)) return { path: filePath, removed: false, machinePreserved: false };
1765
- const configuredMachine = current && typeof current === "object" && !Array.isArray(current) ? (current as Record<string, unknown>).machine : undefined;
1766
- const machine = configuredMachine === false || (typeof configuredMachine === "string" && configuredMachine.trim()) ? configuredMachine : undefined;
1767
- if (options?.preserveMachine && machine !== undefined) nextOverrides[name] = { machine };
1768
- else delete nextOverrides[name];
1769
- if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1770
- else delete nextSubagents.agentOverrides;
1827
+ const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1828
+ const current = nextOverrides[name];
1829
+ if (!Object.prototype.hasOwnProperty.call(nextOverrides, name)) return { path: filePath, removed: false, machinePreserved: false };
1830
+ const configuredMachine = current && typeof current === "object" && !Array.isArray(current) ? (current as Record<string, unknown>).machine : undefined;
1831
+ const machine = configuredMachine === false || (typeof configuredMachine === "string" && configuredMachine.trim()) ? configuredMachine : undefined;
1832
+ if (options?.preserveMachine && machine !== undefined) nextOverrides[name] = { machine };
1833
+ else delete nextOverrides[name];
1834
+ if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1835
+ else delete nextSubagents.agentOverrides;
1771
1836
 
1772
- if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
1773
- else delete settings.subagents;
1837
+ if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
1838
+ else delete settings.subagents;
1774
1839
 
1775
- writeSettingsFile(filePath, settings);
1776
- return { path: filePath, removed: true, machinePreserved: options?.preserveMachine === true && machine !== undefined };
1840
+ writeSettingsFile(filePath, settings);
1841
+ return { path: filePath, removed: true, machinePreserved: options?.preserveMachine === true && machine !== undefined };
1842
+ });
1777
1843
  }
1778
1844
 
1779
1845
  export function mergeBuiltinAgentOverride(
@@ -1785,23 +1851,25 @@ export function mergeBuiltinAgentOverride(
1785
1851
  const filePath = scope === "project" ? getProjectAgentSettingsPath(cwd) : getUserAgentSettingsPath();
1786
1852
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1787
1853
 
1788
- const settings = readSettingsFileStrict(filePath);
1789
- const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
1790
- ? { ...(settings.subagents as Record<string, unknown>) }
1791
- : {};
1792
- const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
1793
- ? { ...(subagents.agentOverrides as Record<string, unknown>) }
1794
- : {};
1795
-
1796
- const existing = agentOverrides[name];
1797
- const base = existing && typeof existing === "object" && !Array.isArray(existing)
1798
- ? existing as Record<string, unknown>
1799
- : {};
1800
- agentOverrides[name] = { ...base, ...cloneOverrideValue(fields) };
1801
- subagents.agentOverrides = agentOverrides;
1802
- settings.subagents = subagents;
1803
- writeSettingsFile(filePath, settings);
1804
- return filePath;
1854
+ return withSettingsFileLease(filePath, () => {
1855
+ const settings = readSettingsFileStrict(filePath);
1856
+ const subagents = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
1857
+ ? { ...(settings.subagents as Record<string, unknown>) }
1858
+ : {};
1859
+ const agentOverrides = subagents.agentOverrides && typeof subagents.agentOverrides === "object" && !Array.isArray(subagents.agentOverrides)
1860
+ ? { ...(subagents.agentOverrides as Record<string, unknown>) }
1861
+ : {};
1862
+
1863
+ const existing = agentOverrides[name];
1864
+ const base = existing && typeof existing === "object" && !Array.isArray(existing)
1865
+ ? existing as Record<string, unknown>
1866
+ : {};
1867
+ agentOverrides[name] = { ...base, ...cloneOverrideValue(fields) };
1868
+ subagents.agentOverrides = agentOverrides;
1869
+ settings.subagents = subagents;
1870
+ writeSettingsFile(filePath, settings);
1871
+ return filePath;
1872
+ });
1805
1873
  }
1806
1874
 
1807
1875
  export function removeBuiltinAgentOverrideFields(
@@ -1814,38 +1882,40 @@ export function removeBuiltinAgentOverrideFields(
1814
1882
  if (!filePath) throw new Error("Project override is not available here. No project config root was found.");
1815
1883
  if (!fs.existsSync(filePath)) return { path: filePath, removed: false };
1816
1884
 
1817
- const settings = readSettingsFileStrict(filePath);
1818
- const subagents = settings.subagents;
1819
- if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false };
1820
- const agentOverrides = (subagents as Record<string, unknown>).agentOverrides;
1821
- if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false };
1822
-
1823
- const entry = (agentOverrides as Record<string, unknown>)[name];
1824
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) return { path: filePath, removed: false };
1825
-
1826
- const nextEntry: Record<string, unknown> = { ...(entry as Record<string, unknown>) };
1827
- let removed = false;
1828
- for (const field of fields) {
1829
- if (Object.prototype.hasOwnProperty.call(nextEntry, field)) {
1830
- delete nextEntry[field];
1831
- removed = true;
1885
+ return withSettingsFileLease(filePath, () => {
1886
+ const settings = readSettingsFileStrict(filePath);
1887
+ const subagents = settings.subagents;
1888
+ if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return { path: filePath, removed: false };
1889
+ const agentOverrides = (subagents as Record<string, unknown>).agentOverrides;
1890
+ if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) return { path: filePath, removed: false };
1891
+
1892
+ const entry = (agentOverrides as Record<string, unknown>)[name];
1893
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return { path: filePath, removed: false };
1894
+
1895
+ const nextEntry: Record<string, unknown> = { ...(entry as Record<string, unknown>) };
1896
+ let removed = false;
1897
+ for (const field of fields) {
1898
+ if (Object.prototype.hasOwnProperty.call(nextEntry, field)) {
1899
+ delete nextEntry[field];
1900
+ removed = true;
1901
+ }
1832
1902
  }
1833
- }
1834
- if (!removed) return { path: filePath, removed: false };
1903
+ if (!removed) return { path: filePath, removed: false };
1835
1904
 
1836
- const nextSubagents = { ...(subagents as Record<string, unknown>) };
1837
- if (Object.keys(nextEntry).length > 0) {
1838
- (nextSubagents.agentOverrides as Record<string, unknown>)[name] = nextEntry;
1839
- } else {
1840
- const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1841
- delete nextOverrides[name];
1842
- if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1843
- else delete nextSubagents.agentOverrides;
1844
- }
1845
- if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
1846
- else delete settings.subagents;
1847
- writeSettingsFile(filePath, settings);
1848
- return { path: filePath, removed: true };
1905
+ const nextSubagents = { ...(subagents as Record<string, unknown>) };
1906
+ if (Object.keys(nextEntry).length > 0) {
1907
+ (nextSubagents.agentOverrides as Record<string, unknown>)[name] = nextEntry;
1908
+ } else {
1909
+ const nextOverrides = { ...(agentOverrides as Record<string, unknown>) };
1910
+ delete nextOverrides[name];
1911
+ if (Object.keys(nextOverrides).length > 0) nextSubagents.agentOverrides = nextOverrides;
1912
+ else delete nextSubagents.agentOverrides;
1913
+ }
1914
+ if (Object.keys(nextSubagents).length > 0) settings.subagents = nextSubagents;
1915
+ else delete settings.subagents;
1916
+ writeSettingsFile(filePath, settings);
1917
+ return { path: filePath, removed: true };
1918
+ });
1849
1919
  }
1850
1920
 
1851
1921
  const DISCOVERY_PRUNED_DIR_NAMES = new Set([".git", "node_modules", ".pi", "sync-backups"]);
@@ -2079,8 +2149,11 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
2079
2149
 
2080
2150
  function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
2081
2151
  if (runner?.type !== "external-cli" && runner?.type !== "external-job") return;
2152
+ // The code-owned Claude Code adapters accept an explicit model and thinking level:
2153
+ // both are translated into their own argv rather than into a Pi child model.
2154
+ const adapterAcceptsOverrides = runner.type === "external-cli" && isClaudeCodeAdapterId(runner.adapter);
2082
2155
  const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "allowedAgents", "model", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission-profile", "permission", "permissions"]
2083
- .filter((field) => frontmatter[field] !== undefined);
2156
+ .filter((field) => frontmatter[field] !== undefined && !(adapterAcceptsOverrides && (field === "model" || field === "thinking")));
2084
2157
  if (unsupported.length > 0) {
2085
2158
  throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
2086
2159
  }
@@ -2288,6 +2361,13 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2288
2361
  : undefined;
2289
2362
  const memory = parseMemoryFrontmatter(frontmatter.memory);
2290
2363
  const machine = validateOptionalMachine(frontmatter.machine, `Agent '${runtimeName}' frontmatter 'machine'`);
2364
+ const launcher = frontmatter.launcher;
2365
+ if (launcher !== undefined && !RUNNER_LAUNCHER_NAME_PATTERN.test(launcher)) {
2366
+ throw new Error(`Agent '${runtimeName}' frontmatter 'launcher' ${JSON.stringify(launcher)} is invalid; launcher names ${RUNNER_LAUNCHER_NAME_RULE}.`);
2367
+ }
2368
+ if (launcher !== undefined && (runner?.type === "external-cli" || runner?.type === "external-job" || machine !== undefined)) {
2369
+ throw new Error(`Agent '${runtimeName}' sets 'launcher', which wraps the local Pi background runner, so it cannot be combined with ${machine !== undefined ? "'machine'" : `runner.type='${runner!.type}'`}.`);
2370
+ }
2291
2371
  const agent: AgentConfig = {
2292
2372
  name: runtimeName,
2293
2373
  ...(runner !== undefined ? { runner } : {}),
@@ -2327,6 +2407,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
2327
2407
  ...(subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions } : {}),
2328
2408
  ...(mutationTools?.length ? { mutationTools } : {}),
2329
2409
  ...(machine !== undefined ? { machine } : {}),
2410
+ ...(launcher !== undefined ? { launcher } : {}),
2330
2411
  ...(frontmatter.output !== undefined ? { output: frontmatter.output } : {}),
2331
2412
  ...(outputMode !== undefined ? { outputMode } : {}),
2332
2413
  ...(outputSchema !== undefined ? { outputSchema } : {}),
@@ -2563,6 +2644,8 @@ export interface AgentDiscoverySnapshot {
2563
2644
  /** Undefined uses synchronous npm lookup; null skips global npm discovery. */
2564
2645
  export interface AgentDiscoveryOptions {
2565
2646
  globalNpmRoot?: string | null;
2647
+ /** False when the session declined project trust: project settings, agents, chains and packages are ignored. Defaults to true. */
2648
+ projectTrusted?: boolean;
2566
2649
  }
2567
2650
 
2568
2651
  interface LoadedAgentDirectory {
@@ -2667,11 +2750,12 @@ function discoveryFingerprint(sources: AgentDiscoverySources): string {
2667
2750
  .join("\n");
2668
2751
  }
2669
2752
 
2670
- function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined, globalNpmRoot?: string | null): string {
2753
+ function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined, globalNpmRoot: string | null | undefined, projectTrusted: boolean): string {
2671
2754
  return JSON.stringify([
2672
2755
  path.resolve(cwd),
2673
2756
  preferredModelProvider ?? null,
2674
2757
  globalNpmRoot === undefined ? ["default"] : ["override", globalNpmRoot],
2758
+ projectTrusted,
2675
2759
  getProjectConfigDir(path.resolve(cwd)),
2676
2760
  getAgentDir(),
2677
2761
  os.homedir(),
@@ -2700,16 +2784,19 @@ function packageEntryIncluded(scope: AgentScope, packageScopes: PackageSubagentP
2700
2784
  return packageScopes.has(scope);
2701
2785
  }
2702
2786
 
2703
- function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string, globalNpmRoot?: string | null): AgentDiscoverySources {
2787
+ function buildAgentDiscoverySources(cwd: string, preferredModelProvider: string | undefined, globalNpmRoot: string | null | undefined, projectTrusted: boolean): AgentDiscoverySources {
2704
2788
  const effectiveCwd = path.resolve(cwd);
2705
2789
  const userDirOld = path.join(getAgentDir(), "agents");
2706
2790
  const userDirNew = path.join(os.homedir(), ".agents");
2707
2791
  const userChainDir = getUserChainDir();
2708
- const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(effectiveCwd);
2709
- const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(effectiveCwd);
2792
+ // The project's settings choose its root, so an untrusted project contributes no directories or settings at all.
2793
+ const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = projectTrusted
2794
+ ? resolveNearestProjectAgentDirs(effectiveCwd)
2795
+ : { readDirs: [], candidateDirs: [], preferredDir: null };
2796
+ const { readDirs: projectChainDirs, preferredDir: projectChainDir } = projectTrusted ? resolveNearestProjectChainDirs(effectiveCwd) : { readDirs: [], preferredDir: null };
2710
2797
  const userSettingsPath = getUserAgentSettingsPath();
2711
- const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
2712
- const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: true, includeProject: true, globalNpmRoot });
2798
+ const projectSettingsPath = projectTrusted ? getProjectAgentSettingsPath(effectiveCwd) : null;
2799
+ const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: true, includeProject: true, globalNpmRoot, projectTrusted });
2713
2800
  const exclusionRoots = agentExclusionRoots(userSettingsPath, projectSettingsPath);
2714
2801
  const isExcluded = agentExclusions(exclusionRoots);
2715
2802
  const userScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(userSettingsPath), isExcluded);
@@ -2795,8 +2882,8 @@ function ensureDiscoveryChains(sources: AgentDiscoverySources): void {
2795
2882
  sources.watchPaths = [...new Set([...sources.watchPaths, ...watchPaths])];
2796
2883
  }
2797
2884
 
2798
- function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false, globalNpmRoot?: string | null): AgentDiscoverySources {
2799
- const key = discoveryCacheKey(cwd, preferredModelProvider, globalNpmRoot);
2885
+ function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false, globalNpmRoot?: string | null, projectTrusted = true): AgentDiscoverySources {
2886
+ const key = discoveryCacheKey(cwd, preferredModelProvider, globalNpmRoot, projectTrusted);
2800
2887
  const cached = agentDiscoveryCache.get(key);
2801
2888
  if (cached && cached.fingerprint === discoveryFingerprint(cached.sources)) {
2802
2889
  if (includeChains) {
@@ -2805,7 +2892,7 @@ function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string,
2805
2892
  }
2806
2893
  return cached.sources;
2807
2894
  }
2808
- const sources = buildAgentDiscoverySources(cwd, preferredModelProvider, globalNpmRoot);
2895
+ const sources = buildAgentDiscoverySources(cwd, preferredModelProvider, globalNpmRoot, projectTrusted);
2809
2896
  const entry = { sources, fingerprint: discoveryFingerprint(sources) };
2810
2897
  agentDiscoveryCache.set(key, entry);
2811
2898
  if (includeChains) {
@@ -2925,12 +3012,12 @@ function buildEffectiveDiscovery(sources: AgentDiscoverySources, scope: AgentSco
2925
3012
  const injectAgents = effectiveProjectSettings.injectAgents !== undefined
2926
3013
  ? effectiveProjectSettings.injectAgents
2927
3014
  : effectiveUserSettings.injectAgents;
2928
- const agents = applySubagentMaxThinking(
2929
- mergeAgentsForScope(scope, configured.user, configured.project, configured.builtin, configured.package).filter((agent) => agent.disabled !== true),
2930
- configured.maxThinking,
2931
- );
3015
+ const merged = mergeAgentsForScope(scope, configured.user, configured.project, configured.builtin, configured.package);
3016
+ const agents = applySubagentMaxThinking(merged.filter((agent) => agent.disabled !== true), configured.maxThinking);
3017
+ const disabledAgents = merged.filter((agent) => agent.disabled === true).map((agent) => agent.name);
2932
3018
  return {
2933
3019
  agents,
3020
+ ...(disabledAgents.length ? { disabledAgents } : {}),
2934
3021
  agentDiagnostics: discoveryDiagnostics(sources, scope),
2935
3022
  projectAgentsDir: sources.projectAgentsDir,
2936
3023
  cwd: sources.cwd,
@@ -2998,8 +3085,18 @@ export function discoverAgentSnapshot(
2998
3085
  options: AgentDiscoveryOptions & { includeChains?: boolean } = {},
2999
3086
  ): AgentDiscoverySnapshot {
3000
3087
  const includeChains = options.includeChains !== false;
3001
- const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains, options.globalNpmRoot);
3002
- return { effective: buildEffectiveDiscovery(sources, scope), all: buildAllDiscovery(sources, includeChains, scope) };
3088
+ const projectTrusted = options.projectTrusted !== false;
3089
+ const trustedScope = trustedDiscoveryScope(cwd, scope, projectTrusted);
3090
+ const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains, options.globalNpmRoot, projectTrusted);
3091
+ return { effective: buildEffectiveDiscovery(sources, trustedScope), all: buildAllDiscovery(sources, includeChains, trustedScope) };
3092
+ }
3093
+
3094
+ // Pi loads nothing from an untrusted project's `.pi` directory, so declined trust leaves user scope.
3095
+ // A trusted lookup keeps its scope as given, including an omitted one from untyped callers.
3096
+ function trustedDiscoveryScope(cwd: string, scope: AgentScope, projectTrusted: boolean): AgentScope {
3097
+ if (projectTrusted) return scope;
3098
+ if (scope === "project") throw new Error(projectScopeRequiresTrustMessage(path.resolve(cwd)));
3099
+ return "user";
3003
3100
  }
3004
3101
 
3005
3102
  function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryResult {
@@ -3051,15 +3148,20 @@ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelPr
3051
3148
  const packageMap = new Map<string, AgentConfig>();
3052
3149
  for (const loaded of packageLoaded) for (const agent of loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
3053
3150
  const packageAgents = applyCustomAgentOverrides(applyDefaults(Array.from(packageMap.values())), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
3054
- const agents = applySubagentMaxThinking(mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents).filter((agent) => agent.disabled !== true), maxThinking);
3151
+ const merged = mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents);
3152
+ const agents = applySubagentMaxThinking(merged.filter((agent) => agent.disabled !== true), maxThinking);
3153
+ const disabledAgents = merged.filter((agent) => agent.disabled === true).map((agent) => agent.name);
3055
3154
  const agentDiagnostics = [...builtinLoaded.diagnostics, ...userLoaded.flatMap((loaded) => loaded.diagnostics), ...projectLoaded.flatMap((loaded) => loaded.diagnostics), ...packageLoaded.flatMap((loaded) => loaded.diagnostics)];
3056
- return { agents, agentDiagnostics, projectAgentsDir, cwd: effectiveCwd, scope, directories, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}), ...(maxThinking !== undefined ? { maxThinking } : {}) };
3155
+ return { agents, ...(disabledAgents.length ? { disabledAgents } : {}), agentDiagnostics, projectAgentsDir, cwd: effectiveCwd, scope, directories, ...(injectAgents?.length ? { injectAgents } : {}), ...(modelScope !== undefined ? { modelScope } : {}), ...(maxThinking !== undefined ? { maxThinking } : {}) };
3057
3156
  }
3058
3157
 
3059
3158
  export function discoverAgents(cwd: string, scope: AgentScope, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryResult {
3060
- if (scope !== "both") return discoverAgentsUncached(cwd, scope, preferredModelProvider, options);
3061
- const sources = getAgentDiscoverySources(cwd, preferredModelProvider, false, options.globalNpmRoot);
3062
- return buildEffectiveDiscovery(sources, scope);
3159
+ const projectTrusted = options.projectTrusted !== false;
3160
+ const trustedScope = trustedDiscoveryScope(cwd, scope, projectTrusted);
3161
+ // The uncached path always loads the project's own package.json entries.
3162
+ if (projectTrusted && trustedScope !== "both") return discoverAgentsUncached(cwd, trustedScope, preferredModelProvider, options);
3163
+ const sources = getAgentDiscoverySources(cwd, preferredModelProvider, false, options.globalNpmRoot, projectTrusted);
3164
+ return buildEffectiveDiscovery(sources, trustedScope);
3063
3165
  }
3064
3166
 
3065
3167
  export function discoverAgentsAll(cwd: string, preferredModelProvider?: string, options: AgentDiscoveryOptions = {}): AgentDiscoveryAllResult {