@xzzpig/pi-subagents 0.8.0 → 0.10.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.
- package/CHANGELOG.md +477 -0
- package/README.md +2 -2
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +195 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +384 -115
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +14 -2
- package/src/agents/agents.ts +935 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +42 -21
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +77 -21
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +65 -29
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +7 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +417 -133
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +60 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +204 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +39 -16
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +84 -17
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +718 -1161
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +489 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1223 -402
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +138 -36
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +364 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +366 -0
- package/src/runs/shared/child-tool-plan.ts +632 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +139 -9
- package/src/runs/shared/model-fallback.ts +146 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +99 -77
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +20 -7
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/sandbox-profile-guard.ts +85 -0
- package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +11 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/sandbox-profile.ts +23 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +545 -70
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +217 -82
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1429 -163
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +988 -59
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -935
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
package/src/agents/agents.ts
CHANGED
|
@@ -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
|
|
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,10 +21,10 @@ 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";
|
|
25
26
|
import { parseThinkingLevel, type ThinkingLevel } from "../shared/thinking-ceiling.ts";
|
|
27
|
+
import { validateSandboxProfileName } from "../shared/sandbox-profile.ts";
|
|
26
28
|
|
|
27
29
|
export type AgentScope = "user" | "project" | "both";
|
|
28
30
|
|
|
@@ -61,6 +63,7 @@ export interface BuiltinAgentOverrideBase {
|
|
|
61
63
|
thinking?: string | false;
|
|
62
64
|
systemPromptMode: SystemPromptMode;
|
|
63
65
|
inheritProjectContext: boolean;
|
|
66
|
+
inheritGlobalContext: boolean;
|
|
64
67
|
inheritSkills: boolean;
|
|
65
68
|
defaultContext?: AgentDefaultContext;
|
|
66
69
|
acceptanceRole?: AcceptanceRole;
|
|
@@ -69,11 +72,15 @@ export interface BuiltinAgentOverrideBase {
|
|
|
69
72
|
skills?: string[];
|
|
70
73
|
skillPath?: string[];
|
|
71
74
|
tools?: string[];
|
|
75
|
+
excludeTools?: string[];
|
|
76
|
+
allowNestedSubagents?: boolean;
|
|
72
77
|
mcpDirectTools?: string[];
|
|
73
78
|
extensions?: string[];
|
|
74
79
|
subagentOnlyExtensions?: string[];
|
|
80
|
+
mutationTools?: string[];
|
|
75
81
|
completionGuard?: boolean;
|
|
76
82
|
toolBudget?: ToolBudgetConfig;
|
|
83
|
+
sandbox?: string;
|
|
77
84
|
}
|
|
78
85
|
|
|
79
86
|
interface BuiltinAgentOverrideConfig {
|
|
@@ -88,6 +95,7 @@ interface BuiltinAgentOverrideConfig {
|
|
|
88
95
|
thinking?: string | false;
|
|
89
96
|
systemPromptMode?: SystemPromptMode;
|
|
90
97
|
inheritProjectContext?: boolean;
|
|
98
|
+
inheritGlobalContext?: boolean;
|
|
91
99
|
inheritSkills?: boolean;
|
|
92
100
|
defaultContext?: AgentDefaultContext | false;
|
|
93
101
|
acceptanceRole?: AcceptanceRole | false;
|
|
@@ -95,16 +103,22 @@ interface BuiltinAgentOverrideConfig {
|
|
|
95
103
|
systemPrompt?: string;
|
|
96
104
|
skills?: string[] | false;
|
|
97
105
|
tools?: string[] | false | "inherit";
|
|
106
|
+
excludeTools?: string[] | false;
|
|
107
|
+
allowNestedSubagents?: boolean;
|
|
98
108
|
extensions?: string[] | false;
|
|
99
109
|
subagentOnlyExtensions?: string[] | false;
|
|
110
|
+
mutationTools?: string[] | false;
|
|
100
111
|
completionGuard?: boolean;
|
|
101
112
|
toolBudget?: ToolBudgetConfig | false;
|
|
113
|
+
sandbox?: string;
|
|
102
114
|
}
|
|
103
115
|
|
|
104
116
|
interface BuiltinAgentOverrideInfo {
|
|
105
117
|
scope: "user" | "project";
|
|
106
118
|
path: string;
|
|
107
119
|
base: BuiltinAgentOverrideBase;
|
|
120
|
+
fields?: string[];
|
|
121
|
+
fieldScopes?: Record<string, Array<"user" | "project">>;
|
|
108
122
|
}
|
|
109
123
|
|
|
110
124
|
export interface AgentModelSourceInfo {
|
|
@@ -126,6 +140,8 @@ export interface AgentConfig {
|
|
|
126
140
|
description: string;
|
|
127
141
|
aliases?: string[];
|
|
128
142
|
tools?: string[];
|
|
143
|
+
excludeTools?: string[];
|
|
144
|
+
allowNestedSubagents?: boolean;
|
|
129
145
|
mcpDirectTools?: string[];
|
|
130
146
|
model?: string;
|
|
131
147
|
modelProvider?: string;
|
|
@@ -134,12 +150,12 @@ export interface AgentConfig {
|
|
|
134
150
|
thinking?: string | false;
|
|
135
151
|
systemPromptMode: SystemPromptMode;
|
|
136
152
|
inheritProjectContext: boolean;
|
|
153
|
+
inheritGlobalContext: boolean;
|
|
137
154
|
inheritSkills: boolean;
|
|
138
155
|
defaultContext?: AgentDefaultContext;
|
|
139
156
|
defaultAsync?: boolean;
|
|
140
157
|
defaultTimeoutMs?: number;
|
|
141
158
|
defaultToolTimeoutMs?: number;
|
|
142
|
-
defaultTurnBudget?: TurnBudgetConfig;
|
|
143
159
|
defaultAcceptance?: AcceptanceInput;
|
|
144
160
|
acceptanceRole?: AcceptanceRole;
|
|
145
161
|
systemPrompt: string;
|
|
@@ -151,6 +167,7 @@ export interface AgentConfig {
|
|
|
151
167
|
extensions?: string[];
|
|
152
168
|
extensionsFromDefault?: boolean;
|
|
153
169
|
subagentOnlyExtensions?: string[];
|
|
170
|
+
mutationTools?: string[];
|
|
154
171
|
output?: string;
|
|
155
172
|
outputMode?: OutputMode;
|
|
156
173
|
defaultReads?: string[];
|
|
@@ -160,6 +177,7 @@ export interface AgentConfig {
|
|
|
160
177
|
maxSubagentDepth?: number;
|
|
161
178
|
completionGuard?: boolean;
|
|
162
179
|
toolBudget?: ToolBudgetConfig;
|
|
180
|
+
sandbox?: string;
|
|
163
181
|
permissions?: PermissionRules;
|
|
164
182
|
memory?: AgentMemoryConfig;
|
|
165
183
|
disabled?: boolean;
|
|
@@ -173,6 +191,8 @@ type ProjectRootResolution = "nearest" | "git-root";
|
|
|
173
191
|
|
|
174
192
|
interface SubagentSettings {
|
|
175
193
|
overrides: Record<string, BuiltinAgentOverrideConfig>;
|
|
194
|
+
providerOverrides: Record<string, Record<string, BuiltinAgentOverrideConfig>>;
|
|
195
|
+
agentScanDirs?: string[];
|
|
176
196
|
defaultModel?: string;
|
|
177
197
|
defaultProvider?: string;
|
|
178
198
|
defaultThinking?: string;
|
|
@@ -184,7 +204,7 @@ interface SubagentSettings {
|
|
|
184
204
|
injectAgents?: string[];
|
|
185
205
|
}
|
|
186
206
|
|
|
187
|
-
const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {} };
|
|
207
|
+
const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {}, providerOverrides: {} };
|
|
188
208
|
const agentFrontmatterFields = new WeakMap<AgentConfig, Set<string>>();
|
|
189
209
|
|
|
190
210
|
export interface ChainStepConfig {
|
|
@@ -264,29 +284,101 @@ export function findBlockingAgentDiagnostic(name: string, agent: AgentConfig | r
|
|
|
264
284
|
return !agents.length || (match && agentDefinitionPriority(match) > highestPriority) ? match : undefined;
|
|
265
285
|
}
|
|
266
286
|
|
|
267
|
-
|
|
287
|
+
export type AgentDefinitionDirectoryState = "absent" | "empty" | "candidates" | "unreadable" | "not-directory";
|
|
288
|
+
|
|
289
|
+
/** A definition directory actually inspected during one agent-discovery operation. */
|
|
290
|
+
export interface AgentDefinitionDirectoryReport {
|
|
291
|
+
source: AgentSource;
|
|
292
|
+
path: string;
|
|
293
|
+
state: AgentDefinitionDirectoryState;
|
|
294
|
+
candidateCount?: number;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Filesystem provenance for a failed agent resolution. Context is created from
|
|
299
|
+
* the discovery result that supplied the effective agents; callers must not
|
|
300
|
+
* pair arbitrary agent arrays with these directory reports.
|
|
301
|
+
*/
|
|
302
|
+
export interface UnknownAgentDiagnosticContext {
|
|
303
|
+
cwd: string;
|
|
304
|
+
scope: AgentScope;
|
|
305
|
+
directories: readonly AgentDefinitionDirectoryReport[];
|
|
306
|
+
agents: readonly AgentConfig[];
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export interface AgentDiscoveryResult {
|
|
268
310
|
agents: AgentConfig[];
|
|
269
311
|
agentDiagnostics?: AgentDiscoveryDiagnostic[];
|
|
270
312
|
projectAgentsDir: string | null;
|
|
313
|
+
cwd: string;
|
|
314
|
+
scope: AgentScope;
|
|
315
|
+
directories: readonly AgentDefinitionDirectoryReport[];
|
|
271
316
|
modelScope?: ModelScopeConfig;
|
|
272
317
|
injectAgents?: string[];
|
|
273
318
|
maxThinking?: ThinkingLevel;
|
|
274
319
|
}
|
|
275
320
|
|
|
321
|
+
/** Create formatter input from the exact discovery operation used for resolution. */
|
|
322
|
+
export function unknownAgentDiagnosticContext(discovered: Pick<AgentDiscoveryResult, "cwd" | "scope" | "directories" | "agents">): UnknownAgentDiagnosticContext {
|
|
323
|
+
return {
|
|
324
|
+
cwd: discovered.cwd,
|
|
325
|
+
scope: discovered.scope,
|
|
326
|
+
directories: discovered.directories,
|
|
327
|
+
agents: discovered.agents,
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Render local discovery evidence without exposing filesystem error details. */
|
|
332
|
+
export function formatUnknownAgentError(name: string, context: UnknownAgentDiagnosticContext, prefix = "Unknown agent"): string {
|
|
333
|
+
const directories = context.directories.map((directory) => {
|
|
334
|
+
const state = directory.state === "candidates"
|
|
335
|
+
? `${directory.candidateCount ?? 0} candidate${directory.candidateCount === 1 ? "" : "s"}`
|
|
336
|
+
: directory.state === "empty" ? "present but empty"
|
|
337
|
+
: directory.state === "not-directory" ? "not a directory"
|
|
338
|
+
: directory.state;
|
|
339
|
+
return `- ${directory.source}: ${directory.path} (${state})`;
|
|
340
|
+
});
|
|
341
|
+
const agents = [...context.agents]
|
|
342
|
+
.sort((left, right) => left.name.localeCompare(right.name) || left.source.localeCompare(right.source))
|
|
343
|
+
.map((agent) => `- ${agent.name} (${agent.source})`);
|
|
344
|
+
return [
|
|
345
|
+
`${prefix}: ${name}`,
|
|
346
|
+
`Effective cwd: ${path.resolve(context.cwd)}`,
|
|
347
|
+
"Consulted agent-definition directories:",
|
|
348
|
+
...(directories.length ? directories : ["- (none)"]),
|
|
349
|
+
"Discovered agents:",
|
|
350
|
+
...(agents.length ? agents : ["- (none)"]),
|
|
351
|
+
].join("\n");
|
|
352
|
+
}
|
|
353
|
+
|
|
276
354
|
function getUserChainDir(): string {
|
|
277
355
|
return path.join(getAgentDir(), "chains");
|
|
278
356
|
}
|
|
279
357
|
|
|
358
|
+
type PackageScope = "root" | "user" | "project";
|
|
359
|
+
type PackageSettingsScope = Exclude<PackageScope, "root">;
|
|
360
|
+
|
|
280
361
|
interface PackageSubagentPath {
|
|
281
362
|
dir: string;
|
|
363
|
+
// A package can be reachable from more than one settings scope. Keep the
|
|
364
|
+
// actual memberships instead of promoting a mixed-scope path to root.
|
|
365
|
+
scope: Set<PackageScope>;
|
|
282
366
|
packageName?: string;
|
|
283
367
|
packageVersion?: string;
|
|
284
368
|
packageRoot: string;
|
|
285
369
|
}
|
|
286
370
|
|
|
371
|
+
interface PackageChainPath {
|
|
372
|
+
dir: string;
|
|
373
|
+
scope: Set<PackageScope>;
|
|
374
|
+
packageRoot: string;
|
|
375
|
+
}
|
|
376
|
+
|
|
287
377
|
interface PackageSubagentPaths {
|
|
288
378
|
agents: PackageSubagentPath[];
|
|
289
|
-
chains:
|
|
379
|
+
chains: PackageChainPath[];
|
|
380
|
+
watchPaths: string[];
|
|
381
|
+
settingsErrors: Partial<Record<PackageSettingsScope, Error>>;
|
|
290
382
|
}
|
|
291
383
|
|
|
292
384
|
let cachedGlobalNpmRoot: string | null = null;
|
|
@@ -311,20 +403,6 @@ function readJsonFileBestEffort(filePath: string): JsonObjectFile | null {
|
|
|
311
403
|
}
|
|
312
404
|
}
|
|
313
405
|
|
|
314
|
-
function readOptionalJsonFile(filePath: string): JsonObjectFile | null {
|
|
315
|
-
let parsed: unknown;
|
|
316
|
-
try {
|
|
317
|
-
parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
|
|
318
|
-
} catch (error) {
|
|
319
|
-
const code = typeof error === "object" && error !== null && "code" in error
|
|
320
|
-
? (error as { code?: unknown }).code
|
|
321
|
-
: undefined;
|
|
322
|
-
if (code === "ENOENT") return null;
|
|
323
|
-
throw error;
|
|
324
|
-
}
|
|
325
|
-
return isJsonObjectRecord(parsed) ? parsed : null;
|
|
326
|
-
}
|
|
327
|
-
|
|
328
406
|
function isSafePackagePath(value: string): boolean {
|
|
329
407
|
return value.length > 0
|
|
330
408
|
&& !path.isAbsolute(value)
|
|
@@ -396,6 +474,10 @@ function resolveSettingsPackageRoot(source: string, baseDir: string): string | u
|
|
|
396
474
|
if (normalized === "." || normalized === ".." || normalized.startsWith("./") || normalized.startsWith("../")) {
|
|
397
475
|
return path.resolve(baseDir, normalized);
|
|
398
476
|
}
|
|
477
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
478
|
+
const parsed = parseGitPackagePath(`git:${trimmed}`);
|
|
479
|
+
return parsed ? path.join(baseDir, "git", parsed.host, parsed.repoPath) : undefined;
|
|
480
|
+
}
|
|
399
481
|
return undefined;
|
|
400
482
|
}
|
|
401
483
|
|
|
@@ -432,7 +514,7 @@ function stringArray(value: unknown): string[] {
|
|
|
432
514
|
return value.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0);
|
|
433
515
|
}
|
|
434
516
|
|
|
435
|
-
function packageMetadata(pkg: Record<string, unknown>, packageRoot: string): Omit<PackageSubagentPath, "dir"> {
|
|
517
|
+
function packageMetadata(pkg: Record<string, unknown>, packageRoot: string): Omit<PackageSubagentPath, "dir" | "scope"> {
|
|
436
518
|
const name = typeof pkg.name === "string" && pkg.name.trim() ? pkg.name.trim() : undefined;
|
|
437
519
|
const version = typeof pkg.version === "string" && pkg.version.trim() ? pkg.version.trim() : undefined;
|
|
438
520
|
return {
|
|
@@ -442,10 +524,10 @@ function packageMetadata(pkg: Record<string, unknown>, packageRoot: string): Omi
|
|
|
442
524
|
};
|
|
443
525
|
}
|
|
444
526
|
|
|
445
|
-
function extractSubagentPathsFromPackageRoot(packageRoot: string): PackageSubagentPaths {
|
|
527
|
+
function extractSubagentPathsFromPackageRoot(packageRoot: string, scope: Set<PackageScope>): PackageSubagentPaths {
|
|
446
528
|
const packageJsonPath = path.join(packageRoot, "package.json");
|
|
447
529
|
const pkg = readJsonFileBestEffort(packageJsonPath);
|
|
448
|
-
if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { agents: [], chains: [] };
|
|
530
|
+
if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { agents: [], chains: [], watchPaths: [packageJsonPath], settingsErrors: {} };
|
|
449
531
|
const pkgRecord = pkg as Record<string, unknown>;
|
|
450
532
|
const metadata = packageMetadata(pkgRecord, packageRoot);
|
|
451
533
|
|
|
@@ -464,16 +546,17 @@ function extractSubagentPathsFromPackageRoot(packageRoot: string): PackageSubage
|
|
|
464
546
|
}
|
|
465
547
|
|
|
466
548
|
const agents: PackageSubagentPath[] = [];
|
|
467
|
-
const chains:
|
|
549
|
+
const chains: PackageChainPath[] = [];
|
|
468
550
|
for (const root of roots) {
|
|
469
|
-
for (const entry of stringArray(root.agents)) agents.push({ dir: path.resolve(packageRoot, entry), ...metadata });
|
|
470
|
-
for (const entry of stringArray(root.chains)) chains.push(path.resolve(packageRoot, entry));
|
|
551
|
+
for (const entry of stringArray(root.agents)) agents.push({ dir: path.resolve(packageRoot, entry), scope, ...metadata });
|
|
552
|
+
for (const entry of stringArray(root.chains)) chains.push({ dir: path.resolve(packageRoot, entry), scope, packageRoot });
|
|
471
553
|
}
|
|
472
|
-
return { agents, chains };
|
|
554
|
+
return { agents, chains, watchPaths: [packageJsonPath], settingsErrors: {} };
|
|
473
555
|
}
|
|
474
556
|
|
|
475
|
-
function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
|
|
557
|
+
function collectPackageRootsFromNodeModules(nodeModulesDir: string, watchPaths?: string[]): string[] {
|
|
476
558
|
const roots: string[] = [];
|
|
559
|
+
watchPaths?.push(nodeModulesDir);
|
|
477
560
|
if (!fs.existsSync(nodeModulesDir)) return roots;
|
|
478
561
|
|
|
479
562
|
let entries: fs.Dirent[];
|
|
@@ -489,6 +572,7 @@ function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
|
|
|
489
572
|
|
|
490
573
|
if (entry.name.startsWith("@")) {
|
|
491
574
|
const scopeDir = path.join(nodeModulesDir, entry.name);
|
|
575
|
+
watchPaths?.push(scopeDir);
|
|
492
576
|
let scopeEntries: fs.Dirent[];
|
|
493
577
|
try {
|
|
494
578
|
scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
|
|
@@ -509,9 +593,8 @@ function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
|
|
|
509
593
|
}
|
|
510
594
|
|
|
511
595
|
function collectSettingsPackageRoots(settingsFile: string, baseDir: string): string[] {
|
|
512
|
-
const settings =
|
|
513
|
-
|
|
514
|
-
const packages = settings.packages;
|
|
596
|
+
const settings = readSettingsFileStrict(settingsFile);
|
|
597
|
+
const packages = (settings as { packages?: unknown }).packages;
|
|
515
598
|
if (!Array.isArray(packages)) return [];
|
|
516
599
|
|
|
517
600
|
const roots: string[] = [];
|
|
@@ -531,52 +614,82 @@ function collectSettingsPackageRoots(settingsFile: string, baseDir: string): str
|
|
|
531
614
|
function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean } = { includeUser: true, includeProject: true }): PackageSubagentPaths {
|
|
532
615
|
const agentDir = getAgentDir();
|
|
533
616
|
const projectRoot = findConfiguredProjectRoot(cwd) ?? cwd;
|
|
534
|
-
const packageRoots = [
|
|
535
|
-
projectRoot,
|
|
617
|
+
const packageRoots: Array<{ root: string; scope: PackageScope }> = [
|
|
618
|
+
{ root: projectRoot, scope: "root" },
|
|
536
619
|
];
|
|
537
|
-
|
|
620
|
+
const watchPaths: string[] = [path.join(projectRoot, "package.json")];
|
|
621
|
+
const settingsErrors: Partial<Record<PackageSettingsScope, Error>> = {};
|
|
622
|
+
const collectScopedSettingsRoots = (scope: PackageSettingsScope, settingsFile: string, baseDir: string): string[] => {
|
|
623
|
+
try {
|
|
624
|
+
return collectSettingsPackageRoots(settingsFile, baseDir);
|
|
625
|
+
} catch (error) {
|
|
626
|
+
// The raw source snapshot includes both settings scopes. Defer a
|
|
627
|
+
// strict failure until a projection actually selects this scope so an
|
|
628
|
+
// unrelated malformed settings file stays out of scoped discovery.
|
|
629
|
+
settingsErrors[scope] = error instanceof Error
|
|
630
|
+
? error
|
|
631
|
+
: new Error(`Failed to read settings file '${settingsFile}': ${String(error)}`, { cause: error });
|
|
632
|
+
return [];
|
|
633
|
+
}
|
|
634
|
+
};
|
|
538
635
|
if (options.includeProject) {
|
|
539
636
|
const projectConfigDir = getProjectConfigDir(projectRoot);
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
);
|
|
637
|
+
const nodeModulesDir = path.join(projectConfigDir, "npm", "node_modules");
|
|
638
|
+
packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "project" as const })));
|
|
639
|
+
packageRoots.push(...collectScopedSettingsRoots("project", path.join(projectConfigDir, "settings.json"), projectConfigDir).map((root) => ({ root, scope: "project" as const })));
|
|
544
640
|
}
|
|
545
641
|
|
|
546
642
|
if (options.includeUser) {
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
);
|
|
643
|
+
const nodeModulesDir = path.join(agentDir, "npm", "node_modules");
|
|
644
|
+
packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "user" as const })));
|
|
645
|
+
packageRoots.push(...collectScopedSettingsRoots("user", path.join(agentDir, "settings.json"), agentDir).map((root) => ({ root, scope: "user" as const })));
|
|
551
646
|
}
|
|
552
647
|
|
|
553
648
|
if (options.includeUser) {
|
|
554
649
|
const globalRoot = getGlobalNpmRoot();
|
|
555
|
-
if (globalRoot)
|
|
650
|
+
if (globalRoot) {
|
|
651
|
+
packageRoots.push(...collectPackageRootsFromNodeModules(globalRoot, watchPaths).map((root) => ({ root, scope: "user" as const })));
|
|
652
|
+
}
|
|
556
653
|
}
|
|
557
654
|
|
|
558
|
-
const seenRoots = new Set<
|
|
559
|
-
const seenAgents = new
|
|
560
|
-
const seenChains = new
|
|
655
|
+
const seenRoots = new Map<string, Set<PackageScope>>();
|
|
656
|
+
const seenAgents = new Map<string, PackageSubagentPath>();
|
|
657
|
+
const seenChains = new Map<string, PackageChainPath>();
|
|
561
658
|
const agents: PackageSubagentPath[] = [];
|
|
562
|
-
const chains:
|
|
563
|
-
for (const packageRoot of packageRoots) {
|
|
659
|
+
const chains: PackageChainPath[] = [];
|
|
660
|
+
for (const { root: packageRoot, scope } of packageRoots) {
|
|
564
661
|
const resolvedRoot = path.resolve(packageRoot);
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
662
|
+
const scopes = seenRoots.get(resolvedRoot);
|
|
663
|
+
if (scopes !== undefined) {
|
|
664
|
+
scopes.add(scope);
|
|
665
|
+
continue;
|
|
666
|
+
}
|
|
667
|
+
const packageScopes = new Set<PackageScope>([scope]);
|
|
668
|
+
seenRoots.set(resolvedRoot, packageScopes);
|
|
669
|
+
const paths = extractSubagentPathsFromPackageRoot(resolvedRoot, packageScopes);
|
|
670
|
+
watchPaths.push(...paths.watchPaths);
|
|
568
671
|
for (const agentPath of paths.agents) {
|
|
569
|
-
|
|
570
|
-
seenAgents.
|
|
672
|
+
const agentKey = `${agentPath.dir}\u0000${agentPath.packageRoot}`;
|
|
673
|
+
const existing = seenAgents.get(agentKey);
|
|
674
|
+
if (existing) {
|
|
675
|
+
for (const packageScope of agentPath.scope) existing.scope.add(packageScope);
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
seenAgents.set(agentKey, agentPath);
|
|
571
679
|
agents.push(agentPath);
|
|
572
680
|
}
|
|
573
681
|
for (const chainDir of paths.chains) {
|
|
574
|
-
|
|
575
|
-
seenChains.
|
|
682
|
+
const chainKey = `${chainDir.dir}\u0000${chainDir.packageRoot}`;
|
|
683
|
+
const existing = seenChains.get(chainKey);
|
|
684
|
+
if (existing) {
|
|
685
|
+
for (const packageScope of chainDir.scope) existing.scope.add(packageScope);
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
seenChains.set(chainKey, chainDir);
|
|
576
689
|
chains.push(chainDir);
|
|
577
690
|
}
|
|
578
691
|
}
|
|
579
|
-
return { agents, chains };
|
|
692
|
+
return { agents, chains, watchPaths, settingsErrors };
|
|
580
693
|
}
|
|
581
694
|
|
|
582
695
|
function normalizeAgentAliases(rawAliases: string[] | undefined, agentName: string): string[] | undefined {
|
|
@@ -662,6 +775,7 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
|
|
|
662
775
|
...(agent.thinking !== undefined ? { thinking: agent.thinking } : {}),
|
|
663
776
|
systemPromptMode: agent.systemPromptMode,
|
|
664
777
|
inheritProjectContext: agent.inheritProjectContext,
|
|
778
|
+
inheritGlobalContext: agent.inheritGlobalContext,
|
|
665
779
|
inheritSkills: agent.inheritSkills,
|
|
666
780
|
...(agent.defaultContext !== undefined ? { defaultContext: agent.defaultContext } : {}),
|
|
667
781
|
...(agent.acceptanceRole !== undefined ? { acceptanceRole: agent.acceptanceRole } : {}),
|
|
@@ -670,11 +784,15 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
|
|
|
670
784
|
...(agent.skills ? { skills: [...agent.skills] } : {}),
|
|
671
785
|
...(agent.skillPath ? { skillPath: [...agent.skillPath] } : {}),
|
|
672
786
|
...(agent.tools ? { tools: [...agent.tools] } : {}),
|
|
787
|
+
...(agent.excludeTools ? { excludeTools: [...agent.excludeTools] } : {}),
|
|
788
|
+
...(agent.allowNestedSubagents !== undefined ? { allowNestedSubagents: agent.allowNestedSubagents } : {}),
|
|
673
789
|
...(agent.mcpDirectTools ? { mcpDirectTools: [...agent.mcpDirectTools] } : {}),
|
|
674
790
|
...(!agent.extensionsFromDefault && agent.extensions ? { extensions: [...agent.extensions] } : {}),
|
|
675
791
|
...(agent.subagentOnlyExtensions ? { subagentOnlyExtensions: [...agent.subagentOnlyExtensions] } : {}),
|
|
792
|
+
...(agent.mutationTools ? { mutationTools: [...agent.mutationTools] } : {}),
|
|
676
793
|
...(agent.completionGuard !== undefined ? { completionGuard: agent.completionGuard } : {}),
|
|
677
794
|
...(agent.toolBudget !== undefined ? { toolBudget: agent.toolBudget } : {}),
|
|
795
|
+
...(agent.sandbox !== undefined ? { sandbox: agent.sandbox } : {}),
|
|
678
796
|
};
|
|
679
797
|
}
|
|
680
798
|
|
|
@@ -693,6 +811,7 @@ function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentO
|
|
|
693
811
|
...(override.thinking !== undefined ? { thinking: override.thinking } : {}),
|
|
694
812
|
...(override.systemPromptMode !== undefined ? { systemPromptMode: override.systemPromptMode } : {}),
|
|
695
813
|
...(override.inheritProjectContext !== undefined ? { inheritProjectContext: override.inheritProjectContext } : {}),
|
|
814
|
+
...(override.inheritGlobalContext !== undefined ? { inheritGlobalContext: override.inheritGlobalContext } : {}),
|
|
696
815
|
...(override.inheritSkills !== undefined ? { inheritSkills: override.inheritSkills } : {}),
|
|
697
816
|
...(override.defaultContext !== undefined ? { defaultContext: override.defaultContext } : {}),
|
|
698
817
|
...(override.acceptanceRole !== undefined ? { acceptanceRole: override.acceptanceRole } : {}),
|
|
@@ -700,10 +819,14 @@ function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentO
|
|
|
700
819
|
...(override.systemPrompt !== undefined ? { systemPrompt: override.systemPrompt } : {}),
|
|
701
820
|
...(override.skills !== undefined ? { skills: override.skills === false ? false : [...override.skills] } : {}),
|
|
702
821
|
...(override.tools !== undefined ? { tools: Array.isArray(override.tools) ? [...override.tools] : override.tools } : {}),
|
|
822
|
+
...(override.excludeTools !== undefined ? { excludeTools: override.excludeTools === false ? false : [...override.excludeTools] } : {}),
|
|
823
|
+
...(override.allowNestedSubagents !== undefined ? { allowNestedSubagents: override.allowNestedSubagents } : {}),
|
|
703
824
|
...(override.extensions !== undefined ? { extensions: override.extensions === false ? false : [...override.extensions] } : {}),
|
|
704
825
|
...(override.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: override.subagentOnlyExtensions === false ? false : [...override.subagentOnlyExtensions] } : {}),
|
|
826
|
+
...(override.mutationTools !== undefined ? { mutationTools: override.mutationTools === false ? false : [...override.mutationTools] } : {}),
|
|
705
827
|
...(override.completionGuard !== undefined ? { completionGuard: override.completionGuard } : {}),
|
|
706
828
|
...(override.toolBudget !== undefined ? { toolBudget: override.toolBudget === false ? false : { ...override.toolBudget, ...(Array.isArray(override.toolBudget.block) ? { block: [...override.toolBudget.block] } : {}) } } : {}),
|
|
829
|
+
...(override.sandbox !== undefined ? { sandbox: override.sandbox } : {}),
|
|
707
830
|
};
|
|
708
831
|
}
|
|
709
832
|
|
|
@@ -751,7 +874,7 @@ export function findNearestProjectRoot(cwd: string): string | null {
|
|
|
751
874
|
return findProjectRootCandidates(cwd)[0] ?? null;
|
|
752
875
|
}
|
|
753
876
|
|
|
754
|
-
function findConfiguredProjectRoot(cwd: string): string | null {
|
|
877
|
+
export function findConfiguredProjectRoot(cwd: string): string | null {
|
|
755
878
|
const candidates = findProjectRootCandidates(cwd);
|
|
756
879
|
const nearestRoot = candidates[0];
|
|
757
880
|
if (!nearestRoot) return null;
|
|
@@ -910,6 +1033,14 @@ function parseBuiltinOverrideEntry(
|
|
|
910
1033
|
}
|
|
911
1034
|
}
|
|
912
1035
|
|
|
1036
|
+
if ("inheritGlobalContext" in input) {
|
|
1037
|
+
if (typeof input.inheritGlobalContext === "boolean") {
|
|
1038
|
+
override.inheritGlobalContext = input.inheritGlobalContext;
|
|
1039
|
+
} else {
|
|
1040
|
+
throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'inheritGlobalContext'; expected a boolean.`);
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
|
|
913
1044
|
if ("inheritSkills" in input) {
|
|
914
1045
|
if (typeof input.inheritSkills === "boolean") {
|
|
915
1046
|
override.inheritSkills = input.inheritSkills;
|
|
@@ -960,6 +1091,10 @@ function parseBuiltinOverrideEntry(
|
|
|
960
1091
|
}
|
|
961
1092
|
}
|
|
962
1093
|
|
|
1094
|
+
if ("sandbox" in input) {
|
|
1095
|
+
override.sandbox = validateSandboxProfileName(input.sandbox, `Builtin override '${name}' in '${filePath}' sandbox`);
|
|
1096
|
+
}
|
|
1097
|
+
|
|
963
1098
|
if ("systemPrompt" in input) {
|
|
964
1099
|
if (typeof input.systemPrompt === "string") override.systemPrompt = input.systemPrompt;
|
|
965
1100
|
else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'systemPrompt'; expected a string.`);
|
|
@@ -982,6 +1117,12 @@ function parseBuiltinOverrideEntry(
|
|
|
982
1117
|
|
|
983
1118
|
const tools = parseToolsOverride(input.tools, { filePath, name });
|
|
984
1119
|
if (tools !== undefined) override.tools = tools;
|
|
1120
|
+
const excludeTools = parseOverrideStringArrayOrFalse(input.excludeTools, { filePath, name, field: "excludeTools" });
|
|
1121
|
+
if (excludeTools !== undefined) override.excludeTools = excludeTools;
|
|
1122
|
+
if ("allowNestedSubagents" in input) {
|
|
1123
|
+
if (typeof input.allowNestedSubagents === "boolean") override.allowNestedSubagents = input.allowNestedSubagents;
|
|
1124
|
+
else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'allowNestedSubagents'; expected a boolean.`);
|
|
1125
|
+
}
|
|
985
1126
|
|
|
986
1127
|
const extensions = parseOverrideStringArrayOrFalse(input.extensions, { filePath, name, field: "extensions" });
|
|
987
1128
|
if (extensions !== undefined) override.extensions = extensions;
|
|
@@ -989,6 +1130,9 @@ function parseBuiltinOverrideEntry(
|
|
|
989
1130
|
const subagentOnlyExtensions = parseOverrideStringArrayOrFalse(input.subagentOnlyExtensions, { filePath, name, field: "subagentOnlyExtensions" });
|
|
990
1131
|
if (subagentOnlyExtensions !== undefined) override.subagentOnlyExtensions = subagentOnlyExtensions;
|
|
991
1132
|
|
|
1133
|
+
const mutationTools = parseOverrideStringArrayOrFalse(input.mutationTools, { filePath, name, field: "mutationTools" });
|
|
1134
|
+
if (mutationTools !== undefined) override.mutationTools = mutationTools;
|
|
1135
|
+
|
|
992
1136
|
return Object.keys(override).length > 0 ? override : undefined;
|
|
993
1137
|
}
|
|
994
1138
|
|
|
@@ -1063,32 +1207,71 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
|
|
|
1063
1207
|
}
|
|
1064
1208
|
injectAgents = subagentsObject.injectAgents.map((item) => item.trim());
|
|
1065
1209
|
}
|
|
1210
|
+
let agentScanDirs: string[] | undefined;
|
|
1211
|
+
if ("agentScanDirs" in subagentsObject) {
|
|
1212
|
+
if (!Array.isArray(subagentsObject.agentScanDirs)
|
|
1213
|
+
|| subagentsObject.agentScanDirs.some((item) => typeof item !== "string" || !item.trim())) {
|
|
1214
|
+
throw new Error(`Subagent settings in '${filePath}' have invalid 'agentScanDirs'; expected an array of non-empty strings.`);
|
|
1215
|
+
}
|
|
1216
|
+
agentScanDirs = subagentsObject.agentScanDirs.map((item) => item.trim());
|
|
1217
|
+
}
|
|
1066
1218
|
const modelScope = parseModelScopeConfig(subagentsObject.modelScope, { filePath });
|
|
1067
1219
|
|
|
1068
1220
|
const parsed: Record<string, BuiltinAgentOverrideConfig> = {};
|
|
1221
|
+
const providerOverrides: Record<string, Record<string, BuiltinAgentOverrideConfig>> = {};
|
|
1069
1222
|
const agentOverrides = subagentsObject.agentOverrides;
|
|
1223
|
+
const agentOverridesByProvider = subagentsObject.agentOverridesByProvider;
|
|
1070
1224
|
const parsedSettings: SubagentSettings = {
|
|
1071
1225
|
overrides: parsed,
|
|
1226
|
+
providerOverrides,
|
|
1072
1227
|
...(defaultModel !== undefined ? { defaultModel } : {}),
|
|
1073
1228
|
...(defaultProvider !== undefined ? { defaultProvider } : {}),
|
|
1074
1229
|
...(defaultThinking !== undefined ? { defaultThinking } : {}),
|
|
1075
1230
|
...(maxThinking !== undefined ? { maxThinking } : {}),
|
|
1076
1231
|
...(defaultExtensions !== undefined ? { defaultExtensions } : {}),
|
|
1232
|
+
...(agentScanDirs !== undefined ? { agentScanDirs } : {}),
|
|
1233
|
+
...(injectAgents !== undefined ? { injectAgents } : {}),
|
|
1077
1234
|
...(disableBuiltins !== undefined ? { disableBuiltins } : {}),
|
|
1078
1235
|
...(disableThinking !== undefined ? { disableThinking } : {}),
|
|
1079
1236
|
...(modelScope !== undefined ? { modelScope } : {}),
|
|
1080
1237
|
...(injectAgents !== undefined ? { injectAgents } : {}),
|
|
1081
1238
|
};
|
|
1082
|
-
if (
|
|
1083
|
-
|
|
1239
|
+
if (agentOverrides && typeof agentOverrides === "object" && !Array.isArray(agentOverrides)) {
|
|
1240
|
+
for (const [name, value] of Object.entries(agentOverrides)) {
|
|
1241
|
+
const override = parseBuiltinOverrideEntry(name, value, filePath);
|
|
1242
|
+
if (override) parsed[name] = override;
|
|
1243
|
+
}
|
|
1084
1244
|
}
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1245
|
+
if (agentOverridesByProvider !== undefined) {
|
|
1246
|
+
if (!agentOverridesByProvider || typeof agentOverridesByProvider !== "object" || Array.isArray(agentOverridesByProvider)) {
|
|
1247
|
+
throw new Error(`Subagent settings in '${filePath}' have invalid 'agentOverridesByProvider'; expected an object keyed by provider.`);
|
|
1248
|
+
}
|
|
1249
|
+
for (const [provider, value] of Object.entries(agentOverridesByProvider)) {
|
|
1250
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1251
|
+
throw new Error(`Subagent settings in '${filePath}' have invalid 'agentOverridesByProvider.${provider}'; expected an object keyed by agent.`);
|
|
1252
|
+
}
|
|
1253
|
+
const entries: Record<string, BuiltinAgentOverrideConfig> = {};
|
|
1254
|
+
for (const [agentName, agentValue] of Object.entries(value)) {
|
|
1255
|
+
const override = parseBuiltinOverrideEntry(`agentOverridesByProvider.${provider}.${agentName}`, agentValue, filePath);
|
|
1256
|
+
if (override) entries[agentName] = override;
|
|
1257
|
+
}
|
|
1258
|
+
providerOverrides[provider] = entries;
|
|
1259
|
+
}
|
|
1088
1260
|
}
|
|
1089
1261
|
return parsedSettings;
|
|
1090
1262
|
}
|
|
1091
1263
|
|
|
1264
|
+
function selectProviderOverrides(settings: SubagentSettings, provider: string | undefined): SubagentSettings {
|
|
1265
|
+
if (!provider) return settings;
|
|
1266
|
+
const selected = settings.providerOverrides[provider];
|
|
1267
|
+
if (!selected) return settings;
|
|
1268
|
+
const overrides = { ...settings.overrides };
|
|
1269
|
+
for (const [name, override] of Object.entries(selected)) {
|
|
1270
|
+
overrides[name] = { ...overrides[name], ...override };
|
|
1271
|
+
}
|
|
1272
|
+
return { ...settings, overrides };
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1092
1275
|
function resolveSubagentDefaultProvider(
|
|
1093
1276
|
userSettings: SubagentSettings,
|
|
1094
1277
|
projectSettings: SubagentSettings,
|
|
@@ -1211,9 +1394,19 @@ function applyBuiltinOverride(
|
|
|
1211
1394
|
override: BuiltinAgentOverrideConfig,
|
|
1212
1395
|
meta: { scope: "user" | "project"; path: string },
|
|
1213
1396
|
): AgentConfig {
|
|
1397
|
+
const overrideInfo: BuiltinAgentOverrideInfo = {
|
|
1398
|
+
...meta,
|
|
1399
|
+
base: agent.override?.base ?? cloneOverrideBase(agent),
|
|
1400
|
+
fields: [...new Set([...(agent.override?.fields ?? []), ...Object.keys(override)])].sort(),
|
|
1401
|
+
fieldScopes: Object.fromEntries(Object.entries({ ...(agent.override?.fieldScopes ?? {}) }).map(([field, scopes]) => [field, [...scopes]])),
|
|
1402
|
+
};
|
|
1403
|
+
for (const field of Object.keys(override)) {
|
|
1404
|
+
const scopes = overrideInfo.fieldScopes![field] ?? [];
|
|
1405
|
+
overrideInfo.fieldScopes![field] = [...new Set([...scopes, meta.scope])].sort();
|
|
1406
|
+
}
|
|
1214
1407
|
const next: AgentConfig = {
|
|
1215
1408
|
...agent,
|
|
1216
|
-
override:
|
|
1409
|
+
override: overrideInfo,
|
|
1217
1410
|
};
|
|
1218
1411
|
|
|
1219
1412
|
if (override.description !== undefined) next.description = override.description;
|
|
@@ -1233,6 +1426,7 @@ function applyBuiltinOverride(
|
|
|
1233
1426
|
if (override.thinking !== undefined) { if (override.thinking === false) delete next.thinking; else next.thinking = override.thinking; }
|
|
1234
1427
|
if (override.systemPromptMode !== undefined) next.systemPromptMode = override.systemPromptMode;
|
|
1235
1428
|
if (override.inheritProjectContext !== undefined) next.inheritProjectContext = override.inheritProjectContext;
|
|
1429
|
+
if (override.inheritGlobalContext !== undefined) next.inheritGlobalContext = override.inheritGlobalContext;
|
|
1236
1430
|
if (override.inheritSkills !== undefined) next.inheritSkills = override.inheritSkills;
|
|
1237
1431
|
if (override.defaultContext !== undefined) { if (override.defaultContext === false) delete next.defaultContext; else next.defaultContext = override.defaultContext; }
|
|
1238
1432
|
if (override.acceptanceRole !== undefined) { if (override.acceptanceRole === false) delete next.acceptanceRole; else next.acceptanceRole = override.acceptanceRole; }
|
|
@@ -1240,10 +1434,14 @@ function applyBuiltinOverride(
|
|
|
1240
1434
|
if (override.systemPrompt !== undefined) next.systemPrompt = override.systemPrompt;
|
|
1241
1435
|
if (override.skills !== undefined) { if (override.skills === false) delete next.skills; else next.skills = [...override.skills]; }
|
|
1242
1436
|
if (override.tools !== undefined) applyToolsOverride(next, override.tools);
|
|
1437
|
+
if (override.excludeTools !== undefined) { if (override.excludeTools === false) delete next.excludeTools; else next.excludeTools = [...override.excludeTools]; }
|
|
1438
|
+
if (override.allowNestedSubagents !== undefined) next.allowNestedSubagents = override.allowNestedSubagents;
|
|
1243
1439
|
if (override.extensions !== undefined) { if (override.extensions === false) delete next.extensions; else next.extensions = [...override.extensions]; }
|
|
1244
1440
|
if (override.subagentOnlyExtensions !== undefined) { if (override.subagentOnlyExtensions === false) delete next.subagentOnlyExtensions; else next.subagentOnlyExtensions = [...override.subagentOnlyExtensions]; }
|
|
1441
|
+
if (override.mutationTools !== undefined) { if (override.mutationTools === false) delete next.mutationTools; else next.mutationTools = [...override.mutationTools]; }
|
|
1245
1442
|
if (override.completionGuard !== undefined) next.completionGuard = override.completionGuard;
|
|
1246
1443
|
if (override.toolBudget !== undefined) { if (override.toolBudget === false) delete next.toolBudget; else next.toolBudget = override.toolBudget; }
|
|
1444
|
+
if (override.sandbox !== undefined) next.sandbox = override.sandbox;
|
|
1247
1445
|
|
|
1248
1446
|
return next;
|
|
1249
1447
|
}
|
|
@@ -1309,116 +1507,12 @@ function applyBuiltinOverrides(
|
|
|
1309
1507
|
});
|
|
1310
1508
|
}
|
|
1311
1509
|
|
|
1312
|
-
export function agentHasFrontmatterField(agent: AgentConfig, ...fields: string[]): boolean {
|
|
1313
|
-
const frontmatterFields = agentFrontmatterFields.get(agent);
|
|
1314
|
-
return frontmatterFields ? fields.some((field) => frontmatterFields.has(field)) : false;
|
|
1315
|
-
}
|
|
1316
|
-
|
|
1317
1510
|
function applyCustomAgentOverride(
|
|
1318
1511
|
agent: AgentConfig,
|
|
1319
1512
|
override: BuiltinAgentOverrideConfig,
|
|
1320
1513
|
meta: { scope: "user" | "project"; path: string },
|
|
1321
1514
|
): AgentConfig {
|
|
1322
|
-
|
|
1323
|
-
let anyFilled = false;
|
|
1324
|
-
|
|
1325
|
-
const mutable = (): AgentConfig => {
|
|
1326
|
-
next ??= { ...agent };
|
|
1327
|
-
return next;
|
|
1328
|
-
};
|
|
1329
|
-
|
|
1330
|
-
const fill = <K extends keyof AgentConfig>(
|
|
1331
|
-
field: K,
|
|
1332
|
-
frontmatterFields: string[],
|
|
1333
|
-
value: AgentConfig[K],
|
|
1334
|
-
): void => {
|
|
1335
|
-
if (agentHasFrontmatterField(agent, ...frontmatterFields)) return;
|
|
1336
|
-
const target = mutable();
|
|
1337
|
-
if (value === undefined) delete target[field]; else target[field] = value;
|
|
1338
|
-
anyFilled = true;
|
|
1339
|
-
};
|
|
1340
|
-
|
|
1341
|
-
if (override.description !== undefined) {
|
|
1342
|
-
mutable().description = override.description;
|
|
1343
|
-
anyFilled = true;
|
|
1344
|
-
}
|
|
1345
|
-
if (override.output !== undefined) {
|
|
1346
|
-
fill("output", ["output"], override.output === false ? undefined : override.output);
|
|
1347
|
-
}
|
|
1348
|
-
if (override.outputMode !== undefined) {
|
|
1349
|
-
fill("outputMode", ["outputMode"], override.outputMode);
|
|
1350
|
-
}
|
|
1351
|
-
if (override.defaultReads !== undefined) {
|
|
1352
|
-
fill("defaultReads", ["defaultReads"], override.defaultReads === false ? undefined : [...override.defaultReads]);
|
|
1353
|
-
}
|
|
1354
|
-
if (override.model !== undefined && !agentHasFrontmatterField(agent, "model")) {
|
|
1355
|
-
const target = mutable();
|
|
1356
|
-
if (override.model === false) delete target.model; else target.model = override.model;
|
|
1357
|
-
delete target.modelSource;
|
|
1358
|
-
anyFilled = true;
|
|
1359
|
-
}
|
|
1360
|
-
if (override.defaultProvider !== undefined) {
|
|
1361
|
-
fill("modelProvider", ["modelProvider", "defaultProvider"], override.defaultProvider === false ? undefined : override.defaultProvider);
|
|
1362
|
-
}
|
|
1363
|
-
if (override.fallbackModels !== undefined) {
|
|
1364
|
-
fill(
|
|
1365
|
-
"fallbackModels",
|
|
1366
|
-
["fallbackModels"],
|
|
1367
|
-
override.fallbackModels === false ? undefined : [...override.fallbackModels],
|
|
1368
|
-
);
|
|
1369
|
-
}
|
|
1370
|
-
if (override.fast !== undefined) {
|
|
1371
|
-
fill("fast", ["fast"], override.fast);
|
|
1372
|
-
}
|
|
1373
|
-
if (override.thinking !== undefined) {
|
|
1374
|
-
fill("thinking", ["thinking"], override.thinking === false ? undefined : override.thinking);
|
|
1375
|
-
}
|
|
1376
|
-
if (override.systemPromptMode !== undefined) {
|
|
1377
|
-
fill("systemPromptMode", ["systemPromptMode"], override.systemPromptMode);
|
|
1378
|
-
}
|
|
1379
|
-
if (override.inheritProjectContext !== undefined) {
|
|
1380
|
-
fill("inheritProjectContext", ["inheritProjectContext"], override.inheritProjectContext);
|
|
1381
|
-
}
|
|
1382
|
-
if (override.inheritSkills !== undefined) {
|
|
1383
|
-
fill("inheritSkills", ["inheritSkills"], override.inheritSkills);
|
|
1384
|
-
}
|
|
1385
|
-
if (override.defaultContext !== undefined) {
|
|
1386
|
-
fill("defaultContext", ["defaultContext"], override.defaultContext === false ? undefined : override.defaultContext);
|
|
1387
|
-
}
|
|
1388
|
-
if (override.acceptanceRole !== undefined) {
|
|
1389
|
-
fill("acceptanceRole", ["acceptanceRole"], override.acceptanceRole === false ? undefined : override.acceptanceRole);
|
|
1390
|
-
}
|
|
1391
|
-
if (override.disabled !== undefined) {
|
|
1392
|
-
// Custom agent files cannot set `disabled`, so project overrides replace user overrides.
|
|
1393
|
-
mutable().disabled = override.disabled;
|
|
1394
|
-
anyFilled = true;
|
|
1395
|
-
}
|
|
1396
|
-
if (override.skills !== undefined) {
|
|
1397
|
-
fill("skills", ["skill", "skills"], override.skills === false ? undefined : [...override.skills]);
|
|
1398
|
-
}
|
|
1399
|
-
if (override.tools !== undefined && !agentHasFrontmatterField(agent, "tools")) {
|
|
1400
|
-
applyToolsOverride(mutable(), override.tools);
|
|
1401
|
-
anyFilled = true;
|
|
1402
|
-
}
|
|
1403
|
-
if (override.extensions !== undefined) {
|
|
1404
|
-
fill("extensions", ["extensions"], override.extensions === false ? undefined : [...override.extensions]);
|
|
1405
|
-
}
|
|
1406
|
-
if (override.subagentOnlyExtensions !== undefined) {
|
|
1407
|
-
fill(
|
|
1408
|
-
"subagentOnlyExtensions",
|
|
1409
|
-
["subagentOnlyExtensions"],
|
|
1410
|
-
override.subagentOnlyExtensions === false ? undefined : [...override.subagentOnlyExtensions],
|
|
1411
|
-
);
|
|
1412
|
-
}
|
|
1413
|
-
if (override.completionGuard !== undefined) {
|
|
1414
|
-
fill("completionGuard", ["completionGuard"], override.completionGuard);
|
|
1415
|
-
}
|
|
1416
|
-
if (override.toolBudget !== undefined) {
|
|
1417
|
-
fill("toolBudget", ["toolBudget"], override.toolBudget === false ? undefined : override.toolBudget);
|
|
1418
|
-
}
|
|
1419
|
-
|
|
1420
|
-
if (!anyFilled || !next) return agent;
|
|
1421
|
-
next.override = { ...meta, base: agent.override?.base ?? cloneOverrideBase(agent) };
|
|
1515
|
+
const next = applyBuiltinOverride(agent, override, meta);
|
|
1422
1516
|
const frontmatterFields = agentFrontmatterFields.get(agent);
|
|
1423
1517
|
if (frontmatterFields) agentFrontmatterFields.set(next, frontmatterFields);
|
|
1424
1518
|
return next;
|
|
@@ -1449,7 +1543,7 @@ function applyCustomAgentOverrides(
|
|
|
1449
1543
|
|
|
1450
1544
|
export function buildBuiltinOverrideConfig(
|
|
1451
1545
|
base: BuiltinAgentOverrideBase,
|
|
1452
|
-
draft: Pick<AgentConfig, "model" | "modelProvider" | "fallbackModels" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "completionGuard" | "toolBudget"> & Partial<Pick<AgentConfig, "description" | "output" | "outputMode" | "defaultReads">>,
|
|
1546
|
+
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" | "sandbox"> & Partial<Pick<AgentConfig, "description" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
|
|
1453
1547
|
): BuiltinAgentOverrideConfig | undefined {
|
|
1454
1548
|
const override: BuiltinAgentOverrideConfig = {};
|
|
1455
1549
|
|
|
@@ -1467,6 +1561,7 @@ export function buildBuiltinOverrideConfig(
|
|
|
1467
1561
|
if (draft.thinking !== base.thinking) override.thinking = draft.thinking ?? false;
|
|
1468
1562
|
if (draft.systemPromptMode !== base.systemPromptMode) override.systemPromptMode = draft.systemPromptMode;
|
|
1469
1563
|
if (draft.inheritProjectContext !== base.inheritProjectContext) override.inheritProjectContext = draft.inheritProjectContext;
|
|
1564
|
+
if (draft.inheritGlobalContext !== base.inheritGlobalContext) override.inheritGlobalContext = draft.inheritGlobalContext;
|
|
1470
1565
|
if (draft.inheritSkills !== base.inheritSkills) override.inheritSkills = draft.inheritSkills;
|
|
1471
1566
|
if (draft.defaultContext !== base.defaultContext) override.defaultContext = draft.defaultContext ?? false;
|
|
1472
1567
|
if (draft.acceptanceRole !== base.acceptanceRole) override.acceptanceRole = draft.acceptanceRole ?? false;
|
|
@@ -1477,14 +1572,18 @@ export function buildBuiltinOverrideConfig(
|
|
|
1477
1572
|
const baseTools = joinToolList(base);
|
|
1478
1573
|
const draftTools = joinToolList(draft);
|
|
1479
1574
|
if (!arraysEqual(draftTools, baseTools)) override.tools = draftTools ? [...draftTools] : false;
|
|
1575
|
+
if (!arraysEqual(draft.excludeTools, base.excludeTools)) override.excludeTools = draft.excludeTools ? [...draft.excludeTools] : false;
|
|
1576
|
+
if (draft.allowNestedSubagents !== base.allowNestedSubagents) override.allowNestedSubagents = draft.allowNestedSubagents === true;
|
|
1480
1577
|
if (!arraysEqual(draft.extensions, base.extensions)) override.extensions = draft.extensions ? [...draft.extensions] : false;
|
|
1481
1578
|
if (!arraysEqual(draft.subagentOnlyExtensions, base.subagentOnlyExtensions)) {
|
|
1482
1579
|
override.subagentOnlyExtensions = draft.subagentOnlyExtensions ? [...draft.subagentOnlyExtensions] : false;
|
|
1483
1580
|
}
|
|
1581
|
+
if (!arraysEqual(draft.mutationTools, base.mutationTools)) override.mutationTools = draft.mutationTools ? [...draft.mutationTools] : false;
|
|
1484
1582
|
if ((draft.completionGuard !== false) !== (base.completionGuard !== false)) {
|
|
1485
1583
|
override.completionGuard = draft.completionGuard !== false;
|
|
1486
1584
|
}
|
|
1487
1585
|
if (JSON.stringify(draft.toolBudget) !== JSON.stringify(base.toolBudget)) override.toolBudget = draft.toolBudget ?? false;
|
|
1586
|
+
if (draft.sandbox !== undefined && draft.sandbox !== base.sandbox) override.sandbox = draft.sandbox;
|
|
1488
1587
|
|
|
1489
1588
|
return Object.keys(override).length > 0 ? override : undefined;
|
|
1490
1589
|
}
|
|
@@ -1610,7 +1709,7 @@ export function removeBuiltinAgentOverrideFields(
|
|
|
1610
1709
|
return { path: filePath, removed: true };
|
|
1611
1710
|
}
|
|
1612
1711
|
|
|
1613
|
-
const DISCOVERY_PRUNED_DIR_NAMES = new Set([".git", "node_modules"]);
|
|
1712
|
+
const DISCOVERY_PRUNED_DIR_NAMES = new Set([".git", "node_modules", ".pi", "sync-backups"]);
|
|
1614
1713
|
|
|
1615
1714
|
function isDiscoveryNestedProjectRoot(dir: string): boolean {
|
|
1616
1715
|
return isDirectory(getProjectConfigDir(dir)) || isDirectory(path.join(dir, ".agents"));
|
|
@@ -1622,9 +1721,24 @@ function shouldPruneDiscoveryDir(rootDir: string, dir: string, dirName: string):
|
|
|
1622
1721
|
return path.resolve(dir) !== path.resolve(rootDir) && isDiscoveryNestedProjectRoot(dir);
|
|
1623
1722
|
}
|
|
1624
1723
|
|
|
1625
|
-
function listFilesRecursive(
|
|
1724
|
+
function listFilesRecursive(
|
|
1725
|
+
dir: string,
|
|
1726
|
+
predicate: (fileName: string) => boolean,
|
|
1727
|
+
rootDir = dir,
|
|
1728
|
+
visitedDirectories = new Set<string>(),
|
|
1729
|
+
inspectedDirectories = new Set<string>(),
|
|
1730
|
+
): string[] {
|
|
1626
1731
|
const files: string[] = [];
|
|
1627
1732
|
if (!fs.existsSync(dir)) return files;
|
|
1733
|
+
inspectedDirectories.add(path.resolve(dir));
|
|
1734
|
+
let realDir: string;
|
|
1735
|
+
try {
|
|
1736
|
+
realDir = fs.realpathSync(dir);
|
|
1737
|
+
} catch {
|
|
1738
|
+
return files;
|
|
1739
|
+
}
|
|
1740
|
+
if (visitedDirectories.has(realDir)) return files;
|
|
1741
|
+
visitedDirectories.add(realDir);
|
|
1628
1742
|
|
|
1629
1743
|
let entries: fs.Dirent[];
|
|
1630
1744
|
try {
|
|
@@ -1635,9 +1749,17 @@ function listFilesRecursive(dir: string, predicate: (fileName: string) => boolea
|
|
|
1635
1749
|
|
|
1636
1750
|
for (const entry of entries) {
|
|
1637
1751
|
const filePath = path.join(dir, entry.name);
|
|
1638
|
-
|
|
1752
|
+
let isDirectory = entry.isDirectory();
|
|
1753
|
+
if (entry.isSymbolicLink()) {
|
|
1754
|
+
try {
|
|
1755
|
+
isDirectory = fs.statSync(filePath).isDirectory();
|
|
1756
|
+
} catch {
|
|
1757
|
+
isDirectory = false;
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
if (isDirectory) {
|
|
1639
1761
|
if (!shouldPruneDiscoveryDir(rootDir, filePath, entry.name)) {
|
|
1640
|
-
files.push(...listFilesRecursive(filePath, predicate, rootDir));
|
|
1762
|
+
files.push(...listFilesRecursive(filePath, predicate, rootDir, visitedDirectories, inspectedDirectories));
|
|
1641
1763
|
}
|
|
1642
1764
|
continue;
|
|
1643
1765
|
}
|
|
@@ -1648,6 +1770,94 @@ function listFilesRecursive(dir: string, predicate: (fileName: string) => boolea
|
|
|
1648
1770
|
return files;
|
|
1649
1771
|
}
|
|
1650
1772
|
|
|
1773
|
+
export interface AgentDefinitionInspection {
|
|
1774
|
+
files: string[];
|
|
1775
|
+
state: AgentDefinitionDirectoryState;
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
const agentDefinitionInspectionDirectories = new WeakMap<AgentDefinitionInspection, string[]>();
|
|
1779
|
+
|
|
1780
|
+
function rememberAgentDefinitionInspection(inspection: AgentDefinitionInspection, directories: Iterable<string>): AgentDefinitionInspection {
|
|
1781
|
+
agentDefinitionInspectionDirectories.set(inspection, [...new Set([...directories].map((directory) => path.resolve(directory)))]);
|
|
1782
|
+
return inspection;
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
function inspectedAgentDefinitionDirectories(inspection: AgentDefinitionInspection, root: string): string[] {
|
|
1786
|
+
return agentDefinitionInspectionDirectories.get(inspection) ?? [path.resolve(root)];
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
/** Narrow filesystem seam so unavailable paths can be tested without permissions. */
|
|
1790
|
+
export interface AgentDefinitionInspectionFs {
|
|
1791
|
+
existsSync(filePath: string): boolean;
|
|
1792
|
+
realpathSync?(filePath: string): string;
|
|
1793
|
+
statSync(filePath: string): { isDirectory(): boolean };
|
|
1794
|
+
readdirSync(dir: string): fs.Dirent[];
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
const DEFAULT_AGENT_DEFINITION_INSPECTION_FS: AgentDefinitionInspectionFs = {
|
|
1798
|
+
existsSync: fs.existsSync,
|
|
1799
|
+
realpathSync: fs.realpathSync,
|
|
1800
|
+
statSync: fs.statSync,
|
|
1801
|
+
readdirSync: (dir) => fs.readdirSync(dir, { withFileTypes: true }),
|
|
1802
|
+
};
|
|
1803
|
+
|
|
1804
|
+
/**
|
|
1805
|
+
* Inspect one agent-definition directory while retaining traversal failure
|
|
1806
|
+
* state. A nested unreadable directory makes the whole inspection unavailable,
|
|
1807
|
+
* preventing a partial traversal from being reported as empty or complete.
|
|
1808
|
+
*/
|
|
1809
|
+
export function inspectAgentDefinitionDirectory(dir: string, operations: AgentDefinitionInspectionFs = DEFAULT_AGENT_DEFINITION_INSPECTION_FS): AgentDefinitionInspection {
|
|
1810
|
+
const root = path.resolve(dir);
|
|
1811
|
+
try {
|
|
1812
|
+
if (!operations.existsSync(root)) return rememberAgentDefinitionInspection({ files: [], state: "absent" }, [root]);
|
|
1813
|
+
if (!operations.statSync(root).isDirectory()) return rememberAgentDefinitionInspection({ files: [], state: "not-directory" }, [root]);
|
|
1814
|
+
} catch {
|
|
1815
|
+
return rememberAgentDefinitionInspection({ files: [], state: "unreadable" }, [root]);
|
|
1816
|
+
}
|
|
1817
|
+
const files: string[] = [];
|
|
1818
|
+
let unreadable = false;
|
|
1819
|
+
const visitedDirectories = new Set<string>();
|
|
1820
|
+
const inspectedDirectories = new Set<string>();
|
|
1821
|
+
const visit = (current: string): void => {
|
|
1822
|
+
inspectedDirectories.add(path.resolve(current));
|
|
1823
|
+
let realDir: string;
|
|
1824
|
+
try {
|
|
1825
|
+
realDir = operations.realpathSync?.(current) ?? path.resolve(current);
|
|
1826
|
+
} catch {
|
|
1827
|
+
unreadable = true;
|
|
1828
|
+
return;
|
|
1829
|
+
}
|
|
1830
|
+
if (visitedDirectories.has(realDir)) return;
|
|
1831
|
+
visitedDirectories.add(realDir);
|
|
1832
|
+
|
|
1833
|
+
let entries: fs.Dirent[];
|
|
1834
|
+
try {
|
|
1835
|
+
entries = operations.readdirSync(current).sort((a, b) => a.name.localeCompare(b.name));
|
|
1836
|
+
} catch {
|
|
1837
|
+
unreadable = true;
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1840
|
+
for (const entry of entries) {
|
|
1841
|
+
const filePath = path.join(current, entry.name);
|
|
1842
|
+
let isDirectory = entry.isDirectory();
|
|
1843
|
+
if (entry.isSymbolicLink()) {
|
|
1844
|
+
try {
|
|
1845
|
+
isDirectory = operations.statSync(filePath).isDirectory();
|
|
1846
|
+
} catch {
|
|
1847
|
+
isDirectory = false;
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
if (isDirectory) {
|
|
1851
|
+
if (!shouldPruneDiscoveryDir(root, filePath, entry.name)) visit(filePath);
|
|
1852
|
+
continue;
|
|
1853
|
+
}
|
|
1854
|
+
if ((entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith(".md") && !entry.name.endsWith(".chain.md") && !isLegacyAgentSkillPath(root, filePath)) files.push(filePath);
|
|
1855
|
+
}
|
|
1856
|
+
};
|
|
1857
|
+
visit(root);
|
|
1858
|
+
return rememberAgentDefinitionInspection({ files, state: unreadable ? "unreadable" : files.length ? "candidates" : "empty" }, inspectedDirectories);
|
|
1859
|
+
}
|
|
1860
|
+
|
|
1651
1861
|
function isLegacyAgentSkillPath(rootDir: string, filePath: string): boolean {
|
|
1652
1862
|
const relative = path.relative(rootDir, filePath);
|
|
1653
1863
|
const parts = relative.split(path.sep).map((part) => part.toLowerCase());
|
|
@@ -1706,24 +1916,29 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
|
|
|
1706
1916
|
if (runner.args !== undefined && (!Array.isArray(runner.args) || runner.args.some((arg) => typeof arg !== "string"))) {
|
|
1707
1917
|
throw new Error(`Agent '${agentName}' external-cli runner args must be an array of strings.`);
|
|
1708
1918
|
}
|
|
1919
|
+
if (runner.adapter !== undefined && !isCodeOwnedExternalCliAdapterId(runner.adapter)) throw new Error(`Agent '${agentName}' external-cli runner adapter must be ${CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL}.`);
|
|
1920
|
+
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.`);
|
|
1709
1921
|
if (runner.promptDelivery !== undefined && runner.promptDelivery !== "stdin") {
|
|
1710
1922
|
throw new Error(`Agent '${agentName}' external-cli runner promptDelivery must be 'stdin'.`);
|
|
1711
1923
|
}
|
|
1712
|
-
const
|
|
1924
|
+
const capabilities = parseExternalCliCapabilityNarrowing(runner.capabilities, `Agent '${agentName}' external-cli runner capabilities`);
|
|
1925
|
+
const supported = new Set(["type", "adapter", "command", "args", "promptDelivery", "capabilities"]);
|
|
1713
1926
|
const unknown = Object.keys(runner).filter((key) => !supported.has(key));
|
|
1714
1927
|
if (unknown.length > 0) throw new Error(`Agent '${agentName}' external-cli runner has unsupported fields: ${unknown.join(", ")}.`);
|
|
1715
1928
|
const runnerArgs = Array.isArray(runner.args) ? runner.args.filter((arg): arg is string => typeof arg === "string") : undefined;
|
|
1716
1929
|
return {
|
|
1717
1930
|
type: "external-cli",
|
|
1931
|
+
...(isCodeOwnedExternalCliAdapterId(runner.adapter) ? { adapter: runner.adapter } : {}),
|
|
1718
1932
|
command: runner.command.trim(),
|
|
1719
1933
|
...(runnerArgs?.length ? { args: runnerArgs } : {}),
|
|
1720
1934
|
...(runner.promptDelivery ? { promptDelivery: "stdin" as const } : {}),
|
|
1935
|
+
...(capabilities ? { capabilities } : {}),
|
|
1721
1936
|
};
|
|
1722
1937
|
}
|
|
1723
1938
|
|
|
1724
1939
|
function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
|
|
1725
1940
|
if (runner?.type !== "external-cli" && runner?.type !== "external-job") return;
|
|
1726
|
-
const unsupported = ["tools", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "permission", "permissions"]
|
|
1941
|
+
const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "sandbox", "permission", "permissions"]
|
|
1727
1942
|
.filter((field) => frontmatter[field] !== undefined);
|
|
1728
1943
|
if (unsupported.length > 0) {
|
|
1729
1944
|
throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
|
|
@@ -1748,9 +1963,9 @@ interface AgentDefinitionFile {
|
|
|
1748
1963
|
content: string;
|
|
1749
1964
|
}
|
|
1750
1965
|
|
|
1751
|
-
function readAgentDefinitionFiles(dir: string): AgentDefinitionFile[] {
|
|
1966
|
+
function readAgentDefinitionFiles(dir: string, inspection = inspectAgentDefinitionDirectory(dir)): AgentDefinitionFile[] {
|
|
1752
1967
|
const files: AgentDefinitionFile[] = [];
|
|
1753
|
-
for (const filePath of
|
|
1968
|
+
for (const filePath of inspection.files) {
|
|
1754
1969
|
if (isLegacyAgentSkillPath(dir, filePath)) {
|
|
1755
1970
|
continue;
|
|
1756
1971
|
}
|
|
@@ -1776,7 +1991,7 @@ function resolveAgentRelativeExtensionPaths(paths: string[] | undefined, agentFi
|
|
|
1776
1991
|
});
|
|
1777
1992
|
}
|
|
1778
1993
|
|
|
1779
|
-
function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir">): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
|
|
1994
|
+
function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir" | "scope">): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
|
|
1780
1995
|
const agents: AgentConfig[] = [];
|
|
1781
1996
|
const diagnostics: AgentDiscoveryDiagnostic[] = [];
|
|
1782
1997
|
|
|
@@ -1805,8 +2020,11 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1805
2020
|
const parsedTools = splitToolList(rawTools);
|
|
1806
2021
|
const tools = parsedTools.tools ?? [];
|
|
1807
2022
|
const mcpDirectTools = parsedTools.mcpDirectTools ?? [];
|
|
2023
|
+
const excludeTools = parseFrontmatterList(frontmatter.excludeTools);
|
|
1808
2024
|
const defaultReads = parseFrontmatterList(frontmatter.defaultReads);
|
|
1809
2025
|
const aliases = normalizeAgentAliases(parseFrontmatterList(frontmatter.aliases ?? frontmatter.alias), runtimeName);
|
|
2026
|
+
const profileError = validateCodeOwnedProfileRunner({ name: runtimeName, localName, aliases, runner });
|
|
2027
|
+
if (profileError) throw new Error(profileError);
|
|
1810
2028
|
const skillStr = frontmatter.skill || frontmatter.skills;
|
|
1811
2029
|
const skills = parseFrontmatterList(skillStr);
|
|
1812
2030
|
const skillPath = parseFrontmatterList(frontmatter.skillPath);
|
|
@@ -1821,6 +2039,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1821
2039
|
: frontmatter.inheritProjectContext === "false"
|
|
1822
2040
|
? false
|
|
1823
2041
|
: defaultInheritProjectContext(localName);
|
|
2042
|
+
const inheritGlobalContext = frontmatter.inheritGlobalContext === "true";
|
|
1824
2043
|
const inheritSkills = frontmatter.inheritSkills === "true"
|
|
1825
2044
|
? true
|
|
1826
2045
|
: frontmatter.inheritSkills === "false"
|
|
@@ -1853,13 +2072,6 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1853
2072
|
}
|
|
1854
2073
|
defaultToolTimeoutMs = parsed;
|
|
1855
2074
|
}
|
|
1856
|
-
let defaultTurnBudget: TurnBudgetConfig | undefined;
|
|
1857
|
-
if (frontmatter.turnBudget !== undefined && frontmatter.turnBudget.trim()) {
|
|
1858
|
-
const parsed = JSON.parse(frontmatter.turnBudget) as unknown;
|
|
1859
|
-
const resolved = resolveTurnBudgetConfig(parsed, `Agent '${localName}' turnBudget frontmatter`);
|
|
1860
|
-
if (resolved.error) throw new Error(resolved.error);
|
|
1861
|
-
defaultTurnBudget = resolved.turnBudget;
|
|
1862
|
-
}
|
|
1863
2075
|
const defaultAcceptance = parseAgentAcceptanceFrontmatter(frontmatter.acceptance, localName);
|
|
1864
2076
|
let outputMode: OutputMode | undefined;
|
|
1865
2077
|
if (frontmatter.outputMode !== undefined) {
|
|
@@ -1874,12 +2086,19 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1874
2086
|
|
|
1875
2087
|
const extensions = resolveAgentRelativeExtensionPaths(parseFrontmatterList(frontmatter.extensions), filePath);
|
|
1876
2088
|
const subagentOnlyExtensions = resolveAgentRelativeExtensionPaths(parseFrontmatterList(frontmatter.subagentOnlyExtensions), filePath);
|
|
2089
|
+
const mutationTools = parseFrontmatterList(frontmatter.mutationTools);
|
|
1877
2090
|
let fast: boolean | undefined;
|
|
1878
2091
|
if (frontmatter.fast !== undefined) {
|
|
1879
2092
|
if (frontmatter.fast === "true") fast = true;
|
|
1880
2093
|
else if (frontmatter.fast === "false") fast = false;
|
|
1881
2094
|
else throw new Error(`Agent '${localName}' has invalid fast frontmatter; expected true or false.`);
|
|
1882
2095
|
}
|
|
2096
|
+
let allowNestedSubagents: boolean | undefined;
|
|
2097
|
+
if (frontmatter.allowNestedSubagents !== undefined) {
|
|
2098
|
+
if (frontmatter.allowNestedSubagents === "true") allowNestedSubagents = true;
|
|
2099
|
+
else if (frontmatter.allowNestedSubagents === "false") allowNestedSubagents = false;
|
|
2100
|
+
else throw new Error(`Agent '${localName}' has invalid allowNestedSubagents frontmatter; expected true or false.`);
|
|
2101
|
+
}
|
|
1883
2102
|
|
|
1884
2103
|
const extraFields: Record<string, string> = {};
|
|
1885
2104
|
for (const [key, value] of Object.entries(frontmatter)) {
|
|
@@ -1887,6 +2106,9 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1887
2106
|
}
|
|
1888
2107
|
|
|
1889
2108
|
const parsedMaxSubagentDepth = Number(frontmatter.maxSubagentDepth);
|
|
2109
|
+
const sandbox = frontmatter.sandbox !== undefined
|
|
2110
|
+
? validateSandboxProfileName(frontmatter.sandbox, `Agent '${localName}' sandbox`)
|
|
2111
|
+
: undefined;
|
|
1890
2112
|
if (frontmatter.permission !== undefined && frontmatter.permissions !== undefined) {
|
|
1891
2113
|
throw new Error(`Agent '${localName}' cannot declare both permission and permissions frontmatter.`);
|
|
1892
2114
|
}
|
|
@@ -1923,6 +2145,8 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1923
2145
|
description: frontmatter.description,
|
|
1924
2146
|
...(aliases !== undefined ? { aliases } : {}),
|
|
1925
2147
|
...(rawTools !== undefined ? { tools } : {}),
|
|
2148
|
+
...(excludeTools !== undefined ? { excludeTools } : {}),
|
|
2149
|
+
...(allowNestedSubagents !== undefined ? { allowNestedSubagents } : {}),
|
|
1926
2150
|
...(mcpDirectTools.length > 0 ? { mcpDirectTools } : {}),
|
|
1927
2151
|
...(frontmatter.model !== undefined ? { model: frontmatter.model } : {}),
|
|
1928
2152
|
...(fallbackModels?.length ? { fallbackModels } : {}),
|
|
@@ -1930,12 +2154,12 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1930
2154
|
...(frontmatter.thinking !== undefined ? { thinking: frontmatter.thinking === "false" ? false : frontmatter.thinking } : {}),
|
|
1931
2155
|
systemPromptMode,
|
|
1932
2156
|
inheritProjectContext,
|
|
2157
|
+
inheritGlobalContext,
|
|
1933
2158
|
inheritSkills,
|
|
1934
2159
|
...(defaultContext !== undefined ? { defaultContext } : {}),
|
|
1935
2160
|
...(defaultAsync !== undefined ? { defaultAsync } : {}),
|
|
1936
2161
|
...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
|
|
1937
2162
|
...(defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs } : {}),
|
|
1938
|
-
...(defaultTurnBudget !== undefined ? { defaultTurnBudget } : {}),
|
|
1939
2163
|
...(defaultAcceptance !== undefined ? { defaultAcceptance } : {}),
|
|
1940
2164
|
...(acceptanceRole !== undefined ? { acceptanceRole } : {}),
|
|
1941
2165
|
systemPrompt: body,
|
|
@@ -1946,6 +2170,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1946
2170
|
...(skillPath?.length ? { skillPath } : {}),
|
|
1947
2171
|
...(extensions !== undefined ? { extensions } : {}),
|
|
1948
2172
|
...(subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions } : {}),
|
|
2173
|
+
...(mutationTools?.length ? { mutationTools } : {}),
|
|
1949
2174
|
...(frontmatter.output !== undefined ? { output: frontmatter.output } : {}),
|
|
1950
2175
|
...(outputMode !== undefined ? { outputMode } : {}),
|
|
1951
2176
|
...(defaultReads?.length ? { defaultReads } : {}),
|
|
@@ -1955,6 +2180,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1955
2180
|
...(maxSubagentDepth !== undefined ? { maxSubagentDepth } : {}),
|
|
1956
2181
|
...(completionGuard !== undefined ? { completionGuard } : {}),
|
|
1957
2182
|
...(toolBudget !== undefined ? { toolBudget } : {}),
|
|
2183
|
+
...(sandbox !== undefined ? { sandbox } : {}),
|
|
1958
2184
|
...(permissions !== undefined ? { permissions } : {}),
|
|
1959
2185
|
...(memory !== undefined ? { memory } : {}),
|
|
1960
2186
|
...(Object.keys(extraFields).length > 0 ? { extraFields } : {}),
|
|
@@ -1969,15 +2195,26 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1969
2195
|
return { agents, diagnostics };
|
|
1970
2196
|
}
|
|
1971
2197
|
|
|
1972
|
-
function loadAgentsFromDir(dir: string, source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir"
|
|
1973
|
-
return loadAgentsFromDefinitionFiles(readAgentDefinitionFiles(dir), source, discoveryPriority, packageSource);
|
|
2198
|
+
function loadAgentsFromDir(dir: string, source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir" | "scope">, inspection = inspectAgentDefinitionDirectory(dir)): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
|
|
2199
|
+
return loadAgentsFromDefinitionFiles(readAgentDefinitionFiles(dir, inspection), source, discoveryPriority, packageSource);
|
|
2200
|
+
}
|
|
2201
|
+
|
|
2202
|
+
function reportAgentDefinitionDirectory(source: AgentSource, dir: string, inspection: AgentDefinitionInspection): AgentDefinitionDirectoryReport {
|
|
2203
|
+
return {
|
|
2204
|
+
source,
|
|
2205
|
+
path: path.resolve(dir),
|
|
2206
|
+
state: inspection.state,
|
|
2207
|
+
...(inspection.state === "candidates" ? { candidateCount: inspection.files.length } : {}),
|
|
2208
|
+
};
|
|
1974
2209
|
}
|
|
1975
2210
|
|
|
1976
|
-
function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainConfig[]; diagnostics: ChainDiscoveryDiagnostic[] } {
|
|
2211
|
+
function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainConfig[]; diagnostics: ChainDiscoveryDiagnostic[]; files: string[]; directories: string[] } {
|
|
1977
2212
|
const chains = new Map<string, ChainConfig>();
|
|
1978
2213
|
const diagnostics: ChainDiscoveryDiagnostic[] = [];
|
|
2214
|
+
const directories = new Set<string>();
|
|
2215
|
+
const files = listFilesRecursive(dir, (fileName) => fileName.endsWith(".chain.md") || fileName.endsWith(".chain.json"), dir, new Set<string>(), directories);
|
|
1979
2216
|
|
|
1980
|
-
for (const filePath of
|
|
2217
|
+
for (const filePath of files) {
|
|
1981
2218
|
let content: string;
|
|
1982
2219
|
try {
|
|
1983
2220
|
content = fs.readFileSync(filePath, "utf-8");
|
|
@@ -1996,7 +2233,7 @@ function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainCon
|
|
|
1996
2233
|
}
|
|
1997
2234
|
}
|
|
1998
2235
|
|
|
1999
|
-
return { chains: Array.from(chains.values()), diagnostics };
|
|
2236
|
+
return { chains: Array.from(chains.values()), diagnostics, files, directories: [...directories] };
|
|
2000
2237
|
}
|
|
2001
2238
|
|
|
2002
2239
|
function isDirectory(p: string): boolean {
|
|
@@ -2007,20 +2244,18 @@ function isDirectory(p: string): boolean {
|
|
|
2007
2244
|
}
|
|
2008
2245
|
}
|
|
2009
2246
|
|
|
2010
|
-
function resolveNearestProjectAgentDirs(cwd: string): { readDirs: string[]; preferredDir: string | null } {
|
|
2247
|
+
function resolveNearestProjectAgentDirs(cwd: string): { readDirs: string[]; candidateDirs: string[]; preferredDir: string | null } {
|
|
2011
2248
|
const projectRoot = findConfiguredProjectRoot(cwd);
|
|
2012
|
-
if (!projectRoot) return { readDirs: [], preferredDir: null };
|
|
2249
|
+
if (!projectRoot) return { readDirs: [], candidateDirs: [], preferredDir: null };
|
|
2013
2250
|
|
|
2014
2251
|
const legacyDir = path.join(projectRoot, ".agents");
|
|
2015
2252
|
const preferredDir = path.join(getProjectConfigDir(projectRoot), "agents");
|
|
2253
|
+
const candidateDirs = [legacyDir, preferredDir];
|
|
2016
2254
|
const readDirs: string[] = [];
|
|
2017
2255
|
if (isDirectory(legacyDir)) readDirs.push(legacyDir);
|
|
2018
2256
|
if (isDirectory(preferredDir)) readDirs.push(preferredDir);
|
|
2019
2257
|
|
|
2020
|
-
return {
|
|
2021
|
-
readDirs,
|
|
2022
|
-
preferredDir,
|
|
2023
|
-
};
|
|
2258
|
+
return { readDirs, candidateDirs, preferredDir };
|
|
2024
2259
|
}
|
|
2025
2260
|
|
|
2026
2261
|
function resolveNearestProjectChainDirs(cwd: string): { readDirs: string[]; preferredDir: string | null } {
|
|
@@ -2034,7 +2269,9 @@ function resolveNearestProjectChainDirs(cwd: string): { readDirs: string[]; pref
|
|
|
2034
2269
|
};
|
|
2035
2270
|
}
|
|
2036
2271
|
const BUILTIN_AGENTS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "agents");
|
|
2037
|
-
|
|
2272
|
+
// Candidate files and inspection state must describe the same cached builtin scan.
|
|
2273
|
+
const BUILTIN_AGENT_DEFINITION_INSPECTION = inspectAgentDefinitionDirectory(BUILTIN_AGENTS_DIR);
|
|
2274
|
+
const BUILTIN_AGENT_DEFINITION_FILES = readAgentDefinitionFiles(BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION);
|
|
2038
2275
|
|
|
2039
2276
|
export const EXTRA_AGENT_DIRS_ENV = "PI_SUBAGENT_EXTRA_AGENT_DIRS";
|
|
2040
2277
|
|
|
@@ -2052,92 +2289,62 @@ function extraUserAgentDirs(): string[] {
|
|
|
2052
2289
|
.filter((dir) => dir.length > 0);
|
|
2053
2290
|
}
|
|
2054
2291
|
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
const userSettingsPath = getUserAgentSettingsPath();
|
|
2060
|
-
const projectSettingsPath = getProjectAgentSettingsPath(cwd);
|
|
2061
|
-
const userSettings = scope === "project" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(userSettingsPath);
|
|
2062
|
-
const projectSettings = scope === "user" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(projectSettingsPath);
|
|
2063
|
-
const defaultProvider = resolveSubagentDefaultProvider(userSettings, projectSettings, projectSettingsPath);
|
|
2064
|
-
const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath, defaultProvider);
|
|
2065
|
-
const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
|
|
2066
|
-
const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, projectSettingsPath);
|
|
2067
|
-
const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
|
|
2068
|
-
const injectAgents = projectSettingsPath && projectSettings.injectAgents !== undefined
|
|
2069
|
-
? projectSettings.injectAgents
|
|
2070
|
-
: userSettings.injectAgents;
|
|
2071
|
-
const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
|
|
2072
|
-
const packageSubagentPaths = collectPackageSubagentPaths(cwd, {
|
|
2073
|
-
includeUser: scope !== "project",
|
|
2074
|
-
includeProject: scope !== "user",
|
|
2075
|
-
});
|
|
2076
|
-
|
|
2077
|
-
const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
|
|
2078
|
-
const builtinAgents = applyBuiltinOverrides(
|
|
2079
|
-
applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions),
|
|
2080
|
-
userSettings,
|
|
2081
|
-
projectSettings,
|
|
2082
|
-
userSettingsPath,
|
|
2083
|
-
projectSettingsPath,
|
|
2084
|
-
);
|
|
2085
|
-
|
|
2086
|
-
const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), userDirOld, userDirNew]
|
|
2087
|
-
.map((dir, discoveryPriority) => loadAgentsFromDir(dir, "user", discoveryPriority));
|
|
2088
|
-
const userAgents = applyCustomAgentOverrides(
|
|
2089
|
-
applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions),
|
|
2090
|
-
userSettings,
|
|
2091
|
-
projectSettings,
|
|
2092
|
-
userSettingsPath,
|
|
2093
|
-
projectSettingsPath,
|
|
2094
|
-
);
|
|
2292
|
+
interface AgentScanDirs {
|
|
2293
|
+
dirs: string[];
|
|
2294
|
+
watchPaths: string[];
|
|
2295
|
+
}
|
|
2095
2296
|
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
for (const loaded of packageLoaded) {
|
|
2107
|
-
for (const agent of loaded.agents) {
|
|
2108
|
-
if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
|
|
2109
|
-
}
|
|
2297
|
+
function readConfiguredAgentScanDirs(filePath: string | null): string[] {
|
|
2298
|
+
if (!filePath) return [];
|
|
2299
|
+
try {
|
|
2300
|
+
const settings = readSettingsFileStrict(filePath);
|
|
2301
|
+
const subagents = settings.subagents;
|
|
2302
|
+
if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return [];
|
|
2303
|
+
const dirs = (subagents as { agentScanDirs?: unknown }).agentScanDirs;
|
|
2304
|
+
return Array.isArray(dirs) ? dirs.filter((dir): dir is string => typeof dir === "string" && dir.trim().length > 0) : [];
|
|
2305
|
+
} catch {
|
|
2306
|
+
return [];
|
|
2110
2307
|
}
|
|
2111
|
-
|
|
2112
|
-
applySubagentDefaults(Array.from(packageMap.values()), defaultModel, defaultProvider, defaultThinking, defaultExtensions),
|
|
2113
|
-
userSettings,
|
|
2114
|
-
projectSettings,
|
|
2115
|
-
userSettingsPath,
|
|
2116
|
-
projectSettingsPath,
|
|
2117
|
-
);
|
|
2118
|
-
const agents = applySubagentMaxThinking(
|
|
2119
|
-
mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents)
|
|
2120
|
-
.filter((agent) => agent.disabled !== true),
|
|
2121
|
-
maxThinking,
|
|
2122
|
-
);
|
|
2308
|
+
}
|
|
2123
2309
|
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2310
|
+
function expandAgentScanDirPattern(pattern: string): AgentScanDirs {
|
|
2311
|
+
const expanded = expandHomePath(pattern.trim()).replace(/[\\/]+/g, path.sep);
|
|
2312
|
+
if (!expanded) return { dirs: [], watchPaths: [] };
|
|
2313
|
+
const wildcardMatches = [...expanded.matchAll(/\*/g)];
|
|
2314
|
+
if (wildcardMatches.length === 0) {
|
|
2315
|
+
const dir = path.resolve(expanded);
|
|
2316
|
+
return { dirs: fs.existsSync(dir) ? [dir] : [], watchPaths: [dir] };
|
|
2317
|
+
}
|
|
2318
|
+
const parts = expanded.split(path.sep);
|
|
2319
|
+
const wildcardIndex = parts.findIndex((part) => part.includes("*"));
|
|
2320
|
+
if (wildcardMatches.length !== 1 || wildcardIndex === -1 || parts[wildcardIndex] !== "*") return { dirs: [], watchPaths: [] };
|
|
2321
|
+
const base = path.resolve(parts.slice(0, wildcardIndex).join(path.sep) || path.sep);
|
|
2322
|
+
const rest = parts.slice(wildcardIndex + 1);
|
|
2323
|
+
let entries: fs.Dirent[];
|
|
2324
|
+
try {
|
|
2325
|
+
entries = fs.readdirSync(base, { withFileTypes: true });
|
|
2326
|
+
} catch {
|
|
2327
|
+
return { dirs: [], watchPaths: [base] };
|
|
2328
|
+
}
|
|
2329
|
+
const candidateDirs = entries.filter((entry) => entry.isDirectory()).map((entry) => path.join(base, entry.name, ...rest));
|
|
2130
2330
|
return {
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
projectAgentsDir,
|
|
2134
|
-
...(modelScope !== undefined ? { modelScope } : {}),
|
|
2135
|
-
...(injectAgents?.length ? { injectAgents } : {}),
|
|
2136
|
-
...(maxThinking !== undefined ? { maxThinking } : {}),
|
|
2331
|
+
dirs: candidateDirs.filter((dir) => fs.existsSync(dir)),
|
|
2332
|
+
watchPaths: [base, ...candidateDirs],
|
|
2137
2333
|
};
|
|
2138
2334
|
}
|
|
2139
2335
|
|
|
2140
|
-
|
|
2336
|
+
function settingsAgentScanDirs(entries: string[]): AgentScanDirs {
|
|
2337
|
+
const dirs = new Set<string>();
|
|
2338
|
+
const watchPaths = new Set<string>();
|
|
2339
|
+
for (const entry of entries) {
|
|
2340
|
+
const expanded = expandAgentScanDirPattern(entry);
|
|
2341
|
+
for (const dir of expanded.dirs) dirs.add(dir);
|
|
2342
|
+
for (const watchPath of expanded.watchPaths) watchPaths.add(watchPath);
|
|
2343
|
+
}
|
|
2344
|
+
return { dirs: [...dirs], watchPaths: [...watchPaths] };
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
export interface AgentDiscoveryAllResult {
|
|
2141
2348
|
builtin: AgentConfig[];
|
|
2142
2349
|
package: AgentConfig[];
|
|
2143
2350
|
user: AgentConfig[];
|
|
@@ -2153,129 +2360,485 @@ export function discoverAgentsAll(cwd: string): {
|
|
|
2153
2360
|
userSettingsPath: string;
|
|
2154
2361
|
projectSettingsPath: string | null;
|
|
2155
2362
|
maxThinking?: ThinkingLevel;
|
|
2156
|
-
}
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
/**
|
|
2366
|
+
* A single fresh source scan with both projections retained. The effective
|
|
2367
|
+
* projection intentionally remains separate from the all-source projection:
|
|
2368
|
+
* disabled and shadowed definitions are needed for diagnostics and runtime
|
|
2369
|
+
* collision checks even when they are not launchable.
|
|
2370
|
+
*/
|
|
2371
|
+
export interface AgentDiscoverySnapshot {
|
|
2372
|
+
effective: AgentDiscoveryResult;
|
|
2373
|
+
all: AgentDiscoveryAllResult;
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
interface LoadedAgentDirectory {
|
|
2377
|
+
dir: string;
|
|
2378
|
+
inspection: AgentDefinitionInspection;
|
|
2379
|
+
loaded: ReturnType<typeof loadAgentsFromDir>;
|
|
2380
|
+
packageEntry?: PackageSubagentPath;
|
|
2381
|
+
}
|
|
2382
|
+
|
|
2383
|
+
interface AgentDiscoverySources {
|
|
2384
|
+
cwd: string;
|
|
2385
|
+
preferredModelProvider?: string;
|
|
2386
|
+
userDir: string;
|
|
2387
|
+
userDirOld: string;
|
|
2388
|
+
userDirNew: string;
|
|
2389
|
+
userChainDir: string;
|
|
2390
|
+
projectAgentDirs: string[];
|
|
2391
|
+
projectCandidateDirs: string[];
|
|
2392
|
+
projectAgentsDir: string | null;
|
|
2393
|
+
projectChainDirs: string[];
|
|
2394
|
+
projectChainDir: string | null;
|
|
2395
|
+
userSettingsPath: string;
|
|
2396
|
+
projectSettingsPath: string | null;
|
|
2397
|
+
userSettings?: SubagentSettings;
|
|
2398
|
+
projectSettings?: SubagentSettings;
|
|
2399
|
+
packageSubagentPaths: PackageSubagentPaths;
|
|
2400
|
+
builtinLoaded: ReturnType<typeof loadAgentsFromDefinitionFiles>;
|
|
2401
|
+
userLoaded: LoadedAgentDirectory[];
|
|
2402
|
+
projectLoaded: LoadedAgentDirectory[];
|
|
2403
|
+
projectInspections: Map<string, AgentDefinitionInspection>;
|
|
2404
|
+
packageLoaded: LoadedAgentDirectory[];
|
|
2405
|
+
userChains?: ReturnType<typeof loadChainsFromDir>;
|
|
2406
|
+
projectChainLoaded?: Array<{ dir: string; loaded: ReturnType<typeof loadChainsFromDir> }>;
|
|
2407
|
+
packageChainLoaded?: Array<{ entry: PackageChainPath; loaded: ReturnType<typeof loadChainsFromDir> }>;
|
|
2408
|
+
watchPaths: string[];
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
interface AgentDiscoveryCacheEntry {
|
|
2412
|
+
sources: AgentDiscoverySources;
|
|
2413
|
+
fingerprint: string;
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
const agentDiscoveryCache = new Map<string, AgentDiscoveryCacheEntry>();
|
|
2417
|
+
|
|
2418
|
+
function isPathWithin(root: string, candidate: string): boolean {
|
|
2419
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
2420
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
function addDirectoryWatchPaths(paths: Set<string>, root: string, files: readonly string[], directories: readonly string[] = []): void {
|
|
2424
|
+
const resolvedRoot = path.resolve(root);
|
|
2425
|
+
paths.add(resolvedRoot);
|
|
2426
|
+
// The initial recursive inspection is already bounded to this discovery
|
|
2427
|
+
// root. Keep every visited directory in the fingerprint so a file added to
|
|
2428
|
+
// an existing empty nested directory invalidates the snapshot too.
|
|
2429
|
+
for (const directory of directories) {
|
|
2430
|
+
if (isPathWithin(resolvedRoot, directory)) paths.add(path.resolve(directory));
|
|
2431
|
+
}
|
|
2432
|
+
for (const file of files) {
|
|
2433
|
+
paths.add(path.resolve(file));
|
|
2434
|
+
let current = path.resolve(path.dirname(file));
|
|
2435
|
+
while (isPathWithin(resolvedRoot, current)) {
|
|
2436
|
+
paths.add(current);
|
|
2437
|
+
if (current === resolvedRoot) break;
|
|
2438
|
+
current = path.dirname(current);
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
function watchPathSignature(filePath: string): string {
|
|
2444
|
+
try {
|
|
2445
|
+
const stat = fs.statSync(filePath);
|
|
2446
|
+
if (stat.isDirectory()) {
|
|
2447
|
+
const entries = fs.readdirSync(filePath, { withFileTypes: true })
|
|
2448
|
+
.sort((left, right) => left.name.localeCompare(right.name))
|
|
2449
|
+
.map((entry) => `${entry.name}:${entry.isDirectory() ? "d" : entry.isSymbolicLink() ? "l" : "f"}`)
|
|
2450
|
+
.join("|");
|
|
2451
|
+
return `directory:${entries}`;
|
|
2452
|
+
}
|
|
2453
|
+
return `file:${stat.size}:${stat.mtimeMs}`;
|
|
2454
|
+
} catch {
|
|
2455
|
+
return "missing";
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
function discoveryFingerprint(paths: readonly string[]): string {
|
|
2460
|
+
return [...new Set(paths)]
|
|
2461
|
+
.sort((left, right) => left.localeCompare(right))
|
|
2462
|
+
.map((filePath) => `${filePath}:${watchPathSignature(filePath)}`)
|
|
2463
|
+
.join("\n");
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2466
|
+
function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined): string {
|
|
2467
|
+
return JSON.stringify([
|
|
2468
|
+
path.resolve(cwd),
|
|
2469
|
+
preferredModelProvider ?? null,
|
|
2470
|
+
getProjectConfigDir(path.resolve(cwd)),
|
|
2471
|
+
getAgentDir(),
|
|
2472
|
+
os.homedir(),
|
|
2473
|
+
process.env.HOME ?? "",
|
|
2474
|
+
process.env.USERPROFILE ?? "",
|
|
2475
|
+
process.env[EXTRA_AGENT_DIRS_ENV] ?? "",
|
|
2476
|
+
process.env.PI_OFFLINE ?? "",
|
|
2477
|
+
process.env.APPDATA ?? "",
|
|
2478
|
+
]);
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
function projectDiscoveryWatchPaths(cwd: string): string[] {
|
|
2482
|
+
const paths: string[] = [];
|
|
2483
|
+
let current = path.resolve(cwd);
|
|
2484
|
+
while (true) {
|
|
2485
|
+
paths.push(getProjectConfigDir(current), path.join(current, ".agents"), path.join(current, ".git"));
|
|
2486
|
+
const parent = path.dirname(current);
|
|
2487
|
+
if (parent === current) break;
|
|
2488
|
+
current = parent;
|
|
2489
|
+
}
|
|
2490
|
+
return paths;
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
function packageEntryIncluded(scope: AgentScope, packageScopes: PackageSubagentPath["scope"]): boolean {
|
|
2494
|
+
if (scope === "both" || packageScopes.has("root")) return true;
|
|
2495
|
+
return packageScopes.has(scope);
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string): AgentDiscoverySources {
|
|
2499
|
+
const effectiveCwd = path.resolve(cwd);
|
|
2157
2500
|
const userDirOld = path.join(getAgentDir(), "agents");
|
|
2158
2501
|
const userDirNew = path.join(os.homedir(), ".agents");
|
|
2159
2502
|
const userChainDir = getUserChainDir();
|
|
2160
|
-
const { readDirs:
|
|
2161
|
-
const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(
|
|
2503
|
+
const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(effectiveCwd);
|
|
2504
|
+
const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(effectiveCwd);
|
|
2162
2505
|
const userSettingsPath = getUserAgentSettingsPath();
|
|
2163
|
-
const projectSettingsPath = getProjectAgentSettingsPath(
|
|
2164
|
-
const
|
|
2165
|
-
const
|
|
2166
|
-
const
|
|
2167
|
-
const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath, defaultProvider);
|
|
2168
|
-
const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
|
|
2169
|
-
const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, projectSettingsPath);
|
|
2170
|
-
const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
|
|
2171
|
-
const injectAgents = projectSettingsPath && projectSettings.injectAgents !== undefined
|
|
2172
|
-
? projectSettings.injectAgents
|
|
2173
|
-
: userSettings.injectAgents;
|
|
2174
|
-
const packageSubagentPaths = collectPackageSubagentPaths(cwd);
|
|
2506
|
+
const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
|
|
2507
|
+
const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd);
|
|
2508
|
+
const userScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(userSettingsPath));
|
|
2509
|
+
const projectScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(projectSettingsPath));
|
|
2175
2510
|
|
|
2176
2511
|
const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
|
|
2177
|
-
const
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2512
|
+
const userLoaded = [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].map((dir, discoveryPriority): LoadedAgentDirectory => {
|
|
2513
|
+
const inspection = inspectAgentDefinitionDirectory(dir);
|
|
2514
|
+
return { dir, inspection, loaded: loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection) };
|
|
2515
|
+
});
|
|
2516
|
+
const projectInspections = new Map(projectCandidateDirs.map((dir) => [dir, inspectAgentDefinitionDirectory(dir)]));
|
|
2517
|
+
const projectLoaded = [...projectScanDirs.dirs, ...projectAgentDirs].map((dir, discoveryPriority): LoadedAgentDirectory => {
|
|
2518
|
+
const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir);
|
|
2519
|
+
return { dir, inspection, loaded: loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection) };
|
|
2520
|
+
});
|
|
2521
|
+
const packageLoaded = packageSubagentPaths.agents.map((entry, index): LoadedAgentDirectory => {
|
|
2522
|
+
const inspection = inspectAgentDefinitionDirectory(entry.dir);
|
|
2523
|
+
return { dir: entry.dir, inspection, packageEntry: entry, loaded: loadAgentsFromDir(entry.dir, "package", packageSubagentPaths.agents.length - index, entry, inspection) };
|
|
2524
|
+
});
|
|
2525
|
+
|
|
2526
|
+
const watchPaths = new Set<string>([
|
|
2181
2527
|
userSettingsPath,
|
|
2182
|
-
projectSettingsPath,
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
.
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2528
|
+
...(projectSettingsPath ? [projectSettingsPath] : []),
|
|
2529
|
+
...projectDiscoveryWatchPaths(effectiveCwd),
|
|
2530
|
+
...findProjectRootCandidates(effectiveCwd).map((root) => path.join(getProjectConfigDir(root), "settings.json")),
|
|
2531
|
+
...userScanDirs.watchPaths,
|
|
2532
|
+
...projectScanDirs.watchPaths,
|
|
2533
|
+
...packageSubagentPaths.watchPaths,
|
|
2534
|
+
]);
|
|
2535
|
+
for (const directory of userLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
|
|
2536
|
+
for (const dir of projectCandidateDirs) {
|
|
2537
|
+
const inspection = projectInspections.get(dir);
|
|
2538
|
+
addDirectoryWatchPaths(watchPaths, dir, inspection?.files ?? [], inspection ? inspectedAgentDefinitionDirectories(inspection, dir) : []);
|
|
2539
|
+
}
|
|
2540
|
+
for (const directory of projectLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
|
|
2541
|
+
for (const directory of packageLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
|
|
2542
|
+
|
|
2543
|
+
const userDir = process.env.PI_CODING_AGENT_DIR ? userDirOld : fs.existsSync(userDirNew) ? userDirNew : userDirOld;
|
|
2544
|
+
return {
|
|
2545
|
+
cwd: effectiveCwd,
|
|
2546
|
+
...(preferredModelProvider !== undefined ? { preferredModelProvider } : {}),
|
|
2547
|
+
userDir,
|
|
2548
|
+
userDirOld,
|
|
2549
|
+
userDirNew,
|
|
2550
|
+
userChainDir,
|
|
2551
|
+
projectAgentDirs,
|
|
2552
|
+
projectCandidateDirs,
|
|
2553
|
+
projectAgentsDir,
|
|
2554
|
+
projectChainDirs,
|
|
2555
|
+
projectChainDir,
|
|
2190
2556
|
userSettingsPath,
|
|
2191
2557
|
projectSettingsPath,
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2558
|
+
packageSubagentPaths,
|
|
2559
|
+
builtinLoaded,
|
|
2560
|
+
userLoaded,
|
|
2561
|
+
projectLoaded,
|
|
2562
|
+
projectInspections,
|
|
2563
|
+
packageLoaded,
|
|
2564
|
+
watchPaths: [...watchPaths],
|
|
2565
|
+
};
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2568
|
+
function ensureDiscoveryChains(sources: AgentDiscoverySources): void {
|
|
2569
|
+
if (sources.userChains) return;
|
|
2570
|
+
sources.packageChainLoaded = sources.packageSubagentPaths.chains.map((entry) => ({ entry, loaded: loadChainsFromDir(entry.dir, "package") }));
|
|
2571
|
+
sources.userChains = loadChainsFromDir(sources.userChainDir, "user");
|
|
2572
|
+
sources.projectChainLoaded = sources.projectChainDirs.map((dir) => ({ dir, loaded: loadChainsFromDir(dir, "project") }));
|
|
2573
|
+
const watchPaths = new Set(sources.watchPaths);
|
|
2574
|
+
addDirectoryWatchPaths(watchPaths, sources.userChainDir, sources.userChains.files, sources.userChains.directories);
|
|
2575
|
+
for (const chain of sources.projectChainLoaded) addDirectoryWatchPaths(watchPaths, chain.dir, chain.loaded.files, chain.loaded.directories);
|
|
2576
|
+
for (const chain of sources.packageChainLoaded) addDirectoryWatchPaths(watchPaths, chain.entry.dir, chain.loaded.files, chain.loaded.directories);
|
|
2577
|
+
sources.watchPaths = [...watchPaths];
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false): AgentDiscoverySources {
|
|
2581
|
+
const key = discoveryCacheKey(cwd, preferredModelProvider);
|
|
2582
|
+
const cached = agentDiscoveryCache.get(key);
|
|
2583
|
+
if (cached && cached.fingerprint === discoveryFingerprint(cached.sources.watchPaths)) {
|
|
2584
|
+
if (includeChains) {
|
|
2585
|
+
ensureDiscoveryChains(cached.sources);
|
|
2586
|
+
cached.fingerprint = discoveryFingerprint(cached.sources.watchPaths);
|
|
2200
2587
|
}
|
|
2588
|
+
return cached.sources;
|
|
2589
|
+
}
|
|
2590
|
+
const sources = buildAgentDiscoverySources(cwd, preferredModelProvider);
|
|
2591
|
+
const entry = { sources, fingerprint: discoveryFingerprint(sources.watchPaths) };
|
|
2592
|
+
agentDiscoveryCache.set(key, entry);
|
|
2593
|
+
if (includeChains) {
|
|
2594
|
+
ensureDiscoveryChains(sources);
|
|
2595
|
+
entry.fingerprint = discoveryFingerprint(sources.watchPaths);
|
|
2596
|
+
}
|
|
2597
|
+
return sources;
|
|
2598
|
+
}
|
|
2599
|
+
|
|
2600
|
+
/** Clear process-local discovery snapshots, primarily for hosts that reload settings in place. */
|
|
2601
|
+
export function clearAgentDiscoveryCache(): void {
|
|
2602
|
+
agentDiscoveryCache.clear();
|
|
2603
|
+
}
|
|
2604
|
+
|
|
2605
|
+
function ensureSettingsForScope(sources: AgentDiscoverySources, scope: AgentScope, preferredModelProvider?: string): void {
|
|
2606
|
+
if (scope !== "project" && sources.userSettings === undefined) {
|
|
2607
|
+
if (sources.packageSubagentPaths.settingsErrors.user) throw sources.packageSubagentPaths.settingsErrors.user;
|
|
2608
|
+
sources.userSettings = selectProviderOverrides(readSubagentSettings(sources.userSettingsPath), preferredModelProvider);
|
|
2609
|
+
}
|
|
2610
|
+
if (scope !== "user" && sources.projectSettings === undefined) {
|
|
2611
|
+
if (sources.packageSubagentPaths.settingsErrors.project) throw sources.packageSubagentPaths.settingsErrors.project;
|
|
2612
|
+
sources.projectSettings = selectProviderOverrides(readSubagentSettings(sources.projectSettingsPath), preferredModelProvider);
|
|
2201
2613
|
}
|
|
2202
|
-
|
|
2203
|
-
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
function settingsForScope(sources: AgentDiscoverySources, scope: AgentScope): { user: SubagentSettings; project: SubagentSettings } {
|
|
2617
|
+
// Parse only settings that participate in this projection. The source cache
|
|
2618
|
+
// still retains both source trees, while malformed out-of-scope settings do
|
|
2619
|
+
// not make an otherwise valid scoped projection fail.
|
|
2620
|
+
ensureSettingsForScope(sources, scope, sources.preferredModelProvider);
|
|
2621
|
+
return {
|
|
2622
|
+
user: scope === "project" ? EMPTY_SUBAGENT_SETTINGS : sources.userSettings ?? EMPTY_SUBAGENT_SETTINGS,
|
|
2623
|
+
project: scope === "user" ? EMPTY_SUBAGENT_SETTINGS : sources.projectSettings ?? EMPTY_SUBAGENT_SETTINGS,
|
|
2624
|
+
};
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
function configuredAgentsForScope(sources: AgentDiscoverySources, scope: AgentScope, settingsScope = scope): {
|
|
2628
|
+
builtin: AgentConfig[];
|
|
2629
|
+
package: AgentConfig[];
|
|
2630
|
+
user: AgentConfig[];
|
|
2631
|
+
project: AgentConfig[];
|
|
2632
|
+
userSettings: SubagentSettings;
|
|
2633
|
+
projectSettings: SubagentSettings;
|
|
2634
|
+
maxThinking?: ThinkingLevel;
|
|
2635
|
+
modelScope?: ModelScopeConfig;
|
|
2636
|
+
} {
|
|
2637
|
+
const { user: userSettings, project: projectSettings } = settingsForScope(sources, settingsScope);
|
|
2638
|
+
const defaultProvider = resolveSubagentDefaultProvider(userSettings, projectSettings, sources.projectSettingsPath);
|
|
2639
|
+
const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath, defaultProvider);
|
|
2640
|
+
const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, sources.projectSettingsPath);
|
|
2641
|
+
const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, sources.projectSettingsPath);
|
|
2642
|
+
const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, sources.projectSettingsPath);
|
|
2643
|
+
const applyDefaults = (agents: AgentConfig[]): AgentConfig[] => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions);
|
|
2644
|
+
const builtin = applyBuiltinOverrides(applyDefaults(sources.builtinLoaded.agents), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
|
|
2645
|
+
const user = applyCustomAgentOverrides(
|
|
2646
|
+
applyDefaults(scope === "project" ? [] : sources.userLoaded.flatMap((loaded) => loaded.loaded.agents)),
|
|
2204
2647
|
userSettings,
|
|
2205
2648
|
projectSettings,
|
|
2206
|
-
userSettingsPath,
|
|
2207
|
-
projectSettingsPath,
|
|
2649
|
+
sources.userSettingsPath,
|
|
2650
|
+
sources.projectSettingsPath,
|
|
2208
2651
|
);
|
|
2209
2652
|
const projectMap = new Map<string, AgentConfig>();
|
|
2210
|
-
const
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
}
|
|
2653
|
+
if (scope !== "user") for (const loaded of sources.projectLoaded) for (const agent of loaded.loaded.agents) projectMap.set(agent.name, agent);
|
|
2654
|
+
const project = applyCustomAgentOverrides(applyDefaults(Array.from(projectMap.values())), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
|
|
2655
|
+
const packageMap = new Map<string, AgentConfig>();
|
|
2656
|
+
for (const loaded of sources.packageLoaded) {
|
|
2657
|
+
if (!loaded.packageEntry || !packageEntryIncluded(scope, loaded.packageEntry.scope)) continue;
|
|
2658
|
+
for (const agent of loaded.loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
|
|
2217
2659
|
}
|
|
2218
|
-
const
|
|
2219
|
-
|
|
2660
|
+
const packageAgents = applyCustomAgentOverrides(applyDefaults(Array.from(packageMap.values())), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
|
|
2661
|
+
return {
|
|
2662
|
+
builtin,
|
|
2663
|
+
package: packageAgents,
|
|
2664
|
+
user,
|
|
2665
|
+
project,
|
|
2220
2666
|
userSettings,
|
|
2221
2667
|
projectSettings,
|
|
2222
|
-
|
|
2223
|
-
|
|
2668
|
+
maxThinking,
|
|
2669
|
+
modelScope: projectSettings.modelScope ?? userSettings.modelScope,
|
|
2670
|
+
};
|
|
2671
|
+
}
|
|
2672
|
+
|
|
2673
|
+
function discoveryDirectories(sources: AgentDiscoverySources, scope: AgentScope): AgentDefinitionDirectoryReport[] {
|
|
2674
|
+
const directories: AgentDefinitionDirectoryReport[] = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
|
|
2675
|
+
if (scope !== "project") for (const directory of sources.userLoaded) directories.push(reportAgentDefinitionDirectory("user", directory.dir, directory.inspection));
|
|
2676
|
+
if (scope !== "user") {
|
|
2677
|
+
const reported = new Set<string>();
|
|
2678
|
+
for (const dir of sources.projectCandidateDirs) {
|
|
2679
|
+
reported.add(path.resolve(dir));
|
|
2680
|
+
directories.push(reportAgentDefinitionDirectory("project", dir, sources.projectInspections.get(dir)!));
|
|
2681
|
+
}
|
|
2682
|
+
for (const directory of sources.projectLoaded) {
|
|
2683
|
+
if (!reported.has(path.resolve(directory.dir))) directories.push(reportAgentDefinitionDirectory("project", directory.dir, directory.inspection));
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
for (const directory of sources.packageLoaded) {
|
|
2687
|
+
if (directory.packageEntry && packageEntryIncluded(scope, directory.packageEntry.scope)) directories.push(reportAgentDefinitionDirectory("package", directory.dir, directory.inspection));
|
|
2688
|
+
}
|
|
2689
|
+
return directories;
|
|
2690
|
+
}
|
|
2691
|
+
|
|
2692
|
+
function discoveryDiagnostics(sources: AgentDiscoverySources, scope: AgentScope): AgentDiscoveryDiagnostic[] {
|
|
2693
|
+
return [
|
|
2694
|
+
...sources.builtinLoaded.diagnostics,
|
|
2695
|
+
...(scope === "project" ? [] : sources.userLoaded.flatMap((loaded) => loaded.loaded.diagnostics)),
|
|
2696
|
+
...(scope === "user" ? [] : sources.projectLoaded.flatMap((loaded) => loaded.loaded.diagnostics)),
|
|
2697
|
+
...sources.packageLoaded
|
|
2698
|
+
.filter((loaded) => loaded.packageEntry && packageEntryIncluded(scope, loaded.packageEntry.scope))
|
|
2699
|
+
.flatMap((loaded) => loaded.loaded.diagnostics),
|
|
2700
|
+
];
|
|
2701
|
+
}
|
|
2702
|
+
|
|
2703
|
+
function buildEffectiveDiscovery(sources: AgentDiscoverySources, scope: AgentScope): AgentDiscoveryResult {
|
|
2704
|
+
const configured = configuredAgentsForScope(sources, scope);
|
|
2705
|
+
const { user: effectiveUserSettings, project: effectiveProjectSettings } = settingsForScope(sources, scope);
|
|
2706
|
+
const injectAgents = effectiveProjectSettings.injectAgents !== undefined
|
|
2707
|
+
? effectiveProjectSettings.injectAgents
|
|
2708
|
+
: effectiveUserSettings.injectAgents;
|
|
2709
|
+
const agents = applySubagentMaxThinking(
|
|
2710
|
+
mergeAgentsForScope(scope, configured.user, configured.project, configured.builtin, configured.package).filter((agent) => agent.disabled !== true),
|
|
2711
|
+
configured.maxThinking,
|
|
2224
2712
|
);
|
|
2713
|
+
return {
|
|
2714
|
+
agents,
|
|
2715
|
+
agentDiagnostics: discoveryDiagnostics(sources, scope),
|
|
2716
|
+
projectAgentsDir: sources.projectAgentsDir,
|
|
2717
|
+
cwd: sources.cwd,
|
|
2718
|
+
scope,
|
|
2719
|
+
directories: discoveryDirectories(sources, scope),
|
|
2720
|
+
...(configured.modelScope !== undefined ? { modelScope: configured.modelScope } : {}),
|
|
2721
|
+
...(injectAgents?.length ? { injectAgents } : {}),
|
|
2722
|
+
...(configured.maxThinking !== undefined ? { maxThinking: configured.maxThinking } : {}),
|
|
2723
|
+
};
|
|
2724
|
+
}
|
|
2225
2725
|
|
|
2226
|
-
|
|
2227
|
-
|
|
2726
|
+
function buildAllDiscovery(sources: AgentDiscoverySources, includeChains: boolean, settingsScope: AgentScope): AgentDiscoveryAllResult {
|
|
2727
|
+
if (includeChains) ensureDiscoveryChains(sources);
|
|
2728
|
+
const configured = configuredAgentsForScope(sources, "both", settingsScope);
|
|
2729
|
+
const { user: allUserSettings, project: allProjectSettings } = settingsForScope(sources, settingsScope);
|
|
2730
|
+
const injectAgents = allProjectSettings.injectAgents !== undefined
|
|
2731
|
+
? allProjectSettings.injectAgents
|
|
2732
|
+
: allUserSettings.injectAgents;
|
|
2228
2733
|
const packageChainMap = new Map<string, ChainConfig>();
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
packageChainDiagnostics.push(...loaded.diagnostics);
|
|
2232
|
-
for (const
|
|
2233
|
-
if (!packageChainMap.has(chain.name)) packageChainMap.set(chain.name, chain);
|
|
2234
|
-
}
|
|
2734
|
+
const packageChainDiagnostics: ChainDiscoveryDiagnostic[] = [];
|
|
2735
|
+
for (const chain of sources.packageChainLoaded ?? []) {
|
|
2736
|
+
packageChainDiagnostics.push(...chain.loaded.diagnostics);
|
|
2737
|
+
for (const definition of chain.loaded.chains) if (!packageChainMap.has(definition.name)) packageChainMap.set(definition.name, definition);
|
|
2235
2738
|
}
|
|
2739
|
+
const projectChainMap = new Map<string, ChainConfig>();
|
|
2236
2740
|
const projectChainDiagnostics: ChainDiscoveryDiagnostic[] = [];
|
|
2237
|
-
for (const
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
for (const chain of loaded.chains) {
|
|
2241
|
-
chainMap.set(chain.name, chain);
|
|
2242
|
-
}
|
|
2741
|
+
for (const chain of sources.projectChainLoaded ?? []) {
|
|
2742
|
+
projectChainDiagnostics.push(...chain.loaded.diagnostics);
|
|
2743
|
+
for (const definition of chain.loaded.chains) projectChainMap.set(definition.name, definition);
|
|
2243
2744
|
}
|
|
2244
|
-
const userChains = loadChainsFromDir(userChainDir, "user");
|
|
2245
2745
|
const chains = [
|
|
2246
2746
|
...Array.from(packageChainMap.values()),
|
|
2247
|
-
...userChains
|
|
2248
|
-
...Array.from(
|
|
2249
|
-
];
|
|
2250
|
-
const chainDiagnostics = [
|
|
2251
|
-
...packageChainDiagnostics,
|
|
2252
|
-
...userChains.diagnostics,
|
|
2253
|
-
...projectChainDiagnostics,
|
|
2254
|
-
];
|
|
2255
|
-
const agentDiagnostics = [
|
|
2256
|
-
...builtinLoaded.diagnostics,
|
|
2257
|
-
...userLoaded.flatMap((loaded) => loaded.diagnostics),
|
|
2258
|
-
...packageAgentDiagnostics,
|
|
2259
|
-
...projectAgentDiagnostics,
|
|
2747
|
+
...(sources.userChains?.chains ?? []),
|
|
2748
|
+
...Array.from(projectChainMap.values()),
|
|
2260
2749
|
];
|
|
2261
|
-
|
|
2262
|
-
const userDir = process.env.PI_CODING_AGENT_DIR ? userDirOld : fs.existsSync(userDirNew) ? userDirNew : userDirOld;
|
|
2263
|
-
|
|
2264
2750
|
return {
|
|
2265
|
-
builtin: applySubagentMaxThinking(builtin, maxThinking),
|
|
2266
|
-
package: applySubagentMaxThinking(
|
|
2267
|
-
user: applySubagentMaxThinking(user, maxThinking),
|
|
2268
|
-
project: applySubagentMaxThinking(project, maxThinking),
|
|
2269
|
-
agentDiagnostics
|
|
2751
|
+
builtin: applySubagentMaxThinking(configured.builtin, configured.maxThinking),
|
|
2752
|
+
package: applySubagentMaxThinking(configured.package, configured.maxThinking),
|
|
2753
|
+
user: applySubagentMaxThinking(configured.user, configured.maxThinking),
|
|
2754
|
+
project: applySubagentMaxThinking(configured.project, configured.maxThinking),
|
|
2755
|
+
agentDiagnostics: [
|
|
2756
|
+
...sources.builtinLoaded.diagnostics,
|
|
2757
|
+
...sources.userLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
|
|
2758
|
+
...sources.packageLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
|
|
2759
|
+
...sources.projectLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
|
|
2760
|
+
],
|
|
2270
2761
|
chains,
|
|
2271
|
-
chainDiagnostics,
|
|
2272
|
-
userDir,
|
|
2273
|
-
projectDir,
|
|
2274
|
-
userChainDir,
|
|
2275
|
-
projectChainDir,
|
|
2276
|
-
userSettingsPath,
|
|
2277
|
-
projectSettingsPath,
|
|
2278
|
-
|
|
2279
|
-
...(maxThinking !== undefined ? { maxThinking } : {}),
|
|
2762
|
+
chainDiagnostics: [...packageChainDiagnostics, ...(sources.userChains?.diagnostics ?? []), ...projectChainDiagnostics],
|
|
2763
|
+
userDir: sources.userDir,
|
|
2764
|
+
projectDir: sources.projectAgentsDir,
|
|
2765
|
+
userChainDir: sources.userChainDir,
|
|
2766
|
+
projectChainDir: sources.projectChainDir,
|
|
2767
|
+
userSettingsPath: sources.userSettingsPath,
|
|
2768
|
+
projectSettingsPath: sources.projectSettingsPath,
|
|
2769
|
+
...(injectAgents?.length ? { injectAgents } : {}),
|
|
2770
|
+
...(configured.maxThinking !== undefined ? { maxThinking: configured.maxThinking } : {}),
|
|
2280
2771
|
};
|
|
2281
2772
|
}
|
|
2773
|
+
|
|
2774
|
+
export function discoverAgentSnapshot(
|
|
2775
|
+
cwd: string,
|
|
2776
|
+
scope: AgentScope,
|
|
2777
|
+
preferredModelProvider?: string,
|
|
2778
|
+
options: { includeChains?: boolean } = {},
|
|
2779
|
+
): AgentDiscoverySnapshot {
|
|
2780
|
+
const includeChains = options.includeChains !== false;
|
|
2781
|
+
const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains);
|
|
2782
|
+
return { effective: buildEffectiveDiscovery(sources, scope), all: buildAllDiscovery(sources, includeChains, scope) };
|
|
2783
|
+
}
|
|
2784
|
+
|
|
2785
|
+
function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelProvider?: string): AgentDiscoveryResult {
|
|
2786
|
+
const effectiveCwd = path.resolve(cwd);
|
|
2787
|
+
const userDirOld = path.join(getAgentDir(), "agents");
|
|
2788
|
+
const userDirNew = path.join(os.homedir(), ".agents");
|
|
2789
|
+
const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(effectiveCwd);
|
|
2790
|
+
const userSettingsPath = getUserAgentSettingsPath();
|
|
2791
|
+
const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
|
|
2792
|
+
const userSettings = selectProviderOverrides(scope === "project" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(userSettingsPath), preferredModelProvider);
|
|
2793
|
+
const projectSettings = selectProviderOverrides(scope === "user" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(projectSettingsPath), preferredModelProvider);
|
|
2794
|
+
const defaultProvider = resolveSubagentDefaultProvider(userSettings, projectSettings, projectSettingsPath);
|
|
2795
|
+
const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath, defaultProvider);
|
|
2796
|
+
const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
|
|
2797
|
+
const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, projectSettingsPath);
|
|
2798
|
+
const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
|
|
2799
|
+
const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
|
|
2800
|
+
const injectAgents = projectSettings.injectAgents !== undefined
|
|
2801
|
+
? projectSettings.injectAgents
|
|
2802
|
+
: userSettings.injectAgents;
|
|
2803
|
+
const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: scope !== "project", includeProject: scope !== "user" });
|
|
2804
|
+
const directories: AgentDefinitionDirectoryReport[] = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
|
|
2805
|
+
const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
|
|
2806
|
+
const builtinAgents = applyBuiltinOverrides(applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
|
|
2807
|
+
const userScanDirs = settingsAgentScanDirs(userSettings.agentScanDirs ?? []);
|
|
2808
|
+
const projectScanDirs = settingsAgentScanDirs(projectSettings.agentScanDirs ?? []);
|
|
2809
|
+
const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].map((dir, discoveryPriority) => {
|
|
2810
|
+
const inspection = inspectAgentDefinitionDirectory(dir);
|
|
2811
|
+
directories.push(reportAgentDefinitionDirectory("user", dir, inspection));
|
|
2812
|
+
return loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection);
|
|
2813
|
+
});
|
|
2814
|
+
const userAgents = applyCustomAgentOverrides(applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
|
|
2815
|
+
const projectInspections = scope === "user" ? new Map<string, AgentDefinitionInspection>() : new Map(projectCandidateDirs.map((dir) => [dir, inspectAgentDefinitionDirectory(dir)]));
|
|
2816
|
+
if (scope !== "user") for (const dir of projectCandidateDirs) directories.push(reportAgentDefinitionDirectory("project", dir, projectInspections.get(dir)!));
|
|
2817
|
+
const projectLoaded = scope === "user" ? [] : [...projectScanDirs.dirs, ...projectAgentDirs].map((dir, discoveryPriority) => {
|
|
2818
|
+
const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir);
|
|
2819
|
+
if (!projectInspections.has(dir)) directories.push(reportAgentDefinitionDirectory("project", dir, inspection));
|
|
2820
|
+
return loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection);
|
|
2821
|
+
});
|
|
2822
|
+
const projectAgents = applyCustomAgentOverrides(applySubagentDefaults(projectLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
|
|
2823
|
+
const packageLoaded = packageSubagentPaths.agents.map((entry, index) => {
|
|
2824
|
+
const inspection = inspectAgentDefinitionDirectory(entry.dir);
|
|
2825
|
+
directories.push(reportAgentDefinitionDirectory("package", entry.dir, inspection));
|
|
2826
|
+
return loadAgentsFromDir(entry.dir, "package", packageSubagentPaths.agents.length - index, entry, inspection);
|
|
2827
|
+
});
|
|
2828
|
+
const packageMap = new Map<string, AgentConfig>();
|
|
2829
|
+
for (const loaded of packageLoaded) for (const agent of loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
|
|
2830
|
+
const packageAgents = applyCustomAgentOverrides(applySubagentDefaults(Array.from(packageMap.values()), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
|
|
2831
|
+
const agents = applySubagentMaxThinking(mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents).filter((agent) => agent.disabled !== true), maxThinking);
|
|
2832
|
+
const agentDiagnostics = [...builtinLoaded.diagnostics, ...userLoaded.flatMap((loaded) => loaded.diagnostics), ...projectLoaded.flatMap((loaded) => loaded.diagnostics), ...packageLoaded.flatMap((loaded) => loaded.diagnostics)];
|
|
2833
|
+
return { agents, agentDiagnostics, projectAgentsDir, cwd: effectiveCwd, scope, directories, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}), ...(maxThinking !== undefined ? { maxThinking } : {}) };
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2836
|
+
export function discoverAgents(cwd: string, scope: AgentScope, preferredModelProvider?: string): AgentDiscoveryResult {
|
|
2837
|
+
if (scope !== "both") return discoverAgentsUncached(cwd, scope, preferredModelProvider);
|
|
2838
|
+
const sources = getAgentDiscoverySources(cwd, preferredModelProvider);
|
|
2839
|
+
return buildEffectiveDiscovery(sources, scope);
|
|
2840
|
+
}
|
|
2841
|
+
|
|
2842
|
+
export function discoverAgentsAll(cwd: string, preferredModelProvider?: string): AgentDiscoveryAllResult {
|
|
2843
|
+
return discoverAgentSnapshot(cwd, "both", preferredModelProvider).all;
|
|
2844
|
+
}
|