@xzzpig/pi-subagents 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +443 -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 +151 -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 +5 -4
- 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 +370 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +12 -2
- package/src/agents/agents.ts +919 -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 +31 -20
- 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 +48 -18
- 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 +57 -21
- 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 +2 -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 +366 -128
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +45 -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 +189 -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 +676 -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 +468 -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 +1172 -400
- 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 +314 -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 +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -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 +142 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +38 -48
- 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 +15 -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/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 +8 -1
- package/src/shared/pruned-fork.ts +450 -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 +524 -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,7 +21,6 @@ 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";
|
|
@@ -61,6 +62,7 @@ export interface BuiltinAgentOverrideBase {
|
|
|
61
62
|
thinking?: string | false;
|
|
62
63
|
systemPromptMode: SystemPromptMode;
|
|
63
64
|
inheritProjectContext: boolean;
|
|
65
|
+
inheritGlobalContext: boolean;
|
|
64
66
|
inheritSkills: boolean;
|
|
65
67
|
defaultContext?: AgentDefaultContext;
|
|
66
68
|
acceptanceRole?: AcceptanceRole;
|
|
@@ -69,9 +71,12 @@ export interface BuiltinAgentOverrideBase {
|
|
|
69
71
|
skills?: string[];
|
|
70
72
|
skillPath?: string[];
|
|
71
73
|
tools?: string[];
|
|
74
|
+
excludeTools?: string[];
|
|
75
|
+
allowNestedSubagents?: boolean;
|
|
72
76
|
mcpDirectTools?: string[];
|
|
73
77
|
extensions?: string[];
|
|
74
78
|
subagentOnlyExtensions?: string[];
|
|
79
|
+
mutationTools?: string[];
|
|
75
80
|
completionGuard?: boolean;
|
|
76
81
|
toolBudget?: ToolBudgetConfig;
|
|
77
82
|
}
|
|
@@ -88,6 +93,7 @@ interface BuiltinAgentOverrideConfig {
|
|
|
88
93
|
thinking?: string | false;
|
|
89
94
|
systemPromptMode?: SystemPromptMode;
|
|
90
95
|
inheritProjectContext?: boolean;
|
|
96
|
+
inheritGlobalContext?: boolean;
|
|
91
97
|
inheritSkills?: boolean;
|
|
92
98
|
defaultContext?: AgentDefaultContext | false;
|
|
93
99
|
acceptanceRole?: AcceptanceRole | false;
|
|
@@ -95,8 +101,11 @@ interface BuiltinAgentOverrideConfig {
|
|
|
95
101
|
systemPrompt?: string;
|
|
96
102
|
skills?: string[] | false;
|
|
97
103
|
tools?: string[] | false | "inherit";
|
|
104
|
+
excludeTools?: string[] | false;
|
|
105
|
+
allowNestedSubagents?: boolean;
|
|
98
106
|
extensions?: string[] | false;
|
|
99
107
|
subagentOnlyExtensions?: string[] | false;
|
|
108
|
+
mutationTools?: string[] | false;
|
|
100
109
|
completionGuard?: boolean;
|
|
101
110
|
toolBudget?: ToolBudgetConfig | false;
|
|
102
111
|
}
|
|
@@ -105,6 +114,8 @@ interface BuiltinAgentOverrideInfo {
|
|
|
105
114
|
scope: "user" | "project";
|
|
106
115
|
path: string;
|
|
107
116
|
base: BuiltinAgentOverrideBase;
|
|
117
|
+
fields?: string[];
|
|
118
|
+
fieldScopes?: Record<string, Array<"user" | "project">>;
|
|
108
119
|
}
|
|
109
120
|
|
|
110
121
|
export interface AgentModelSourceInfo {
|
|
@@ -126,6 +137,8 @@ export interface AgentConfig {
|
|
|
126
137
|
description: string;
|
|
127
138
|
aliases?: string[];
|
|
128
139
|
tools?: string[];
|
|
140
|
+
excludeTools?: string[];
|
|
141
|
+
allowNestedSubagents?: boolean;
|
|
129
142
|
mcpDirectTools?: string[];
|
|
130
143
|
model?: string;
|
|
131
144
|
modelProvider?: string;
|
|
@@ -134,12 +147,12 @@ export interface AgentConfig {
|
|
|
134
147
|
thinking?: string | false;
|
|
135
148
|
systemPromptMode: SystemPromptMode;
|
|
136
149
|
inheritProjectContext: boolean;
|
|
150
|
+
inheritGlobalContext: boolean;
|
|
137
151
|
inheritSkills: boolean;
|
|
138
152
|
defaultContext?: AgentDefaultContext;
|
|
139
153
|
defaultAsync?: boolean;
|
|
140
154
|
defaultTimeoutMs?: number;
|
|
141
155
|
defaultToolTimeoutMs?: number;
|
|
142
|
-
defaultTurnBudget?: TurnBudgetConfig;
|
|
143
156
|
defaultAcceptance?: AcceptanceInput;
|
|
144
157
|
acceptanceRole?: AcceptanceRole;
|
|
145
158
|
systemPrompt: string;
|
|
@@ -151,6 +164,7 @@ export interface AgentConfig {
|
|
|
151
164
|
extensions?: string[];
|
|
152
165
|
extensionsFromDefault?: boolean;
|
|
153
166
|
subagentOnlyExtensions?: string[];
|
|
167
|
+
mutationTools?: string[];
|
|
154
168
|
output?: string;
|
|
155
169
|
outputMode?: OutputMode;
|
|
156
170
|
defaultReads?: string[];
|
|
@@ -173,6 +187,8 @@ type ProjectRootResolution = "nearest" | "git-root";
|
|
|
173
187
|
|
|
174
188
|
interface SubagentSettings {
|
|
175
189
|
overrides: Record<string, BuiltinAgentOverrideConfig>;
|
|
190
|
+
providerOverrides: Record<string, Record<string, BuiltinAgentOverrideConfig>>;
|
|
191
|
+
agentScanDirs?: string[];
|
|
176
192
|
defaultModel?: string;
|
|
177
193
|
defaultProvider?: string;
|
|
178
194
|
defaultThinking?: string;
|
|
@@ -184,7 +200,7 @@ interface SubagentSettings {
|
|
|
184
200
|
injectAgents?: string[];
|
|
185
201
|
}
|
|
186
202
|
|
|
187
|
-
const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {} };
|
|
203
|
+
const EMPTY_SUBAGENT_SETTINGS: SubagentSettings = { overrides: {}, providerOverrides: {} };
|
|
188
204
|
const agentFrontmatterFields = new WeakMap<AgentConfig, Set<string>>();
|
|
189
205
|
|
|
190
206
|
export interface ChainStepConfig {
|
|
@@ -264,29 +280,101 @@ export function findBlockingAgentDiagnostic(name: string, agent: AgentConfig | r
|
|
|
264
280
|
return !agents.length || (match && agentDefinitionPriority(match) > highestPriority) ? match : undefined;
|
|
265
281
|
}
|
|
266
282
|
|
|
267
|
-
|
|
283
|
+
export type AgentDefinitionDirectoryState = "absent" | "empty" | "candidates" | "unreadable" | "not-directory";
|
|
284
|
+
|
|
285
|
+
/** A definition directory actually inspected during one agent-discovery operation. */
|
|
286
|
+
export interface AgentDefinitionDirectoryReport {
|
|
287
|
+
source: AgentSource;
|
|
288
|
+
path: string;
|
|
289
|
+
state: AgentDefinitionDirectoryState;
|
|
290
|
+
candidateCount?: number;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Filesystem provenance for a failed agent resolution. Context is created from
|
|
295
|
+
* the discovery result that supplied the effective agents; callers must not
|
|
296
|
+
* pair arbitrary agent arrays with these directory reports.
|
|
297
|
+
*/
|
|
298
|
+
export interface UnknownAgentDiagnosticContext {
|
|
299
|
+
cwd: string;
|
|
300
|
+
scope: AgentScope;
|
|
301
|
+
directories: readonly AgentDefinitionDirectoryReport[];
|
|
302
|
+
agents: readonly AgentConfig[];
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
export interface AgentDiscoveryResult {
|
|
268
306
|
agents: AgentConfig[];
|
|
269
307
|
agentDiagnostics?: AgentDiscoveryDiagnostic[];
|
|
270
308
|
projectAgentsDir: string | null;
|
|
309
|
+
cwd: string;
|
|
310
|
+
scope: AgentScope;
|
|
311
|
+
directories: readonly AgentDefinitionDirectoryReport[];
|
|
271
312
|
modelScope?: ModelScopeConfig;
|
|
272
313
|
injectAgents?: string[];
|
|
273
314
|
maxThinking?: ThinkingLevel;
|
|
274
315
|
}
|
|
275
316
|
|
|
317
|
+
/** Create formatter input from the exact discovery operation used for resolution. */
|
|
318
|
+
export function unknownAgentDiagnosticContext(discovered: Pick<AgentDiscoveryResult, "cwd" | "scope" | "directories" | "agents">): UnknownAgentDiagnosticContext {
|
|
319
|
+
return {
|
|
320
|
+
cwd: discovered.cwd,
|
|
321
|
+
scope: discovered.scope,
|
|
322
|
+
directories: discovered.directories,
|
|
323
|
+
agents: discovered.agents,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Render local discovery evidence without exposing filesystem error details. */
|
|
328
|
+
export function formatUnknownAgentError(name: string, context: UnknownAgentDiagnosticContext, prefix = "Unknown agent"): string {
|
|
329
|
+
const directories = context.directories.map((directory) => {
|
|
330
|
+
const state = directory.state === "candidates"
|
|
331
|
+
? `${directory.candidateCount ?? 0} candidate${directory.candidateCount === 1 ? "" : "s"}`
|
|
332
|
+
: directory.state === "empty" ? "present but empty"
|
|
333
|
+
: directory.state === "not-directory" ? "not a directory"
|
|
334
|
+
: directory.state;
|
|
335
|
+
return `- ${directory.source}: ${directory.path} (${state})`;
|
|
336
|
+
});
|
|
337
|
+
const agents = [...context.agents]
|
|
338
|
+
.sort((left, right) => left.name.localeCompare(right.name) || left.source.localeCompare(right.source))
|
|
339
|
+
.map((agent) => `- ${agent.name} (${agent.source})`);
|
|
340
|
+
return [
|
|
341
|
+
`${prefix}: ${name}`,
|
|
342
|
+
`Effective cwd: ${path.resolve(context.cwd)}`,
|
|
343
|
+
"Consulted agent-definition directories:",
|
|
344
|
+
...(directories.length ? directories : ["- (none)"]),
|
|
345
|
+
"Discovered agents:",
|
|
346
|
+
...(agents.length ? agents : ["- (none)"]),
|
|
347
|
+
].join("\n");
|
|
348
|
+
}
|
|
349
|
+
|
|
276
350
|
function getUserChainDir(): string {
|
|
277
351
|
return path.join(getAgentDir(), "chains");
|
|
278
352
|
}
|
|
279
353
|
|
|
354
|
+
type PackageScope = "root" | "user" | "project";
|
|
355
|
+
type PackageSettingsScope = Exclude<PackageScope, "root">;
|
|
356
|
+
|
|
280
357
|
interface PackageSubagentPath {
|
|
281
358
|
dir: string;
|
|
359
|
+
// A package can be reachable from more than one settings scope. Keep the
|
|
360
|
+
// actual memberships instead of promoting a mixed-scope path to root.
|
|
361
|
+
scope: Set<PackageScope>;
|
|
282
362
|
packageName?: string;
|
|
283
363
|
packageVersion?: string;
|
|
284
364
|
packageRoot: string;
|
|
285
365
|
}
|
|
286
366
|
|
|
367
|
+
interface PackageChainPath {
|
|
368
|
+
dir: string;
|
|
369
|
+
scope: Set<PackageScope>;
|
|
370
|
+
packageRoot: string;
|
|
371
|
+
}
|
|
372
|
+
|
|
287
373
|
interface PackageSubagentPaths {
|
|
288
374
|
agents: PackageSubagentPath[];
|
|
289
|
-
chains:
|
|
375
|
+
chains: PackageChainPath[];
|
|
376
|
+
watchPaths: string[];
|
|
377
|
+
settingsErrors: Partial<Record<PackageSettingsScope, Error>>;
|
|
290
378
|
}
|
|
291
379
|
|
|
292
380
|
let cachedGlobalNpmRoot: string | null = null;
|
|
@@ -311,20 +399,6 @@ function readJsonFileBestEffort(filePath: string): JsonObjectFile | null {
|
|
|
311
399
|
}
|
|
312
400
|
}
|
|
313
401
|
|
|
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
402
|
function isSafePackagePath(value: string): boolean {
|
|
329
403
|
return value.length > 0
|
|
330
404
|
&& !path.isAbsolute(value)
|
|
@@ -396,6 +470,10 @@ function resolveSettingsPackageRoot(source: string, baseDir: string): string | u
|
|
|
396
470
|
if (normalized === "." || normalized === ".." || normalized.startsWith("./") || normalized.startsWith("../")) {
|
|
397
471
|
return path.resolve(baseDir, normalized);
|
|
398
472
|
}
|
|
473
|
+
if (/^https?:\/\//i.test(trimmed)) {
|
|
474
|
+
const parsed = parseGitPackagePath(`git:${trimmed}`);
|
|
475
|
+
return parsed ? path.join(baseDir, "git", parsed.host, parsed.repoPath) : undefined;
|
|
476
|
+
}
|
|
399
477
|
return undefined;
|
|
400
478
|
}
|
|
401
479
|
|
|
@@ -432,7 +510,7 @@ function stringArray(value: unknown): string[] {
|
|
|
432
510
|
return value.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0);
|
|
433
511
|
}
|
|
434
512
|
|
|
435
|
-
function packageMetadata(pkg: Record<string, unknown>, packageRoot: string): Omit<PackageSubagentPath, "dir"> {
|
|
513
|
+
function packageMetadata(pkg: Record<string, unknown>, packageRoot: string): Omit<PackageSubagentPath, "dir" | "scope"> {
|
|
436
514
|
const name = typeof pkg.name === "string" && pkg.name.trim() ? pkg.name.trim() : undefined;
|
|
437
515
|
const version = typeof pkg.version === "string" && pkg.version.trim() ? pkg.version.trim() : undefined;
|
|
438
516
|
return {
|
|
@@ -442,10 +520,10 @@ function packageMetadata(pkg: Record<string, unknown>, packageRoot: string): Omi
|
|
|
442
520
|
};
|
|
443
521
|
}
|
|
444
522
|
|
|
445
|
-
function extractSubagentPathsFromPackageRoot(packageRoot: string): PackageSubagentPaths {
|
|
523
|
+
function extractSubagentPathsFromPackageRoot(packageRoot: string, scope: Set<PackageScope>): PackageSubagentPaths {
|
|
446
524
|
const packageJsonPath = path.join(packageRoot, "package.json");
|
|
447
525
|
const pkg = readJsonFileBestEffort(packageJsonPath);
|
|
448
|
-
if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { agents: [], chains: [] };
|
|
526
|
+
if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) return { agents: [], chains: [], watchPaths: [packageJsonPath], settingsErrors: {} };
|
|
449
527
|
const pkgRecord = pkg as Record<string, unknown>;
|
|
450
528
|
const metadata = packageMetadata(pkgRecord, packageRoot);
|
|
451
529
|
|
|
@@ -464,16 +542,17 @@ function extractSubagentPathsFromPackageRoot(packageRoot: string): PackageSubage
|
|
|
464
542
|
}
|
|
465
543
|
|
|
466
544
|
const agents: PackageSubagentPath[] = [];
|
|
467
|
-
const chains:
|
|
545
|
+
const chains: PackageChainPath[] = [];
|
|
468
546
|
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));
|
|
547
|
+
for (const entry of stringArray(root.agents)) agents.push({ dir: path.resolve(packageRoot, entry), scope, ...metadata });
|
|
548
|
+
for (const entry of stringArray(root.chains)) chains.push({ dir: path.resolve(packageRoot, entry), scope, packageRoot });
|
|
471
549
|
}
|
|
472
|
-
return { agents, chains };
|
|
550
|
+
return { agents, chains, watchPaths: [packageJsonPath], settingsErrors: {} };
|
|
473
551
|
}
|
|
474
552
|
|
|
475
|
-
function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
|
|
553
|
+
function collectPackageRootsFromNodeModules(nodeModulesDir: string, watchPaths?: string[]): string[] {
|
|
476
554
|
const roots: string[] = [];
|
|
555
|
+
watchPaths?.push(nodeModulesDir);
|
|
477
556
|
if (!fs.existsSync(nodeModulesDir)) return roots;
|
|
478
557
|
|
|
479
558
|
let entries: fs.Dirent[];
|
|
@@ -489,6 +568,7 @@ function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
|
|
|
489
568
|
|
|
490
569
|
if (entry.name.startsWith("@")) {
|
|
491
570
|
const scopeDir = path.join(nodeModulesDir, entry.name);
|
|
571
|
+
watchPaths?.push(scopeDir);
|
|
492
572
|
let scopeEntries: fs.Dirent[];
|
|
493
573
|
try {
|
|
494
574
|
scopeEntries = fs.readdirSync(scopeDir, { withFileTypes: true });
|
|
@@ -509,9 +589,8 @@ function collectPackageRootsFromNodeModules(nodeModulesDir: string): string[] {
|
|
|
509
589
|
}
|
|
510
590
|
|
|
511
591
|
function collectSettingsPackageRoots(settingsFile: string, baseDir: string): string[] {
|
|
512
|
-
const settings =
|
|
513
|
-
|
|
514
|
-
const packages = settings.packages;
|
|
592
|
+
const settings = readSettingsFileStrict(settingsFile);
|
|
593
|
+
const packages = (settings as { packages?: unknown }).packages;
|
|
515
594
|
if (!Array.isArray(packages)) return [];
|
|
516
595
|
|
|
517
596
|
const roots: string[] = [];
|
|
@@ -531,52 +610,82 @@ function collectSettingsPackageRoots(settingsFile: string, baseDir: string): str
|
|
|
531
610
|
function collectPackageSubagentPaths(cwd: string, options: { includeUser: boolean; includeProject: boolean } = { includeUser: true, includeProject: true }): PackageSubagentPaths {
|
|
532
611
|
const agentDir = getAgentDir();
|
|
533
612
|
const projectRoot = findConfiguredProjectRoot(cwd) ?? cwd;
|
|
534
|
-
const packageRoots = [
|
|
535
|
-
projectRoot,
|
|
613
|
+
const packageRoots: Array<{ root: string; scope: PackageScope }> = [
|
|
614
|
+
{ root: projectRoot, scope: "root" },
|
|
536
615
|
];
|
|
537
|
-
|
|
616
|
+
const watchPaths: string[] = [path.join(projectRoot, "package.json")];
|
|
617
|
+
const settingsErrors: Partial<Record<PackageSettingsScope, Error>> = {};
|
|
618
|
+
const collectScopedSettingsRoots = (scope: PackageSettingsScope, settingsFile: string, baseDir: string): string[] => {
|
|
619
|
+
try {
|
|
620
|
+
return collectSettingsPackageRoots(settingsFile, baseDir);
|
|
621
|
+
} catch (error) {
|
|
622
|
+
// The raw source snapshot includes both settings scopes. Defer a
|
|
623
|
+
// strict failure until a projection actually selects this scope so an
|
|
624
|
+
// unrelated malformed settings file stays out of scoped discovery.
|
|
625
|
+
settingsErrors[scope] = error instanceof Error
|
|
626
|
+
? error
|
|
627
|
+
: new Error(`Failed to read settings file '${settingsFile}': ${String(error)}`, { cause: error });
|
|
628
|
+
return [];
|
|
629
|
+
}
|
|
630
|
+
};
|
|
538
631
|
if (options.includeProject) {
|
|
539
632
|
const projectConfigDir = getProjectConfigDir(projectRoot);
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
);
|
|
633
|
+
const nodeModulesDir = path.join(projectConfigDir, "npm", "node_modules");
|
|
634
|
+
packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "project" as const })));
|
|
635
|
+
packageRoots.push(...collectScopedSettingsRoots("project", path.join(projectConfigDir, "settings.json"), projectConfigDir).map((root) => ({ root, scope: "project" as const })));
|
|
544
636
|
}
|
|
545
637
|
|
|
546
638
|
if (options.includeUser) {
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
);
|
|
639
|
+
const nodeModulesDir = path.join(agentDir, "npm", "node_modules");
|
|
640
|
+
packageRoots.push(...collectPackageRootsFromNodeModules(nodeModulesDir, watchPaths).map((root) => ({ root, scope: "user" as const })));
|
|
641
|
+
packageRoots.push(...collectScopedSettingsRoots("user", path.join(agentDir, "settings.json"), agentDir).map((root) => ({ root, scope: "user" as const })));
|
|
551
642
|
}
|
|
552
643
|
|
|
553
644
|
if (options.includeUser) {
|
|
554
645
|
const globalRoot = getGlobalNpmRoot();
|
|
555
|
-
if (globalRoot)
|
|
646
|
+
if (globalRoot) {
|
|
647
|
+
packageRoots.push(...collectPackageRootsFromNodeModules(globalRoot, watchPaths).map((root) => ({ root, scope: "user" as const })));
|
|
648
|
+
}
|
|
556
649
|
}
|
|
557
650
|
|
|
558
|
-
const seenRoots = new Set<
|
|
559
|
-
const seenAgents = new
|
|
560
|
-
const seenChains = new
|
|
651
|
+
const seenRoots = new Map<string, Set<PackageScope>>();
|
|
652
|
+
const seenAgents = new Map<string, PackageSubagentPath>();
|
|
653
|
+
const seenChains = new Map<string, PackageChainPath>();
|
|
561
654
|
const agents: PackageSubagentPath[] = [];
|
|
562
|
-
const chains:
|
|
563
|
-
for (const packageRoot of packageRoots) {
|
|
655
|
+
const chains: PackageChainPath[] = [];
|
|
656
|
+
for (const { root: packageRoot, scope } of packageRoots) {
|
|
564
657
|
const resolvedRoot = path.resolve(packageRoot);
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
658
|
+
const scopes = seenRoots.get(resolvedRoot);
|
|
659
|
+
if (scopes !== undefined) {
|
|
660
|
+
scopes.add(scope);
|
|
661
|
+
continue;
|
|
662
|
+
}
|
|
663
|
+
const packageScopes = new Set<PackageScope>([scope]);
|
|
664
|
+
seenRoots.set(resolvedRoot, packageScopes);
|
|
665
|
+
const paths = extractSubagentPathsFromPackageRoot(resolvedRoot, packageScopes);
|
|
666
|
+
watchPaths.push(...paths.watchPaths);
|
|
568
667
|
for (const agentPath of paths.agents) {
|
|
569
|
-
|
|
570
|
-
seenAgents.
|
|
668
|
+
const agentKey = `${agentPath.dir}\u0000${agentPath.packageRoot}`;
|
|
669
|
+
const existing = seenAgents.get(agentKey);
|
|
670
|
+
if (existing) {
|
|
671
|
+
for (const packageScope of agentPath.scope) existing.scope.add(packageScope);
|
|
672
|
+
continue;
|
|
673
|
+
}
|
|
674
|
+
seenAgents.set(agentKey, agentPath);
|
|
571
675
|
agents.push(agentPath);
|
|
572
676
|
}
|
|
573
677
|
for (const chainDir of paths.chains) {
|
|
574
|
-
|
|
575
|
-
seenChains.
|
|
678
|
+
const chainKey = `${chainDir.dir}\u0000${chainDir.packageRoot}`;
|
|
679
|
+
const existing = seenChains.get(chainKey);
|
|
680
|
+
if (existing) {
|
|
681
|
+
for (const packageScope of chainDir.scope) existing.scope.add(packageScope);
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
seenChains.set(chainKey, chainDir);
|
|
576
685
|
chains.push(chainDir);
|
|
577
686
|
}
|
|
578
687
|
}
|
|
579
|
-
return { agents, chains };
|
|
688
|
+
return { agents, chains, watchPaths, settingsErrors };
|
|
580
689
|
}
|
|
581
690
|
|
|
582
691
|
function normalizeAgentAliases(rawAliases: string[] | undefined, agentName: string): string[] | undefined {
|
|
@@ -662,6 +771,7 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
|
|
|
662
771
|
...(agent.thinking !== undefined ? { thinking: agent.thinking } : {}),
|
|
663
772
|
systemPromptMode: agent.systemPromptMode,
|
|
664
773
|
inheritProjectContext: agent.inheritProjectContext,
|
|
774
|
+
inheritGlobalContext: agent.inheritGlobalContext,
|
|
665
775
|
inheritSkills: agent.inheritSkills,
|
|
666
776
|
...(agent.defaultContext !== undefined ? { defaultContext: agent.defaultContext } : {}),
|
|
667
777
|
...(agent.acceptanceRole !== undefined ? { acceptanceRole: agent.acceptanceRole } : {}),
|
|
@@ -670,9 +780,12 @@ function cloneOverrideBase(agent: AgentConfig): BuiltinAgentOverrideBase {
|
|
|
670
780
|
...(agent.skills ? { skills: [...agent.skills] } : {}),
|
|
671
781
|
...(agent.skillPath ? { skillPath: [...agent.skillPath] } : {}),
|
|
672
782
|
...(agent.tools ? { tools: [...agent.tools] } : {}),
|
|
783
|
+
...(agent.excludeTools ? { excludeTools: [...agent.excludeTools] } : {}),
|
|
784
|
+
...(agent.allowNestedSubagents !== undefined ? { allowNestedSubagents: agent.allowNestedSubagents } : {}),
|
|
673
785
|
...(agent.mcpDirectTools ? { mcpDirectTools: [...agent.mcpDirectTools] } : {}),
|
|
674
786
|
...(!agent.extensionsFromDefault && agent.extensions ? { extensions: [...agent.extensions] } : {}),
|
|
675
787
|
...(agent.subagentOnlyExtensions ? { subagentOnlyExtensions: [...agent.subagentOnlyExtensions] } : {}),
|
|
788
|
+
...(agent.mutationTools ? { mutationTools: [...agent.mutationTools] } : {}),
|
|
676
789
|
...(agent.completionGuard !== undefined ? { completionGuard: agent.completionGuard } : {}),
|
|
677
790
|
...(agent.toolBudget !== undefined ? { toolBudget: agent.toolBudget } : {}),
|
|
678
791
|
};
|
|
@@ -693,6 +806,7 @@ function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentO
|
|
|
693
806
|
...(override.thinking !== undefined ? { thinking: override.thinking } : {}),
|
|
694
807
|
...(override.systemPromptMode !== undefined ? { systemPromptMode: override.systemPromptMode } : {}),
|
|
695
808
|
...(override.inheritProjectContext !== undefined ? { inheritProjectContext: override.inheritProjectContext } : {}),
|
|
809
|
+
...(override.inheritGlobalContext !== undefined ? { inheritGlobalContext: override.inheritGlobalContext } : {}),
|
|
696
810
|
...(override.inheritSkills !== undefined ? { inheritSkills: override.inheritSkills } : {}),
|
|
697
811
|
...(override.defaultContext !== undefined ? { defaultContext: override.defaultContext } : {}),
|
|
698
812
|
...(override.acceptanceRole !== undefined ? { acceptanceRole: override.acceptanceRole } : {}),
|
|
@@ -700,8 +814,11 @@ function cloneOverrideValue(override: BuiltinAgentOverrideConfig): BuiltinAgentO
|
|
|
700
814
|
...(override.systemPrompt !== undefined ? { systemPrompt: override.systemPrompt } : {}),
|
|
701
815
|
...(override.skills !== undefined ? { skills: override.skills === false ? false : [...override.skills] } : {}),
|
|
702
816
|
...(override.tools !== undefined ? { tools: Array.isArray(override.tools) ? [...override.tools] : override.tools } : {}),
|
|
817
|
+
...(override.excludeTools !== undefined ? { excludeTools: override.excludeTools === false ? false : [...override.excludeTools] } : {}),
|
|
818
|
+
...(override.allowNestedSubagents !== undefined ? { allowNestedSubagents: override.allowNestedSubagents } : {}),
|
|
703
819
|
...(override.extensions !== undefined ? { extensions: override.extensions === false ? false : [...override.extensions] } : {}),
|
|
704
820
|
...(override.subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions: override.subagentOnlyExtensions === false ? false : [...override.subagentOnlyExtensions] } : {}),
|
|
821
|
+
...(override.mutationTools !== undefined ? { mutationTools: override.mutationTools === false ? false : [...override.mutationTools] } : {}),
|
|
705
822
|
...(override.completionGuard !== undefined ? { completionGuard: override.completionGuard } : {}),
|
|
706
823
|
...(override.toolBudget !== undefined ? { toolBudget: override.toolBudget === false ? false : { ...override.toolBudget, ...(Array.isArray(override.toolBudget.block) ? { block: [...override.toolBudget.block] } : {}) } } : {}),
|
|
707
824
|
};
|
|
@@ -751,7 +868,7 @@ export function findNearestProjectRoot(cwd: string): string | null {
|
|
|
751
868
|
return findProjectRootCandidates(cwd)[0] ?? null;
|
|
752
869
|
}
|
|
753
870
|
|
|
754
|
-
function findConfiguredProjectRoot(cwd: string): string | null {
|
|
871
|
+
export function findConfiguredProjectRoot(cwd: string): string | null {
|
|
755
872
|
const candidates = findProjectRootCandidates(cwd);
|
|
756
873
|
const nearestRoot = candidates[0];
|
|
757
874
|
if (!nearestRoot) return null;
|
|
@@ -910,6 +1027,14 @@ function parseBuiltinOverrideEntry(
|
|
|
910
1027
|
}
|
|
911
1028
|
}
|
|
912
1029
|
|
|
1030
|
+
if ("inheritGlobalContext" in input) {
|
|
1031
|
+
if (typeof input.inheritGlobalContext === "boolean") {
|
|
1032
|
+
override.inheritGlobalContext = input.inheritGlobalContext;
|
|
1033
|
+
} else {
|
|
1034
|
+
throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'inheritGlobalContext'; expected a boolean.`);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
|
|
913
1038
|
if ("inheritSkills" in input) {
|
|
914
1039
|
if (typeof input.inheritSkills === "boolean") {
|
|
915
1040
|
override.inheritSkills = input.inheritSkills;
|
|
@@ -982,6 +1107,12 @@ function parseBuiltinOverrideEntry(
|
|
|
982
1107
|
|
|
983
1108
|
const tools = parseToolsOverride(input.tools, { filePath, name });
|
|
984
1109
|
if (tools !== undefined) override.tools = tools;
|
|
1110
|
+
const excludeTools = parseOverrideStringArrayOrFalse(input.excludeTools, { filePath, name, field: "excludeTools" });
|
|
1111
|
+
if (excludeTools !== undefined) override.excludeTools = excludeTools;
|
|
1112
|
+
if ("allowNestedSubagents" in input) {
|
|
1113
|
+
if (typeof input.allowNestedSubagents === "boolean") override.allowNestedSubagents = input.allowNestedSubagents;
|
|
1114
|
+
else throw new Error(`Builtin override '${name}' in '${filePath}' has invalid 'allowNestedSubagents'; expected a boolean.`);
|
|
1115
|
+
}
|
|
985
1116
|
|
|
986
1117
|
const extensions = parseOverrideStringArrayOrFalse(input.extensions, { filePath, name, field: "extensions" });
|
|
987
1118
|
if (extensions !== undefined) override.extensions = extensions;
|
|
@@ -989,6 +1120,9 @@ function parseBuiltinOverrideEntry(
|
|
|
989
1120
|
const subagentOnlyExtensions = parseOverrideStringArrayOrFalse(input.subagentOnlyExtensions, { filePath, name, field: "subagentOnlyExtensions" });
|
|
990
1121
|
if (subagentOnlyExtensions !== undefined) override.subagentOnlyExtensions = subagentOnlyExtensions;
|
|
991
1122
|
|
|
1123
|
+
const mutationTools = parseOverrideStringArrayOrFalse(input.mutationTools, { filePath, name, field: "mutationTools" });
|
|
1124
|
+
if (mutationTools !== undefined) override.mutationTools = mutationTools;
|
|
1125
|
+
|
|
992
1126
|
return Object.keys(override).length > 0 ? override : undefined;
|
|
993
1127
|
}
|
|
994
1128
|
|
|
@@ -1063,32 +1197,71 @@ function readSubagentSettings(filePath: string | null): SubagentSettings {
|
|
|
1063
1197
|
}
|
|
1064
1198
|
injectAgents = subagentsObject.injectAgents.map((item) => item.trim());
|
|
1065
1199
|
}
|
|
1200
|
+
let agentScanDirs: string[] | undefined;
|
|
1201
|
+
if ("agentScanDirs" in subagentsObject) {
|
|
1202
|
+
if (!Array.isArray(subagentsObject.agentScanDirs)
|
|
1203
|
+
|| subagentsObject.agentScanDirs.some((item) => typeof item !== "string" || !item.trim())) {
|
|
1204
|
+
throw new Error(`Subagent settings in '${filePath}' have invalid 'agentScanDirs'; expected an array of non-empty strings.`);
|
|
1205
|
+
}
|
|
1206
|
+
agentScanDirs = subagentsObject.agentScanDirs.map((item) => item.trim());
|
|
1207
|
+
}
|
|
1066
1208
|
const modelScope = parseModelScopeConfig(subagentsObject.modelScope, { filePath });
|
|
1067
1209
|
|
|
1068
1210
|
const parsed: Record<string, BuiltinAgentOverrideConfig> = {};
|
|
1211
|
+
const providerOverrides: Record<string, Record<string, BuiltinAgentOverrideConfig>> = {};
|
|
1069
1212
|
const agentOverrides = subagentsObject.agentOverrides;
|
|
1213
|
+
const agentOverridesByProvider = subagentsObject.agentOverridesByProvider;
|
|
1070
1214
|
const parsedSettings: SubagentSettings = {
|
|
1071
1215
|
overrides: parsed,
|
|
1216
|
+
providerOverrides,
|
|
1072
1217
|
...(defaultModel !== undefined ? { defaultModel } : {}),
|
|
1073
1218
|
...(defaultProvider !== undefined ? { defaultProvider } : {}),
|
|
1074
1219
|
...(defaultThinking !== undefined ? { defaultThinking } : {}),
|
|
1075
1220
|
...(maxThinking !== undefined ? { maxThinking } : {}),
|
|
1076
1221
|
...(defaultExtensions !== undefined ? { defaultExtensions } : {}),
|
|
1222
|
+
...(agentScanDirs !== undefined ? { agentScanDirs } : {}),
|
|
1223
|
+
...(injectAgents !== undefined ? { injectAgents } : {}),
|
|
1077
1224
|
...(disableBuiltins !== undefined ? { disableBuiltins } : {}),
|
|
1078
1225
|
...(disableThinking !== undefined ? { disableThinking } : {}),
|
|
1079
1226
|
...(modelScope !== undefined ? { modelScope } : {}),
|
|
1080
1227
|
...(injectAgents !== undefined ? { injectAgents } : {}),
|
|
1081
1228
|
};
|
|
1082
|
-
if (
|
|
1083
|
-
|
|
1229
|
+
if (agentOverrides && typeof agentOverrides === "object" && !Array.isArray(agentOverrides)) {
|
|
1230
|
+
for (const [name, value] of Object.entries(agentOverrides)) {
|
|
1231
|
+
const override = parseBuiltinOverrideEntry(name, value, filePath);
|
|
1232
|
+
if (override) parsed[name] = override;
|
|
1233
|
+
}
|
|
1084
1234
|
}
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1235
|
+
if (agentOverridesByProvider !== undefined) {
|
|
1236
|
+
if (!agentOverridesByProvider || typeof agentOverridesByProvider !== "object" || Array.isArray(agentOverridesByProvider)) {
|
|
1237
|
+
throw new Error(`Subagent settings in '${filePath}' have invalid 'agentOverridesByProvider'; expected an object keyed by provider.`);
|
|
1238
|
+
}
|
|
1239
|
+
for (const [provider, value] of Object.entries(agentOverridesByProvider)) {
|
|
1240
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
1241
|
+
throw new Error(`Subagent settings in '${filePath}' have invalid 'agentOverridesByProvider.${provider}'; expected an object keyed by agent.`);
|
|
1242
|
+
}
|
|
1243
|
+
const entries: Record<string, BuiltinAgentOverrideConfig> = {};
|
|
1244
|
+
for (const [agentName, agentValue] of Object.entries(value)) {
|
|
1245
|
+
const override = parseBuiltinOverrideEntry(`agentOverridesByProvider.${provider}.${agentName}`, agentValue, filePath);
|
|
1246
|
+
if (override) entries[agentName] = override;
|
|
1247
|
+
}
|
|
1248
|
+
providerOverrides[provider] = entries;
|
|
1249
|
+
}
|
|
1088
1250
|
}
|
|
1089
1251
|
return parsedSettings;
|
|
1090
1252
|
}
|
|
1091
1253
|
|
|
1254
|
+
function selectProviderOverrides(settings: SubagentSettings, provider: string | undefined): SubagentSettings {
|
|
1255
|
+
if (!provider) return settings;
|
|
1256
|
+
const selected = settings.providerOverrides[provider];
|
|
1257
|
+
if (!selected) return settings;
|
|
1258
|
+
const overrides = { ...settings.overrides };
|
|
1259
|
+
for (const [name, override] of Object.entries(selected)) {
|
|
1260
|
+
overrides[name] = { ...overrides[name], ...override };
|
|
1261
|
+
}
|
|
1262
|
+
return { ...settings, overrides };
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1092
1265
|
function resolveSubagentDefaultProvider(
|
|
1093
1266
|
userSettings: SubagentSettings,
|
|
1094
1267
|
projectSettings: SubagentSettings,
|
|
@@ -1211,9 +1384,19 @@ function applyBuiltinOverride(
|
|
|
1211
1384
|
override: BuiltinAgentOverrideConfig,
|
|
1212
1385
|
meta: { scope: "user" | "project"; path: string },
|
|
1213
1386
|
): AgentConfig {
|
|
1387
|
+
const overrideInfo: BuiltinAgentOverrideInfo = {
|
|
1388
|
+
...meta,
|
|
1389
|
+
base: agent.override?.base ?? cloneOverrideBase(agent),
|
|
1390
|
+
fields: [...new Set([...(agent.override?.fields ?? []), ...Object.keys(override)])].sort(),
|
|
1391
|
+
fieldScopes: Object.fromEntries(Object.entries({ ...(agent.override?.fieldScopes ?? {}) }).map(([field, scopes]) => [field, [...scopes]])),
|
|
1392
|
+
};
|
|
1393
|
+
for (const field of Object.keys(override)) {
|
|
1394
|
+
const scopes = overrideInfo.fieldScopes![field] ?? [];
|
|
1395
|
+
overrideInfo.fieldScopes![field] = [...new Set([...scopes, meta.scope])].sort();
|
|
1396
|
+
}
|
|
1214
1397
|
const next: AgentConfig = {
|
|
1215
1398
|
...agent,
|
|
1216
|
-
override:
|
|
1399
|
+
override: overrideInfo,
|
|
1217
1400
|
};
|
|
1218
1401
|
|
|
1219
1402
|
if (override.description !== undefined) next.description = override.description;
|
|
@@ -1233,6 +1416,7 @@ function applyBuiltinOverride(
|
|
|
1233
1416
|
if (override.thinking !== undefined) { if (override.thinking === false) delete next.thinking; else next.thinking = override.thinking; }
|
|
1234
1417
|
if (override.systemPromptMode !== undefined) next.systemPromptMode = override.systemPromptMode;
|
|
1235
1418
|
if (override.inheritProjectContext !== undefined) next.inheritProjectContext = override.inheritProjectContext;
|
|
1419
|
+
if (override.inheritGlobalContext !== undefined) next.inheritGlobalContext = override.inheritGlobalContext;
|
|
1236
1420
|
if (override.inheritSkills !== undefined) next.inheritSkills = override.inheritSkills;
|
|
1237
1421
|
if (override.defaultContext !== undefined) { if (override.defaultContext === false) delete next.defaultContext; else next.defaultContext = override.defaultContext; }
|
|
1238
1422
|
if (override.acceptanceRole !== undefined) { if (override.acceptanceRole === false) delete next.acceptanceRole; else next.acceptanceRole = override.acceptanceRole; }
|
|
@@ -1240,8 +1424,11 @@ function applyBuiltinOverride(
|
|
|
1240
1424
|
if (override.systemPrompt !== undefined) next.systemPrompt = override.systemPrompt;
|
|
1241
1425
|
if (override.skills !== undefined) { if (override.skills === false) delete next.skills; else next.skills = [...override.skills]; }
|
|
1242
1426
|
if (override.tools !== undefined) applyToolsOverride(next, override.tools);
|
|
1427
|
+
if (override.excludeTools !== undefined) { if (override.excludeTools === false) delete next.excludeTools; else next.excludeTools = [...override.excludeTools]; }
|
|
1428
|
+
if (override.allowNestedSubagents !== undefined) next.allowNestedSubagents = override.allowNestedSubagents;
|
|
1243
1429
|
if (override.extensions !== undefined) { if (override.extensions === false) delete next.extensions; else next.extensions = [...override.extensions]; }
|
|
1244
1430
|
if (override.subagentOnlyExtensions !== undefined) { if (override.subagentOnlyExtensions === false) delete next.subagentOnlyExtensions; else next.subagentOnlyExtensions = [...override.subagentOnlyExtensions]; }
|
|
1431
|
+
if (override.mutationTools !== undefined) { if (override.mutationTools === false) delete next.mutationTools; else next.mutationTools = [...override.mutationTools]; }
|
|
1245
1432
|
if (override.completionGuard !== undefined) next.completionGuard = override.completionGuard;
|
|
1246
1433
|
if (override.toolBudget !== undefined) { if (override.toolBudget === false) delete next.toolBudget; else next.toolBudget = override.toolBudget; }
|
|
1247
1434
|
|
|
@@ -1309,116 +1496,12 @@ function applyBuiltinOverrides(
|
|
|
1309
1496
|
});
|
|
1310
1497
|
}
|
|
1311
1498
|
|
|
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
1499
|
function applyCustomAgentOverride(
|
|
1318
1500
|
agent: AgentConfig,
|
|
1319
1501
|
override: BuiltinAgentOverrideConfig,
|
|
1320
1502
|
meta: { scope: "user" | "project"; path: string },
|
|
1321
1503
|
): 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) };
|
|
1504
|
+
const next = applyBuiltinOverride(agent, override, meta);
|
|
1422
1505
|
const frontmatterFields = agentFrontmatterFields.get(agent);
|
|
1423
1506
|
if (frontmatterFields) agentFrontmatterFields.set(next, frontmatterFields);
|
|
1424
1507
|
return next;
|
|
@@ -1449,7 +1532,7 @@ function applyCustomAgentOverrides(
|
|
|
1449
1532
|
|
|
1450
1533
|
export function buildBuiltinOverrideConfig(
|
|
1451
1534
|
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">>,
|
|
1535
|
+
draft: Pick<AgentConfig, "model" | "modelProvider" | "fallbackModels" | "fast" | "thinking" | "systemPromptMode" | "inheritProjectContext" | "inheritGlobalContext" | "inheritSkills" | "defaultContext" | "acceptanceRole" | "disabled" | "systemPrompt" | "skills" | "tools" | "allowNestedSubagents" | "mcpDirectTools" | "extensions" | "subagentOnlyExtensions" | "mutationTools" | "completionGuard" | "toolBudget"> & Partial<Pick<AgentConfig, "description" | "output" | "outputMode" | "defaultReads" | "excludeTools">>,
|
|
1453
1536
|
): BuiltinAgentOverrideConfig | undefined {
|
|
1454
1537
|
const override: BuiltinAgentOverrideConfig = {};
|
|
1455
1538
|
|
|
@@ -1467,6 +1550,7 @@ export function buildBuiltinOverrideConfig(
|
|
|
1467
1550
|
if (draft.thinking !== base.thinking) override.thinking = draft.thinking ?? false;
|
|
1468
1551
|
if (draft.systemPromptMode !== base.systemPromptMode) override.systemPromptMode = draft.systemPromptMode;
|
|
1469
1552
|
if (draft.inheritProjectContext !== base.inheritProjectContext) override.inheritProjectContext = draft.inheritProjectContext;
|
|
1553
|
+
if (draft.inheritGlobalContext !== base.inheritGlobalContext) override.inheritGlobalContext = draft.inheritGlobalContext;
|
|
1470
1554
|
if (draft.inheritSkills !== base.inheritSkills) override.inheritSkills = draft.inheritSkills;
|
|
1471
1555
|
if (draft.defaultContext !== base.defaultContext) override.defaultContext = draft.defaultContext ?? false;
|
|
1472
1556
|
if (draft.acceptanceRole !== base.acceptanceRole) override.acceptanceRole = draft.acceptanceRole ?? false;
|
|
@@ -1477,10 +1561,13 @@ export function buildBuiltinOverrideConfig(
|
|
|
1477
1561
|
const baseTools = joinToolList(base);
|
|
1478
1562
|
const draftTools = joinToolList(draft);
|
|
1479
1563
|
if (!arraysEqual(draftTools, baseTools)) override.tools = draftTools ? [...draftTools] : false;
|
|
1564
|
+
if (!arraysEqual(draft.excludeTools, base.excludeTools)) override.excludeTools = draft.excludeTools ? [...draft.excludeTools] : false;
|
|
1565
|
+
if (draft.allowNestedSubagents !== base.allowNestedSubagents) override.allowNestedSubagents = draft.allowNestedSubagents === true;
|
|
1480
1566
|
if (!arraysEqual(draft.extensions, base.extensions)) override.extensions = draft.extensions ? [...draft.extensions] : false;
|
|
1481
1567
|
if (!arraysEqual(draft.subagentOnlyExtensions, base.subagentOnlyExtensions)) {
|
|
1482
1568
|
override.subagentOnlyExtensions = draft.subagentOnlyExtensions ? [...draft.subagentOnlyExtensions] : false;
|
|
1483
1569
|
}
|
|
1570
|
+
if (!arraysEqual(draft.mutationTools, base.mutationTools)) override.mutationTools = draft.mutationTools ? [...draft.mutationTools] : false;
|
|
1484
1571
|
if ((draft.completionGuard !== false) !== (base.completionGuard !== false)) {
|
|
1485
1572
|
override.completionGuard = draft.completionGuard !== false;
|
|
1486
1573
|
}
|
|
@@ -1610,7 +1697,7 @@ export function removeBuiltinAgentOverrideFields(
|
|
|
1610
1697
|
return { path: filePath, removed: true };
|
|
1611
1698
|
}
|
|
1612
1699
|
|
|
1613
|
-
const DISCOVERY_PRUNED_DIR_NAMES = new Set([".git", "node_modules"]);
|
|
1700
|
+
const DISCOVERY_PRUNED_DIR_NAMES = new Set([".git", "node_modules", ".pi", "sync-backups"]);
|
|
1614
1701
|
|
|
1615
1702
|
function isDiscoveryNestedProjectRoot(dir: string): boolean {
|
|
1616
1703
|
return isDirectory(getProjectConfigDir(dir)) || isDirectory(path.join(dir, ".agents"));
|
|
@@ -1622,9 +1709,24 @@ function shouldPruneDiscoveryDir(rootDir: string, dir: string, dirName: string):
|
|
|
1622
1709
|
return path.resolve(dir) !== path.resolve(rootDir) && isDiscoveryNestedProjectRoot(dir);
|
|
1623
1710
|
}
|
|
1624
1711
|
|
|
1625
|
-
function listFilesRecursive(
|
|
1712
|
+
function listFilesRecursive(
|
|
1713
|
+
dir: string,
|
|
1714
|
+
predicate: (fileName: string) => boolean,
|
|
1715
|
+
rootDir = dir,
|
|
1716
|
+
visitedDirectories = new Set<string>(),
|
|
1717
|
+
inspectedDirectories = new Set<string>(),
|
|
1718
|
+
): string[] {
|
|
1626
1719
|
const files: string[] = [];
|
|
1627
1720
|
if (!fs.existsSync(dir)) return files;
|
|
1721
|
+
inspectedDirectories.add(path.resolve(dir));
|
|
1722
|
+
let realDir: string;
|
|
1723
|
+
try {
|
|
1724
|
+
realDir = fs.realpathSync(dir);
|
|
1725
|
+
} catch {
|
|
1726
|
+
return files;
|
|
1727
|
+
}
|
|
1728
|
+
if (visitedDirectories.has(realDir)) return files;
|
|
1729
|
+
visitedDirectories.add(realDir);
|
|
1628
1730
|
|
|
1629
1731
|
let entries: fs.Dirent[];
|
|
1630
1732
|
try {
|
|
@@ -1635,9 +1737,17 @@ function listFilesRecursive(dir: string, predicate: (fileName: string) => boolea
|
|
|
1635
1737
|
|
|
1636
1738
|
for (const entry of entries) {
|
|
1637
1739
|
const filePath = path.join(dir, entry.name);
|
|
1638
|
-
|
|
1740
|
+
let isDirectory = entry.isDirectory();
|
|
1741
|
+
if (entry.isSymbolicLink()) {
|
|
1742
|
+
try {
|
|
1743
|
+
isDirectory = fs.statSync(filePath).isDirectory();
|
|
1744
|
+
} catch {
|
|
1745
|
+
isDirectory = false;
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
if (isDirectory) {
|
|
1639
1749
|
if (!shouldPruneDiscoveryDir(rootDir, filePath, entry.name)) {
|
|
1640
|
-
files.push(...listFilesRecursive(filePath, predicate, rootDir));
|
|
1750
|
+
files.push(...listFilesRecursive(filePath, predicate, rootDir, visitedDirectories, inspectedDirectories));
|
|
1641
1751
|
}
|
|
1642
1752
|
continue;
|
|
1643
1753
|
}
|
|
@@ -1648,6 +1758,94 @@ function listFilesRecursive(dir: string, predicate: (fileName: string) => boolea
|
|
|
1648
1758
|
return files;
|
|
1649
1759
|
}
|
|
1650
1760
|
|
|
1761
|
+
export interface AgentDefinitionInspection {
|
|
1762
|
+
files: string[];
|
|
1763
|
+
state: AgentDefinitionDirectoryState;
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
const agentDefinitionInspectionDirectories = new WeakMap<AgentDefinitionInspection, string[]>();
|
|
1767
|
+
|
|
1768
|
+
function rememberAgentDefinitionInspection(inspection: AgentDefinitionInspection, directories: Iterable<string>): AgentDefinitionInspection {
|
|
1769
|
+
agentDefinitionInspectionDirectories.set(inspection, [...new Set([...directories].map((directory) => path.resolve(directory)))]);
|
|
1770
|
+
return inspection;
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
function inspectedAgentDefinitionDirectories(inspection: AgentDefinitionInspection, root: string): string[] {
|
|
1774
|
+
return agentDefinitionInspectionDirectories.get(inspection) ?? [path.resolve(root)];
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
/** Narrow filesystem seam so unavailable paths can be tested without permissions. */
|
|
1778
|
+
export interface AgentDefinitionInspectionFs {
|
|
1779
|
+
existsSync(filePath: string): boolean;
|
|
1780
|
+
realpathSync?(filePath: string): string;
|
|
1781
|
+
statSync(filePath: string): { isDirectory(): boolean };
|
|
1782
|
+
readdirSync(dir: string): fs.Dirent[];
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
const DEFAULT_AGENT_DEFINITION_INSPECTION_FS: AgentDefinitionInspectionFs = {
|
|
1786
|
+
existsSync: fs.existsSync,
|
|
1787
|
+
realpathSync: fs.realpathSync,
|
|
1788
|
+
statSync: fs.statSync,
|
|
1789
|
+
readdirSync: (dir) => fs.readdirSync(dir, { withFileTypes: true }),
|
|
1790
|
+
};
|
|
1791
|
+
|
|
1792
|
+
/**
|
|
1793
|
+
* Inspect one agent-definition directory while retaining traversal failure
|
|
1794
|
+
* state. A nested unreadable directory makes the whole inspection unavailable,
|
|
1795
|
+
* preventing a partial traversal from being reported as empty or complete.
|
|
1796
|
+
*/
|
|
1797
|
+
export function inspectAgentDefinitionDirectory(dir: string, operations: AgentDefinitionInspectionFs = DEFAULT_AGENT_DEFINITION_INSPECTION_FS): AgentDefinitionInspection {
|
|
1798
|
+
const root = path.resolve(dir);
|
|
1799
|
+
try {
|
|
1800
|
+
if (!operations.existsSync(root)) return rememberAgentDefinitionInspection({ files: [], state: "absent" }, [root]);
|
|
1801
|
+
if (!operations.statSync(root).isDirectory()) return rememberAgentDefinitionInspection({ files: [], state: "not-directory" }, [root]);
|
|
1802
|
+
} catch {
|
|
1803
|
+
return rememberAgentDefinitionInspection({ files: [], state: "unreadable" }, [root]);
|
|
1804
|
+
}
|
|
1805
|
+
const files: string[] = [];
|
|
1806
|
+
let unreadable = false;
|
|
1807
|
+
const visitedDirectories = new Set<string>();
|
|
1808
|
+
const inspectedDirectories = new Set<string>();
|
|
1809
|
+
const visit = (current: string): void => {
|
|
1810
|
+
inspectedDirectories.add(path.resolve(current));
|
|
1811
|
+
let realDir: string;
|
|
1812
|
+
try {
|
|
1813
|
+
realDir = operations.realpathSync?.(current) ?? path.resolve(current);
|
|
1814
|
+
} catch {
|
|
1815
|
+
unreadable = true;
|
|
1816
|
+
return;
|
|
1817
|
+
}
|
|
1818
|
+
if (visitedDirectories.has(realDir)) return;
|
|
1819
|
+
visitedDirectories.add(realDir);
|
|
1820
|
+
|
|
1821
|
+
let entries: fs.Dirent[];
|
|
1822
|
+
try {
|
|
1823
|
+
entries = operations.readdirSync(current).sort((a, b) => a.name.localeCompare(b.name));
|
|
1824
|
+
} catch {
|
|
1825
|
+
unreadable = true;
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
for (const entry of entries) {
|
|
1829
|
+
const filePath = path.join(current, entry.name);
|
|
1830
|
+
let isDirectory = entry.isDirectory();
|
|
1831
|
+
if (entry.isSymbolicLink()) {
|
|
1832
|
+
try {
|
|
1833
|
+
isDirectory = operations.statSync(filePath).isDirectory();
|
|
1834
|
+
} catch {
|
|
1835
|
+
isDirectory = false;
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
if (isDirectory) {
|
|
1839
|
+
if (!shouldPruneDiscoveryDir(root, filePath, entry.name)) visit(filePath);
|
|
1840
|
+
continue;
|
|
1841
|
+
}
|
|
1842
|
+
if ((entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith(".md") && !entry.name.endsWith(".chain.md") && !isLegacyAgentSkillPath(root, filePath)) files.push(filePath);
|
|
1843
|
+
}
|
|
1844
|
+
};
|
|
1845
|
+
visit(root);
|
|
1846
|
+
return rememberAgentDefinitionInspection({ files, state: unreadable ? "unreadable" : files.length ? "candidates" : "empty" }, inspectedDirectories);
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1651
1849
|
function isLegacyAgentSkillPath(rootDir: string, filePath: string): boolean {
|
|
1652
1850
|
const relative = path.relative(rootDir, filePath);
|
|
1653
1851
|
const parts = relative.split(path.sep).map((part) => part.toLowerCase());
|
|
@@ -1706,24 +1904,29 @@ function parseAgentRunnerFrontmatter(raw: string | undefined, agentName: string)
|
|
|
1706
1904
|
if (runner.args !== undefined && (!Array.isArray(runner.args) || runner.args.some((arg) => typeof arg !== "string"))) {
|
|
1707
1905
|
throw new Error(`Agent '${agentName}' external-cli runner args must be an array of strings.`);
|
|
1708
1906
|
}
|
|
1907
|
+
if (runner.adapter !== undefined && !isCodeOwnedExternalCliAdapterId(runner.adapter)) throw new Error(`Agent '${agentName}' external-cli runner adapter must be ${CODE_OWNED_EXTERNAL_CLI_ADAPTER_LABEL}.`);
|
|
1908
|
+
if (runner.adapter !== undefined && Array.isArray(runner.args) && runner.args.length > 0) throw new Error(`Agent '${agentName}' ${runner.adapter} adapter owns its argv; runner args are not supported.`);
|
|
1709
1909
|
if (runner.promptDelivery !== undefined && runner.promptDelivery !== "stdin") {
|
|
1710
1910
|
throw new Error(`Agent '${agentName}' external-cli runner promptDelivery must be 'stdin'.`);
|
|
1711
1911
|
}
|
|
1712
|
-
const
|
|
1912
|
+
const capabilities = parseExternalCliCapabilityNarrowing(runner.capabilities, `Agent '${agentName}' external-cli runner capabilities`);
|
|
1913
|
+
const supported = new Set(["type", "adapter", "command", "args", "promptDelivery", "capabilities"]);
|
|
1713
1914
|
const unknown = Object.keys(runner).filter((key) => !supported.has(key));
|
|
1714
1915
|
if (unknown.length > 0) throw new Error(`Agent '${agentName}' external-cli runner has unsupported fields: ${unknown.join(", ")}.`);
|
|
1715
1916
|
const runnerArgs = Array.isArray(runner.args) ? runner.args.filter((arg): arg is string => typeof arg === "string") : undefined;
|
|
1716
1917
|
return {
|
|
1717
1918
|
type: "external-cli",
|
|
1919
|
+
...(isCodeOwnedExternalCliAdapterId(runner.adapter) ? { adapter: runner.adapter } : {}),
|
|
1718
1920
|
command: runner.command.trim(),
|
|
1719
1921
|
...(runnerArgs?.length ? { args: runnerArgs } : {}),
|
|
1720
1922
|
...(runner.promptDelivery ? { promptDelivery: "stdin" as const } : {}),
|
|
1923
|
+
...(capabilities ? { capabilities } : {}),
|
|
1721
1924
|
};
|
|
1722
1925
|
}
|
|
1723
1926
|
|
|
1724
1927
|
function validateExternalRunnerProfile(frontmatter: Record<string, string>, agentName: string, runner: AgentRunnerConfig | undefined): void {
|
|
1725
1928
|
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"]
|
|
1929
|
+
const unsupported = ["tools", "excludeTools", "allowNestedSubagents", "model", "fallbackModels", "thinking", "extensions", "subagentOnlyExtensions", "mutationTools", "maxSubagentDepth", "completionGuard", "skills", "skill", "skillPath", "toolBudget", "permission", "permissions"]
|
|
1727
1930
|
.filter((field) => frontmatter[field] !== undefined);
|
|
1728
1931
|
if (unsupported.length > 0) {
|
|
1729
1932
|
throw new Error(`Agent '${agentName}' uses runner.type='${runner.type}' and declares unsupported Pi-only fields: ${unsupported.join(", ")}.`);
|
|
@@ -1748,9 +1951,9 @@ interface AgentDefinitionFile {
|
|
|
1748
1951
|
content: string;
|
|
1749
1952
|
}
|
|
1750
1953
|
|
|
1751
|
-
function readAgentDefinitionFiles(dir: string): AgentDefinitionFile[] {
|
|
1954
|
+
function readAgentDefinitionFiles(dir: string, inspection = inspectAgentDefinitionDirectory(dir)): AgentDefinitionFile[] {
|
|
1752
1955
|
const files: AgentDefinitionFile[] = [];
|
|
1753
|
-
for (const filePath of
|
|
1956
|
+
for (const filePath of inspection.files) {
|
|
1754
1957
|
if (isLegacyAgentSkillPath(dir, filePath)) {
|
|
1755
1958
|
continue;
|
|
1756
1959
|
}
|
|
@@ -1776,7 +1979,7 @@ function resolveAgentRelativeExtensionPaths(paths: string[] | undefined, agentFi
|
|
|
1776
1979
|
});
|
|
1777
1980
|
}
|
|
1778
1981
|
|
|
1779
|
-
function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir">): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
|
|
1982
|
+
function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir" | "scope">): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
|
|
1780
1983
|
const agents: AgentConfig[] = [];
|
|
1781
1984
|
const diagnostics: AgentDiscoveryDiagnostic[] = [];
|
|
1782
1985
|
|
|
@@ -1805,8 +2008,11 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1805
2008
|
const parsedTools = splitToolList(rawTools);
|
|
1806
2009
|
const tools = parsedTools.tools ?? [];
|
|
1807
2010
|
const mcpDirectTools = parsedTools.mcpDirectTools ?? [];
|
|
2011
|
+
const excludeTools = parseFrontmatterList(frontmatter.excludeTools);
|
|
1808
2012
|
const defaultReads = parseFrontmatterList(frontmatter.defaultReads);
|
|
1809
2013
|
const aliases = normalizeAgentAliases(parseFrontmatterList(frontmatter.aliases ?? frontmatter.alias), runtimeName);
|
|
2014
|
+
const profileError = validateCodeOwnedProfileRunner({ name: runtimeName, localName, aliases, runner });
|
|
2015
|
+
if (profileError) throw new Error(profileError);
|
|
1810
2016
|
const skillStr = frontmatter.skill || frontmatter.skills;
|
|
1811
2017
|
const skills = parseFrontmatterList(skillStr);
|
|
1812
2018
|
const skillPath = parseFrontmatterList(frontmatter.skillPath);
|
|
@@ -1821,6 +2027,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1821
2027
|
: frontmatter.inheritProjectContext === "false"
|
|
1822
2028
|
? false
|
|
1823
2029
|
: defaultInheritProjectContext(localName);
|
|
2030
|
+
const inheritGlobalContext = frontmatter.inheritGlobalContext === "true";
|
|
1824
2031
|
const inheritSkills = frontmatter.inheritSkills === "true"
|
|
1825
2032
|
? true
|
|
1826
2033
|
: frontmatter.inheritSkills === "false"
|
|
@@ -1853,13 +2060,6 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1853
2060
|
}
|
|
1854
2061
|
defaultToolTimeoutMs = parsed;
|
|
1855
2062
|
}
|
|
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
2063
|
const defaultAcceptance = parseAgentAcceptanceFrontmatter(frontmatter.acceptance, localName);
|
|
1864
2064
|
let outputMode: OutputMode | undefined;
|
|
1865
2065
|
if (frontmatter.outputMode !== undefined) {
|
|
@@ -1874,12 +2074,19 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1874
2074
|
|
|
1875
2075
|
const extensions = resolveAgentRelativeExtensionPaths(parseFrontmatterList(frontmatter.extensions), filePath);
|
|
1876
2076
|
const subagentOnlyExtensions = resolveAgentRelativeExtensionPaths(parseFrontmatterList(frontmatter.subagentOnlyExtensions), filePath);
|
|
2077
|
+
const mutationTools = parseFrontmatterList(frontmatter.mutationTools);
|
|
1877
2078
|
let fast: boolean | undefined;
|
|
1878
2079
|
if (frontmatter.fast !== undefined) {
|
|
1879
2080
|
if (frontmatter.fast === "true") fast = true;
|
|
1880
2081
|
else if (frontmatter.fast === "false") fast = false;
|
|
1881
2082
|
else throw new Error(`Agent '${localName}' has invalid fast frontmatter; expected true or false.`);
|
|
1882
2083
|
}
|
|
2084
|
+
let allowNestedSubagents: boolean | undefined;
|
|
2085
|
+
if (frontmatter.allowNestedSubagents !== undefined) {
|
|
2086
|
+
if (frontmatter.allowNestedSubagents === "true") allowNestedSubagents = true;
|
|
2087
|
+
else if (frontmatter.allowNestedSubagents === "false") allowNestedSubagents = false;
|
|
2088
|
+
else throw new Error(`Agent '${localName}' has invalid allowNestedSubagents frontmatter; expected true or false.`);
|
|
2089
|
+
}
|
|
1883
2090
|
|
|
1884
2091
|
const extraFields: Record<string, string> = {};
|
|
1885
2092
|
for (const [key, value] of Object.entries(frontmatter)) {
|
|
@@ -1923,6 +2130,8 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1923
2130
|
description: frontmatter.description,
|
|
1924
2131
|
...(aliases !== undefined ? { aliases } : {}),
|
|
1925
2132
|
...(rawTools !== undefined ? { tools } : {}),
|
|
2133
|
+
...(excludeTools !== undefined ? { excludeTools } : {}),
|
|
2134
|
+
...(allowNestedSubagents !== undefined ? { allowNestedSubagents } : {}),
|
|
1926
2135
|
...(mcpDirectTools.length > 0 ? { mcpDirectTools } : {}),
|
|
1927
2136
|
...(frontmatter.model !== undefined ? { model: frontmatter.model } : {}),
|
|
1928
2137
|
...(fallbackModels?.length ? { fallbackModels } : {}),
|
|
@@ -1930,12 +2139,12 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1930
2139
|
...(frontmatter.thinking !== undefined ? { thinking: frontmatter.thinking === "false" ? false : frontmatter.thinking } : {}),
|
|
1931
2140
|
systemPromptMode,
|
|
1932
2141
|
inheritProjectContext,
|
|
2142
|
+
inheritGlobalContext,
|
|
1933
2143
|
inheritSkills,
|
|
1934
2144
|
...(defaultContext !== undefined ? { defaultContext } : {}),
|
|
1935
2145
|
...(defaultAsync !== undefined ? { defaultAsync } : {}),
|
|
1936
2146
|
...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
|
|
1937
2147
|
...(defaultToolTimeoutMs !== undefined ? { defaultToolTimeoutMs } : {}),
|
|
1938
|
-
...(defaultTurnBudget !== undefined ? { defaultTurnBudget } : {}),
|
|
1939
2148
|
...(defaultAcceptance !== undefined ? { defaultAcceptance } : {}),
|
|
1940
2149
|
...(acceptanceRole !== undefined ? { acceptanceRole } : {}),
|
|
1941
2150
|
systemPrompt: body,
|
|
@@ -1946,6 +2155,7 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1946
2155
|
...(skillPath?.length ? { skillPath } : {}),
|
|
1947
2156
|
...(extensions !== undefined ? { extensions } : {}),
|
|
1948
2157
|
...(subagentOnlyExtensions !== undefined ? { subagentOnlyExtensions } : {}),
|
|
2158
|
+
...(mutationTools?.length ? { mutationTools } : {}),
|
|
1949
2159
|
...(frontmatter.output !== undefined ? { output: frontmatter.output } : {}),
|
|
1950
2160
|
...(outputMode !== undefined ? { outputMode } : {}),
|
|
1951
2161
|
...(defaultReads?.length ? { defaultReads } : {}),
|
|
@@ -1969,15 +2179,26 @@ function loadAgentsFromDefinitionFiles(files: AgentDefinitionFile[], source: Age
|
|
|
1969
2179
|
return { agents, diagnostics };
|
|
1970
2180
|
}
|
|
1971
2181
|
|
|
1972
|
-
function loadAgentsFromDir(dir: string, source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir"
|
|
1973
|
-
return loadAgentsFromDefinitionFiles(readAgentDefinitionFiles(dir), source, discoveryPriority, packageSource);
|
|
2182
|
+
function loadAgentsFromDir(dir: string, source: AgentSource, discoveryPriority?: number, packageSource?: Omit<PackageSubagentPath, "dir" | "scope">, inspection = inspectAgentDefinitionDirectory(dir)): { agents: AgentConfig[]; diagnostics: AgentDiscoveryDiagnostic[] } {
|
|
2183
|
+
return loadAgentsFromDefinitionFiles(readAgentDefinitionFiles(dir, inspection), source, discoveryPriority, packageSource);
|
|
1974
2184
|
}
|
|
1975
2185
|
|
|
1976
|
-
function
|
|
2186
|
+
function reportAgentDefinitionDirectory(source: AgentSource, dir: string, inspection: AgentDefinitionInspection): AgentDefinitionDirectoryReport {
|
|
2187
|
+
return {
|
|
2188
|
+
source,
|
|
2189
|
+
path: path.resolve(dir),
|
|
2190
|
+
state: inspection.state,
|
|
2191
|
+
...(inspection.state === "candidates" ? { candidateCount: inspection.files.length } : {}),
|
|
2192
|
+
};
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainConfig[]; diagnostics: ChainDiscoveryDiagnostic[]; files: string[]; directories: string[] } {
|
|
1977
2196
|
const chains = new Map<string, ChainConfig>();
|
|
1978
2197
|
const diagnostics: ChainDiscoveryDiagnostic[] = [];
|
|
2198
|
+
const directories = new Set<string>();
|
|
2199
|
+
const files = listFilesRecursive(dir, (fileName) => fileName.endsWith(".chain.md") || fileName.endsWith(".chain.json"), dir, new Set<string>(), directories);
|
|
1979
2200
|
|
|
1980
|
-
for (const filePath of
|
|
2201
|
+
for (const filePath of files) {
|
|
1981
2202
|
let content: string;
|
|
1982
2203
|
try {
|
|
1983
2204
|
content = fs.readFileSync(filePath, "utf-8");
|
|
@@ -1996,7 +2217,7 @@ function loadChainsFromDir(dir: string, source: AgentSource): { chains: ChainCon
|
|
|
1996
2217
|
}
|
|
1997
2218
|
}
|
|
1998
2219
|
|
|
1999
|
-
return { chains: Array.from(chains.values()), diagnostics };
|
|
2220
|
+
return { chains: Array.from(chains.values()), diagnostics, files, directories: [...directories] };
|
|
2000
2221
|
}
|
|
2001
2222
|
|
|
2002
2223
|
function isDirectory(p: string): boolean {
|
|
@@ -2007,20 +2228,18 @@ function isDirectory(p: string): boolean {
|
|
|
2007
2228
|
}
|
|
2008
2229
|
}
|
|
2009
2230
|
|
|
2010
|
-
function resolveNearestProjectAgentDirs(cwd: string): { readDirs: string[]; preferredDir: string | null } {
|
|
2231
|
+
function resolveNearestProjectAgentDirs(cwd: string): { readDirs: string[]; candidateDirs: string[]; preferredDir: string | null } {
|
|
2011
2232
|
const projectRoot = findConfiguredProjectRoot(cwd);
|
|
2012
|
-
if (!projectRoot) return { readDirs: [], preferredDir: null };
|
|
2233
|
+
if (!projectRoot) return { readDirs: [], candidateDirs: [], preferredDir: null };
|
|
2013
2234
|
|
|
2014
2235
|
const legacyDir = path.join(projectRoot, ".agents");
|
|
2015
2236
|
const preferredDir = path.join(getProjectConfigDir(projectRoot), "agents");
|
|
2237
|
+
const candidateDirs = [legacyDir, preferredDir];
|
|
2016
2238
|
const readDirs: string[] = [];
|
|
2017
2239
|
if (isDirectory(legacyDir)) readDirs.push(legacyDir);
|
|
2018
2240
|
if (isDirectory(preferredDir)) readDirs.push(preferredDir);
|
|
2019
2241
|
|
|
2020
|
-
return {
|
|
2021
|
-
readDirs,
|
|
2022
|
-
preferredDir,
|
|
2023
|
-
};
|
|
2242
|
+
return { readDirs, candidateDirs, preferredDir };
|
|
2024
2243
|
}
|
|
2025
2244
|
|
|
2026
2245
|
function resolveNearestProjectChainDirs(cwd: string): { readDirs: string[]; preferredDir: string | null } {
|
|
@@ -2034,7 +2253,9 @@ function resolveNearestProjectChainDirs(cwd: string): { readDirs: string[]; pref
|
|
|
2034
2253
|
};
|
|
2035
2254
|
}
|
|
2036
2255
|
const BUILTIN_AGENTS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "agents");
|
|
2037
|
-
|
|
2256
|
+
// Candidate files and inspection state must describe the same cached builtin scan.
|
|
2257
|
+
const BUILTIN_AGENT_DEFINITION_INSPECTION = inspectAgentDefinitionDirectory(BUILTIN_AGENTS_DIR);
|
|
2258
|
+
const BUILTIN_AGENT_DEFINITION_FILES = readAgentDefinitionFiles(BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION);
|
|
2038
2259
|
|
|
2039
2260
|
export const EXTRA_AGENT_DIRS_ENV = "PI_SUBAGENT_EXTRA_AGENT_DIRS";
|
|
2040
2261
|
|
|
@@ -2052,92 +2273,62 @@ function extraUserAgentDirs(): string[] {
|
|
|
2052
2273
|
.filter((dir) => dir.length > 0);
|
|
2053
2274
|
}
|
|
2054
2275
|
|
|
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
|
-
);
|
|
2276
|
+
interface AgentScanDirs {
|
|
2277
|
+
dirs: string[];
|
|
2278
|
+
watchPaths: string[];
|
|
2279
|
+
}
|
|
2095
2280
|
|
|
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
|
-
}
|
|
2281
|
+
function readConfiguredAgentScanDirs(filePath: string | null): string[] {
|
|
2282
|
+
if (!filePath) return [];
|
|
2283
|
+
try {
|
|
2284
|
+
const settings = readSettingsFileStrict(filePath);
|
|
2285
|
+
const subagents = settings.subagents;
|
|
2286
|
+
if (!subagents || typeof subagents !== "object" || Array.isArray(subagents)) return [];
|
|
2287
|
+
const dirs = (subagents as { agentScanDirs?: unknown }).agentScanDirs;
|
|
2288
|
+
return Array.isArray(dirs) ? dirs.filter((dir): dir is string => typeof dir === "string" && dir.trim().length > 0) : [];
|
|
2289
|
+
} catch {
|
|
2290
|
+
return [];
|
|
2110
2291
|
}
|
|
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
|
-
);
|
|
2292
|
+
}
|
|
2123
2293
|
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2294
|
+
function expandAgentScanDirPattern(pattern: string): AgentScanDirs {
|
|
2295
|
+
const expanded = expandHomePath(pattern.trim()).replace(/[\\/]+/g, path.sep);
|
|
2296
|
+
if (!expanded) return { dirs: [], watchPaths: [] };
|
|
2297
|
+
const wildcardMatches = [...expanded.matchAll(/\*/g)];
|
|
2298
|
+
if (wildcardMatches.length === 0) {
|
|
2299
|
+
const dir = path.resolve(expanded);
|
|
2300
|
+
return { dirs: fs.existsSync(dir) ? [dir] : [], watchPaths: [dir] };
|
|
2301
|
+
}
|
|
2302
|
+
const parts = expanded.split(path.sep);
|
|
2303
|
+
const wildcardIndex = parts.findIndex((part) => part.includes("*"));
|
|
2304
|
+
if (wildcardMatches.length !== 1 || wildcardIndex === -1 || parts[wildcardIndex] !== "*") return { dirs: [], watchPaths: [] };
|
|
2305
|
+
const base = path.resolve(parts.slice(0, wildcardIndex).join(path.sep) || path.sep);
|
|
2306
|
+
const rest = parts.slice(wildcardIndex + 1);
|
|
2307
|
+
let entries: fs.Dirent[];
|
|
2308
|
+
try {
|
|
2309
|
+
entries = fs.readdirSync(base, { withFileTypes: true });
|
|
2310
|
+
} catch {
|
|
2311
|
+
return { dirs: [], watchPaths: [base] };
|
|
2312
|
+
}
|
|
2313
|
+
const candidateDirs = entries.filter((entry) => entry.isDirectory()).map((entry) => path.join(base, entry.name, ...rest));
|
|
2130
2314
|
return {
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
projectAgentsDir,
|
|
2134
|
-
...(modelScope !== undefined ? { modelScope } : {}),
|
|
2135
|
-
...(injectAgents?.length ? { injectAgents } : {}),
|
|
2136
|
-
...(maxThinking !== undefined ? { maxThinking } : {}),
|
|
2315
|
+
dirs: candidateDirs.filter((dir) => fs.existsSync(dir)),
|
|
2316
|
+
watchPaths: [base, ...candidateDirs],
|
|
2137
2317
|
};
|
|
2138
2318
|
}
|
|
2139
2319
|
|
|
2140
|
-
|
|
2320
|
+
function settingsAgentScanDirs(entries: string[]): AgentScanDirs {
|
|
2321
|
+
const dirs = new Set<string>();
|
|
2322
|
+
const watchPaths = new Set<string>();
|
|
2323
|
+
for (const entry of entries) {
|
|
2324
|
+
const expanded = expandAgentScanDirPattern(entry);
|
|
2325
|
+
for (const dir of expanded.dirs) dirs.add(dir);
|
|
2326
|
+
for (const watchPath of expanded.watchPaths) watchPaths.add(watchPath);
|
|
2327
|
+
}
|
|
2328
|
+
return { dirs: [...dirs], watchPaths: [...watchPaths] };
|
|
2329
|
+
}
|
|
2330
|
+
|
|
2331
|
+
export interface AgentDiscoveryAllResult {
|
|
2141
2332
|
builtin: AgentConfig[];
|
|
2142
2333
|
package: AgentConfig[];
|
|
2143
2334
|
user: AgentConfig[];
|
|
@@ -2153,129 +2344,485 @@ export function discoverAgentsAll(cwd: string): {
|
|
|
2153
2344
|
userSettingsPath: string;
|
|
2154
2345
|
projectSettingsPath: string | null;
|
|
2155
2346
|
maxThinking?: ThinkingLevel;
|
|
2156
|
-
}
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
/**
|
|
2350
|
+
* A single fresh source scan with both projections retained. The effective
|
|
2351
|
+
* projection intentionally remains separate from the all-source projection:
|
|
2352
|
+
* disabled and shadowed definitions are needed for diagnostics and runtime
|
|
2353
|
+
* collision checks even when they are not launchable.
|
|
2354
|
+
*/
|
|
2355
|
+
export interface AgentDiscoverySnapshot {
|
|
2356
|
+
effective: AgentDiscoveryResult;
|
|
2357
|
+
all: AgentDiscoveryAllResult;
|
|
2358
|
+
}
|
|
2359
|
+
|
|
2360
|
+
interface LoadedAgentDirectory {
|
|
2361
|
+
dir: string;
|
|
2362
|
+
inspection: AgentDefinitionInspection;
|
|
2363
|
+
loaded: ReturnType<typeof loadAgentsFromDir>;
|
|
2364
|
+
packageEntry?: PackageSubagentPath;
|
|
2365
|
+
}
|
|
2366
|
+
|
|
2367
|
+
interface AgentDiscoverySources {
|
|
2368
|
+
cwd: string;
|
|
2369
|
+
preferredModelProvider?: string;
|
|
2370
|
+
userDir: string;
|
|
2371
|
+
userDirOld: string;
|
|
2372
|
+
userDirNew: string;
|
|
2373
|
+
userChainDir: string;
|
|
2374
|
+
projectAgentDirs: string[];
|
|
2375
|
+
projectCandidateDirs: string[];
|
|
2376
|
+
projectAgentsDir: string | null;
|
|
2377
|
+
projectChainDirs: string[];
|
|
2378
|
+
projectChainDir: string | null;
|
|
2379
|
+
userSettingsPath: string;
|
|
2380
|
+
projectSettingsPath: string | null;
|
|
2381
|
+
userSettings?: SubagentSettings;
|
|
2382
|
+
projectSettings?: SubagentSettings;
|
|
2383
|
+
packageSubagentPaths: PackageSubagentPaths;
|
|
2384
|
+
builtinLoaded: ReturnType<typeof loadAgentsFromDefinitionFiles>;
|
|
2385
|
+
userLoaded: LoadedAgentDirectory[];
|
|
2386
|
+
projectLoaded: LoadedAgentDirectory[];
|
|
2387
|
+
projectInspections: Map<string, AgentDefinitionInspection>;
|
|
2388
|
+
packageLoaded: LoadedAgentDirectory[];
|
|
2389
|
+
userChains?: ReturnType<typeof loadChainsFromDir>;
|
|
2390
|
+
projectChainLoaded?: Array<{ dir: string; loaded: ReturnType<typeof loadChainsFromDir> }>;
|
|
2391
|
+
packageChainLoaded?: Array<{ entry: PackageChainPath; loaded: ReturnType<typeof loadChainsFromDir> }>;
|
|
2392
|
+
watchPaths: string[];
|
|
2393
|
+
}
|
|
2394
|
+
|
|
2395
|
+
interface AgentDiscoveryCacheEntry {
|
|
2396
|
+
sources: AgentDiscoverySources;
|
|
2397
|
+
fingerprint: string;
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
const agentDiscoveryCache = new Map<string, AgentDiscoveryCacheEntry>();
|
|
2401
|
+
|
|
2402
|
+
function isPathWithin(root: string, candidate: string): boolean {
|
|
2403
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
2404
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2407
|
+
function addDirectoryWatchPaths(paths: Set<string>, root: string, files: readonly string[], directories: readonly string[] = []): void {
|
|
2408
|
+
const resolvedRoot = path.resolve(root);
|
|
2409
|
+
paths.add(resolvedRoot);
|
|
2410
|
+
// The initial recursive inspection is already bounded to this discovery
|
|
2411
|
+
// root. Keep every visited directory in the fingerprint so a file added to
|
|
2412
|
+
// an existing empty nested directory invalidates the snapshot too.
|
|
2413
|
+
for (const directory of directories) {
|
|
2414
|
+
if (isPathWithin(resolvedRoot, directory)) paths.add(path.resolve(directory));
|
|
2415
|
+
}
|
|
2416
|
+
for (const file of files) {
|
|
2417
|
+
paths.add(path.resolve(file));
|
|
2418
|
+
let current = path.resolve(path.dirname(file));
|
|
2419
|
+
while (isPathWithin(resolvedRoot, current)) {
|
|
2420
|
+
paths.add(current);
|
|
2421
|
+
if (current === resolvedRoot) break;
|
|
2422
|
+
current = path.dirname(current);
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
function watchPathSignature(filePath: string): string {
|
|
2428
|
+
try {
|
|
2429
|
+
const stat = fs.statSync(filePath);
|
|
2430
|
+
if (stat.isDirectory()) {
|
|
2431
|
+
const entries = fs.readdirSync(filePath, { withFileTypes: true })
|
|
2432
|
+
.sort((left, right) => left.name.localeCompare(right.name))
|
|
2433
|
+
.map((entry) => `${entry.name}:${entry.isDirectory() ? "d" : entry.isSymbolicLink() ? "l" : "f"}`)
|
|
2434
|
+
.join("|");
|
|
2435
|
+
return `directory:${entries}`;
|
|
2436
|
+
}
|
|
2437
|
+
return `file:${stat.size}:${stat.mtimeMs}`;
|
|
2438
|
+
} catch {
|
|
2439
|
+
return "missing";
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
function discoveryFingerprint(paths: readonly string[]): string {
|
|
2444
|
+
return [...new Set(paths)]
|
|
2445
|
+
.sort((left, right) => left.localeCompare(right))
|
|
2446
|
+
.map((filePath) => `${filePath}:${watchPathSignature(filePath)}`)
|
|
2447
|
+
.join("\n");
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
function discoveryCacheKey(cwd: string, preferredModelProvider: string | undefined): string {
|
|
2451
|
+
return JSON.stringify([
|
|
2452
|
+
path.resolve(cwd),
|
|
2453
|
+
preferredModelProvider ?? null,
|
|
2454
|
+
getProjectConfigDir(path.resolve(cwd)),
|
|
2455
|
+
getAgentDir(),
|
|
2456
|
+
os.homedir(),
|
|
2457
|
+
process.env.HOME ?? "",
|
|
2458
|
+
process.env.USERPROFILE ?? "",
|
|
2459
|
+
process.env[EXTRA_AGENT_DIRS_ENV] ?? "",
|
|
2460
|
+
process.env.PI_OFFLINE ?? "",
|
|
2461
|
+
process.env.APPDATA ?? "",
|
|
2462
|
+
]);
|
|
2463
|
+
}
|
|
2464
|
+
|
|
2465
|
+
function projectDiscoveryWatchPaths(cwd: string): string[] {
|
|
2466
|
+
const paths: string[] = [];
|
|
2467
|
+
let current = path.resolve(cwd);
|
|
2468
|
+
while (true) {
|
|
2469
|
+
paths.push(getProjectConfigDir(current), path.join(current, ".agents"), path.join(current, ".git"));
|
|
2470
|
+
const parent = path.dirname(current);
|
|
2471
|
+
if (parent === current) break;
|
|
2472
|
+
current = parent;
|
|
2473
|
+
}
|
|
2474
|
+
return paths;
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
function packageEntryIncluded(scope: AgentScope, packageScopes: PackageSubagentPath["scope"]): boolean {
|
|
2478
|
+
if (scope === "both" || packageScopes.has("root")) return true;
|
|
2479
|
+
return packageScopes.has(scope);
|
|
2480
|
+
}
|
|
2481
|
+
|
|
2482
|
+
function buildAgentDiscoverySources(cwd: string, preferredModelProvider?: string): AgentDiscoverySources {
|
|
2483
|
+
const effectiveCwd = path.resolve(cwd);
|
|
2157
2484
|
const userDirOld = path.join(getAgentDir(), "agents");
|
|
2158
2485
|
const userDirNew = path.join(os.homedir(), ".agents");
|
|
2159
2486
|
const userChainDir = getUserChainDir();
|
|
2160
|
-
const { readDirs:
|
|
2161
|
-
const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(
|
|
2487
|
+
const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(effectiveCwd);
|
|
2488
|
+
const { readDirs: projectChainDirs, preferredDir: projectChainDir } = resolveNearestProjectChainDirs(effectiveCwd);
|
|
2162
2489
|
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);
|
|
2490
|
+
const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
|
|
2491
|
+
const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd);
|
|
2492
|
+
const userScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(userSettingsPath));
|
|
2493
|
+
const projectScanDirs = settingsAgentScanDirs(readConfiguredAgentScanDirs(projectSettingsPath));
|
|
2175
2494
|
|
|
2176
2495
|
const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
|
|
2177
|
-
const
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2496
|
+
const userLoaded = [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].map((dir, discoveryPriority): LoadedAgentDirectory => {
|
|
2497
|
+
const inspection = inspectAgentDefinitionDirectory(dir);
|
|
2498
|
+
return { dir, inspection, loaded: loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection) };
|
|
2499
|
+
});
|
|
2500
|
+
const projectInspections = new Map(projectCandidateDirs.map((dir) => [dir, inspectAgentDefinitionDirectory(dir)]));
|
|
2501
|
+
const projectLoaded = [...projectScanDirs.dirs, ...projectAgentDirs].map((dir, discoveryPriority): LoadedAgentDirectory => {
|
|
2502
|
+
const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir);
|
|
2503
|
+
return { dir, inspection, loaded: loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection) };
|
|
2504
|
+
});
|
|
2505
|
+
const packageLoaded = packageSubagentPaths.agents.map((entry, index): LoadedAgentDirectory => {
|
|
2506
|
+
const inspection = inspectAgentDefinitionDirectory(entry.dir);
|
|
2507
|
+
return { dir: entry.dir, inspection, packageEntry: entry, loaded: loadAgentsFromDir(entry.dir, "package", packageSubagentPaths.agents.length - index, entry, inspection) };
|
|
2508
|
+
});
|
|
2509
|
+
|
|
2510
|
+
const watchPaths = new Set<string>([
|
|
2181
2511
|
userSettingsPath,
|
|
2182
|
-
projectSettingsPath,
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
.
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2512
|
+
...(projectSettingsPath ? [projectSettingsPath] : []),
|
|
2513
|
+
...projectDiscoveryWatchPaths(effectiveCwd),
|
|
2514
|
+
...findProjectRootCandidates(effectiveCwd).map((root) => path.join(getProjectConfigDir(root), "settings.json")),
|
|
2515
|
+
...userScanDirs.watchPaths,
|
|
2516
|
+
...projectScanDirs.watchPaths,
|
|
2517
|
+
...packageSubagentPaths.watchPaths,
|
|
2518
|
+
]);
|
|
2519
|
+
for (const directory of userLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
|
|
2520
|
+
for (const dir of projectCandidateDirs) {
|
|
2521
|
+
const inspection = projectInspections.get(dir);
|
|
2522
|
+
addDirectoryWatchPaths(watchPaths, dir, inspection?.files ?? [], inspection ? inspectedAgentDefinitionDirectories(inspection, dir) : []);
|
|
2523
|
+
}
|
|
2524
|
+
for (const directory of projectLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
|
|
2525
|
+
for (const directory of packageLoaded) addDirectoryWatchPaths(watchPaths, directory.dir, directory.inspection.files, inspectedAgentDefinitionDirectories(directory.inspection, directory.dir));
|
|
2526
|
+
|
|
2527
|
+
const userDir = process.env.PI_CODING_AGENT_DIR ? userDirOld : fs.existsSync(userDirNew) ? userDirNew : userDirOld;
|
|
2528
|
+
return {
|
|
2529
|
+
cwd: effectiveCwd,
|
|
2530
|
+
...(preferredModelProvider !== undefined ? { preferredModelProvider } : {}),
|
|
2531
|
+
userDir,
|
|
2532
|
+
userDirOld,
|
|
2533
|
+
userDirNew,
|
|
2534
|
+
userChainDir,
|
|
2535
|
+
projectAgentDirs,
|
|
2536
|
+
projectCandidateDirs,
|
|
2537
|
+
projectAgentsDir,
|
|
2538
|
+
projectChainDirs,
|
|
2539
|
+
projectChainDir,
|
|
2190
2540
|
userSettingsPath,
|
|
2191
2541
|
projectSettingsPath,
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2542
|
+
packageSubagentPaths,
|
|
2543
|
+
builtinLoaded,
|
|
2544
|
+
userLoaded,
|
|
2545
|
+
projectLoaded,
|
|
2546
|
+
projectInspections,
|
|
2547
|
+
packageLoaded,
|
|
2548
|
+
watchPaths: [...watchPaths],
|
|
2549
|
+
};
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
function ensureDiscoveryChains(sources: AgentDiscoverySources): void {
|
|
2553
|
+
if (sources.userChains) return;
|
|
2554
|
+
sources.packageChainLoaded = sources.packageSubagentPaths.chains.map((entry) => ({ entry, loaded: loadChainsFromDir(entry.dir, "package") }));
|
|
2555
|
+
sources.userChains = loadChainsFromDir(sources.userChainDir, "user");
|
|
2556
|
+
sources.projectChainLoaded = sources.projectChainDirs.map((dir) => ({ dir, loaded: loadChainsFromDir(dir, "project") }));
|
|
2557
|
+
const watchPaths = new Set(sources.watchPaths);
|
|
2558
|
+
addDirectoryWatchPaths(watchPaths, sources.userChainDir, sources.userChains.files, sources.userChains.directories);
|
|
2559
|
+
for (const chain of sources.projectChainLoaded) addDirectoryWatchPaths(watchPaths, chain.dir, chain.loaded.files, chain.loaded.directories);
|
|
2560
|
+
for (const chain of sources.packageChainLoaded) addDirectoryWatchPaths(watchPaths, chain.entry.dir, chain.loaded.files, chain.loaded.directories);
|
|
2561
|
+
sources.watchPaths = [...watchPaths];
|
|
2562
|
+
}
|
|
2563
|
+
|
|
2564
|
+
function getAgentDiscoverySources(cwd: string, preferredModelProvider?: string, includeChains = false): AgentDiscoverySources {
|
|
2565
|
+
const key = discoveryCacheKey(cwd, preferredModelProvider);
|
|
2566
|
+
const cached = agentDiscoveryCache.get(key);
|
|
2567
|
+
if (cached && cached.fingerprint === discoveryFingerprint(cached.sources.watchPaths)) {
|
|
2568
|
+
if (includeChains) {
|
|
2569
|
+
ensureDiscoveryChains(cached.sources);
|
|
2570
|
+
cached.fingerprint = discoveryFingerprint(cached.sources.watchPaths);
|
|
2200
2571
|
}
|
|
2572
|
+
return cached.sources;
|
|
2201
2573
|
}
|
|
2202
|
-
const
|
|
2203
|
-
|
|
2574
|
+
const sources = buildAgentDiscoverySources(cwd, preferredModelProvider);
|
|
2575
|
+
const entry = { sources, fingerprint: discoveryFingerprint(sources.watchPaths) };
|
|
2576
|
+
agentDiscoveryCache.set(key, entry);
|
|
2577
|
+
if (includeChains) {
|
|
2578
|
+
ensureDiscoveryChains(sources);
|
|
2579
|
+
entry.fingerprint = discoveryFingerprint(sources.watchPaths);
|
|
2580
|
+
}
|
|
2581
|
+
return sources;
|
|
2582
|
+
}
|
|
2583
|
+
|
|
2584
|
+
/** Clear process-local discovery snapshots, primarily for hosts that reload settings in place. */
|
|
2585
|
+
export function clearAgentDiscoveryCache(): void {
|
|
2586
|
+
agentDiscoveryCache.clear();
|
|
2587
|
+
}
|
|
2588
|
+
|
|
2589
|
+
function ensureSettingsForScope(sources: AgentDiscoverySources, scope: AgentScope, preferredModelProvider?: string): void {
|
|
2590
|
+
if (scope !== "project" && sources.userSettings === undefined) {
|
|
2591
|
+
if (sources.packageSubagentPaths.settingsErrors.user) throw sources.packageSubagentPaths.settingsErrors.user;
|
|
2592
|
+
sources.userSettings = selectProviderOverrides(readSubagentSettings(sources.userSettingsPath), preferredModelProvider);
|
|
2593
|
+
}
|
|
2594
|
+
if (scope !== "user" && sources.projectSettings === undefined) {
|
|
2595
|
+
if (sources.packageSubagentPaths.settingsErrors.project) throw sources.packageSubagentPaths.settingsErrors.project;
|
|
2596
|
+
sources.projectSettings = selectProviderOverrides(readSubagentSettings(sources.projectSettingsPath), preferredModelProvider);
|
|
2597
|
+
}
|
|
2598
|
+
}
|
|
2599
|
+
|
|
2600
|
+
function settingsForScope(sources: AgentDiscoverySources, scope: AgentScope): { user: SubagentSettings; project: SubagentSettings } {
|
|
2601
|
+
// Parse only settings that participate in this projection. The source cache
|
|
2602
|
+
// still retains both source trees, while malformed out-of-scope settings do
|
|
2603
|
+
// not make an otherwise valid scoped projection fail.
|
|
2604
|
+
ensureSettingsForScope(sources, scope, sources.preferredModelProvider);
|
|
2605
|
+
return {
|
|
2606
|
+
user: scope === "project" ? EMPTY_SUBAGENT_SETTINGS : sources.userSettings ?? EMPTY_SUBAGENT_SETTINGS,
|
|
2607
|
+
project: scope === "user" ? EMPTY_SUBAGENT_SETTINGS : sources.projectSettings ?? EMPTY_SUBAGENT_SETTINGS,
|
|
2608
|
+
};
|
|
2609
|
+
}
|
|
2610
|
+
|
|
2611
|
+
function configuredAgentsForScope(sources: AgentDiscoverySources, scope: AgentScope, settingsScope = scope): {
|
|
2612
|
+
builtin: AgentConfig[];
|
|
2613
|
+
package: AgentConfig[];
|
|
2614
|
+
user: AgentConfig[];
|
|
2615
|
+
project: AgentConfig[];
|
|
2616
|
+
userSettings: SubagentSettings;
|
|
2617
|
+
projectSettings: SubagentSettings;
|
|
2618
|
+
maxThinking?: ThinkingLevel;
|
|
2619
|
+
modelScope?: ModelScopeConfig;
|
|
2620
|
+
} {
|
|
2621
|
+
const { user: userSettings, project: projectSettings } = settingsForScope(sources, settingsScope);
|
|
2622
|
+
const defaultProvider = resolveSubagentDefaultProvider(userSettings, projectSettings, sources.projectSettingsPath);
|
|
2623
|
+
const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath, defaultProvider);
|
|
2624
|
+
const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, sources.projectSettingsPath);
|
|
2625
|
+
const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, sources.projectSettingsPath);
|
|
2626
|
+
const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, sources.projectSettingsPath);
|
|
2627
|
+
const applyDefaults = (agents: AgentConfig[]): AgentConfig[] => applySubagentDefaults(agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions);
|
|
2628
|
+
const builtin = applyBuiltinOverrides(applyDefaults(sources.builtinLoaded.agents), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
|
|
2629
|
+
const user = applyCustomAgentOverrides(
|
|
2630
|
+
applyDefaults(scope === "project" ? [] : sources.userLoaded.flatMap((loaded) => loaded.loaded.agents)),
|
|
2204
2631
|
userSettings,
|
|
2205
2632
|
projectSettings,
|
|
2206
|
-
userSettingsPath,
|
|
2207
|
-
projectSettingsPath,
|
|
2633
|
+
sources.userSettingsPath,
|
|
2634
|
+
sources.projectSettingsPath,
|
|
2208
2635
|
);
|
|
2209
2636
|
const projectMap = new Map<string, AgentConfig>();
|
|
2210
|
-
const
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
}
|
|
2637
|
+
if (scope !== "user") for (const loaded of sources.projectLoaded) for (const agent of loaded.loaded.agents) projectMap.set(agent.name, agent);
|
|
2638
|
+
const project = applyCustomAgentOverrides(applyDefaults(Array.from(projectMap.values())), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
|
|
2639
|
+
const packageMap = new Map<string, AgentConfig>();
|
|
2640
|
+
for (const loaded of sources.packageLoaded) {
|
|
2641
|
+
if (!loaded.packageEntry || !packageEntryIncluded(scope, loaded.packageEntry.scope)) continue;
|
|
2642
|
+
for (const agent of loaded.loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
|
|
2217
2643
|
}
|
|
2218
|
-
const
|
|
2219
|
-
|
|
2644
|
+
const packageAgents = applyCustomAgentOverrides(applyDefaults(Array.from(packageMap.values())), userSettings, projectSettings, sources.userSettingsPath, sources.projectSettingsPath);
|
|
2645
|
+
return {
|
|
2646
|
+
builtin,
|
|
2647
|
+
package: packageAgents,
|
|
2648
|
+
user,
|
|
2649
|
+
project,
|
|
2220
2650
|
userSettings,
|
|
2221
2651
|
projectSettings,
|
|
2222
|
-
|
|
2223
|
-
|
|
2652
|
+
maxThinking,
|
|
2653
|
+
modelScope: projectSettings.modelScope ?? userSettings.modelScope,
|
|
2654
|
+
};
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
function discoveryDirectories(sources: AgentDiscoverySources, scope: AgentScope): AgentDefinitionDirectoryReport[] {
|
|
2658
|
+
const directories: AgentDefinitionDirectoryReport[] = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
|
|
2659
|
+
if (scope !== "project") for (const directory of sources.userLoaded) directories.push(reportAgentDefinitionDirectory("user", directory.dir, directory.inspection));
|
|
2660
|
+
if (scope !== "user") {
|
|
2661
|
+
const reported = new Set<string>();
|
|
2662
|
+
for (const dir of sources.projectCandidateDirs) {
|
|
2663
|
+
reported.add(path.resolve(dir));
|
|
2664
|
+
directories.push(reportAgentDefinitionDirectory("project", dir, sources.projectInspections.get(dir)!));
|
|
2665
|
+
}
|
|
2666
|
+
for (const directory of sources.projectLoaded) {
|
|
2667
|
+
if (!reported.has(path.resolve(directory.dir))) directories.push(reportAgentDefinitionDirectory("project", directory.dir, directory.inspection));
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
for (const directory of sources.packageLoaded) {
|
|
2671
|
+
if (directory.packageEntry && packageEntryIncluded(scope, directory.packageEntry.scope)) directories.push(reportAgentDefinitionDirectory("package", directory.dir, directory.inspection));
|
|
2672
|
+
}
|
|
2673
|
+
return directories;
|
|
2674
|
+
}
|
|
2675
|
+
|
|
2676
|
+
function discoveryDiagnostics(sources: AgentDiscoverySources, scope: AgentScope): AgentDiscoveryDiagnostic[] {
|
|
2677
|
+
return [
|
|
2678
|
+
...sources.builtinLoaded.diagnostics,
|
|
2679
|
+
...(scope === "project" ? [] : sources.userLoaded.flatMap((loaded) => loaded.loaded.diagnostics)),
|
|
2680
|
+
...(scope === "user" ? [] : sources.projectLoaded.flatMap((loaded) => loaded.loaded.diagnostics)),
|
|
2681
|
+
...sources.packageLoaded
|
|
2682
|
+
.filter((loaded) => loaded.packageEntry && packageEntryIncluded(scope, loaded.packageEntry.scope))
|
|
2683
|
+
.flatMap((loaded) => loaded.loaded.diagnostics),
|
|
2684
|
+
];
|
|
2685
|
+
}
|
|
2686
|
+
|
|
2687
|
+
function buildEffectiveDiscovery(sources: AgentDiscoverySources, scope: AgentScope): AgentDiscoveryResult {
|
|
2688
|
+
const configured = configuredAgentsForScope(sources, scope);
|
|
2689
|
+
const { user: effectiveUserSettings, project: effectiveProjectSettings } = settingsForScope(sources, scope);
|
|
2690
|
+
const injectAgents = effectiveProjectSettings.injectAgents !== undefined
|
|
2691
|
+
? effectiveProjectSettings.injectAgents
|
|
2692
|
+
: effectiveUserSettings.injectAgents;
|
|
2693
|
+
const agents = applySubagentMaxThinking(
|
|
2694
|
+
mergeAgentsForScope(scope, configured.user, configured.project, configured.builtin, configured.package).filter((agent) => agent.disabled !== true),
|
|
2695
|
+
configured.maxThinking,
|
|
2224
2696
|
);
|
|
2697
|
+
return {
|
|
2698
|
+
agents,
|
|
2699
|
+
agentDiagnostics: discoveryDiagnostics(sources, scope),
|
|
2700
|
+
projectAgentsDir: sources.projectAgentsDir,
|
|
2701
|
+
cwd: sources.cwd,
|
|
2702
|
+
scope,
|
|
2703
|
+
directories: discoveryDirectories(sources, scope),
|
|
2704
|
+
...(configured.modelScope !== undefined ? { modelScope: configured.modelScope } : {}),
|
|
2705
|
+
...(injectAgents?.length ? { injectAgents } : {}),
|
|
2706
|
+
...(configured.maxThinking !== undefined ? { maxThinking: configured.maxThinking } : {}),
|
|
2707
|
+
};
|
|
2708
|
+
}
|
|
2225
2709
|
|
|
2226
|
-
|
|
2227
|
-
|
|
2710
|
+
function buildAllDiscovery(sources: AgentDiscoverySources, includeChains: boolean, settingsScope: AgentScope): AgentDiscoveryAllResult {
|
|
2711
|
+
if (includeChains) ensureDiscoveryChains(sources);
|
|
2712
|
+
const configured = configuredAgentsForScope(sources, "both", settingsScope);
|
|
2713
|
+
const { user: allUserSettings, project: allProjectSettings } = settingsForScope(sources, settingsScope);
|
|
2714
|
+
const injectAgents = allProjectSettings.injectAgents !== undefined
|
|
2715
|
+
? allProjectSettings.injectAgents
|
|
2716
|
+
: allUserSettings.injectAgents;
|
|
2228
2717
|
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
|
-
}
|
|
2718
|
+
const packageChainDiagnostics: ChainDiscoveryDiagnostic[] = [];
|
|
2719
|
+
for (const chain of sources.packageChainLoaded ?? []) {
|
|
2720
|
+
packageChainDiagnostics.push(...chain.loaded.diagnostics);
|
|
2721
|
+
for (const definition of chain.loaded.chains) if (!packageChainMap.has(definition.name)) packageChainMap.set(definition.name, definition);
|
|
2235
2722
|
}
|
|
2723
|
+
const projectChainMap = new Map<string, ChainConfig>();
|
|
2236
2724
|
const projectChainDiagnostics: ChainDiscoveryDiagnostic[] = [];
|
|
2237
|
-
for (const
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
for (const chain of loaded.chains) {
|
|
2241
|
-
chainMap.set(chain.name, chain);
|
|
2242
|
-
}
|
|
2725
|
+
for (const chain of sources.projectChainLoaded ?? []) {
|
|
2726
|
+
projectChainDiagnostics.push(...chain.loaded.diagnostics);
|
|
2727
|
+
for (const definition of chain.loaded.chains) projectChainMap.set(definition.name, definition);
|
|
2243
2728
|
}
|
|
2244
|
-
const userChains = loadChainsFromDir(userChainDir, "user");
|
|
2245
2729
|
const chains = [
|
|
2246
2730
|
...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,
|
|
2731
|
+
...(sources.userChains?.chains ?? []),
|
|
2732
|
+
...Array.from(projectChainMap.values()),
|
|
2260
2733
|
];
|
|
2261
|
-
|
|
2262
|
-
const userDir = process.env.PI_CODING_AGENT_DIR ? userDirOld : fs.existsSync(userDirNew) ? userDirNew : userDirOld;
|
|
2263
|
-
|
|
2264
2734
|
return {
|
|
2265
|
-
builtin: applySubagentMaxThinking(builtin, maxThinking),
|
|
2266
|
-
package: applySubagentMaxThinking(
|
|
2267
|
-
user: applySubagentMaxThinking(user, maxThinking),
|
|
2268
|
-
project: applySubagentMaxThinking(project, maxThinking),
|
|
2269
|
-
agentDiagnostics
|
|
2735
|
+
builtin: applySubagentMaxThinking(configured.builtin, configured.maxThinking),
|
|
2736
|
+
package: applySubagentMaxThinking(configured.package, configured.maxThinking),
|
|
2737
|
+
user: applySubagentMaxThinking(configured.user, configured.maxThinking),
|
|
2738
|
+
project: applySubagentMaxThinking(configured.project, configured.maxThinking),
|
|
2739
|
+
agentDiagnostics: [
|
|
2740
|
+
...sources.builtinLoaded.diagnostics,
|
|
2741
|
+
...sources.userLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
|
|
2742
|
+
...sources.packageLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
|
|
2743
|
+
...sources.projectLoaded.flatMap((loaded) => loaded.loaded.diagnostics),
|
|
2744
|
+
],
|
|
2270
2745
|
chains,
|
|
2271
|
-
chainDiagnostics,
|
|
2272
|
-
userDir,
|
|
2273
|
-
projectDir,
|
|
2274
|
-
userChainDir,
|
|
2275
|
-
projectChainDir,
|
|
2276
|
-
userSettingsPath,
|
|
2277
|
-
projectSettingsPath,
|
|
2278
|
-
|
|
2279
|
-
...(maxThinking !== undefined ? { maxThinking } : {}),
|
|
2746
|
+
chainDiagnostics: [...packageChainDiagnostics, ...(sources.userChains?.diagnostics ?? []), ...projectChainDiagnostics],
|
|
2747
|
+
userDir: sources.userDir,
|
|
2748
|
+
projectDir: sources.projectAgentsDir,
|
|
2749
|
+
userChainDir: sources.userChainDir,
|
|
2750
|
+
projectChainDir: sources.projectChainDir,
|
|
2751
|
+
userSettingsPath: sources.userSettingsPath,
|
|
2752
|
+
projectSettingsPath: sources.projectSettingsPath,
|
|
2753
|
+
...(injectAgents?.length ? { injectAgents } : {}),
|
|
2754
|
+
...(configured.maxThinking !== undefined ? { maxThinking: configured.maxThinking } : {}),
|
|
2280
2755
|
};
|
|
2281
2756
|
}
|
|
2757
|
+
|
|
2758
|
+
export function discoverAgentSnapshot(
|
|
2759
|
+
cwd: string,
|
|
2760
|
+
scope: AgentScope,
|
|
2761
|
+
preferredModelProvider?: string,
|
|
2762
|
+
options: { includeChains?: boolean } = {},
|
|
2763
|
+
): AgentDiscoverySnapshot {
|
|
2764
|
+
const includeChains = options.includeChains !== false;
|
|
2765
|
+
const sources = getAgentDiscoverySources(cwd, preferredModelProvider, includeChains);
|
|
2766
|
+
return { effective: buildEffectiveDiscovery(sources, scope), all: buildAllDiscovery(sources, includeChains, scope) };
|
|
2767
|
+
}
|
|
2768
|
+
|
|
2769
|
+
function discoverAgentsUncached(cwd: string, scope: AgentScope, preferredModelProvider?: string): AgentDiscoveryResult {
|
|
2770
|
+
const effectiveCwd = path.resolve(cwd);
|
|
2771
|
+
const userDirOld = path.join(getAgentDir(), "agents");
|
|
2772
|
+
const userDirNew = path.join(os.homedir(), ".agents");
|
|
2773
|
+
const { readDirs: projectAgentDirs, candidateDirs: projectCandidateDirs, preferredDir: projectAgentsDir } = resolveNearestProjectAgentDirs(effectiveCwd);
|
|
2774
|
+
const userSettingsPath = getUserAgentSettingsPath();
|
|
2775
|
+
const projectSettingsPath = getProjectAgentSettingsPath(effectiveCwd);
|
|
2776
|
+
const userSettings = selectProviderOverrides(scope === "project" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(userSettingsPath), preferredModelProvider);
|
|
2777
|
+
const projectSettings = selectProviderOverrides(scope === "user" ? EMPTY_SUBAGENT_SETTINGS : readSubagentSettings(projectSettingsPath), preferredModelProvider);
|
|
2778
|
+
const defaultProvider = resolveSubagentDefaultProvider(userSettings, projectSettings, projectSettingsPath);
|
|
2779
|
+
const defaultModel = resolveSubagentDefaultModel(userSettings, projectSettings, userSettingsPath, projectSettingsPath, defaultProvider);
|
|
2780
|
+
const defaultThinking = resolveSubagentDefaultThinking(userSettings, projectSettings, projectSettingsPath);
|
|
2781
|
+
const maxThinking = resolveSubagentMaxThinking(userSettings, projectSettings, projectSettingsPath);
|
|
2782
|
+
const defaultExtensions = resolveSubagentDefaultExtensions(userSettings, projectSettings, projectSettingsPath);
|
|
2783
|
+
const modelScope = projectSettings.modelScope ?? userSettings.modelScope;
|
|
2784
|
+
const injectAgents = projectSettings.injectAgents !== undefined
|
|
2785
|
+
? projectSettings.injectAgents
|
|
2786
|
+
: userSettings.injectAgents;
|
|
2787
|
+
const packageSubagentPaths = collectPackageSubagentPaths(effectiveCwd, { includeUser: scope !== "project", includeProject: scope !== "user" });
|
|
2788
|
+
const directories: AgentDefinitionDirectoryReport[] = [reportAgentDefinitionDirectory("builtin", BUILTIN_AGENTS_DIR, BUILTIN_AGENT_DEFINITION_INSPECTION)];
|
|
2789
|
+
const builtinLoaded = loadAgentsFromDefinitionFiles(BUILTIN_AGENT_DEFINITION_FILES, "builtin");
|
|
2790
|
+
const builtinAgents = applyBuiltinOverrides(applySubagentDefaults(builtinLoaded.agents, defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
|
|
2791
|
+
const userScanDirs = settingsAgentScanDirs(userSettings.agentScanDirs ?? []);
|
|
2792
|
+
const projectScanDirs = settingsAgentScanDirs(projectSettings.agentScanDirs ?? []);
|
|
2793
|
+
const userLoaded = scope === "project" ? [] : [...extraUserAgentDirs(), ...userScanDirs.dirs, userDirOld, userDirNew].map((dir, discoveryPriority) => {
|
|
2794
|
+
const inspection = inspectAgentDefinitionDirectory(dir);
|
|
2795
|
+
directories.push(reportAgentDefinitionDirectory("user", dir, inspection));
|
|
2796
|
+
return loadAgentsFromDir(dir, "user", discoveryPriority, undefined, inspection);
|
|
2797
|
+
});
|
|
2798
|
+
const userAgents = applyCustomAgentOverrides(applySubagentDefaults(userLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
|
|
2799
|
+
const projectInspections = scope === "user" ? new Map<string, AgentDefinitionInspection>() : new Map(projectCandidateDirs.map((dir) => [dir, inspectAgentDefinitionDirectory(dir)]));
|
|
2800
|
+
if (scope !== "user") for (const dir of projectCandidateDirs) directories.push(reportAgentDefinitionDirectory("project", dir, projectInspections.get(dir)!));
|
|
2801
|
+
const projectLoaded = scope === "user" ? [] : [...projectScanDirs.dirs, ...projectAgentDirs].map((dir, discoveryPriority) => {
|
|
2802
|
+
const inspection = projectInspections.get(dir) ?? inspectAgentDefinitionDirectory(dir);
|
|
2803
|
+
if (!projectInspections.has(dir)) directories.push(reportAgentDefinitionDirectory("project", dir, inspection));
|
|
2804
|
+
return loadAgentsFromDir(dir, "project", dir === projectAgentsDir ? 1 : discoveryPriority, undefined, inspection);
|
|
2805
|
+
});
|
|
2806
|
+
const projectAgents = applyCustomAgentOverrides(applySubagentDefaults(projectLoaded.flatMap((loaded) => loaded.agents), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
|
|
2807
|
+
const packageLoaded = packageSubagentPaths.agents.map((entry, index) => {
|
|
2808
|
+
const inspection = inspectAgentDefinitionDirectory(entry.dir);
|
|
2809
|
+
directories.push(reportAgentDefinitionDirectory("package", entry.dir, inspection));
|
|
2810
|
+
return loadAgentsFromDir(entry.dir, "package", packageSubagentPaths.agents.length - index, entry, inspection);
|
|
2811
|
+
});
|
|
2812
|
+
const packageMap = new Map<string, AgentConfig>();
|
|
2813
|
+
for (const loaded of packageLoaded) for (const agent of loaded.agents) if (!packageMap.has(agent.name)) packageMap.set(agent.name, agent);
|
|
2814
|
+
const packageAgents = applyCustomAgentOverrides(applySubagentDefaults(Array.from(packageMap.values()), defaultModel, defaultProvider, defaultThinking, defaultExtensions), userSettings, projectSettings, userSettingsPath, projectSettingsPath);
|
|
2815
|
+
const agents = applySubagentMaxThinking(mergeAgentsForScope(scope, userAgents, projectAgents, builtinAgents, packageAgents).filter((agent) => agent.disabled !== true), maxThinking);
|
|
2816
|
+
const agentDiagnostics = [...builtinLoaded.diagnostics, ...userLoaded.flatMap((loaded) => loaded.diagnostics), ...projectLoaded.flatMap((loaded) => loaded.diagnostics), ...packageLoaded.flatMap((loaded) => loaded.diagnostics)];
|
|
2817
|
+
return { agents, agentDiagnostics, projectAgentsDir, cwd: effectiveCwd, scope, directories, ...(modelScope !== undefined ? { modelScope } : {}), ...(injectAgents?.length ? { injectAgents } : {}), ...(maxThinking !== undefined ? { maxThinking } : {}) };
|
|
2818
|
+
}
|
|
2819
|
+
|
|
2820
|
+
export function discoverAgents(cwd: string, scope: AgentScope, preferredModelProvider?: string): AgentDiscoveryResult {
|
|
2821
|
+
if (scope !== "both") return discoverAgentsUncached(cwd, scope, preferredModelProvider);
|
|
2822
|
+
const sources = getAgentDiscoverySources(cwd, preferredModelProvider);
|
|
2823
|
+
return buildEffectiveDiscovery(sources, scope);
|
|
2824
|
+
}
|
|
2825
|
+
|
|
2826
|
+
export function discoverAgentsAll(cwd: string, preferredModelProvider?: string): AgentDiscoveryAllResult {
|
|
2827
|
+
return discoverAgentSnapshot(cwd, "both", preferredModelProvider).all;
|
|
2828
|
+
}
|