@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -8,8 +8,10 @@ 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, OutputMode, ToolBudgetConfig, TurnBudgetConfig } from "../shared/types.ts";
11
+ import type { AcceptanceInput, AcceptanceRole, AgentRunnerConfig, OutputMode, ToolBudgetConfig } from "../shared/types.ts";
12
+ import { CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL, isCodeOwnedExternalCliAdapterId, parseExternalCliCapabilityNarrowing, validateCodeOwnedProfileRunner } from "../runs/shared/external-cli-contract.ts";
12
13
  import { getAgentDir, getProjectConfigDir } from "../shared/utils.ts";
14
+ import { expandHomePath } from "../shared/settings.ts";
13
15
  import { KNOWN_FIELDS } from "./agent-serializer.ts";
14
16
  import { parseChain, parseJsonChain } from "./chain-serializer.ts";
15
17
  import { mergeAgentsForScope } from "./agent-selection.ts";
@@ -19,9 +21,9 @@ import { parseModelScopeConfig, type ModelScopeConfig } from "../runs/shared/mod
19
21
  export { BUILTIN_AGENT_NAMES } from "./builtin-names.ts";
20
22
  export { buildRuntimeName, frontmatterNameForConfig, parsePackageName } from "./identity.ts";
21
23
  import { parseMemoryFrontmatter } from "./agent-memory.ts";
22
- import { resolveTurnBudgetConfig } from "../runs/shared/turn-budget.ts";
23
24
  import { validateAcceptanceInput } from "../runs/shared/acceptance.ts";
24
25
  import { validatePermissionRules, type PermissionRules } from "../runs/shared/permissions.ts";
26
+ import { parseThinkingLevel, type ThinkingLevel } from "../shared/thinking-ceiling.ts";
25
27
 
26
28
  export type AgentScope = "user" | "project" | "both";
27
29
 
@@ -50,12 +52,17 @@ export function defaultInheritSkills(): boolean {
50
52
 
51
53
  export interface BuiltinAgentOverrideBase {
52
54
  description?: string;
55
+ output?: string;
53
56
  outputMode?: OutputMode;
57
+ defaultReads?: string[];
54
58
  model?: string;
59
+ modelProvider?: string;
55
60
  fallbackModels?: string[];
61
+ fast?: boolean;
56
62
  thinking?: string | false;
57
63
  systemPromptMode: SystemPromptMode;
58
64
  inheritProjectContext: boolean;
65
+ inheritGlobalContext: boolean;
59
66
  inheritSkills: boolean;
60
67
  defaultContext?: AgentDefaultContext;
61
68
  acceptanceRole?: AcceptanceRole;
@@ -64,21 +71,29 @@ export interface BuiltinAgentOverrideBase {
64
71
  skills?: string[];
65
72
  skillPath?: string[];
66
73
  tools?: string[];
74
+ excludeTools?: string[];
75
+ allowNestedSubagents?: boolean;
67
76
  mcpDirectTools?: string[];
68
77
  extensions?: string[];
69
78
  subagentOnlyExtensions?: string[];
79
+ mutationTools?: string[];
70
80
  completionGuard?: boolean;
71
81
  toolBudget?: ToolBudgetConfig;
72
82
  }
73
83
 
74
84
  interface BuiltinAgentOverrideConfig {
75
85
  description?: string;
86
+ output?: string | false;
76
87
  outputMode?: OutputMode;
88
+ defaultReads?: string[] | false;
77
89
  model?: string | false;
90
+ defaultProvider?: string | false;
78
91
  fallbackModels?: string[] | false;
92
+ fast?: boolean;
79
93
  thinking?: string | false;
80
94
  systemPromptMode?: SystemPromptMode;
81
95
  inheritProjectContext?: boolean;
96
+ inheritGlobalContext?: boolean;
82
97
  inheritSkills?: boolean;
83
98
  defaultContext?: AgentDefaultContext | false;
84
99
  acceptanceRole?: AcceptanceRole | false;
@@ -86,8 +101,11 @@ interface BuiltinAgentOverrideConfig {
86
101
  systemPrompt?: string;
87
102
  skills?: string[] | false;
88
103
  tools?: string[] | false | "inherit";
104
+ excludeTools?: string[] | false;
105
+ allowNestedSubagents?: boolean;
89
106
  extensions?: string[] | false;
90
107
  subagentOnlyExtensions?: string[] | false;
108
+ mutationTools?: string[] | false;
91
109
  completionGuard?: boolean;
92
110
  toolBudget?: ToolBudgetConfig | false;
93
111
  }
@@ -96,6 +114,8 @@ interface BuiltinAgentOverrideInfo {
96
114
  scope: "user" | "project";
97
115
  path: string;
98
116
  base: BuiltinAgentOverrideBase;
117
+ fields?: string[];
118
+ fieldScopes?: Record<string, Array<"user" | "project">>;
99
119
  }
100
120
 
101
121
  export interface AgentModelSourceInfo {
@@ -103,6 +123,7 @@ export interface AgentModelSourceInfo {
103
123
  scope: "user" | "project";
104
124
  path: string;
105
125
  model: string;
126
+ defaultProvider?: string;
106
127
  }
107
128
 
108
129
  export interface AgentConfig {
@@ -110,21 +131,28 @@ export interface AgentConfig {
110
131
  runner?: AgentRunnerConfig;
111
132
  localName?: string;
112
133
  packageName?: string;
134
+ packageSourceName?: string;
135
+ packageSourceVersion?: string;
136
+ packageSourceRoot?: string;
113
137
  description: string;
114
138
  aliases?: string[];
115
139
  tools?: string[];
140
+ excludeTools?: string[];
141
+ allowNestedSubagents?: boolean;
116
142
  mcpDirectTools?: string[];
117
143
  model?: string;
144
+ modelProvider?: string;
118
145
  fallbackModels?: string[];
146
+ fast?: boolean;
119
147
  thinking?: string | false;
120
148
  systemPromptMode: SystemPromptMode;
121
149
  inheritProjectContext: boolean;
150
+ inheritGlobalContext: boolean;
122
151
  inheritSkills: boolean;
123
152
  defaultContext?: AgentDefaultContext;
124
153
  defaultAsync?: boolean;
125
154
  defaultTimeoutMs?: number;
126
155
  defaultToolTimeoutMs?: number;
127
- defaultTurnBudget?: TurnBudgetConfig;
128
156
  defaultAcceptance?: AcceptanceInput;
129
157
  acceptanceRole?: AcceptanceRole;
130
158
  systemPrompt: string;
@@ -136,6 +164,7 @@ export interface AgentConfig {
136
164
  extensions?: string[];
137
165
  extensionsFromDefault?: boolean;
138
166
  subagentOnlyExtensions?: string[];
167
+ mutationTools?: string[];
139
168
  output?: string;
140
169
  outputMode?: OutputMode;
141
170
  defaultReads?: string[];
@@ -151,14 +180,19 @@ export interface AgentConfig {
151
180
  extraFields?: Record<string, string>;
152
181
  override?: BuiltinAgentOverrideInfo;
153
182
  modelSource?: AgentModelSourceInfo;
183
+ maxThinking?: ThinkingLevel;
154
184
  }
155
185
 
156
186
  type ProjectRootResolution = "nearest" | "git-root";
157
187
 
158
188
  interface SubagentSettings {
159
189
  overrides: Record<string, BuiltinAgentOverrideConfig>;
190
+ providerOverrides: Record<string, Record<string, BuiltinAgentOverrideConfig>>;
191
+ agentScanDirs?: string[];
160
192
  defaultModel?: string;
193
+ defaultProvider?: string;
161
194
  defaultThinking?: string;
195
+ maxThinking?: ThinkingLevel;
162
196
  defaultExtensions?: string[];
163
197
  disableBuiltins?: boolean;
164
198
  disableThinking?: boolean;
@@ -166,7 +200,7 @@ interface SubagentSettings {
166
200
  injectAgents?: string[];
167
201
  }
168
202
 
169
- const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {} };
203
+ const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {}, providerOverrides: {} };
170
204
  const agentFrontmatterFields = new WeakMap<AgentConfig, Set<string>>();
171
205
 
172
206
  export interface ChainStepConfig {
@@ -246,21 +280,101 @@ export function findBlockingAgentDiagnostic(name: string, agent: AgentConfig | r
246
280
  return !agents.length || (match && agentDefinitionPriority(match) > highestPriority) ? match : undefined;
247
281
  }
248
282
 
249
- interface AgentDiscoveryResult {
283
+ export type AgentDefinitionDirectoryState = "absent" | "empty" | "candidates" | "unreadable" | "not-directory";
284
+
285
+ /** A definition directory actually inspected during one agent-discovery operation. */
286
+ export interface AgentDefinitionDirectoryReport {
287
+ source: AgentSource;
288
+ path: string;
289
+ state: AgentDefinitionDirectoryState;
290
+ candidateCount?: number;
291
+ }
292
+
293
+ /**
294
+ * Filesystem provenance for a failed agent resolution. Context is created from
295
+ * the discovery result that supplied the effective agents; callers must not
296
+ * pair arbitrary agent arrays with these directory reports.
297
+ */
298
+ export interface UnknownAgentDiagnosticContext {
299
+ cwd: string;
300
+ scope: AgentScope;
301
+ directories: readonly AgentDefinitionDirectoryReport[];
302
+ agents: readonly AgentConfig[];
303
+ }
304
+
305
+ export interface AgentDiscoveryResult {
250
306
  agents: AgentConfig[];
251
307
  agentDiagnostics?: AgentDiscoveryDiagnostic[];
252
308
  projectAgentsDir: string | null;
309
+ cwd: string;
310
+ scope: AgentScope;
311
+ directories: readonly AgentDefinitionDirectoryReport[];
253
312
  modelScope?: ModelScopeConfig;
254
313
  injectAgents?: string[];
314
+ maxThinking?: ThinkingLevel;
315
+ }
316
+
317
+ /** Create formatter input from the exact discovery operation used for resolution. */
318
+ export function unknownAgentDiagnosticContext(discovered: Pick<AgentDiscoveryResult, "cwd" | "scope" | "directories" | "agents">): UnknownAgentDiagnosticContext {
319
+ return {
320
+ cwd: discovered.cwd,
321
+ scope: discovered.scope,
322
+ directories: discovered.directories,
323
+ agents: discovered.agents,
324
+ };
325
+ }
326
+
327
+ /** Render local discovery evidence without exposing filesystem error details. */
328
+ export function formatUnknownAgentError(name: string, context: UnknownAgentDiagnosticContext, prefix = "Unknown agent"): string {
329
+ const directories = context.directories.map((directory) => {
330
+ const state = directory.state === "candidates"
331
+ ? `${directory.candidateCount ?? 0} candidate${directory.candidateCount === 1 ? "" : "s"}`
332
+ : directory.state === "empty" ? "present but empty"
333
+ : directory.state === "not-directory" ? "not a directory"
334
+ : directory.state;
335
+ return `- ${directory.source}: ${directory.path} (${state})`;
336
+ });
337
+ const agents = [...context.agents]
338
+ .sort((left, right) => left.name.localeCompare(right.name) || left.source.localeCompare(right.source))
339
+ .map((agent) => `- ${agent.name} (${agent.source})`);
340
+ return [
341
+ `${prefix}: ${name}`,
342
+ `Effective cwd: ${path.resolve(context.cwd)}`,
343
+ "Consulted agent-definition directories:",
344
+ ...(directories.length ? directories : ["- (none)"]),
345
+ "Discovered agents:",
346
+ ...(agents.length ? agents : ["- (none)"]),
347
+ ].join("\n");
255
348
  }
256
349
 
257
350
  function getUserChainDir(): string {
258
351
  return path.join(getAgentDir(), "chains");
259
352
  }
260
353
 
354
+ type PackageScope = "root" | "user" | "project";
355
+ type PackageSettingsScope = Exclude<PackageScope, "root">;
356
+
357
+ interface PackageSubagentPath {
358
+ dir: string;
359
+ // A package can be reachable from more than one settings scope. Keep the
360
+ // actual memberships instead of promoting a mixed-scope path to root.
361
+ scope: Set<PackageScope>;
362
+ packageName?: string;
363
+ packageVersion?: string;
364
+ packageRoot: string;
365
+ }
366
+
367
+ interface PackageChainPath {
368
+ dir: string;
369
+ scope: Set<PackageScope>;
370
+ packageRoot: string;
371
+ }
372
+
261
373
  interface PackageSubagentPaths {
262
- agents: string[];
263
- chains: string[];
374
+ agents: PackageSubagentPath[];
375
+ chains: PackageChainPath[];
376
+ watchPaths: string[];
377
+ settingsErrors: Partial<Record<PackageSettingsScope, Error>>;
264
378
  }
265
379
 
266
380
  let cachedGlobalNpmRoot: string | null = null;
@@ -285,20 +399,6 @@ function readJsonFileBestEffort(filePath: string): JsonObjectFile | null {
285
399
  }
286
400
  }
287
401
 
288
- function readOptionalJsonFile(filePath: string): JsonObjectFile | null {
289
- let parsed: unknown;
290
- try {
291
- parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
292
- } catch (error) {
293
- const code = typeof error === "object" && error !== null && "code" in error
294
- ? (error as { code?: unknown }).code
295
- : undefined;
296
- if (code === "ENOENT") return null;
297
- throw error;
298
- }
299
- return isJsonObjectRecord(parsed) ? parsed : null;
300
- }
301
-
302
402
  function isSafePackagePath(value: string): boolean {
303
403
  return value.length > 0
304
404
  && !path.isAbsolute(value)
@@ -370,6 +470,10 @@ function resolveSettingsPackageRoot(source: string, baseDir: string): string | u
370
470
  if (normalized === "." || normalized === ".." || normalized.startsWith("./") || normalized.startsWith("../")) {
371
471
  return path.resolve(baseDir, normalized);
372
472
  }
473
+ if (/^https?:\/\//i.test(trimmed)) {
474
+ const parsed = parseGitPackagePath(`git:${trimmed}`);
475
+ return parsed ? path.join(baseDir, "git", parsed.host, parsed.repoPath) : undefined;
476
+ }
373
477
  return undefined;
374
478
  }
375
479
 
@@ -406,18 +510,30 @@ function stringArray(value: unknown): string[] {
406
510
  return value.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0);
407
511
  }
408
512
 
409
- function extractSubagentPathsFromPackageRoot(packageRoot: string): PackageSubagentPaths {
513
+ function packageMetadata(pkg: Record<string, unknown>, packageRoot: string): Omit<PackageSubagentPath, "dir" | "scope"> {
514
+ const name = typeof pkg.name === "string" && pkg.name.trim() ? pkg.name.trim() : undefined;
515
+ const version = typeof pkg.version === "string" && pkg.version.trim() ? pkg.version.trim() : undefined;
516
+ return {
517
+ packageRoot,
518
+ ...(name ? { packageName: name } : {}),
519
+ ...(version ? { packageVersion: version } : {}),
520
+ };
521
+ }
522
+
523
+ function extractSubagentPathsFromPackageRoot(packageRoot: string, scope: Set<PackageScope>): PackageSubagentPaths {
410
524
  const packageJsonPath = path.join(packageRoot, "package.json");
411
525
  const pkg = readJsonFileBestEffort(packageJsonPath);
412
- if (!pkg) return { agents: [], chains: [] };
526
+ if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { agents: [], chains: [], watchPaths: [packageJsonPath], settingsErrors: {} };
527
+ const pkgRecord = pkg as Record<string, unknown>;
528
+ const metadata = packageMetadata(pkgRecord, packageRoot);
413
529
 
414
530
  const roots: Record<string, unknown>[] = [];
415
- const piSubagents = pkg["pi-subagents"];
531
+ const piSubagents = pkgRecord["pi-subagents"];
416
532
  if (piSubagents && typeof piSubagents === "object" && !Array.isArray(piSubagents)) {
417
533
  roots.push(piSubagents as Record<string, unknown>);
418
534
  }
419
535
 
420
- const pi = pkg.pi;
536
+ const pi = pkgRecord.pi;
421
537
  if (pi && typeof pi === "object" && !Array.isArray(pi)) {
422
538
  const subagents = (pi as { subagents?: unknown }).subagents;
423
539
  if (subagents && typeof subagents === "object" && !Array.isArray(subagents)) {
@@ -425,17 +541,18 @@ function extractSubagentPathsFromPackageRoot(packageRoot: string): PackageSubage
425
541
  }
426
542
  }
427
543
 
428
- const agents: string[] = [];
429
- const chains: string[] = [];
544
+ const agents: PackageSubagentPath[] = [];
545
+ const chains: PackageChainPath[] = [];
430
546
  for (const root of roots) {
431
- for (const entry of stringArray(root.agents)) agents.push(path.resolve(packageRoot, entry));
432
- for (const entry of stringArray(root.chains)) chains.push(path.resolve(packageRoot, entry));
547
+ for (const entry of stringArray(root.agents)) agents.push({ dir: path.resolve(packageRoot, entry), scope, ...metadata });
548
+ for (const entry of stringArray(root.chains)) chains.push({ dir: path.resolve(packageRoot, entry), scope, packageRoot });
433
549
  }
434
- return { agents, chains };
550
+ return { agents, chains, watchPaths: [packageJsonPath], settingsErrors: {} };
435
551
  }
436
552
 
437
- function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
553
+ function collectPackageRootsFromNodeModules(nodeModulesDir: string, watchPaths?: string[]): string[] {
438
554
  const roots: string[] = [];
555
+ watchPaths?.push(nodeModulesDir);
439
556
  if (!fs.existsSync(nodeModulesDir)) return roots;
440
557
 
441
558
  let entries: fs.Dirent[];
@@ -451,6 +568,7 @@ function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
451
568
 
452
569
  if (entry.name.startsWith("@")) {
453
570
  const scopeDir = path.join(nodeModulesDir, entry.name);
571
+ watchPaths?.push(scopeDir);
454
572
  let scopeEntries: fs.Dirent[];
455
573
  try {
456
574
  scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
@@ -471,9 +589,8 @@ function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
471
589
  }
472
590
 
473
591
  function collectSettingsPackageRoots(settingsFile: string, baseDir: string): string[] {
474
- const settings = readOptionalJsonFile(settingsFile);
475
- if (!settings) return [];
476
- const packages = settings.packages;
592
+ const settings = readSettingsFileStrict(settingsFile);
593
+ const packages = (settings as { packages?: unknown }).packages;
477
594
  if (!Array.isArray(packages)) return [];
478
595
 
479
596
  const roots: string[] = [];
@@ -493,52 +610,82 @@ function collectSettingsPackageRoots(settingsFile: string, baseDir: string): str
493
610
  function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean } = { includeUser: true, includeProject: true }): PackageSubagentPaths {
494
611
  const agentDir = getAgentDir();
495
612
  const projectRoot = findConfiguredProjectRoot(cwd) ?? cwd;
496
- const packageRoots = [
497
- projectRoot,
613
+ const packageRoots: Array<{ root: string; scope: PackageScope }> = [
614
+ { root: projectRoot, scope: "root" },
498
615
  ];
499
-
616
+ const watchPaths: string[] = [path.join(projectRoot, "package.json")];
617
+ const settingsErrors: Partial<Record<PackageSettingsScope, Error>> = {};
618
+ const collectScopedSettingsRoots = (scope: PackageSettingsScope, settingsFile: string, baseDir: string): string[] => {
619
+ try {
620
+ return collectSettingsPackageRoots(settingsFile, baseDir);
621
+ } catch (error) {
622
+ // The raw source snapshot includes both settings scopes. Defer a
623
+ // strict failure until a projection actually selects this scope so an
624
+ // unrelated malformed settings file stays out of scoped discovery.
625
+ settingsErrors[scope] = error instanceof Error
626
+ ? error
627
+ : new Error(`Failed to read settings file '${settingsFile}': ${String(error)}`, { cause: error });
628
+ return [];
629
+ }
630
+ };
500
631
  if (options.includeProject) {
501
632
  const projectConfigDir = getProjectConfigDir(projectRoot);
502
- packageRoots.push(
503
- ...collectPackageRootsFromNodeModules(path.join(projectConfigDir, "npm", "node_modules")),
504
- ...collectSettingsPackageRoots(path.join(projectConfigDir, "settings.json"), projectConfigDir),
505
- );
633
+ const nodeModulesDir = path.join(projectConfigDir, "npm", "node_modules");
634
+ packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "project" as const })));
635
+ packageRoots.push(...collectScopedSettingsRoots("project", path.join(projectConfigDir, "settings.json"), projectConfigDir).map((root) => ({ root, scope: "project" as const })));
506
636
  }
507
637
 
508
638
  if (options.includeUser) {
509
- packageRoots.push(
510
- ...collectPackageRootsFromNodeModules(path.join(agentDir, "npm", "node_modules")),
511
- ...collectSettingsPackageRoots(path.join(agentDir, "settings.json"), agentDir),
512
- );
639
+ const nodeModulesDir = path.join(agentDir, "npm", "node_modules");
640
+ packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "user" as const })));
641
+ packageRoots.push(...collectScopedSettingsRoots("user", path.join(agentDir, "settings.json"), agentDir).map((root) => ({ root, scope: "user" as const })));
513
642
  }
514
643
 
515
644
  if (options.includeUser) {
516
645
  const globalRoot = getGlobalNpmRoot();
517
- if (globalRoot) packageRoots.push(...collectPackageRootsFromNodeModules(globalRoot));
646
+ if (globalRoot) {
647
+ packageRoots.push(...collectPackageRootsFromNodeModules(globalRoot, watchPaths).map((root) => ({ root, scope: "user" as const })));
648
+ }
518
649
  }
519
650
 
520
- const seenRoots = new Set<string>();
521
- const seenAgents = new Set<string>();
522
- const seenChains = new Set<string>();
523
- const agents: string[] = [];
524
- const chains: string[] = [];
525
- for (const packageRoot of packageRoots) {
651
+ const seenRoots = new Map<string, Set<PackageScope>>();
652
+ const seenAgents = new Map<string, PackageSubagentPath>();
653
+ const seenChains = new Map<string, PackageChainPath>();
654
+ const agents: PackageSubagentPath[] = [];
655
+ const chains: PackageChainPath[] = [];
656
+ for (const { root: packageRoot, scope } of packageRoots) {
526
657
  const resolvedRoot = path.resolve(packageRoot);
527
- if (seenRoots.has(resolvedRoot)) continue;
528
- seenRoots.add(resolvedRoot);
529
- const paths = extractSubagentPathsFromPackageRoot(resolvedRoot);
530
- for (const agentDir of paths.agents) {
531
- if (seenAgents.has(agentDir)) continue;
532
- seenAgents.add(agentDir);
533
- agents.push(agentDir);
658
+ const scopes = seenRoots.get(resolvedRoot);
659
+ if (scopes !== undefined) {
660
+ scopes.add(scope);
661
+ continue;
662
+ }
663
+ const packageScopes = new Set<PackageScope>([scope]);
664
+ seenRoots.set(resolvedRoot, packageScopes);
665
+ const paths = extractSubagentPathsFromPackageRoot(resolvedRoot, packageScopes);
666
+ watchPaths.push(...paths.watchPaths);
667
+ for (const agentPath of paths.agents) {
668
+ const agentKey = `${agentPath.dir}\u0000${agentPath.packageRoot}`;
669
+ const existing = seenAgents.get(agentKey);
670
+ if (existing) {
671
+ for (const packageScope of agentPath.scope) existing.scope.add(packageScope);
672
+ continue;
673
+ }
674
+ seenAgents.set(agentKey, agentPath);
675
+ agents.push(agentPath);
534
676
  }
535
677
  for (const chainDir of paths.chains) {
536
- if (seenChains.has(chainDir)) continue;
537
- seenChains.add(chainDir);
678
+ const chainKey = `${chainDir.dir}\u0000${chainDir.packageRoot}`;
679
+ const existing = seenChains.get(chainKey);
680
+ if (existing) {
681
+ for (const packageScope of chainDir.scope) existing.scope.add(packageScope);
682
+ continue;
683
+ }
684
+ seenChains.set(chainKey, chainDir);
538
685
  chains.push(chainDir);
539
686
  }
540
687
  }
541
- return { agents, chains };
688
+ return { agents, chains, watchPaths, settingsErrors };
542
689
  }
543
690
 
544
691
  function normalizeAgentAliases(rawAliases: string[] | undefined, agentName: string): string[] | undefined {
@@ -614,12 +761,17 @@ function arraysEqual(a: string[] | undefined, b: string[] | undefined): boolean
614
761
  function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
615
762
  return {
616
763
  description: agent.description,
764
+ ...(agent.output !== undefined ? { output: agent.output } : {}),
617
765
  ...(agent.outputMode !== undefined ? { outputMode: agent.outputMode } : {}),
766
+ ...(agent.defaultReads !== undefined ? { defaultReads: [...agent.defaultReads] } : {}),
618
767
  ...(agent.model !== undefined ? { model: agent.model } : {}),
768
+ ...(agent.modelProvider !== undefined ? { modelProvider: agent.modelProvider } : {}),
619
769
  ...(agent.fallbackModels ? { fallbackModels: [...agent.fallbackModels] } : {}),
770
+ ...(agent.fast !== undefined ? { fast: agent.fast } : {}),
620
771
  ...(agent.thinking !== undefined ? { thinking: agent.thinking } : {}),
621
772
  systemPromptMode: agent.systemPromptMode,
622
773
  inheritProjectContext: agent.inheritProjectContext,
774
+ inheritGlobalContext: agent.inheritGlobalContext,
623
775
  inheritSkills: agent.inheritSkills,
624
776
  ...(agent.defaultContext !== undefined ? { defaultContext: agent.defaultContext } : {}),
625
777
  ...(agent.acceptanceRole !== undefined ? { acceptanceRole: agent.acceptanceRole } : {}),
@@ -628,9 +780,12 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
628
780
  ...(agent.skills ? { skills: [...agent.skills] } : {}),
629
781
  ...(agent.skillPath ? { skillPath: [...agent.skillPath] } : {}),
630
782
  ...(agent.tools ? { tools: [...agent.tools] } : {}),
783
+ ...(agent.excludeTools ? { excludeTools: [...agent.excludeTools] } : {}),
784
+ ...(agent.allowNestedSubagents !== undefined ? { allowNestedSubagents: agent.allowNestedSubagents } : {}),
631
785
  ...(agent.mcpDirectTools ? { mcpDirectTools: [...agent.mcpDirectTools] } : {}),
632
786
  ...(!agent.extensionsFromDefault && agent.extensions ? { extensions: [...agent.extensions] } : {}),
633
787
  ...(agent.subagentOnlyExtensions ? { subagentOnlyExtensions: [...agent.subagentOnlyExtensions] } : {}),
788
+ ...(agent.mutationTools ? { mutationTools: [...agent.mutationTools] } : {}),
634
789
  ...(agent.completionGuard !== undefined ? { completionGuard: agent.completionGuard } : {}),
635
790
  ...(agent.toolBudget !== undefined ? { toolBudget: agent.toolBudget } : {}),
636
791
  };
@@ -639,14 +794,19 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
639
794
  function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentOverrideConfig {
640
795
  return {
641
796
  ...(override.description !== undefined ? { description: override.description } : {}),
797
+ ...(override.output !== undefined ? { output: override.output } : {}),
642
798
  ...(override.outputMode !== undefined ? { outputMode: override.outputMode } : {}),
799
+ ...(override.defaultReads !== undefined ? { defaultReads: override.defaultReads === false ? false : [...override.defaultReads] } : {}),
643
800
  ...(override.model !== undefined ? { model: override.model } : {}),
801
+ ...(override.defaultProvider !== undefined ? { defaultProvider: override.defaultProvider } : {}),
644
802
  ...(override.fallbackModels !== undefined
645
803
  ? { fallbackModels: override.fallbackModels === false ? false : [...override.fallbackModels] }
646
804
  : {}),
805
+ ...(override.fast !== undefined ? { fast: override.fast } : {}),
647
806
  ...(override.thinking !== undefined ? { thinking: override.thinking } : {}),
648
807
  ...(override.systemPromptMode !== undefined ? { systemPromptMode: override.systemPromptMode } : {}),
649
808
  ...(override.inheritProjectContext !== undefined ? { inheritProjectContext: override.inheritProjectContext } : {}),
809
+ ...(override.inheritGlobalContext !== undefined ? { inheritGlobalContext: override.inheritGlobalContext } : {}),
650
810
  ...(override.inheritSkills !== undefined ? { inheritSkills: override.inheritSkills } : {}),
651
811
  ...(override.defaultContext !== undefined ? { defaultContext: override.defaultContext } : {}),
652
812
  ...(override.acceptanceRole !== undefined ? { acceptanceRole: override.acceptanceRole } : {}),
@@ -654,8 +814,11 @@ function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentO
654
814
  ...(override.systemPrompt !== undefined ? { systemPrompt: override.systemPrompt } : {}),
655
815
  ...(override.skills !== undefined ? { skills: override.skills === false ? false : [...override.skills] } : {}),
656
816
  ...(override.tools !== undefined ? { tools: Array.isArray(override.tools) ? [...override.tools] : override.tools } : {}),
817
+ ...(override.excludeTools !== undefined ? { excludeTools: override.excludeTools === false ? false : [...override.excludeTools] } : {}),
818
+ ...(override.allowNestedSubagents !== undefined ? { allowNestedSubagents: override.allowNestedSubagents } : {}),
657
819
  ...(override.extensions !== undefined ? { extensions: override.extensions === false ? false : [...override.extensions] } : {}),
658
820
  ...(override.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: override.subagentOnlyExtensions === false ? false : [...override.subagentOnlyExtensions] } : {}),
821
+ ...(override.mutationTools !== undefined ? { mutationTools: override.mutationTools === false ? false : [...override.mutationTools] } : {}),
659
822
  ...(override.completionGuard !== undefined ? { completionGuard: override.completionGuard } : {}),
660
823
  ...(override.toolBudget !== undefined ? { toolBudget: override.toolBudget === false ? false : { ...override.toolBudget, ...(Array.isArray(override.toolBudget.block) ? { block: [...override.toolBudget.block] } : {}) } } : {}),
661
824
  };
@@ -705,7 +868,7 @@ export function findNearestProjectRoot(cwd: string): string | null {
705
868
  return findProjectRootCandidates(cwd)[0] ?? null;
706
869
  }
707
870
 
708
- function findConfiguredProjectRoot(cwd: string): string | null {
871
+ export function findConfiguredProjectRoot(cwd: string): string | null {
709
872
  const candidates = findProjectRootCandidates(cwd);
710
873
  const nearestRoot = candidates[0];
711
874
  if (!nearestRoot) return null;
@@ -820,6 +983,11 @@ function parseBuiltinOverrideEntry(
820
983
  }
821
984
  }
822
985
 
986
+ if ("output" in input) {
987
+ if ((typeof input.output === "string" && input.output.trim()) || input.output === false) override.output = input.output;
988
+ else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'output'; expected a non-empty string or false.`);
989
+ }
990
+
823
991
  if ("outputMode" in input) {
824
992
  if (input.outputMode === "inline" || input.outputMode === "file-only") {
825
993
  override.outputMode = input.outputMode;
@@ -833,6 +1001,11 @@ function parseBuiltinOverrideEntry(
833
1001
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'model'; expected a string or false.`);
834
1002
  }
835
1003
 
1004
+ if ("fast" in input) {
1005
+ if (typeof input.fast === "boolean") override.fast = input.fast;
1006
+ else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'fast'; expected a boolean.`);
1007
+ }
1008
+
836
1009
  if ("thinking" in input) {
837
1010
  if (typeof input.thinking === "string" || input.thinking === false) override.thinking = input.thinking;
838
1011
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'thinking'; expected a string or false.`);
@@ -854,6 +1027,14 @@ function parseBuiltinOverrideEntry(
854
1027
  }
855
1028
  }
856
1029
 
1030
+ if ("inheritGlobalContext" in input) {
1031
+ if (typeof input.inheritGlobalContext === "boolean") {
1032
+ override.inheritGlobalContext = input.inheritGlobalContext;
1033
+ } else {
1034
+ throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'inheritGlobalContext'; expected a boolean.`);
1035
+ }
1036
+ }
1037
+
857
1038
  if ("inheritSkills" in input) {
858
1039
  if (typeof input.inheritSkills === "boolean") {
859
1040
  override.inheritSkills = input.inheritSkills;
@@ -909,14 +1090,29 @@ function parseBuiltinOverrideEntry(
909
1090
  else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'systemPrompt'; expected a string.`);
910
1091
  }
911
1092
 
1093
+ const defaultReads = parseOverrideStringArrayOrFalse(input.defaultReads, { filePath, name, field: "defaultReads" });
1094
+ if (defaultReads !== undefined) override.defaultReads = defaultReads;
1095
+
912
1096
  const fallbackModels = parseOverrideStringArrayOrFalse(input.fallbackModels, { filePath, name, field: "fallbackModels" });
913
1097
  if (fallbackModels !== undefined) override.fallbackModels = fallbackModels;
914
1098
 
1099
+ if ("defaultProvider" in input) {
1100
+ if (input.defaultProvider === false) override.defaultProvider = false;
1101
+ else if (typeof input.defaultProvider === "string" && input.defaultProvider.trim()) override.defaultProvider = input.defaultProvider.trim();
1102
+ else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'defaultProvider'; expected a non-empty string or false.`);
1103
+ }
1104
+
915
1105
  const skills = parseOverrideStringArrayOrFalse(input.skills, { filePath, name, field: "skills" });
916
1106
  if (skills !== undefined) override.skills = skills;
917
1107
 
918
1108
  const tools = parseToolsOverride(input.tools, { filePath, name });
919
1109
  if (tools !== undefined) override.tools = tools;
1110
+ const excludeTools = parseOverrideStringArrayOrFalse(input.excludeTools, { filePath, name, field: "excludeTools" });
1111
+ if (excludeTools !== undefined) override.excludeTools = excludeTools;
1112
+ if ("allowNestedSubagents" in input) {
1113
+ if (typeof input.allowNestedSubagents === "boolean") override.allowNestedSubagents = input.allowNestedSubagents;
1114
+ else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'allowNestedSubagents'; expected a boolean.`);
1115
+ }
920
1116
 
921
1117
  const extensions = parseOverrideStringArrayOrFalse(input.extensions, { filePath, name, field: "extensions" });
922
1118
  if (extensions !== undefined) override.extensions = extensions;
@@ -924,6 +1120,9 @@ function parseBuiltinOverrideEntry(
924
1120
  const subagentOnlyExtensions = parseOverrideStringArrayOrFalse(input.subagentOnlyExtensions, { filePath, name, field: "subagentOnlyExtensions" });
925
1121
  if (subagentOnlyExtensions !== undefined) override.subagentOnlyExtensions = subagentOnlyExtensions;
926
1122
 
1123
+ const mutationTools = parseOverrideStringArrayOrFalse(input.mutationTools, { filePath, name, field: "mutationTools" });
1124
+ if (mutationTools !== undefined) override.mutationTools = mutationTools;
1125
+
927
1126
  return Object.keys(override).length > 0 ? override : undefined;
928
1127
  }
929
1128
 
@@ -958,6 +1157,14 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
958
1157
  throw new Error(`Subagent settings in '${filePath}' have invalid 'defaultModel'; expected a non-empty string.`);
959
1158
  }
960
1159
  }
1160
+ let defaultProvider: string | undefined;
1161
+ if ("defaultProvider" in subagentsObject) {
1162
+ if (typeof subagentsObject.defaultProvider === "string" && subagentsObject.defaultProvider.trim()) {
1163
+ defaultProvider = subagentsObject.defaultProvider.trim();
1164
+ } else {
1165
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'defaultProvider'; expected a non-empty string.`);
1166
+ }
1167
+ }
961
1168
  let defaultThinking: string | undefined;
962
1169
  if ("defaultThinking" in subagentsObject) {
963
1170
  if (typeof subagentsObject.defaultThinking === "string" && subagentsObject.defaultThinking.trim()) {
@@ -966,6 +1173,14 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
966
1173
  throw new Error(`Subagent settings in '${filePath}' have invalid 'defaultThinking'; expected a non-empty string.`);
967
1174
  }
968
1175
  }
1176
+ let maxThinking: ThinkingLevel | undefined;
1177
+ if ("maxThinking" in subagentsObject) {
1178
+ try {
1179
+ maxThinking = parseThinkingLevel(subagentsObject.maxThinking, `'${filePath}' subagents.maxThinking`);
1180
+ } catch (error) {
1181
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'maxThinking'; expected one of off, minimal, low, medium, high, xhigh, or max.`, { cause: error instanceof Error ? error : undefined });
1182
+ }
1183
+ }
969
1184
  let defaultExtensions: string[] | undefined;
970
1185
  if ("defaultExtensions" in subagentsObject) {
971
1186
  if (!Array.isArray(subagentsObject.defaultExtensions)
@@ -982,49 +1197,104 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
982
1197
  }
983
1198
  injectAgents = subagentsObject.injectAgents.map((item) => item.trim());
984
1199
  }
1200
+ let agentScanDirs: string[] | undefined;
1201
+ if ("agentScanDirs" in subagentsObject) {
1202
+ if (!Array.isArray(subagentsObject.agentScanDirs)
1203
+ || subagentsObject.agentScanDirs.some((item) => typeof item !== "string" || !item.trim())) {
1204
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'agentScanDirs'; expected an array of non-empty strings.`);
1205
+ }
1206
+ agentScanDirs = subagentsObject.agentScanDirs.map((item) => item.trim());
1207
+ }
985
1208
  const modelScope = parseModelScopeConfig(subagentsObject.modelScope, { filePath });
986
1209
 
987
1210
  const parsed: Record<string, BuiltinAgentOverrideConfig> = {};
1211
+ const providerOverrides: Record<string, Record<string, BuiltinAgentOverrideConfig>> = {};
988
1212
  const agentOverrides = subagentsObject.agentOverrides;
1213
+ const agentOverridesByProvider = subagentsObject.agentOverridesByProvider;
989
1214
  const parsedSettings: SubagentSettings = {
990
1215
  overrides: parsed,
1216
+ providerOverrides,
991
1217
  ...(defaultModel !== undefined ? { defaultModel } : {}),
1218
+ ...(defaultProvider !== undefined ? { defaultProvider } : {}),
992
1219
  ...(defaultThinking !== undefined ? { defaultThinking } : {}),
1220
+ ...(maxThinking !== undefined ? { maxThinking } : {}),
993
1221
  ...(defaultExtensions !== undefined ? { defaultExtensions } : {}),
1222
+ ...(agentScanDirs !== undefined ? { agentScanDirs } : {}),
1223
+ ...(injectAgents !== undefined ? { injectAgents } : {}),
994
1224
  ...(disableBuiltins !== undefined ? { disableBuiltins } : {}),
995
1225
  ...(disableThinking !== undefined ? { disableThinking } : {}),
996
1226
  ...(modelScope !== undefined ? { modelScope } : {}),
997
1227
  ...(injectAgents !== undefined ? { injectAgents } : {}),
998
1228
  };
999
- if (!agentOverrides || typeof agentOverrides !== "object" || Array.isArray(agentOverrides)) {
1000
- return parsedSettings;
1229
+ if (agentOverrides && typeof agentOverrides === "object" && !Array.isArray(agentOverrides)) {
1230
+ for (const [name, value] of Object.entries(agentOverrides)) {
1231
+ const override = parseBuiltinOverrideEntry(name, value, filePath);
1232
+ if (override) parsed[name] = override;
1233
+ }
1001
1234
  }
1002
- for (const [name, value] of Object.entries(agentOverrides)) {
1003
- const override = parseBuiltinOverrideEntry(name, value, filePath);
1004
- if (override) parsed[name] = override;
1235
+ if (agentOverridesByProvider !== undefined) {
1236
+ if (!agentOverridesByProvider || typeof agentOverridesByProvider !== "object" || Array.isArray(agentOverridesByProvider)) {
1237
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'agentOverridesByProvider'; expected an object keyed by provider.`);
1238
+ }
1239
+ for (const [provider, value] of Object.entries(agentOverridesByProvider)) {
1240
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1241
+ throw new Error(`Subagent settings in '${filePath}' have invalid 'agentOverridesByProvider.${provider}'; expected an object keyed by agent.`);
1242
+ }
1243
+ const entries: Record<string, BuiltinAgentOverrideConfig> = {};
1244
+ for (const [agentName, agentValue] of Object.entries(value)) {
1245
+ const override = parseBuiltinOverrideEntry(`agentOverridesByProvider.${provider}.${agentName}`, agentValue, filePath);
1246
+ if (override) entries[agentName] = override;
1247
+ }
1248
+ providerOverrides[provider] = entries;
1249
+ }
1005
1250
  }
1006
1251
  return parsedSettings;
1007
1252
  }
1008
1253
 
1254
+ function selectProviderOverrides(settings: SubagentSettings, provider: string | undefined): SubagentSettings {
1255
+ if (!provider) return settings;
1256
+ const selected = settings.providerOverrides[provider];
1257
+ if (!selected) return settings;
1258
+ const overrides = { ...settings.overrides };
1259
+ for (const [name, override] of Object.entries(selected)) {
1260
+ overrides[name] = { ...overrides[name], ...override };
1261
+ }
1262
+ return { ...settings, overrides };
1263
+ }
1264
+
1265
+ function resolveSubagentDefaultProvider(
1266
+ userSettings: SubagentSettings,
1267
+ projectSettings: SubagentSettings,
1268
+ projectSettingsPath: string | null,
1269
+ ): string | undefined {
1270
+ if (projectSettingsPath && projectSettings.defaultProvider !== undefined) return projectSettings.defaultProvider;
1271
+ return userSettings.defaultProvider;
1272
+ }
1273
+
1009
1274
  function resolveSubagentDefaultModel(
1010
1275
  userSettings: SubagentSettings,
1011
1276
  projectSettings: SubagentSettings,
1012
1277
  userSettingsPath: string,
1013
1278
  projectSettingsPath: string | null,
1279
+ defaultProvider: string | undefined,
1014
1280
  ): AgentModelSourceInfo | undefined {
1015
1281
  if (projectSettingsPath && projectSettings.defaultModel !== undefined) {
1016
- return { type: "subagents.defaultModel", scope: "project", path: projectSettingsPath, model: projectSettings.defaultModel };
1282
+ return { type: "subagents.defaultModel", scope: "project", path: projectSettingsPath, model: projectSettings.defaultModel, ...(defaultProvider ? { defaultProvider } : {}) };
1017
1283
  }
1018
1284
  return userSettings.defaultModel !== undefined
1019
- ? { type: "subagents.defaultModel", scope: "user", path: userSettingsPath, model: userSettings.defaultModel }
1285
+ ? { type: "subagents.defaultModel", scope: "user", path: userSettingsPath, model: userSettings.defaultModel, ...(defaultProvider ? { defaultProvider } : {}) }
1020
1286
  : undefined;
1021
1287
  }
1022
1288
 
1023
- function applySubagentDefaultModel(agents: AgentConfig[], defaultModel: AgentModelSourceInfo | undefined): AgentConfig[] {
1024
- if (!defaultModel) return agents;
1289
+ function applySubagentDefaultModel(agents: AgentConfig[], defaultModel: AgentModelSourceInfo | undefined, defaultProvider: string | undefined): AgentConfig[] {
1290
+ if (!defaultModel && !defaultProvider) return agents;
1025
1291
  return agents.map((agent) => {
1026
- if (agent.model !== undefined) return agent;
1027
- const next = { ...agent, model: defaultModel.model, modelSource: defaultModel };
1292
+ if (agent.model !== undefined && (agent.modelProvider !== undefined || !defaultProvider)) return agent;
1293
+ const next = {
1294
+ ...agent,
1295
+ ...(agent.model === undefined && defaultModel ? { model: defaultModel.model, modelSource: defaultModel } : {}),
1296
+ ...(defaultProvider ? { modelProvider: defaultProvider } : {}),
1297
+ };
1028
1298
  const frontmatterFields = agentFrontmatterFields.get(agent);
1029
1299
  if (frontmatterFields) agentFrontmatterFields.set(next, frontmatterFields);
1030
1300
  return next;
@@ -1051,6 +1321,20 @@ function applySubagentDefaultThinking(agents: AgentConfig[], defaultThinking: st
1051
1321
  });
1052
1322
  }
1053
1323
 
1324
+ function resolveSubagentMaxThinking(
1325
+ userSettings: SubagentSettings,
1326
+ projectSettings: SubagentSettings,
1327
+ projectSettingsPath: string | null,
1328
+ ): ThinkingLevel | undefined {
1329
+ if (projectSettingsPath && projectSettings.maxThinking !== undefined) return projectSettings.maxThinking;
1330
+ return userSettings.maxThinking;
1331
+ }
1332
+
1333
+ function applySubagentMaxThinking(agents: AgentConfig[], maxThinking: ThinkingLevel | undefined): AgentConfig[] {
1334
+ if (maxThinking === undefined) return agents;
1335
+ return agents.map((agent) => agent.maxThinking === maxThinking ? agent : { ...agent, maxThinking });
1336
+ }
1337
+
1054
1338
  function resolveSubagentDefaultExtensions(
1055
1339
  userSettings: SubagentSettings,
1056
1340
  projectSettings: SubagentSettings,
@@ -1074,11 +1358,12 @@ function applySubagentDefaultExtensions(agents: AgentConfig[], defaultExtensions
1074
1358
  function applySubagentDefaults(
1075
1359
  agents: AgentConfig[],
1076
1360
  defaultModel: AgentModelSourceInfo | undefined,
1361
+ defaultProvider: string | undefined,
1077
1362
  defaultThinking: string | undefined,
1078
1363
  defaultExtensions: string[] | undefined,
1079
1364
  ): AgentConfig[] {
1080
1365
  return applySubagentDefaultExtensions(
1081
- applySubagentDefaultThinking(applySubagentDefaultModel(agents, defaultModel), defaultThinking),
1366
+ applySubagentDefaultThinking(applySubagentDefaultModel(agents, defaultModel, defaultProvider), defaultThinking),
1082
1367
  defaultExtensions,
1083
1368
  );
1084
1369
  }
@@ -1099,21 +1384,39 @@ function applyBuiltinOverride(
1099
1384
  override: BuiltinAgentOverrideConfig,
1100
1385
  meta: { scope: "user" | "project"; path: string },
1101
1386
  ): AgentConfig {
1387
+ const overrideInfo: BuiltinAgentOverrideInfo = {
1388
+ ...meta,
1389
+ base: agent.override?.base ?? cloneOverrideBase(agent),
1390
+ fields: [...new Set([...(agent.override?.fields ?? []), ...Object.keys(override)])].sort(),
1391
+ fieldScopes: Object.fromEntries(Object.entries({ ...(agent.override?.fieldScopes ?? {}) }).map(([field, scopes]) => [field, [...scopes]])),
1392
+ };
1393
+ for (const field of Object.keys(override)) {
1394
+ const scopes = overrideInfo.fieldScopes![field] ?? [];
1395
+ overrideInfo.fieldScopes![field] = [...new Set([...scopes, meta.scope])].sort();
1396
+ }
1102
1397
  const next: AgentConfig = {
1103
1398
  ...agent,
1104
- override: { ...meta, base: cloneOverrideBase(agent) },
1399
+ override: overrideInfo,
1105
1400
  };
1106
1401
 
1107
1402
  if (override.description !== undefined) next.description = override.description;
1403
+ if (override.output !== undefined) { if (override.output === false) delete next.output; else next.output = override.output; }
1108
1404
  if (override.outputMode !== undefined) next.outputMode = override.outputMode;
1405
+ if (override.defaultReads !== undefined) { if (override.defaultReads === false) delete next.defaultReads; else next.defaultReads = [...override.defaultReads]; }
1109
1406
  if (override.model !== undefined) {
1110
1407
  if (override.model === false) delete next.model; else next.model = override.model;
1111
1408
  delete next.modelSource;
1112
1409
  }
1410
+ if (override.defaultProvider !== undefined) {
1411
+ if (override.defaultProvider === false) delete next.modelProvider;
1412
+ else next.modelProvider = override.defaultProvider;
1413
+ }
1113
1414
  if (override.fallbackModels !== undefined) { if (override.fallbackModels === false) delete next.fallbackModels; else next.fallbackModels = [...override.fallbackModels]; }
1415
+ if (override.fast !== undefined) next.fast = override.fast;
1114
1416
  if (override.thinking !== undefined) { if (override.thinking === false) delete next.thinking; else next.thinking = override.thinking; }
1115
1417
  if (override.systemPromptMode !== undefined) next.systemPromptMode = override.systemPromptMode;
1116
1418
  if (override.inheritProjectContext !== undefined) next.inheritProjectContext = override.inheritProjectContext;
1419
+ if (override.inheritGlobalContext !== undefined) next.inheritGlobalContext = override.inheritGlobalContext;
1117
1420
  if (override.inheritSkills !== undefined) next.inheritSkills = override.inheritSkills;
1118
1421
  if (override.defaultContext !== undefined) { if (override.defaultContext === false) delete next.defaultContext; else next.defaultContext = override.defaultContext; }
1119
1422
  if (override.acceptanceRole !== undefined) { if (override.acceptanceRole === false) delete next.acceptanceRole; else next.acceptanceRole = override.acceptanceRole; }
@@ -1121,8 +1424,11 @@ function applyBuiltinOverride(
1121
1424
  if (override.systemPrompt !== undefined) next.systemPrompt = override.systemPrompt;
1122
1425
  if (override.skills !== undefined) { if (override.skills === false) delete next.skills; else next.skills = [...override.skills]; }
1123
1426
  if (override.tools !== undefined) applyToolsOverride(next, override.tools);
1427
+ if (override.excludeTools !== undefined) { if (override.excludeTools === false) delete next.excludeTools; else next.excludeTools = [...override.excludeTools]; }
1428
+ if (override.allowNestedSubagents !== undefined) next.allowNestedSubagents = override.allowNestedSubagents;
1124
1429
  if (override.extensions !== undefined) { if (override.extensions === false) delete next.extensions; else next.extensions = [...override.extensions]; }
1125
1430
  if (override.subagentOnlyExtensions !== undefined) { if (override.subagentOnlyExtensions === false) delete next.subagentOnlyExtensions; else next.subagentOnlyExtensions = [...override.subagentOnlyExtensions]; }
1431
+ if (override.mutationTools !== undefined) { if (override.mutationTools === false) delete next.mutationTools; else next.mutationTools = [...override.mutationTools]; }
1126
1432
  if (override.completionGuard !== undefined) next.completionGuard = override.completionGuard;
1127
1433
  if (override.toolBudget !== undefined) { if (override.toolBudget === false) delete next.toolBudget; else next.toolBudget = override.toolBudget; }
1128
1434
 
@@ -1190,103 +1496,12 @@ function applyBuiltinOverrides(
1190
1496
  });
1191
1497
  }
1192
1498
 
1193
- export function agentHasFrontmatterField(agent: AgentConfig, ...fields: string[]): boolean {
1194
- const frontmatterFields = agentFrontmatterFields.get(agent);
1195
- return frontmatterFields ? fields.some((field) => frontmatterFields.has(field)) : false;
1196
- }
1197
-
1198
1499
  function applyCustomAgentOverride(
1199
1500
  agent: AgentConfig,
1200
1501
  override: BuiltinAgentOverrideConfig,
1201
1502
  meta: { scope: "user" | "project"; path: string },
1202
1503
  ): AgentConfig {
1203
- let next: AgentConfig | undefined;
1204
- let anyFilled = false;
1205
-
1206
- const mutable = (): AgentConfig => {
1207
- next ??= { ...agent };
1208
- return next;
1209
- };
1210
-
1211
- const fill = <K extends keyof AgentConfig>(
1212
- field: K,
1213
- frontmatterFields: string[],
1214
- value: AgentConfig[K],
1215
- ): void => {
1216
- if (agentHasFrontmatterField(agent, ...frontmatterFields)) return;
1217
- const target = mutable();
1218
- if (value === undefined) delete target[field]; else target[field] = value;
1219
- anyFilled = true;
1220
- };
1221
-
1222
- if (override.description !== undefined) {
1223
- mutable().description = override.description;
1224
- anyFilled = true;
1225
- }
1226
- if (override.outputMode !== undefined) {
1227
- fill("outputMode", ["outputMode"], override.outputMode);
1228
- }
1229
- if (override.model !== undefined && !agentHasFrontmatterField(agent, "model")) {
1230
- const target = mutable();
1231
- if (override.model === false) delete target.model; else target.model = override.model;
1232
- delete target.modelSource;
1233
- anyFilled = true;
1234
- }
1235
- if (override.fallbackModels !== undefined) {
1236
- fill(
1237
- "fallbackModels",
1238
- ["fallbackModels"],
1239
- override.fallbackModels === false ? undefined : [...override.fallbackModels],
1240
- );
1241
- }
1242
- if (override.thinking !== undefined) {
1243
- fill("thinking", ["thinking"], override.thinking === false ? undefined : override.thinking);
1244
- }
1245
- if (override.systemPromptMode !== undefined) {
1246
- fill("systemPromptMode", ["systemPromptMode"], override.systemPromptMode);
1247
- }
1248
- if (override.inheritProjectContext !== undefined) {
1249
- fill("inheritProjectContext", ["inheritProjectContext"], override.inheritProjectContext);
1250
- }
1251
- if (override.inheritSkills !== undefined) {
1252
- fill("inheritSkills", ["inheritSkills"], override.inheritSkills);
1253
- }
1254
- if (override.defaultContext !== undefined) {
1255
- fill("defaultContext", ["defaultContext"], override.defaultContext === false ? undefined : override.defaultContext);
1256
- }
1257
- if (override.acceptanceRole !== undefined) {
1258
- fill("acceptanceRole", ["acceptanceRole"], override.acceptanceRole === false ? undefined : override.acceptanceRole);
1259
- }
1260
- if (override.disabled !== undefined && agent.disabled === undefined) {
1261
- mutable().disabled = override.disabled;
1262
- anyFilled = true;
1263
- }
1264
- if (override.skills !== undefined) {
1265
- fill("skills", ["skill", "skills"], override.skills === false ? undefined : [...override.skills]);
1266
- }
1267
- if (override.tools !== undefined && !agentHasFrontmatterField(agent, "tools")) {
1268
- applyToolsOverride(mutable(), override.tools);
1269
- anyFilled = true;
1270
- }
1271
- if (override.extensions !== undefined) {
1272
- fill("extensions", ["extensions"], override.extensions === false ? undefined : [...override.extensions]);
1273
- }
1274
- if (override.subagentOnlyExtensions !== undefined) {
1275
- fill(
1276
- "subagentOnlyExtensions",
1277
- ["subagentOnlyExtensions"],
1278
- override.subagentOnlyExtensions === false ? undefined : [...override.subagentOnlyExtensions],
1279
- );
1280
- }
1281
- if (override.completionGuard !== undefined) {
1282
- fill("completionGuard", ["completionGuard"], override.completionGuard);
1283
- }
1284
- if (override.toolBudget !== undefined) {
1285
- fill("toolBudget", ["toolBudget"], override.toolBudget === false ? undefined : override.toolBudget);
1286
- }
1287
-
1288
- if (!anyFilled || !next) return agent;
1289
- next.override = { ...meta, base: cloneOverrideBase(agent) };
1504
+ const next = applyBuiltinOverride(agent, override, meta);
1290
1505
  const frontmatterFields = agentFrontmatterFields.get(agent);
1291
1506
  if (frontmatterFields) agentFrontmatterFields.set(next, frontmatterFields);
1292
1507
  return next;
@@ -1299,24 +1514,25 @@ function applyCustomAgentOverrides(
1299
1514
  userSettingsPath: string,
1300
1515
  projectSettingsPath: string | null,
1301
1516
  ): AgentConfig[] {
1517
+ // Apply user then project so project fields win without dropping user-only fields.
1302
1518
  return agents.map((agent) => {
1519
+ const userOverride = userSettings.overrides[agent.name];
1520
+ const withUserOverride = userOverride
1521
+ ? applyCustomAgentOverride(agent, userOverride, { scope: "user", path: userSettingsPath })
1522
+ : agent;
1523
+
1303
1524
  const projectOverride = projectSettings.overrides[agent.name];
1304
1525
  if (projectOverride && projectSettingsPath) {
1305
- return applyCustomAgentOverride(agent, projectOverride, { scope: "project", path: projectSettingsPath });
1526
+ return applyCustomAgentOverride(withUserOverride, projectOverride, { scope: "project", path: projectSettingsPath });
1306
1527
  }
1307
1528
 
1308
- const userOverride = userSettings.overrides[agent.name];
1309
- if (userOverride) {
1310
- return applyCustomAgentOverride(agent, userOverride, { scope: "user", path: userSettingsPath });
1311
- }
1312
-
1313
- return agent;
1529
+ return withUserOverride;
1314
1530
  });
1315
1531
  }
1316
1532
 
1317
1533
  export function buildBuiltinOverrideConfig(
1318
1534
  base: BuiltinAgentOverrideBase,
1319
- draft: Pick<AgentConfig, "model" | "fallbackModels" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "completionGuard" | "toolBudget"> & Partial<Pick<AgentConfig, "description" | "outputMode">>,
1535
+ draft: Pick<AgentConfig, "model" | "modelProvider" | "fallbackModels" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "allowNestedSubagents" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "mutationTools" | "completionGuard" | "toolBudget"> & Partial<Pick<AgentConfig, "description" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
1320
1536
  ): BuiltinAgentOverrideConfig | undefined {
1321
1537
  const override: BuiltinAgentOverrideConfig = {};
1322
1538
 
@@ -1324,12 +1540,17 @@ export function buildBuiltinOverrideConfig(
1324
1540
  const description = draft.description.trim();
1325
1541
  if (description && description !== base.description) override.description = description;
1326
1542
  }
1543
+ if (draft.output !== base.output) override.output = draft.output ?? false;
1327
1544
  if (draft.outputMode !== undefined && draft.outputMode !== base.outputMode) override.outputMode = draft.outputMode;
1545
+ if (!arraysEqual(draft.defaultReads, base.defaultReads)) override.defaultReads = draft.defaultReads ? [...draft.defaultReads] : false;
1328
1546
  if (draft.model !== base.model) override.model = draft.model ?? false;
1547
+ if (draft.modelProvider !== base.modelProvider) override.defaultProvider = draft.modelProvider ?? false;
1329
1548
  if (!arraysEqual(draft.fallbackModels, base.fallbackModels)) override.fallbackModels = draft.fallbackModels ? [...draft.fallbackModels] : false;
1549
+ if (draft.fast !== base.fast) override.fast = draft.fast === true;
1330
1550
  if (draft.thinking !== base.thinking) override.thinking = draft.thinking ?? false;
1331
1551
  if (draft.systemPromptMode !== base.systemPromptMode) override.systemPromptMode = draft.systemPromptMode;
1332
1552
  if (draft.inheritProjectContext !== base.inheritProjectContext) override.inheritProjectContext = draft.inheritProjectContext;
1553
+ if (draft.inheritGlobalContext !== base.inheritGlobalContext) override.inheritGlobalContext = draft.inheritGlobalContext;
1333
1554
  if (draft.inheritSkills !== base.inheritSkills) override.inheritSkills = draft.inheritSkills;
1334
1555
  if (draft.defaultContext !== base.defaultContext) override.defaultContext = draft.defaultContext ?? false;
1335
1556
  if (draft.acceptanceRole !== base.acceptanceRole) override.acceptanceRole = draft.acceptanceRole ?? false;
@@ -1340,10 +1561,13 @@ export function buildBuiltinOverrideConfig(
1340
1561
  const baseTools = joinToolList(base);
1341
1562
  const draftTools = joinToolList(draft);
1342
1563
  if (!arraysEqual(draftTools, baseTools)) override.tools = draftTools ? [...draftTools] : false;
1564
+ if (!arraysEqual(draft.excludeTools, base.excludeTools)) override.excludeTools = draft.excludeTools ? [...draft.excludeTools] : false;
1565
+ if (draft.allowNestedSubagents !== base.allowNestedSubagents) override.allowNestedSubagents = draft.allowNestedSubagents === true;
1343
1566
  if (!arraysEqual(draft.extensions, base.extensions)) override.extensions = draft.extensions ? [...draft.extensions] : false;
1344
1567
  if (!arraysEqual(draft.subagentOnlyExtensions, base.subagentOnlyExtensions)) {
1345
1568
  override.subagentOnlyExtensions = draft.subagentOnlyExtensions ? [...draft.subagentOnlyExtensions] : false;
1346
1569
  }
1570
+ if (!arraysEqual(draft.mutationTools, base.mutationTools)) override.mutationTools = draft.mutationTools ? [...draft.mutationTools] : false;
1347
1571
  if ((draft.completionGuard !== false) !== (base.completionGuard !== false)) {
1348
1572
  override.completionGuard = draft.completionGuard !== false;
1349
1573
  }
@@ -1473,7 +1697,7 @@ export function removeBuiltinAgentOverrideFields(
1473
1697
  return { path: filePath, removed: true };
1474
1698
  }
1475
1699
 
1476
- const DISCOVERY_PRUNED_DIR_NAMES = new Set([".git", "node_modules"]);
1700
+ const DISCOVERY_PRUNED_DIR_NAMES = new Set([".git", "node_modules", ".pi", "sync-backups"]);
1477
1701
 
1478
1702
  function isDiscoveryNestedProjectRoot(dir: string): boolean {
1479
1703
  return isDirectory(getProjectConfigDir(dir)) || isDirectory(path.join(dir, ".agents"));
@@ -1485,9 +1709,24 @@ function shouldPruneDiscoveryDir(rootDir: string, dir: string, dirName: string):
1485
1709
  return path.resolve(dir) !== path.resolve(rootDir) && isDiscoveryNestedProjectRoot(dir);
1486
1710
  }
1487
1711
 
1488
- function listFilesRecursive(dir: string, predicate: (fileName: string) => boolean, rootDir = dir): string[] {
1712
+ function listFilesRecursive(
1713
+ dir: string,
1714
+ predicate: (fileName: string) => boolean,
1715
+ rootDir = dir,
1716
+ visitedDirectories = new Set<string>(),
1717
+ inspectedDirectories = new Set<string>(),
1718
+ ): string[] {
1489
1719
  const files: string[] = [];
1490
1720
  if (!fs.existsSync(dir)) return files;
1721
+ inspectedDirectories.add(path.resolve(dir));
1722
+ let realDir: string;
1723
+ try {
1724
+ realDir = fs.realpathSync(dir);
1725
+ } catch {
1726
+ return files;
1727
+ }
1728
+ if (visitedDirectories.has(realDir)) return files;
1729
+ visitedDirectories.add(realDir);
1491
1730
 
1492
1731
  let entries: fs.Dirent[];
1493
1732
  try {
@@ -1498,9 +1737,17 @@ function listFilesRecursive(dir: string, predicate: (fileName: string) => boolea
1498
1737
 
1499
1738
  for (const entry of entries) {
1500
1739
  const filePath = path.join(dir, entry.name);
1501
- if (entry.isDirectory()) {
1740
+ let isDirectory = entry.isDirectory();
1741
+ if (entry.isSymbolicLink()) {
1742
+ try {
1743
+ isDirectory = fs.statSync(filePath).isDirectory();
1744
+ } catch {
1745
+ isDirectory = false;
1746
+ }
1747
+ }
1748
+ if (isDirectory) {
1502
1749
  if (!shouldPruneDiscoveryDir(rootDir, filePath, entry.name)) {
1503
- files.push(...listFilesRecursive(filePath, predicate, rootDir));
1750
+ files.push(...listFilesRecursive(filePath, predicate, rootDir, visitedDirectories, inspectedDirectories));
1504
1751
  }
1505
1752
  continue;
1506
1753
  }
@@ -1511,6 +1758,94 @@ function listFilesRecursive(dir: string, predicate: (fileName: string) => boolea
1511
1758
  return files;
1512
1759
  }
1513
1760
 
1761
+ export interface AgentDefinitionInspection {
1762
+ files: string[];
1763
+ state: AgentDefinitionDirectoryState;
1764
+ }
1765
+
1766
+ const agentDefinitionInspectionDirectories = new WeakMap<AgentDefinitionInspection, string[]>();
1767
+
1768
+ function rememberAgentDefinitionInspection(inspection: AgentDefinitionInspection, directories: Iterable<string>): AgentDefinitionInspection {
1769
+ agentDefinitionInspectionDirectories.set(inspection, [...new Set([...directories].map((directory) => path.resolve(directory)))]);
1770
+ return inspection;
1771
+ }
1772
+
1773
+ function inspectedAgentDefinitionDirectories(inspection: AgentDefinitionInspection, root: string): string[] {
1774
+ return agentDefinitionInspectionDirectories.get(inspection) ?? [path.resolve(root)];
1775
+ }
1776
+
1777
+ /** Narrow filesystem seam so unavailable paths can be tested without permissions. */
1778
+ export interface AgentDefinitionInspectionFs {
1779
+ existsSync(filePath: string): boolean;
1780
+ realpathSync?(filePath: string): string;
1781
+ statSync(filePath: string): { isDirectory(): boolean };
1782
+ readdirSync(dir: string): fs.Dirent[];
1783
+ }
1784
+
1785
+ const DEFAULT_AGENT_DEFINITION_INSPECTION_FS: AgentDefinitionInspectionFs = {
1786
+ existsSync: fs.existsSync,
1787
+ realpathSync: fs.realpathSync,
1788
+ statSync: fs.statSync,
1789
+ readdirSync: (dir) => fs.readdirSync(dir, { withFileTypes: true }),
1790
+ };
1791
+
1792
+ /**
1793
+ * Inspect one agent-definition directory while retaining traversal failure
1794
+ * state. A nested unreadable directory makes the whole inspection unavailable,
1795
+ * preventing a partial traversal from being reported as empty or complete.
1796
+ */
1797
+ export function inspectAgentDefinitionDirectory(dir: string, operations: AgentDefinitionInspectionFs = DEFAULT_AGENT_DEFINITION_INSPECTION_FS): AgentDefinitionInspection {
1798
+ const root = path.resolve(dir);
1799
+ try {
1800
+ if (!operations.existsSync(root)) return rememberAgentDefinitionInspection({ files: [], state: "absent" }, [root]);
1801
+ if (!operations.statSync(root).isDirectory()) return rememberAgentDefinitionInspection({ files: [], state: "not-directory" }, [root]);
1802
+ } catch {
1803
+ return rememberAgentDefinitionInspection({ files: [], state: "unreadable" }, [root]);
1804
+ }
1805
+ const files: string[] = [];
1806
+ let unreadable = false;
1807
+ const visitedDirectories = new Set<string>();
1808
+ const inspectedDirectories = new Set<string>();
1809
+ const visit = (current: string): void => {
1810
+ inspectedDirectories.add(path.resolve(current));
1811
+ let realDir: string;
1812
+ try {
1813
+ realDir = operations.realpathSync?.(current) ?? path.resolve(current);
1814
+ } catch {
1815
+ unreadable = true;
1816
+ return;
1817
+ }
1818
+ if (visitedDirectories.has(realDir)) return;
1819
+ visitedDirectories.add(realDir);
1820
+
1821
+ let entries: fs.Dirent[];
1822
+ try {
1823
+ entries = operations.readdirSync(current).sort((a, b) => a.name.localeCompare(b.name));
1824
+ } catch {
1825
+ unreadable = true;
1826
+ return;
1827
+ }
1828
+ for (const entry of entries) {
1829
+ const filePath = path.join(current, entry.name);
1830
+ let isDirectory = entry.isDirectory();
1831
+ if (entry.isSymbolicLink()) {
1832
+ try {
1833
+ isDirectory = operations.statSync(filePath).isDirectory();
1834
+ } catch {
1835
+ isDirectory = false;
1836
+ }
1837
+ }
1838
+ if (isDirectory) {
1839
+ if (!shouldPruneDiscoveryDir(root, filePath, entry.name)) visit(filePath);
1840
+ continue;
1841
+ }
1842
+ if ((entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith(".md") && !entry.name.endsWith(".chain.md") && !isLegacyAgentSkillPath(root, filePath)) files.push(filePath);
1843
+ }
1844
+ };
1845
+ visit(root);
1846
+ return rememberAgentDefinitionInspection({ files, state: unreadable ? "unreadable" : files.length ? "candidates" : "empty" }, inspectedDirectories);
1847
+ }
1848
+
1514
1849
  function isLegacyAgentSkillPath(rootDir: string, filePath: string): boolean {
1515
1850
  const relative = path.relative(rootDir, filePath);
1516
1851
  const parts = relative.split(path.sep).map((part) => part.toLowerCase());
@@ -1569,24 +1904,29 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
1569
1904
  if (runner.args !== undefined && (!Array.isArray(runner.args) || runner.args.some((arg) => typeof arg !== "string"))) {
1570
1905
  throw new Error(`Agent '${agentName}' external-cli runner args must be an array of strings.`);
1571
1906
  }
1907
+ if (runner.adapter !== undefined && !isCodeOwnedExternalCliAdapterId(runner.adapter)) throw new Error(`Agent '${agentName}' external-cli runner adapter must be ${CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL}.`);
1908
+ if (runner.adapter !== undefined && Array.isArray(runner.args) && runner.args.length > 0) throw new Error(`Agent '${agentName}' ${runner.adapter} adapter owns its argv; runner args are not supported.`);
1572
1909
  if (runner.promptDelivery !== undefined && runner.promptDelivery !== "stdin") {
1573
1910
  throw new Error(`Agent '${agentName}' external-cli runner promptDelivery must be 'stdin'.`);
1574
1911
  }
1575
- const supported = new Set(["type", "command", "args", "promptDelivery"]);
1912
+ const capabilities = parseExternalCliCapabilityNarrowing(runner.capabilities, `Agent '${agentName}' external-cli runner capabilities`);
1913
+ const supported = new Set(["type", "adapter", "command", "args", "promptDelivery", "capabilities"]);
1576
1914
  const unknown = Object.keys(runner).filter((key) => !supported.has(key));
1577
1915
  if (unknown.length > 0) throw new Error(`Agent '${agentName}' external-cli runner has unsupported fields: ${unknown.join(", ")}.`);
1578
1916
  const runnerArgs = Array.isArray(runner.args) ? runner.args.filter((arg): arg is string => typeof arg === "string") : undefined;
1579
1917
  return {
1580
1918
  type: "external-cli",
1919
+ ...(isCodeOwnedExternalCliAdapterId(runner.adapter) ? { adapter: runner.adapter } : {}),
1581
1920
  command: runner.command.trim(),
1582
1921
  ...(runnerArgs?.length ? { args: runnerArgs } : {}),
1583
1922
  ...(runner.promptDelivery ? { promptDelivery: "stdin" as const } : {}),
1923
+ ...(capabilities ? { capabilities } : {}),
1584
1924
  };
1585
1925
  }
1586
1926
 
1587
1927
  function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
1588
1928
  if (runner?.type !== "external-cli" && runner?.type !== "external-job") return;
1589
- const unsupported = ["tools", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "permission", "permissions"]
1929
+ const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "permission", "permissions"]
1590
1930
  .filter((field) => frontmatter[field] !== undefined);
1591
1931
  if (unsupported.length > 0) {
1592
1932
  throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
@@ -1611,9 +1951,9 @@ interface AgentDefinitionFile {
1611
1951
  content: string;
1612
1952
  }
1613
1953
 
1614
- function readAgentDefinitionFiles(dir: string): AgentDefinitionFile[] {
1954
+ function readAgentDefinitionFiles(dir: string, inspection = inspectAgentDefinitionDirectory(dir)): AgentDefinitionFile[] {
1615
1955
  const files: AgentDefinitionFile[] = [];
1616
- for (const filePath of listFilesRecursive(dir, (fileName) => fileName.endsWith(".md") && !fileName.endsWith(".chain.md"))) {
1956
+ for (const filePath of inspection.files) {
1617
1957
  if (isLegacyAgentSkillPath(dir, filePath)) {
1618
1958
  continue;
1619
1959
  }
@@ -1639,7 +1979,7 @@ function resolveAgentRelativeExtensionPaths(paths: string[] | undefined, agentFi
1639
1979
  });
1640
1980
  }
1641
1981
 
1642
- function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: AgentSource, discoveryPriority?: number): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
1982
+ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir" | "scope">): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
1643
1983
  const agents: AgentConfig[] = [];
1644
1984
  const diagnostics: AgentDiscoveryDiagnostic[] = [];
1645
1985
 
@@ -1668,8 +2008,11 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1668
2008
  const parsedTools = splitToolList(rawTools);
1669
2009
  const tools = parsedTools.tools ?? [];
1670
2010
  const mcpDirectTools = parsedTools.mcpDirectTools ?? [];
2011
+ const excludeTools = parseFrontmatterList(frontmatter.excludeTools);
1671
2012
  const defaultReads = parseFrontmatterList(frontmatter.defaultReads);
1672
2013
  const aliases = normalizeAgentAliases(parseFrontmatterList(frontmatter.aliases ?? frontmatter.alias), runtimeName);
2014
+ const profileError = validateCodeOwnedProfileRunner({ name: runtimeName, localName, aliases, runner });
2015
+ if (profileError) throw new Error(profileError);
1673
2016
  const skillStr = frontmatter.skill || frontmatter.skills;
1674
2017
  const skills = parseFrontmatterList(skillStr);
1675
2018
  const skillPath = parseFrontmatterList(frontmatter.skillPath);
@@ -1684,6 +2027,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1684
2027
  : frontmatter.inheritProjectContext === "false"
1685
2028
  ? false
1686
2029
  : defaultInheritProjectContext(localName);
2030
+ const inheritGlobalContext = frontmatter.inheritGlobalContext === "true";
1687
2031
  const inheritSkills = frontmatter.inheritSkills === "true"
1688
2032
  ? true
1689
2033
  : frontmatter.inheritSkills === "false"
@@ -1716,13 +2060,6 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1716
2060
  }
1717
2061
  defaultToolTimeoutMs = parsed;
1718
2062
  }
1719
- let defaultTurnBudget: TurnBudgetConfig | undefined;
1720
- if (frontmatter.turnBudget !== undefined && frontmatter.turnBudget.trim()) {
1721
- const parsed = JSON.parse(frontmatter.turnBudget) as unknown;
1722
- const resolved = resolveTurnBudgetConfig(parsed, `Agent '${localName}' turnBudget frontmatter`);
1723
- if (resolved.error) throw new Error(resolved.error);
1724
- defaultTurnBudget = resolved.turnBudget;
1725
- }
1726
2063
  const defaultAcceptance = parseAgentAcceptanceFrontmatter(frontmatter.acceptance, localName);
1727
2064
  let outputMode: OutputMode | undefined;
1728
2065
  if (frontmatter.outputMode !== undefined) {
@@ -1737,6 +2074,19 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1737
2074
 
1738
2075
  const extensions = resolveAgentRelativeExtensionPaths(parseFrontmatterList(frontmatter.extensions), filePath);
1739
2076
  const subagentOnlyExtensions = resolveAgentRelativeExtensionPaths(parseFrontmatterList(frontmatter.subagentOnlyExtensions), filePath);
2077
+ const mutationTools = parseFrontmatterList(frontmatter.mutationTools);
2078
+ let fast: boolean | undefined;
2079
+ if (frontmatter.fast !== undefined) {
2080
+ if (frontmatter.fast === "true") fast = true;
2081
+ else if (frontmatter.fast === "false") fast = false;
2082
+ else throw new Error(`Agent '${localName}' has invalid fast frontmatter; expected true or false.`);
2083
+ }
2084
+ let allowNestedSubagents: boolean | undefined;
2085
+ if (frontmatter.allowNestedSubagents !== undefined) {
2086
+ if (frontmatter.allowNestedSubagents === "true") allowNestedSubagents = true;
2087
+ else if (frontmatter.allowNestedSubagents === "false") allowNestedSubagents = false;
2088
+ else throw new Error(`Agent '${localName}' has invalid allowNestedSubagents frontmatter; expected true or false.`);
2089
+ }
1740
2090
 
1741
2091
  const extraFields: Record<string, string> = {};
1742
2092
  for (const [key, value] of Object.entries(frontmatter)) {
@@ -1774,21 +2124,27 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1774
2124
  ...(runner !== undefined ? { runner } : {}),
1775
2125
  localName,
1776
2126
  ...(packageName !== undefined ? { packageName } : {}),
2127
+ ...(packageSource?.packageName ? { packageSourceName: packageSource.packageName } : {}),
2128
+ ...(packageSource?.packageVersion ? { packageSourceVersion: packageSource.packageVersion } : {}),
2129
+ ...(packageSource?.packageRoot ? { packageSourceRoot: packageSource.packageRoot } : {}),
1777
2130
  description: frontmatter.description,
1778
2131
  ...(aliases !== undefined ? { aliases } : {}),
1779
2132
  ...(rawTools !== undefined ? { tools } : {}),
2133
+ ...(excludeTools !== undefined ? { excludeTools } : {}),
2134
+ ...(allowNestedSubagents !== undefined ? { allowNestedSubagents } : {}),
1780
2135
  ...(mcpDirectTools.length > 0 ? { mcpDirectTools } : {}),
1781
2136
  ...(frontmatter.model !== undefined ? { model: frontmatter.model } : {}),
1782
2137
  ...(fallbackModels?.length ? { fallbackModels } : {}),
2138
+ ...(fast !== undefined ? { fast } : {}),
1783
2139
  ...(frontmatter.thinking !== undefined ? { thinking: frontmatter.thinking === "false" ? false : frontmatter.thinking } : {}),
1784
2140
  systemPromptMode,
1785
2141
  inheritProjectContext,
2142
+ inheritGlobalContext,
1786
2143
  inheritSkills,
1787
2144
  ...(defaultContext !== undefined ? { defaultContext } : {}),
1788
2145
  ...(defaultAsync !== undefined ? { defaultAsync } : {}),
1789
2146
  ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
1790
2147
  ...(defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs } : {}),
1791
- ...(defaultTurnBudget !== undefined ? { defaultTurnBudget } : {}),
1792
2148
  ...(defaultAcceptance !== undefined ? { defaultAcceptance } : {}),
1793
2149
  ...(acceptanceRole !== undefined ? { acceptanceRole } : {}),
1794
2150
  systemPrompt: body,
@@ -1799,6 +2155,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1799
2155
  ...(skillPath?.length ? { skillPath } : {}),
1800
2156
  ...(extensions !== undefined ? { extensions } : {}),
1801
2157
  ...(subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions } : {}),
2158
+ ...(mutationTools?.length ? { mutationTools } : {}),
1802
2159
  ...(frontmatter.output !== undefined ? { output: frontmatter.output } : {}),
1803
2160
  ...(outputMode !== undefined ? { outputMode } : {}),
1804
2161
  ...(defaultReads?.length ? { defaultReads } : {}),
@@ -1822,15 +2179,26 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
1822
2179
  return { agents, diagnostics };
1823
2180
  }
1824
2181
 
1825
- function loadAgentsFromDir(dir: string, source: AgentSource, discoveryPriority?: number): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
1826
- return loadAgentsFromDefinitionFiles(readAgentDefinitionFiles(dir), source, discoveryPriority);
2182
+ function loadAgentsFromDir(dir: string, source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir" | "scope">, inspection = inspectAgentDefinitionDirectory(dir)): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
2183
+ return loadAgentsFromDefinitionFiles(readAgentDefinitionFiles(dir, inspection), source, discoveryPriority, packageSource);
1827
2184
  }
1828
2185
 
1829
- function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainConfig[]; diagnostics: ChainDiscoveryDiagnostic[] } {
2186
+ function reportAgentDefinitionDirectory(source: AgentSource, dir: string, inspection: AgentDefinitionInspection): AgentDefinitionDirectoryReport {
2187
+ return {
2188
+ source,
2189
+ path: path.resolve(dir),
2190
+ state: inspection.state,
2191
+ ...(inspection.state === "candidates" ? { candidateCount: inspection.files.length } : {}),
2192
+ };
2193
+ }
2194
+
2195
+ function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainConfig[]; diagnostics: ChainDiscoveryDiagnostic[]; files: string[]; directories: string[] } {
1830
2196
  const chains = new Map<string, ChainConfig>();
1831
2197
  const diagnostics: ChainDiscoveryDiagnostic[] = [];
2198
+ const directories = new Set<string>();
2199
+ const files = listFilesRecursive(dir, (fileName) => fileName.endsWith(".chain.md") || fileName.endsWith(".chain.json"), dir, new Set<string>(), directories);
1832
2200
 
1833
- for (const filePath of listFilesRecursive(dir, (fileName) => fileName.endsWith(".chain.md") || fileName.endsWith(".chain.json"))) {
2201
+ for (const filePath of files) {
1834
2202
  let content: string;
1835
2203
  try {
1836
2204
  content = fs.readFileSync(filePath, "utf-8");
@@ -1849,7 +2217,7 @@ function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainCon
1849
2217
  }
1850
2218
  }
1851
2219
 
1852
- return { chains: Array.from(chains.values()), diagnostics };
2220
+ return { chains: Array.from(chains.values()), diagnostics, files, directories: [...directories] };
1853
2221
  }
1854
2222
 
1855
2223
  function isDirectory(p: string): boolean {
@@ -1860,20 +2228,18 @@ function isDirectory(p: string): boolean {
1860
2228
  }
1861
2229
  }
1862
2230
 
1863
- function resolveNearestProjectAgentDirs(cwd: string): { readDirs: string[]; preferredDir: string | null } {
2231
+ function resolveNearestProjectAgentDirs(cwd: string): { readDirs: string[]; candidateDirs: string[]; preferredDir: string | null } {
1864
2232
  const projectRoot = findConfiguredProjectRoot(cwd);
1865
- if (!projectRoot) return { readDirs: [], preferredDir: null };
2233
+ if (!projectRoot) return { readDirs: [], candidateDirs: [], preferredDir: null };
1866
2234
 
1867
2235
  const legacyDir = path.join(projectRoot, ".agents");
1868
2236
  const preferredDir = path.join(getProjectConfigDir(projectRoot), "agents");
2237
+ const candidateDirs = [legacyDir, preferredDir];
1869
2238
  const readDirs: string[] = [];
1870
2239
  if (isDirectory(legacyDir)) readDirs.push(legacyDir);
1871
2240
  if (isDirectory(preferredDir)) readDirs.push(preferredDir);
1872
2241
 
1873
- return {
1874
- readDirs,
1875
- preferredDir,
1876
- };
2242
+ return { readDirs, candidateDirs, preferredDir };
1877
2243
  }
1878
2244
 
1879
2245
  function resolveNearestProjectChainDirs(cwd: string): { readDirs: string[]; preferredDir: string | null } {
@@ -1887,7 +2253,9 @@ function resolveNearestProjectChainDirs(cwd: string): { readDirs: string[]; pref
1887
2253
  };
1888
2254
  }
1889
2255
  const BUILTIN_AGENTS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "agents");
1890
- const BUILTIN_AGENT_DEFINITION_FILES = readAgentDefinitionFiles(BUILTIN_AGENTS_DIR);
2256
+ // Candidate files and inspection state must describe the same cached builtin scan.
2257
+ const BUILTIN_AGENT_DEFINITION_INSPECTION = inspectAgentDefinitionDirectory(BUILTIN_AGENTS_DIR);
2258
+ const BUILTIN_AGENT_DEFINITION_FILES = readAgentDefinitionFiles(BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION);
1891
2259
 
1892
2260
  export const EXTRA_AGENT_DIRS_ENV = "PI_SUBAGENT_EXTRA_AGENT_DIRS";
1893
2261
 
@@ -1905,80 +2273,62 @@ function extraUserAgentDirs(): string[] {
1905
2273
  .filter((dir) => dir.length > 0);
1906
2274
  }
1907
2275
 
1908
- export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryResult {
1909
- const userDirOld = path.join(getAgentDir(), "agents");
1910
- const userDirNew = path.join(os.homedir(), ".agents");
1911
- const { readDirs: projectAgentDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(cwd);
1912
- const userSettingsPath = getUserAgentSettingsPath();
1913
- const projectSettingsPath = getProjectAgentSettingsPath(cwd);
1914
- const userSettings = scope === "project" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(userSettingsPath);
1915
- const projectSettings = scope === "user" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(projectSettingsPath);
1916
- const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath);
1917
- const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
1918
- const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
1919
- const injectAgents = projectSettingsPath && projectSettings.injectAgents !== undefined
1920
- ? projectSettings.injectAgents
1921
- : userSettings.injectAgents;
1922
- const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
1923
- const packageSubagentPaths = collectPackageSubagentPaths(cwd, {
1924
- includeUser: scope !== "project",
1925
- includeProject: scope !== "user",
1926
- });
2276
+ interface AgentScanDirs {
2277
+ dirs: string[];
2278
+ watchPaths: string[];
2279
+ }
1927
2280
 
1928
- const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
1929
- const builtinAgents = applyBuiltinOverrides(
1930
- applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultThinking, defaultExtensions),
1931
- userSettings,
1932
- projectSettings,
1933
- userSettingsPath,
1934
- projectSettingsPath,
1935
- );
2281
+ function readConfiguredAgentScanDirs(filePath: string | null): string[] {
2282
+ if (!filePath) return [];
2283
+ try {
2284
+ const settings = readSettingsFileStrict(filePath);
2285
+ const subagents = settings.subagents;
2286
+ if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return [];
2287
+ const dirs = (subagents as { agentScanDirs?: unknown }).agentScanDirs;
2288
+ return Array.isArray(dirs) ? dirs.filter((dir): dir is string => typeof dir === "string" && dir.trim().length > 0) : [];
2289
+ } catch {
2290
+ return [];
2291
+ }
2292
+ }
1936
2293
 
1937
- const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), userDirOld, userDirNew]
1938
- .map((dir, discoveryPriority) => loadAgentsFromDir(dir, "user", discoveryPriority));
1939
- const userAgents = applyCustomAgentOverrides(
1940
- applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultThinking, defaultExtensions),
1941
- userSettings,
1942
- projectSettings,
1943
- userSettingsPath,
1944
- projectSettingsPath,
1945
- );
2294
+ function expandAgentScanDirPattern(pattern: string): AgentScanDirs {
2295
+ const expanded = expandHomePath(pattern.trim()).replace(/[\\/]+/g, path.sep);
2296
+ if (!expanded) return { dirs: [], watchPaths: [] };
2297
+ const wildcardMatches = [...expanded.matchAll(/\*/g)];
2298
+ if (wildcardMatches.length === 0) {
2299
+ const dir = path.resolve(expanded);
2300
+ return { dirs: fs.existsSync(dir) ? [dir] : [], watchPaths: [dir] };
2301
+ }
2302
+ const parts = expanded.split(path.sep);
2303
+ const wildcardIndex = parts.findIndex((part) => part.includes("*"));
2304
+ if (wildcardMatches.length !== 1 || wildcardIndex === -1 || parts[wildcardIndex] !== "*") return { dirs: [], watchPaths: [] };
2305
+ const base = path.resolve(parts.slice(0, wildcardIndex).join(path.sep) || path.sep);
2306
+ const rest = parts.slice(wildcardIndex + 1);
2307
+ let entries: fs.Dirent[];
2308
+ try {
2309
+ entries = fs.readdirSync(base, { withFileTypes: true });
2310
+ } catch {
2311
+ return { dirs: [], watchPaths: [base] };
2312
+ }
2313
+ const candidateDirs = entries.filter((entry) => entry.isDirectory()).map((entry) => path.join(base, entry.name, ...rest));
2314
+ return {
2315
+ dirs: candidateDirs.filter((dir) => fs.existsSync(dir)),
2316
+ watchPaths: [base, ...candidateDirs],
2317
+ };
2318
+ }
1946
2319
 
1947
- const projectLoaded = scope === "user" ? [] : projectAgentDirs.map((dir) => loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : 0));
1948
- const projectAgents = applyCustomAgentOverrides(
1949
- applySubagentDefaults(projectLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultThinking, defaultExtensions),
1950
- userSettings,
1951
- projectSettings,
1952
- userSettingsPath,
1953
- projectSettingsPath,
1954
- );
1955
- const packageLoaded = packageSubagentPaths.agents.map((dir, index) => loadAgentsFromDir(dir, "package", packageSubagentPaths.agents.length - index));
1956
- const packageMap = new Map<string, AgentConfig>();
1957
- for (const loaded of packageLoaded) {
1958
- for (const agent of loaded.agents) {
1959
- if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
1960
- }
2320
+ function settingsAgentScanDirs(entries: string[]): AgentScanDirs {
2321
+ const dirs = new Set<string>();
2322
+ const watchPaths = new Set<string>();
2323
+ for (const entry of entries) {
2324
+ const expanded = expandAgentScanDirPattern(entry);
2325
+ for (const dir of expanded.dirs) dirs.add(dir);
2326
+ for (const watchPath of expanded.watchPaths) watchPaths.add(watchPath);
1961
2327
  }
1962
- const packageAgents = applyCustomAgentOverrides(
1963
- applySubagentDefaults(Array.from(packageMap.values()), defaultModel, defaultThinking, defaultExtensions),
1964
- userSettings,
1965
- projectSettings,
1966
- userSettingsPath,
1967
- projectSettingsPath,
1968
- );
1969
- const agents = mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents)
1970
- .filter((agent) => agent.disabled !== true);
1971
-
1972
- const agentDiagnostics = [
1973
- ...builtinLoaded.diagnostics,
1974
- ...userLoaded.flatMap((loaded) => loaded.diagnostics),
1975
- ...projectLoaded.flatMap((loaded) => loaded.diagnostics),
1976
- ...packageLoaded.flatMap((loaded) => loaded.diagnostics),
1977
- ];
1978
- return { agents, agentDiagnostics, projectAgentsDir, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}) };
2328
+ return { dirs: [...dirs], watchPaths: [...watchPaths] };
1979
2329
  }
1980
2330
 
1981
- export function discoverAgentsAll(cwd: string): {
2331
+ export interface AgentDiscoveryAllResult {
1982
2332
  builtin: AgentConfig[];
1983
2333
  package: AgentConfig[];
1984
2334
  user: AgentConfig[];
@@ -1993,111 +2343,486 @@ export function discoverAgentsAll(cwd: string): {
1993
2343
  projectChainDir: string | null;
1994
2344
  userSettingsPath: string;
1995
2345
  projectSettingsPath: string | null;
1996
- } {
2346
+ maxThinking?: ThinkingLevel;
2347
+ }
2348
+
2349
+ /**
2350
+ * A single fresh source scan with both projections retained. The effective
2351
+ * projection intentionally remains separate from the all-source projection:
2352
+ * disabled and shadowed definitions are needed for diagnostics and runtime
2353
+ * collision checks even when they are not launchable.
2354
+ */
2355
+ export interface AgentDiscoverySnapshot {
2356
+ effective: AgentDiscoveryResult;
2357
+ all: AgentDiscoveryAllResult;
2358
+ }
2359
+
2360
+ interface LoadedAgentDirectory {
2361
+ dir: string;
2362
+ inspection: AgentDefinitionInspection;
2363
+ loaded: ReturnType<typeof loadAgentsFromDir>;
2364
+ packageEntry?: PackageSubagentPath;
2365
+ }
2366
+
2367
+ interface AgentDiscoverySources {
2368
+ cwd: string;
2369
+ preferredModelProvider?: string;
2370
+ userDir: string;
2371
+ userDirOld: string;
2372
+ userDirNew: string;
2373
+ userChainDir: string;
2374
+ projectAgentDirs: string[];
2375
+ projectCandidateDirs: string[];
2376
+ projectAgentsDir: string | null;
2377
+ projectChainDirs: string[];
2378
+ projectChainDir: string | null;
2379
+ userSettingsPath: string;
2380
+ projectSettingsPath: string | null;
2381
+ userSettings?: SubagentSettings;
2382
+ projectSettings?: SubagentSettings;
2383
+ packageSubagentPaths: PackageSubagentPaths;
2384
+ builtinLoaded: ReturnType<typeof loadAgentsFromDefinitionFiles>;
2385
+ userLoaded: LoadedAgentDirectory[];
2386
+ projectLoaded: LoadedAgentDirectory[];
2387
+ projectInspections: Map<string, AgentDefinitionInspection>;
2388
+ packageLoaded: LoadedAgentDirectory[];
2389
+ userChains?: ReturnType<typeof loadChainsFromDir>;
2390
+ projectChainLoaded?: Array<{ dir: string; loaded: ReturnType<typeof loadChainsFromDir> }>;
2391
+ packageChainLoaded?: Array<{ entry: PackageChainPath; loaded: ReturnType<typeof loadChainsFromDir> }>;
2392
+ watchPaths: string[];
2393
+ }
2394
+
2395
+ interface AgentDiscoveryCacheEntry {
2396
+ sources: AgentDiscoverySources;
2397
+ fingerprint: string;
2398
+ }
2399
+
2400
+ const agentDiscoveryCache = new Map<string, AgentDiscoveryCacheEntry>();
2401
+
2402
+ function isPathWithin(root: string, candidate: string): boolean {
2403
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
2404
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
2405
+ }
2406
+
2407
+ function addDirectoryWatchPaths(paths: Set<string>, root: string, files: readonly string[], directories: readonly string[] = []): void {
2408
+ const resolvedRoot = path.resolve(root);
2409
+ paths.add(resolvedRoot);
2410
+ // The initial recursive inspection is already bounded to this discovery
2411
+ // root. Keep every visited directory in the fingerprint so a file added to
2412
+ // an existing empty nested directory invalidates the snapshot too.
2413
+ for (const directory of directories) {
2414
+ if (isPathWithin(resolvedRoot, directory)) paths.add(path.resolve(directory));
2415
+ }
2416
+ for (const file of files) {
2417
+ paths.add(path.resolve(file));
2418
+ let current = path.resolve(path.dirname(file));
2419
+ while (isPathWithin(resolvedRoot, current)) {
2420
+ paths.add(current);
2421
+ if (current === resolvedRoot) break;
2422
+ current = path.dirname(current);
2423
+ }
2424
+ }
2425
+ }
2426
+
2427
+ function watchPathSignature(filePath: string): string {
2428
+ try {
2429
+ const stat = fs.statSync(filePath);
2430
+ if (stat.isDirectory()) {
2431
+ const entries = fs.readdirSync(filePath, { withFileTypes: true })
2432
+ .sort((left, right) => left.name.localeCompare(right.name))
2433
+ .map((entry) => `${entry.name}:${entry.isDirectory() ? "d" : entry.isSymbolicLink() ? "l" : "f"}`)
2434
+ .join("|");
2435
+ return `directory:${entries}`;
2436
+ }
2437
+ return `file:${stat.size}:${stat.mtimeMs}`;
2438
+ } catch {
2439
+ return "missing";
2440
+ }
2441
+ }
2442
+
2443
+ function discoveryFingerprint(paths: readonly string[]): string {
2444
+ return [...new Set(paths)]
2445
+ .sort((left, right) => left.localeCompare(right))
2446
+ .map((filePath) => `${filePath}:${watchPathSignature(filePath)}`)
2447
+ .join("\n");
2448
+ }
2449
+
2450
+ function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined): string {
2451
+ return JSON.stringify([
2452
+ path.resolve(cwd),
2453
+ preferredModelProvider ?? null,
2454
+ getProjectConfigDir(path.resolve(cwd)),
2455
+ getAgentDir(),
2456
+ os.homedir(),
2457
+ process.env.HOME ?? "",
2458
+ process.env.USERPROFILE ?? "",
2459
+ process.env[EXTRA_AGENT_DIRS_ENV] ?? "",
2460
+ process.env.PI_OFFLINE ?? "",
2461
+ process.env.APPDATA ?? "",
2462
+ ]);
2463
+ }
2464
+
2465
+ function projectDiscoveryWatchPaths(cwd: string): string[] {
2466
+ const paths: string[] = [];
2467
+ let current = path.resolve(cwd);
2468
+ while (true) {
2469
+ paths.push(getProjectConfigDir(current), path.join(current, ".agents"), path.join(current, ".git"));
2470
+ const parent = path.dirname(current);
2471
+ if (parent === current) break;
2472
+ current = parent;
2473
+ }
2474
+ return paths;
2475
+ }
2476
+
2477
+ function packageEntryIncluded(scope: AgentScope, packageScopes: PackageSubagentPath["scope"]): boolean {
2478
+ if (scope === "both" || packageScopes.has("root")) return true;
2479
+ return packageScopes.has(scope);
2480
+ }
2481
+
2482
+ function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string): AgentDiscoverySources {
2483
+ const effectiveCwd = path.resolve(cwd);
1997
2484
  const userDirOld = path.join(getAgentDir(), "agents");
1998
2485
  const userDirNew = path.join(os.homedir(), ".agents");
1999
2486
  const userChainDir = getUserChainDir();
2000
- const { readDirs: projectDirs, preferredDir: projectDir } = resolveNearestProjectAgentDirs(cwd);
2001
- const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(cwd);
2487
+ const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(effectiveCwd);
2488
+ const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(effectiveCwd);
2002
2489
  const userSettingsPath = getUserAgentSettingsPath();
2003
- const projectSettingsPath = getProjectAgentSettingsPath(cwd);
2004
- const userSettings = readSubagentSettings(userSettingsPath);
2005
- const projectSettings = readSubagentSettings(projectSettingsPath);
2006
- const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2007
- const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
2008
- const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
2009
- const injectAgents = projectSettingsPath && projectSettings.injectAgents !== undefined
2010
- ? projectSettings.injectAgents
2011
- : userSettings.injectAgents;
2012
- const packageSubagentPaths = collectPackageSubagentPaths(cwd);
2490
+ const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
2491
+ const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd);
2492
+ const userScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(userSettingsPath));
2493
+ const projectScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(projectSettingsPath));
2013
2494
 
2014
2495
  const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
2015
- const builtin = applyBuiltinOverrides(
2016
- applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultThinking, defaultExtensions),
2017
- userSettings,
2018
- projectSettings,
2496
+ const userLoaded = [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].map((dir, discoveryPriority): LoadedAgentDirectory => {
2497
+ const inspection = inspectAgentDefinitionDirectory(dir);
2498
+ return { dir, inspection, loaded: loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection) };
2499
+ });
2500
+ const projectInspections = new Map(projectCandidateDirs.map((dir) => [dir, inspectAgentDefinitionDirectory(dir)]));
2501
+ const projectLoaded = [...projectScanDirs.dirs, ...projectAgentDirs].map((dir, discoveryPriority): LoadedAgentDirectory => {
2502
+ const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir);
2503
+ return { dir, inspection, loaded: loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection) };
2504
+ });
2505
+ const packageLoaded = packageSubagentPaths.agents.map((entry, index): LoadedAgentDirectory => {
2506
+ const inspection = inspectAgentDefinitionDirectory(entry.dir);
2507
+ return { dir: entry.dir, inspection, packageEntry: entry, loaded: loadAgentsFromDir(entry.dir, "package", packageSubagentPaths.agents.length - index, entry, inspection) };
2508
+ });
2509
+
2510
+ const watchPaths = new Set<string>([
2019
2511
  userSettingsPath,
2020
- projectSettingsPath,
2021
- );
2022
- const userLoaded = [...extraUserAgentDirs(), userDirOld, userDirNew]
2023
- .map((dir, discoveryPriority) => loadAgentsFromDir(dir, "user", discoveryPriority));
2024
- const user = applyCustomAgentOverrides(
2025
- applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultThinking, defaultExtensions),
2026
- userSettings,
2027
- projectSettings,
2512
+ ...(projectSettingsPath ? [projectSettingsPath] : []),
2513
+ ...projectDiscoveryWatchPaths(effectiveCwd),
2514
+ ...findProjectRootCandidates(effectiveCwd).map((root) => path.join(getProjectConfigDir(root), "settings.json")),
2515
+ ...userScanDirs.watchPaths,
2516
+ ...projectScanDirs.watchPaths,
2517
+ ...packageSubagentPaths.watchPaths,
2518
+ ]);
2519
+ for (const directory of userLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
2520
+ for (const dir of projectCandidateDirs) {
2521
+ const inspection = projectInspections.get(dir);
2522
+ addDirectoryWatchPaths(watchPaths, dir, inspection?.files ?? [], inspection ? inspectedAgentDefinitionDirectories(inspection, dir) : []);
2523
+ }
2524
+ for (const directory of projectLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
2525
+ for (const directory of packageLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
2526
+
2527
+ const userDir = process.env.PI_CODING_AGENT_DIR ? userDirOld : fs.existsSync(userDirNew) ? userDirNew : userDirOld;
2528
+ return {
2529
+ cwd: effectiveCwd,
2530
+ ...(preferredModelProvider !== undefined ? { preferredModelProvider } : {}),
2531
+ userDir,
2532
+ userDirOld,
2533
+ userDirNew,
2534
+ userChainDir,
2535
+ projectAgentDirs,
2536
+ projectCandidateDirs,
2537
+ projectAgentsDir,
2538
+ projectChainDirs,
2539
+ projectChainDir,
2028
2540
  userSettingsPath,
2029
2541
  projectSettingsPath,
2030
- );
2031
- const packageMap = new Map<string, AgentConfig>();
2032
- const packageAgentDiagnostics: AgentDiscoveryDiagnostic[] = [];
2033
- for (const [index, dir] of packageSubagentPaths.agents.entries()) {
2034
- const loaded = loadAgentsFromDir(dir, "package", packageSubagentPaths.agents.length - index);
2035
- packageAgentDiagnostics.push(...loaded.diagnostics);
2036
- for (const agent of loaded.agents) {
2037
- if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
2542
+ packageSubagentPaths,
2543
+ builtinLoaded,
2544
+ userLoaded,
2545
+ projectLoaded,
2546
+ projectInspections,
2547
+ packageLoaded,
2548
+ watchPaths: [...watchPaths],
2549
+ };
2550
+ }
2551
+
2552
+ function ensureDiscoveryChains(sources: AgentDiscoverySources): void {
2553
+ if (sources.userChains) return;
2554
+ sources.packageChainLoaded = sources.packageSubagentPaths.chains.map((entry) => ({ entry, loaded: loadChainsFromDir(entry.dir, "package") }));
2555
+ sources.userChains = loadChainsFromDir(sources.userChainDir, "user");
2556
+ sources.projectChainLoaded = sources.projectChainDirs.map((dir) => ({ dir, loaded: loadChainsFromDir(dir, "project") }));
2557
+ const watchPaths = new Set(sources.watchPaths);
2558
+ addDirectoryWatchPaths(watchPaths, sources.userChainDir, sources.userChains.files, sources.userChains.directories);
2559
+ for (const chain of sources.projectChainLoaded) addDirectoryWatchPaths(watchPaths, chain.dir, chain.loaded.files, chain.loaded.directories);
2560
+ for (const chain of sources.packageChainLoaded) addDirectoryWatchPaths(watchPaths, chain.entry.dir, chain.loaded.files, chain.loaded.directories);
2561
+ sources.watchPaths = [...watchPaths];
2562
+ }
2563
+
2564
+ function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false): AgentDiscoverySources {
2565
+ const key = discoveryCacheKey(cwd, preferredModelProvider);
2566
+ const cached = agentDiscoveryCache.get(key);
2567
+ if (cached && cached.fingerprint === discoveryFingerprint(cached.sources.watchPaths)) {
2568
+ if (includeChains) {
2569
+ ensureDiscoveryChains(cached.sources);
2570
+ cached.fingerprint = discoveryFingerprint(cached.sources.watchPaths);
2038
2571
  }
2572
+ return cached.sources;
2039
2573
  }
2040
- const packageAgents = applyCustomAgentOverrides(
2041
- applySubagentDefaults(Array.from(packageMap.values()), defaultModel, defaultThinking, defaultExtensions),
2574
+ const sources = buildAgentDiscoverySources(cwd, preferredModelProvider);
2575
+ const entry = { sources, fingerprint: discoveryFingerprint(sources.watchPaths) };
2576
+ agentDiscoveryCache.set(key, entry);
2577
+ if (includeChains) {
2578
+ ensureDiscoveryChains(sources);
2579
+ entry.fingerprint = discoveryFingerprint(sources.watchPaths);
2580
+ }
2581
+ return sources;
2582
+ }
2583
+
2584
+ /** Clear process-local discovery snapshots, primarily for hosts that reload settings in place. */
2585
+ export function clearAgentDiscoveryCache(): void {
2586
+ agentDiscoveryCache.clear();
2587
+ }
2588
+
2589
+ function ensureSettingsForScope(sources: AgentDiscoverySources, scope: AgentScope, preferredModelProvider?: string): void {
2590
+ if (scope !== "project" && sources.userSettings === undefined) {
2591
+ if (sources.packageSubagentPaths.settingsErrors.user) throw sources.packageSubagentPaths.settingsErrors.user;
2592
+ sources.userSettings = selectProviderOverrides(readSubagentSettings(sources.userSettingsPath), preferredModelProvider);
2593
+ }
2594
+ if (scope !== "user" && sources.projectSettings === undefined) {
2595
+ if (sources.packageSubagentPaths.settingsErrors.project) throw sources.packageSubagentPaths.settingsErrors.project;
2596
+ sources.projectSettings = selectProviderOverrides(readSubagentSettings(sources.projectSettingsPath), preferredModelProvider);
2597
+ }
2598
+ }
2599
+
2600
+ function settingsForScope(sources: AgentDiscoverySources, scope: AgentScope): { user: SubagentSettings; project: SubagentSettings } {
2601
+ // Parse only settings that participate in this projection. The source cache
2602
+ // still retains both source trees, while malformed out-of-scope settings do
2603
+ // not make an otherwise valid scoped projection fail.
2604
+ ensureSettingsForScope(sources, scope, sources.preferredModelProvider);
2605
+ return {
2606
+ user: scope === "project" ? EMPTY_SUBAGENT_SETTINGS : sources.userSettings ?? EMPTY_SUBAGENT_SETTINGS,
2607
+ project: scope === "user" ? EMPTY_SUBAGENT_SETTINGS : sources.projectSettings ?? EMPTY_SUBAGENT_SETTINGS,
2608
+ };
2609
+ }
2610
+
2611
+ function configuredAgentsForScope(sources: AgentDiscoverySources, scope: AgentScope, settingsScope = scope): {
2612
+ builtin: AgentConfig[];
2613
+ package: AgentConfig[];
2614
+ user: AgentConfig[];
2615
+ project: AgentConfig[];
2616
+ userSettings: SubagentSettings;
2617
+ projectSettings: SubagentSettings;
2618
+ maxThinking?: ThinkingLevel;
2619
+ modelScope?: ModelScopeConfig;
2620
+ } {
2621
+ const { user: userSettings, project: projectSettings } = settingsForScope(sources, settingsScope);
2622
+ const defaultProvider = resolveSubagentDefaultProvider(userSettings, projectSettings, sources.projectSettingsPath);
2623
+ const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath, defaultProvider);
2624
+ const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, sources.projectSettingsPath);
2625
+ const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, sources.projectSettingsPath);
2626
+ const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, sources.projectSettingsPath);
2627
+ const applyDefaults = (agents: AgentConfig[]): AgentConfig[] => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions);
2628
+ const builtin = applyBuiltinOverrides(applyDefaults(sources.builtinLoaded.agents), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
2629
+ const user = applyCustomAgentOverrides(
2630
+ applyDefaults(scope === "project" ? [] : sources.userLoaded.flatMap((loaded) => loaded.loaded.agents)),
2042
2631
  userSettings,
2043
2632
  projectSettings,
2044
- userSettingsPath,
2045
- projectSettingsPath,
2633
+ sources.userSettingsPath,
2634
+ sources.projectSettingsPath,
2046
2635
  );
2047
2636
  const projectMap = new Map<string, AgentConfig>();
2048
- const projectAgentDiagnostics: AgentDiscoveryDiagnostic[] = [];
2049
- for (const dir of projectDirs) {
2050
- const loaded = loadAgentsFromDir(dir, "project", dir === projectDir ? 1 : 0);
2051
- projectAgentDiagnostics.push(...loaded.diagnostics);
2052
- for (const agent of loaded.agents) {
2053
- projectMap.set(agent.name, agent);
2054
- }
2637
+ if (scope !== "user") for (const loaded of sources.projectLoaded) for (const agent of loaded.loaded.agents) projectMap.set(agent.name, agent);
2638
+ const project = applyCustomAgentOverrides(applyDefaults(Array.from(projectMap.values())), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
2639
+ const packageMap = new Map<string, AgentConfig>();
2640
+ for (const loaded of sources.packageLoaded) {
2641
+ if (!loaded.packageEntry || !packageEntryIncluded(scope, loaded.packageEntry.scope)) continue;
2642
+ for (const agent of loaded.loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
2055
2643
  }
2056
- const project = applyCustomAgentOverrides(
2057
- applySubagentDefaults(Array.from(projectMap.values()), defaultModel, defaultThinking, defaultExtensions),
2644
+ const packageAgents = applyCustomAgentOverrides(applyDefaults(Array.from(packageMap.values())), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
2645
+ return {
2646
+ builtin,
2647
+ package: packageAgents,
2648
+ user,
2649
+ project,
2058
2650
  userSettings,
2059
2651
  projectSettings,
2060
- userSettingsPath,
2061
- projectSettingsPath,
2652
+ maxThinking,
2653
+ modelScope: projectSettings.modelScope ?? userSettings.modelScope,
2654
+ };
2655
+ }
2656
+
2657
+ function discoveryDirectories(sources: AgentDiscoverySources, scope: AgentScope): AgentDefinitionDirectoryReport[] {
2658
+ const directories: AgentDefinitionDirectoryReport[] = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
2659
+ if (scope !== "project") for (const directory of sources.userLoaded) directories.push(reportAgentDefinitionDirectory("user", directory.dir, directory.inspection));
2660
+ if (scope !== "user") {
2661
+ const reported = new Set<string>();
2662
+ for (const dir of sources.projectCandidateDirs) {
2663
+ reported.add(path.resolve(dir));
2664
+ directories.push(reportAgentDefinitionDirectory("project", dir, sources.projectInspections.get(dir)!));
2665
+ }
2666
+ for (const directory of sources.projectLoaded) {
2667
+ if (!reported.has(path.resolve(directory.dir))) directories.push(reportAgentDefinitionDirectory("project", directory.dir, directory.inspection));
2668
+ }
2669
+ }
2670
+ for (const directory of sources.packageLoaded) {
2671
+ if (directory.packageEntry && packageEntryIncluded(scope, directory.packageEntry.scope)) directories.push(reportAgentDefinitionDirectory("package", directory.dir, directory.inspection));
2672
+ }
2673
+ return directories;
2674
+ }
2675
+
2676
+ function discoveryDiagnostics(sources: AgentDiscoverySources, scope: AgentScope): AgentDiscoveryDiagnostic[] {
2677
+ return [
2678
+ ...sources.builtinLoaded.diagnostics,
2679
+ ...(scope === "project" ? [] : sources.userLoaded.flatMap((loaded) => loaded.loaded.diagnostics)),
2680
+ ...(scope === "user" ? [] : sources.projectLoaded.flatMap((loaded) => loaded.loaded.diagnostics)),
2681
+ ...sources.packageLoaded
2682
+ .filter((loaded) => loaded.packageEntry && packageEntryIncluded(scope, loaded.packageEntry.scope))
2683
+ .flatMap((loaded) => loaded.loaded.diagnostics),
2684
+ ];
2685
+ }
2686
+
2687
+ function buildEffectiveDiscovery(sources: AgentDiscoverySources, scope: AgentScope): AgentDiscoveryResult {
2688
+ const configured = configuredAgentsForScope(sources, scope);
2689
+ const { user: effectiveUserSettings, project: effectiveProjectSettings } = settingsForScope(sources, scope);
2690
+ const injectAgents = effectiveProjectSettings.injectAgents !== undefined
2691
+ ? effectiveProjectSettings.injectAgents
2692
+ : effectiveUserSettings.injectAgents;
2693
+ const agents = applySubagentMaxThinking(
2694
+ mergeAgentsForScope(scope, configured.user, configured.project, configured.builtin, configured.package).filter((agent) => agent.disabled !== true),
2695
+ configured.maxThinking,
2062
2696
  );
2697
+ return {
2698
+ agents,
2699
+ agentDiagnostics: discoveryDiagnostics(sources, scope),
2700
+ projectAgentsDir: sources.projectAgentsDir,
2701
+ cwd: sources.cwd,
2702
+ scope,
2703
+ directories: discoveryDirectories(sources, scope),
2704
+ ...(configured.modelScope !== undefined ? { modelScope: configured.modelScope } : {}),
2705
+ ...(injectAgents?.length ? { injectAgents } : {}),
2706
+ ...(configured.maxThinking !== undefined ? { maxThinking: configured.maxThinking } : {}),
2707
+ };
2708
+ }
2063
2709
 
2064
- const chainMap = new Map<string, ChainConfig>();
2065
- const packageChainDiagnostics: ChainDiscoveryDiagnostic[] = [];
2710
+ function buildAllDiscovery(sources: AgentDiscoverySources, includeChains: boolean, settingsScope: AgentScope): AgentDiscoveryAllResult {
2711
+ if (includeChains) ensureDiscoveryChains(sources);
2712
+ const configured = configuredAgentsForScope(sources, "both", settingsScope);
2713
+ const { user: allUserSettings, project: allProjectSettings } = settingsForScope(sources, settingsScope);
2714
+ const injectAgents = allProjectSettings.injectAgents !== undefined
2715
+ ? allProjectSettings.injectAgents
2716
+ : allUserSettings.injectAgents;
2066
2717
  const packageChainMap = new Map<string, ChainConfig>();
2067
- for (const dir of packageSubagentPaths.chains) {
2068
- const loaded = loadChainsFromDir(dir, "package");
2069
- packageChainDiagnostics.push(...loaded.diagnostics);
2070
- for (const chain of loaded.chains) {
2071
- if (!packageChainMap.has(chain.name)) packageChainMap.set(chain.name, chain);
2072
- }
2718
+ const packageChainDiagnostics: ChainDiscoveryDiagnostic[] = [];
2719
+ for (const chain of sources.packageChainLoaded ?? []) {
2720
+ packageChainDiagnostics.push(...chain.loaded.diagnostics);
2721
+ for (const definition of chain.loaded.chains) if (!packageChainMap.has(definition.name)) packageChainMap.set(definition.name, definition);
2073
2722
  }
2723
+ const projectChainMap = new Map<string, ChainConfig>();
2074
2724
  const projectChainDiagnostics: ChainDiscoveryDiagnostic[] = [];
2075
- for (const dir of projectChainDirs) {
2076
- const loaded = loadChainsFromDir(dir, "project");
2077
- projectChainDiagnostics.push(...loaded.diagnostics);
2078
- for (const chain of loaded.chains) {
2079
- chainMap.set(chain.name, chain);
2080
- }
2725
+ for (const chain of sources.projectChainLoaded ?? []) {
2726
+ projectChainDiagnostics.push(...chain.loaded.diagnostics);
2727
+ for (const definition of chain.loaded.chains) projectChainMap.set(definition.name, definition);
2081
2728
  }
2082
- const userChains = loadChainsFromDir(userChainDir, "user");
2083
2729
  const chains = [
2084
2730
  ...Array.from(packageChainMap.values()),
2085
- ...userChains.chains,
2086
- ...Array.from(chainMap.values()),
2087
- ];
2088
- const chainDiagnostics = [
2089
- ...packageChainDiagnostics,
2090
- ...userChains.diagnostics,
2091
- ...projectChainDiagnostics,
2092
- ];
2093
- const agentDiagnostics = [
2094
- ...builtinLoaded.diagnostics,
2095
- ...userLoaded.flatMap((loaded) => loaded.diagnostics),
2096
- ...packageAgentDiagnostics,
2097
- ...projectAgentDiagnostics,
2731
+ ...(sources.userChains?.chains ?? []),
2732
+ ...Array.from(projectChainMap.values()),
2098
2733
  ];
2734
+ return {
2735
+ builtin: applySubagentMaxThinking(configured.builtin, configured.maxThinking),
2736
+ package: applySubagentMaxThinking(configured.package, configured.maxThinking),
2737
+ user: applySubagentMaxThinking(configured.user, configured.maxThinking),
2738
+ project: applySubagentMaxThinking(configured.project, configured.maxThinking),
2739
+ agentDiagnostics: [
2740
+ ...sources.builtinLoaded.diagnostics,
2741
+ ...sources.userLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
2742
+ ...sources.packageLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
2743
+ ...sources.projectLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
2744
+ ],
2745
+ chains,
2746
+ chainDiagnostics: [...packageChainDiagnostics, ...(sources.userChains?.diagnostics ?? []), ...projectChainDiagnostics],
2747
+ userDir: sources.userDir,
2748
+ projectDir: sources.projectAgentsDir,
2749
+ userChainDir: sources.userChainDir,
2750
+ projectChainDir: sources.projectChainDir,
2751
+ userSettingsPath: sources.userSettingsPath,
2752
+ projectSettingsPath: sources.projectSettingsPath,
2753
+ ...(injectAgents?.length ? { injectAgents } : {}),
2754
+ ...(configured.maxThinking !== undefined ? { maxThinking: configured.maxThinking } : {}),
2755
+ };
2756
+ }
2099
2757
 
2100
- const userDir = process.env.PI_CODING_AGENT_DIR ? userDirOld : fs.existsSync(userDirNew) ? userDirNew : userDirOld;
2758
+ export function discoverAgentSnapshot(
2759
+ cwd: string,
2760
+ scope: AgentScope,
2761
+ preferredModelProvider?: string,
2762
+ options: { includeChains?: boolean } = {},
2763
+ ): AgentDiscoverySnapshot {
2764
+ const includeChains = options.includeChains !== false;
2765
+ const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains);
2766
+ return { effective: buildEffectiveDiscovery(sources, scope), all: buildAllDiscovery(sources, includeChains, scope) };
2767
+ }
2768
+
2769
+ function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelProvider?: string): AgentDiscoveryResult {
2770
+ const effectiveCwd = path.resolve(cwd);
2771
+ const userDirOld = path.join(getAgentDir(), "agents");
2772
+ const userDirNew = path.join(os.homedir(), ".agents");
2773
+ const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(effectiveCwd);
2774
+ const userSettingsPath = getUserAgentSettingsPath();
2775
+ const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
2776
+ const userSettings = selectProviderOverrides(scope === "project" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(userSettingsPath), preferredModelProvider);
2777
+ const projectSettings = selectProviderOverrides(scope === "user" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(projectSettingsPath), preferredModelProvider);
2778
+ const defaultProvider = resolveSubagentDefaultProvider(userSettings, projectSettings, projectSettingsPath);
2779
+ const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath, defaultProvider);
2780
+ const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
2781
+ const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, projectSettingsPath);
2782
+ const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
2783
+ const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
2784
+ const injectAgents = projectSettings.injectAgents !== undefined
2785
+ ? projectSettings.injectAgents
2786
+ : userSettings.injectAgents;
2787
+ const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: scope !== "project", includeProject: scope !== "user" });
2788
+ const directories: AgentDefinitionDirectoryReport[] = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
2789
+ const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
2790
+ const builtinAgents = applyBuiltinOverrides(applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2791
+ const userScanDirs = settingsAgentScanDirs(userSettings.agentScanDirs ?? []);
2792
+ const projectScanDirs = settingsAgentScanDirs(projectSettings.agentScanDirs ?? []);
2793
+ const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].map((dir, discoveryPriority) => {
2794
+ const inspection = inspectAgentDefinitionDirectory(dir);
2795
+ directories.push(reportAgentDefinitionDirectory("user", dir, inspection));
2796
+ return loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection);
2797
+ });
2798
+ const userAgents = applyCustomAgentOverrides(applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2799
+ const projectInspections = scope === "user" ? new Map<string, AgentDefinitionInspection>() : new Map(projectCandidateDirs.map((dir) => [dir, inspectAgentDefinitionDirectory(dir)]));
2800
+ if (scope !== "user") for (const dir of projectCandidateDirs) directories.push(reportAgentDefinitionDirectory("project", dir, projectInspections.get(dir)!));
2801
+ const projectLoaded = scope === "user" ? [] : [...projectScanDirs.dirs, ...projectAgentDirs].map((dir, discoveryPriority) => {
2802
+ const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir);
2803
+ if (!projectInspections.has(dir)) directories.push(reportAgentDefinitionDirectory("project", dir, inspection));
2804
+ return loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection);
2805
+ });
2806
+ const projectAgents = applyCustomAgentOverrides(applySubagentDefaults(projectLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2807
+ const packageLoaded = packageSubagentPaths.agents.map((entry, index) => {
2808
+ const inspection = inspectAgentDefinitionDirectory(entry.dir);
2809
+ directories.push(reportAgentDefinitionDirectory("package", entry.dir, inspection));
2810
+ return loadAgentsFromDir(entry.dir, "package", packageSubagentPaths.agents.length - index, entry, inspection);
2811
+ });
2812
+ const packageMap = new Map<string, AgentConfig>();
2813
+ for (const loaded of packageLoaded) for (const agent of loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
2814
+ const packageAgents = applyCustomAgentOverrides(applySubagentDefaults(Array.from(packageMap.values()), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
2815
+ const agents = applySubagentMaxThinking(mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents).filter((agent) => agent.disabled !== true), maxThinking);
2816
+ const agentDiagnostics = [...builtinLoaded.diagnostics, ...userLoaded.flatMap((loaded) => loaded.diagnostics), ...projectLoaded.flatMap((loaded) => loaded.diagnostics), ...packageLoaded.flatMap((loaded) => loaded.diagnostics)];
2817
+ return { agents, agentDiagnostics, projectAgentsDir, cwd: effectiveCwd, scope, directories, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}), ...(maxThinking !== undefined ? { maxThinking } : {}) };
2818
+ }
2819
+
2820
+ export function discoverAgents(cwd: string, scope: AgentScope, preferredModelProvider?: string): AgentDiscoveryResult {
2821
+ if (scope !== "both") return discoverAgentsUncached(cwd, scope, preferredModelProvider);
2822
+ const sources = getAgentDiscoverySources(cwd, preferredModelProvider);
2823
+ return buildEffectiveDiscovery(sources, scope);
2824
+ }
2101
2825
 
2102
- return { builtin, package: packageAgents, user, project, agentDiagnostics, chains, chainDiagnostics, userDir, projectDir, userChainDir, projectChainDir, userSettingsPath, projectSettingsPath, ...(injectAgents?.length ? { injectAgents } : {}) };
2826
+ export function discoverAgentsAll(cwd: string, preferredModelProvider?: string): AgentDiscoveryAllResult {
2827
+ return discoverAgentSnapshot(cwd, "both", preferredModelProvider).all;
2103
2828
  }