返回源码地图

packages/coding-agent/src/core/resource-loader.ts

v1.3.0 · 71023aec1546 · 08/12:bootstrap project trust、资源发现与reload;未审所有包解析分支

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2import { basename, dirname, join, resolve, sep } from "node:path";
3import { detectCapabilities, getTerminalColorMode, type TerminalColorMode } from "@earendil-works/pi-tui";
4import chalk from "chalk";
5import { CONFIG_DIR_NAME } from "../config.ts";
6import { loadThemeFromPath, type Theme } from "../modes/interactive/theme/theme.ts";
7import type { ResourceDiagnostic } from "./diagnostics.ts";
8
9export type { ResourceCollision, ResourceDiagnostic } from "./diagnostics.ts";
10
11import { canonicalizePath, isLocalPath, resolvePath } from "../utils/paths.ts";
12import { stripBom } from "../utils/text.ts";
13import { createEventBus, type EventBus } from "./event-bus.ts";
14import {
15 clearExtensionCache,
16 createExtensionRuntime,
17 loadExtensionFromFactory,
18 loadExtensionsCached,
19} from "./extensions/loader.ts";
20import type {
21 Extension,
22 ExtensionFactory,
23 ExtensionRuntime,
24 InlineExtension,
25 LoadExtensionsResult,
26} from "./extensions/types.ts";
27import { findGitPaths } from "./footer-data-provider.ts";
28import { DefaultPackageManager, type PathMetadata, type ResolvedResource } from "./package-manager.ts";
29import type { PromptTemplate } from "./prompt-templates.ts";
30import { loadPromptTemplates } from "./prompt-templates.ts";
31import { SettingsManager } from "./settings-manager.ts";
32import type { Skill } from "./skills.ts";
33import { loadSkills } from "./skills.ts";
34import {
35 BUILTIN_PATH_PREFIX,
36 createSourceInfo,
37 getSyntheticPathSource,
38 isSyntheticPath,
39 type SourceInfo,
40} from "./source-info.ts";
41import { resetTimings } from "./timings.ts";
42
43export interface ResourceExtensionPaths {
44 skillPaths?: Array<{ path: string; metadata: PathMetadata }>;
45 promptPaths?: Array<{ path: string; metadata: PathMetadata }>;
46 themePaths?: Array<{ path: string; metadata: PathMetadata }>;
47}
48
49export interface ResourceLoaderReloadOptions {
50 resolveProjectTrust?: (input: { extensionsResult: LoadExtensionsResult }) => Promise<boolean>;
51}
52
53const HOST_PROVIDED_EXTENSION_PACKAGES = new Set([
54 "@earendil-works/pi-agent-core",
55 "@earendil-works/pi-ai",
56 "@earendil-works/pi-coding-agent",
57 "@earendil-works/pi-tui",
58 "@mariozechner/pi-agent-core",
59 "@mariozechner/pi-ai",
60 "@mariozechner/pi-coding-agent",
61 "@mariozechner/pi-tui",
62 "@sinclair/typebox",
63 "typebox",
64]);
65
66function collectExtensionPackageWarnings(
67 extensionPaths: string[],
68 metadataByPath: Map<string, PathMetadata>,
69): Array<{ path: string; warning: string }> {
70 const warnings: Array<{ path: string; warning: string }> = [];
71 const packageRoots = new Set(
72 extensionPaths
73 .map((extensionPath) => metadataByPath.get(extensionPath)?.packageRoot)
74 .filter((packageRoot): packageRoot is string => packageRoot !== undefined),
75 );
76 for (const packageRoot of packageRoots) {
77 const packageJsonPath = join(packageRoot, "package.json");
78 if (!existsSync(packageJsonPath)) continue;
79 const manifest = JSON.parse(stripBom(readFileSync(packageJsonPath, "utf-8"))) as { dependencies?: unknown };
80 if (
81 typeof manifest.dependencies !== "object" ||
82 manifest.dependencies === null ||
83 Array.isArray(manifest.dependencies)
84 ) {
85 continue;
86 }
87 const hostDependencies = Object.keys(manifest.dependencies)
88 .filter((name) => HOST_PROVIDED_EXTENSION_PACKAGES.has(name))
89 .sort();
90 if (hostDependencies.length === 0) continue;
91 warnings.push({
92 path: packageJsonPath,
93 warning: `Host-provided extension packages must be declared in peerDependencies with a "*" range, not dependencies: ${hostDependencies.join(", ")}. Installed copies can bypass the extension loader and create duplicate runtime modules.`,
94 });
95 }
96 return warnings;
97}
98
99function mergeExtensionWarnings(
100 result: LoadExtensionsResult,
101 warnings: Array<{ path: string; warning: string }>,
102): void {
103 result.warnings = [
104 ...new Map([...(result.warnings ?? []), ...warnings].map((warning) => [warning.path, warning])).values(),
105 ];
106}
107
108type BuiltinExtension = Exclude<InlineExtension, ExtensionFactory>;
109
110/** Built-in extensions supply the code of `builtin:<name>` extension paths (see `InlineExtension`). */
111export function isBuiltinExtension(input: InlineExtension): input is BuiltinExtension {
112 return typeof input !== "function" && input.builtin === true;
113}
114
115/**
116 * Leave out replaceable extensions (see `InlineExtension`) that share a tool, command, or flag name
117 * with another extension. For example, a third-party MCP extension that registers `/mcp` replaces
118 * the built-in MCP extension instead of both connecting the same servers.
119 */
120function omitReplacedExtensions(
121 extensions: Extension[],
122 warnings?: Array<{ path: string; warning: string }>,
123): Extension[] {
124 const names = (extension: Extension) => [
125 ...[...extension.tools.keys()].map((name) => `tool:${name}`),
126 ...[...extension.commands.keys()].map((name) => `command:${name}`),
127 ...[...extension.flags.keys()].map((name) => `flag:${name}`),
128 ];
129 const taken = new Map(
130 extensions
131 .filter((extension) => !extension.replaceable)
132 .flatMap((extension) => names(extension).map((name) => [name, extension] as const)),
133 );
134 return extensions.filter((extension) => {
135 if (!extension.replaceable) return true;
136 const replacement = names(extension)
137 .map((name) => ({ name, extension: taken.get(name) }))
138 .find((value): value is { name: string; extension: Extension } => value.extension !== undefined);
139 if (!replacement) return true;
140 if (extension.path.startsWith(BUILTIN_PATH_PREFIX)) {
141 const builtinName = extension.path.slice(BUILTIN_PATH_PREFIX.length);
142 const [kind, rawName] = replacement.name.split(":", 2);
143 const registeredName = kind === "command" ? `/${rawName}` : kind === "flag" ? `--${rawName}` : rawName;
144 warnings?.push({
145 path: extension.path,
146 warning: `Extension ${replacement.extension.path} registers ${kind} \`${registeredName}\`, so built-in extension \`${builtinName}\` was not loaded. To use \`${builtinName}\`, run \`pi config\` and make sure it is enabled under Built-in extensions, then disable or remove the existing extension. We recommend only having one or the other loaded at a time.`,
147 });
148 }
149 return false;
150 });
151}
152
153export interface ResourceLoader {
154 getExtensions(): LoadExtensionsResult;
155 getSkills(): { skills: Skill[]; diagnostics: ResourceDiagnostic[] };
156 getPrompts(): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] };
157 getThemes(): { themes: Theme[]; diagnostics: ResourceDiagnostic[] };
158 getAgentsFiles(): { agentsFiles: Array<{ path: string; content: string }> };
159 getSystemPrompt(): string | undefined;
160 getSystemPromptSource(): { path: string } | undefined;
161 getAppendSystemPrompt(): string[];
162 getAppendSystemPromptSources(): Array<{ path: string }>;
163 extendResources(paths: ResourceExtensionPaths): void;
164 reload(options?: ResourceLoaderReloadOptions): Promise<void>;
165}
166
167function resolvePromptInput(input: string | undefined, description: string): string | undefined {
168 if (!input) {
169 return undefined;
170 }
171
172 if (existsSync(input)) {
173 try {
174 return stripBom(readFileSync(input, "utf-8"));
175 } catch (error) {
176 console.error(chalk.yellow(`Warning: Could not read ${description} file ${input}: ${error}`));
177 return input;
178 }
179 }
180
181 return input;
182}
183
184function loadContextFileFromDir(dir: string): { path: string; content: string } | null {
185 const candidates = ["AGENTS.override.md", "AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"];
186 for (const filename of candidates) {
187 const filePath = join(dir, filename);
188 if (existsSync(filePath)) {
189 try {
190 if (!statSync(filePath).isFile()) {
191 continue;
192 }
193 return {
194 path: filePath,
195 content: stripBom(readFileSync(filePath, "utf-8")),
196 };
197 } catch (error) {
198 console.error(chalk.yellow(`Warning: Could not read ${filePath}: ${error}`));
199 }
200 }
201 }
202 return null;
203}
204
205/**
206 * The main repo's context file that a nested linked worktree's own copy shadows: both
207 * occupy the same logical repository scope, so loading both applies that context twice. Returns
208 * undefined when nothing is shadowed, leaving normal ancestor inheritance alone.
209 *
210 * Returned canonicalized (realpath), because `git worktree add` writes the `.git`
211 * file's `gitdir:` target in realpath form while cwd may still be symlinked
212 * (macOS `/tmp` -> `/private/tmp`).
213 */
214function findShadowedContextFile(cwd: string): string | undefined {
215 const gitPaths = findGitPaths(cwd);
216 if (!gitPaths) return undefined;
217 const commonGitDir = canonicalizePath(gitPaths.commonGitDir);
218 const worktreeRoot = canonicalizePath(gitPaths.repoDir);
219 const mainRepoRoot = dirname(commonGitDir);
220 // False for an ordinary repo, where the two are the same dir, and for a sibling
221 // worktree (`git worktree add ../feat`), whose main repo is not an ancestor.
222 if (!worktreeRoot.startsWith(`${mainRepoRoot}${sep}`)) return undefined;
223 // dirname of the common git dir is the main worktree root only when that dir is
224 // itself checked out from the same repo. In a bare layout (`proj/.bare` +
225 // `proj/main`) it is just the directory holding `.bare`, which tracks nothing; a
226 // submodule's gitdir has no `commondir`, so it lands under `.git/modules`.
227 if (canonicalizePath(join(mainRepoRoot, ".git")) !== commonGitDir) return undefined;
228 const worktreeContextFile = loadContextFileFromDir(worktreeRoot);
229 return worktreeContextFile ? join(mainRepoRoot, basename(worktreeContextFile.path)) : undefined;
230}
231
232export function loadProjectContextFiles(options: {
233 cwd: string;
234 agentDir: string;
235}): Array<{ path: string; content: string }> {
236 const resolvedCwd = resolvePath(options.cwd);
237 const resolvedAgentDir = resolvePath(options.agentDir);
238
239 const contextFiles: Array<{ path: string; content: string }> = [];
240 const seenPaths = new Set<string>();
241
242 const globalContext = loadContextFileFromDir(resolvedAgentDir);
243 if (globalContext) {
244 contextFiles.push(globalContext);
245 seenPaths.add(globalContext.path);
246 }
247
248 const ancestorContextFiles: Array<{ path: string; content: string }> = [];
249
250 const shadowedContextFile = findShadowedContextFile(resolvedCwd);
251 let currentDir = resolvedCwd;
252
253 while (true) {
254 const contextFile = loadContextFileFromDir(currentDir);
255 // Compare the directory's real path, not the file's: a worktree AGENTS.md that
256 // symlinks to the main repo's file resolves to the shadowed path itself.
257 const isShadowed =
258 shadowedContextFile !== undefined &&
259 contextFile !== null &&
260 join(canonicalizePath(currentDir), basename(contextFile.path)) === shadowedContextFile;
261 if (contextFile && !isShadowed && !seenPaths.has(contextFile.path)) {
262 ancestorContextFiles.unshift(contextFile);
263 seenPaths.add(contextFile.path);
264 }
265
266 const parentDir = dirname(currentDir);
267 if (parentDir === currentDir) break;
268 currentDir = parentDir;
269 }
270
271 contextFiles.push(...ancestorContextFiles);
272
273 return contextFiles;
274}
275
276export interface DefaultResourceLoaderOptions {
277 cwd: string;
278 agentDir: string;
279 settingsManager?: SettingsManager;
280 eventBus?: EventBus;
281 additionalExtensionPaths?: string[];
282 additionalSkillPaths?: string[];
283 additionalPromptTemplatePaths?: string[];
284 additionalThemePaths?: string[];
285 extensionFactories?: InlineExtension[];
286 noExtensions?: boolean;
287 /** Built-in extensions not to load, by name (such as `mcp`), even when settings or `-e` enable them. */
288 disabledBuiltinExtensions?: string[];
289 noSkills?: boolean;
290 noPromptTemplates?: boolean;
291 noThemes?: boolean;
292 noContextFiles?: boolean;
293 systemPrompt?: string;
294 appendSystemPrompt?: string[];
295 extensionsOverride?: (base: LoadExtensionsResult) => LoadExtensionsResult;
296 skillsOverride?: (base: { skills: Skill[]; diagnostics: ResourceDiagnostic[] }) => {
297 skills: Skill[];
298 diagnostics: ResourceDiagnostic[];
299 };
300 promptsOverride?: (base: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] }) => {
301 prompts: PromptTemplate[];
302 diagnostics: ResourceDiagnostic[];
303 };
304 themesOverride?: (base: { themes: Theme[]; diagnostics: ResourceDiagnostic[] }) => {
305 themes: Theme[];
306 diagnostics: ResourceDiagnostic[];
307 };
308 agentsFilesOverride?: (base: { agentsFiles: Array<{ path: string; content: string }> }) => {
309 agentsFiles: Array<{ path: string; content: string }>;
310 };
311 systemPromptOverride?: (base: string | undefined) => string | undefined;
312 appendSystemPromptOverride?: (base: string[]) => string[];
313}
314
315export class DefaultResourceLoader implements ResourceLoader {
316 private cwd: string;
317 private agentDir: string;
318 private settingsManager: SettingsManager;
319 private eventBus: EventBus;
320 private packageManager: DefaultPackageManager;
321 private additionalExtensionPaths: string[];
322 private additionalSkillPaths: string[];
323 private additionalPromptTemplatePaths: string[];
324 private additionalThemePaths: string[];
325 private extensionFactories: InlineExtension[];
326 private builtinExtensions: Map<string, BuiltinExtension>;
327 private noExtensions: boolean;
328 private disabledBuiltinExtensions: Set<string>;
329 private noSkills: boolean;
330 private noPromptTemplates: boolean;
331 private noThemes: boolean;
332 private noContextFiles: boolean;
333 private systemPromptSource?: string;
334 private appendSystemPromptSource?: string[];
335 private extensionsOverride?: (base: LoadExtensionsResult) => LoadExtensionsResult;
336 private skillsOverride?: (base: { skills: Skill[]; diagnostics: ResourceDiagnostic[] }) => {
337 skills: Skill[];
338 diagnostics: ResourceDiagnostic[];
339 };
340 private promptsOverride?: (base: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] }) => {
341 prompts: PromptTemplate[];
342 diagnostics: ResourceDiagnostic[];
343 };
344 private themesOverride?: (base: { themes: Theme[]; diagnostics: ResourceDiagnostic[] }) => {
345 themes: Theme[];
346 diagnostics: ResourceDiagnostic[];
347 };
348 private agentsFilesOverride?: (base: { agentsFiles: Array<{ path: string; content: string }> }) => {
349 agentsFiles: Array<{ path: string; content: string }>;
350 };
351 private systemPromptOverride?: (base: string | undefined) => string | undefined;
352 private appendSystemPromptOverride?: (base: string[]) => string[];
353
354 private extensionsResult: LoadExtensionsResult;
355 private skills: Skill[];
356 private skillDiagnostics: ResourceDiagnostic[];
357 private prompts: PromptTemplate[];
358 private promptDiagnostics: ResourceDiagnostic[];
359 private themes: Theme[];
360 private themeDiagnostics: ResourceDiagnostic[];
361 private agentsFiles: Array<{ path: string; content: string }>;
362 private systemPrompt?: string;
363 private systemPromptSourcePath?: string;
364 private appendSystemPrompt: string[];
365 private appendSystemPromptSourcePaths: string[];
366 private lastSkillPaths: string[];
367 private extensionSkillSourceInfos: Map<string, SourceInfo>;
368 private extensionPromptSourceInfos: Map<string, SourceInfo>;
369 private extensionThemeSourceInfos: Map<string, SourceInfo>;
370 private resourceMetadataByPath: Map<string, PathMetadata>;
371 private lastPromptPaths: string[];
372 private lastThemePaths: string[];
373 private loaded: boolean;
374
375 constructor(options: DefaultResourceLoaderOptions) {
376 this.cwd = resolvePath(options.cwd);
377 this.agentDir = resolvePath(options.agentDir);
378 this.settingsManager = options.settingsManager ?? SettingsManager.create(this.cwd, this.agentDir);
379 this.eventBus = options.eventBus ?? createEventBus();
380 const factories = options.extensionFactories ?? [];
381 this.extensionFactories = factories.filter((input) => !isBuiltinExtension(input));
382 this.builtinExtensions = new Map(factories.filter(isBuiltinExtension).map((input) => [input.name, input]));
383 this.packageManager = new DefaultPackageManager({
384 cwd: this.cwd,
385 agentDir: this.agentDir,
386 settingsManager: this.settingsManager,
387 builtinExtensions: [...this.builtinExtensions.keys()],
388 });
389 this.additionalExtensionPaths = options.additionalExtensionPaths ?? [];
390 this.additionalSkillPaths = options.additionalSkillPaths ?? [];
391 this.additionalPromptTemplatePaths = options.additionalPromptTemplatePaths ?? [];
392 this.additionalThemePaths = options.additionalThemePaths ?? [];
393 this.noExtensions = options.noExtensions ?? false;
394 this.disabledBuiltinExtensions = new Set(options.disabledBuiltinExtensions);
395 this.noSkills = options.noSkills ?? false;
396 this.noPromptTemplates = options.noPromptTemplates ?? false;
397 this.noThemes = options.noThemes ?? false;
398 this.noContextFiles = options.noContextFiles ?? false;
399 this.systemPromptSource = options.systemPrompt;
400 this.appendSystemPromptSource = options.appendSystemPrompt;
401 this.extensionsOverride = options.extensionsOverride;
402 this.skillsOverride = options.skillsOverride;
403 this.promptsOverride = options.promptsOverride;
404 this.themesOverride = options.themesOverride;
405 this.agentsFilesOverride = options.agentsFilesOverride;
406 this.systemPromptOverride = options.systemPromptOverride;
407 this.appendSystemPromptOverride = options.appendSystemPromptOverride;
408
409 this.extensionsResult = { extensions: [], errors: [], runtime: createExtensionRuntime() };
410 this.skills = [];
411 this.skillDiagnostics = [];
412 this.prompts = [];
413 this.promptDiagnostics = [];
414 this.themes = [];
415 this.themeDiagnostics = [];
416 this.agentsFiles = [];
417 this.appendSystemPrompt = [];
418 this.appendSystemPromptSourcePaths = [];
419 this.lastSkillPaths = [];
420 this.extensionSkillSourceInfos = new Map();
421 this.extensionPromptSourceInfos = new Map();
422 this.extensionThemeSourceInfos = new Map();
423 this.resourceMetadataByPath = new Map();
424 this.lastPromptPaths = [];
425 this.lastThemePaths = [];
426 this.loaded = false;
427 }
428
429 getExtensions(): LoadExtensionsResult {
430 return this.extensionsResult;
431 }
432
433 getSkills(): { skills: Skill[]; diagnostics: ResourceDiagnostic[] } {
434 return { skills: this.skills, diagnostics: this.skillDiagnostics };
435 }
436
437 getPrompts(): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] } {
438 return { prompts: this.prompts, diagnostics: this.promptDiagnostics };
439 }
440
441 getThemes(): { themes: Theme[]; diagnostics: ResourceDiagnostic[] } {
442 return { themes: this.themes, diagnostics: this.themeDiagnostics };
443 }
444
445 getAgentsFiles(): { agentsFiles: Array<{ path: string; content: string }> } {
446 return { agentsFiles: this.agentsFiles };
447 }
448
449 getSystemPrompt(): string | undefined {
450 return this.systemPrompt;
451 }
452
453 getSystemPromptSource(): { path: string } | undefined {
454 return this.systemPromptSourcePath ? { path: this.systemPromptSourcePath } : undefined;
455 }
456
457 getAppendSystemPrompt(): string[] {
458 return this.appendSystemPrompt;
459 }
460
461 getAppendSystemPromptSources(): Array<{ path: string }> {
462 return this.appendSystemPromptSourcePaths.map((path) => ({ path }));
463 }
464
465 extendResources(paths: ResourceExtensionPaths): void {
466 const skillPaths = this.normalizeExtensionPaths(paths.skillPaths ?? []);
467 const promptPaths = this.normalizeExtensionPaths(paths.promptPaths ?? []);
468 const themePaths = this.normalizeExtensionPaths(paths.themePaths ?? []);
469
470 for (const entry of skillPaths) {
471 this.extensionSkillSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));
472 }
473 for (const entry of promptPaths) {
474 this.extensionPromptSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));
475 }
476 for (const entry of themePaths) {
477 this.extensionThemeSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));
478 }
479
480 if (skillPaths.length > 0) {
481 this.lastSkillPaths = this.mergePaths(
482 this.lastSkillPaths,
483 skillPaths.map((entry) => entry.path),
484 );
485 this.updateSkillsFromPaths(this.lastSkillPaths, this.resourceMetadataByPath);
486 }
487
488 if (promptPaths.length > 0) {
489 this.lastPromptPaths = this.mergePaths(
490 this.lastPromptPaths,
491 promptPaths.map((entry) => entry.path),
492 );
493 this.updatePromptsFromPaths(this.lastPromptPaths, this.resourceMetadataByPath);
494 }
495
496 if (themePaths.length > 0) {
497 this.lastThemePaths = this.mergePaths(
498 this.lastThemePaths,
499 themePaths.map((entry) => entry.path),
500 );
501 this.updateThemesFromPaths(this.lastThemePaths, this.resourceMetadataByPath);
502 }
503 }
504
505 async loadProjectTrustExtensions(): Promise<LoadExtensionsResult> {
506 // Force untrusted project settings for the bootstrap pass. This keeps project-local
507 // extensions/packages out while still loading user/global and temporary CLI extensions.
508 this.settingsManager.setProjectTrusted(false);
509 await this.settingsManager.reload();
510 return this.loadCurrentExtensionSet({ includeInlineFactories: true });
511 }
512
513 async reload(options?: ResourceLoaderReloadOptions): Promise<void> {
514 resetTimings("extensions");
515
516 if (this.loaded) {
517 clearExtensionCache();
518 }
519
520 let preTrustExtensions: LoadExtensionsResult | undefined;
521 if (options?.resolveProjectTrust) {
522 preTrustExtensions = await this.loadProjectTrustExtensions();
523 const projectTrusted = await options.resolveProjectTrust({ extensionsResult: preTrustExtensions });
524 this.settingsManager.setProjectTrusted(projectTrusted);
525 }
526
527 // reload() preserves SettingsManager.projectTrusted and reloads settings for that trust state.
528 await this.settingsManager.reload();
529 const resolvedPaths = await this.packageManager.resolve();
530 const cliExtensionPaths = await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, {
531 temporary: true,
532 });
533 // Kept on the instance so post-reload passes (extendResources) can still resolve package metadata.
534 this.resourceMetadataByPath = new Map();
535 const metadataByPath = this.resourceMetadataByPath;
536
537 this.extensionSkillSourceInfos = new Map();
538 this.extensionPromptSourceInfos = new Map();
539 this.extensionThemeSourceInfos = new Map();
540
541 // Helper to extract enabled paths and store metadata
542 const getEnabledResources = (resources: ResolvedResource[]): ResolvedResource[] => {
543 for (const r of resources) {
544 if (!metadataByPath.has(r.path)) {
545 metadataByPath.set(r.path, r.metadata);
546 }
547 }
548 return resources.filter((r) => r.enabled);
549 };
550
551 const getEnabledPaths = (resources: ResolvedResource[]): string[] =>
552 getEnabledResources(resources).map((r) => r.path);
553 const enabledExtensions = getEnabledPaths(resolvedPaths.extensions);
554 const enabledSkillResources = getEnabledResources(resolvedPaths.skills);
555 const enabledPrompts = getEnabledPaths(resolvedPaths.prompts);
556 const enabledThemes = getEnabledPaths(resolvedPaths.themes);
557
558 const enabledSkills = enabledSkillResources.map((resource) => this.mapSkillPath(resource, metadataByPath));
559
560 // Add CLI paths metadata
561 for (const r of cliExtensionPaths.extensions) {
562 if (!metadataByPath.has(r.path)) {
563 metadataByPath.set(r.path, { source: "cli", scope: "temporary", origin: "top-level" });
564 }
565 }
566 for (const r of cliExtensionPaths.skills) {
567 if (!metadataByPath.has(r.path)) {
568 metadataByPath.set(r.path, { source: "cli", scope: "temporary", origin: "top-level" });
569 }
570 }
571
572 const cliEnabledExtensions = getEnabledPaths(cliExtensionPaths.extensions);
573 const cliEnabledSkills = getEnabledPaths(cliExtensionPaths.skills);
574 const cliEnabledPrompts = getEnabledPaths(cliExtensionPaths.prompts);
575 const cliEnabledThemes = getEnabledPaths(cliExtensionPaths.themes);
576
577 const extensionPaths = (
578 this.noExtensions ? cliEnabledExtensions : this.mergePaths(cliEnabledExtensions, enabledExtensions)
579 ).filter(
580 (path) =>
581 !path.startsWith(BUILTIN_PATH_PREFIX) ||
582 !this.disabledBuiltinExtensions.has(path.slice(BUILTIN_PATH_PREFIX.length)),
583 );
584
585 const packageWarnings = collectExtensionPackageWarnings(extensionPaths, metadataByPath);
586 const extensionsResult = await this.loadFinalExtensionSet(extensionPaths, preTrustExtensions);
587 mergeExtensionWarnings(extensionsResult, packageWarnings);
588 for (const p of this.additionalExtensionPaths) {
589 if (isLocalPath(p)) {
590 const resolved = this.resolveResourcePath(p);
591 if (!existsSync(resolved)) {
592 extensionsResult.errors.push({ path: resolved, error: `Extension path does not exist: ${resolved}` });
593 }
594 }
595 }
596 this.extensionsResult = this.extensionsOverride ? this.extensionsOverride(extensionsResult) : extensionsResult;
597 this.applyExtensionSourceInfo(this.extensionsResult.extensions, metadataByPath);
598
599 const skillPaths = this.noSkills
600 ? this.mergePaths(cliEnabledSkills, this.additionalSkillPaths)
601 : this.mergePaths([...cliEnabledSkills, ...enabledSkills], this.additionalSkillPaths);
602
603 this.lastSkillPaths = skillPaths;
604 this.updateSkillsFromPaths(skillPaths, metadataByPath);
605 for (const p of this.additionalSkillPaths) {
606 if (isLocalPath(p)) {
607 const resolved = this.resolveResourcePath(p);
608 if (!existsSync(resolved) && !this.skillDiagnostics.some((d) => d.path === resolved)) {
609 this.skillDiagnostics.push({ type: "error", message: "Skill path does not exist", path: resolved });
610 }
611 }
612 }
613
614 const promptPaths = this.noPromptTemplates
615 ? this.mergePaths(cliEnabledPrompts, this.additionalPromptTemplatePaths)
616 : this.mergePaths([...cliEnabledPrompts, ...enabledPrompts], this.additionalPromptTemplatePaths);
617
618 this.lastPromptPaths = promptPaths;
619 this.updatePromptsFromPaths(promptPaths, metadataByPath);
620 for (const p of this.additionalPromptTemplatePaths) {
621 if (isLocalPath(p)) {
622 const resolved = this.resolveResourcePath(p);
623 if (!existsSync(resolved) && !this.promptDiagnostics.some((d) => d.path === resolved)) {
624 this.promptDiagnostics.push({
625 type: "error",
626 message: "Prompt template path does not exist",
627 path: resolved,
628 });
629 }
630 }
631 }
632
633 const themePaths = this.noThemes
634 ? this.mergePaths(cliEnabledThemes, this.additionalThemePaths)
635 : this.mergePaths([...cliEnabledThemes, ...enabledThemes], this.additionalThemePaths);
636
637 this.lastThemePaths = themePaths;
638 this.updateThemesFromPaths(themePaths, metadataByPath);
639 for (const p of this.additionalThemePaths) {
640 const resolved = this.resolveResourcePath(p);
641 if (!existsSync(resolved) && !this.themeDiagnostics.some((d) => d.path === resolved)) {
642 this.themeDiagnostics.push({ type: "error", message: "Theme path does not exist", path: resolved });
643 }
644 }
645
646 const agentsFiles = {
647 agentsFiles: this.noContextFiles
648 ? []
649 : loadProjectContextFiles({
650 cwd: this.cwd,
651 agentDir: this.agentDir,
652 }),
653 };
654 const resolvedAgentsFiles = this.agentsFilesOverride ? this.agentsFilesOverride(agentsFiles) : agentsFiles;
655 this.agentsFiles = resolvedAgentsFiles.agentsFiles;
656
657 const systemPromptSource = this.systemPromptSource ?? this.discoverSystemPromptFile();
658 const baseSystemPrompt = resolvePromptInput(systemPromptSource, "system prompt");
659 this.systemPrompt = this.systemPromptOverride ? this.systemPromptOverride(baseSystemPrompt) : baseSystemPrompt;
660 this.systemPromptSourcePath =
661 systemPromptSource && existsSync(systemPromptSource) ? resolvePath(systemPromptSource) : undefined;
662
663 let appendSources = this.appendSystemPromptSource;
664 if (!appendSources) {
665 const discoveredAppendSystemPromptFile = this.discoverAppendSystemPromptFile();
666 appendSources = discoveredAppendSystemPromptFile ? [discoveredAppendSystemPromptFile] : [];
667 }
668 const baseAppend = appendSources
669 .map((s) => resolvePromptInput(s, "append system prompt"))
670 .filter((s): s is string => s !== undefined);
671 this.appendSystemPrompt = this.appendSystemPromptOverride
672 ? this.appendSystemPromptOverride(baseAppend)
673 : baseAppend;
674 this.appendSystemPromptSourcePaths = appendSources
675 .filter((source) => existsSync(source))
676 .map((source) => resolvePath(source));
677 this.loaded = true;
678 }
679
680 private async loadCurrentExtensionSet(options: { includeInlineFactories: boolean }): Promise<LoadExtensionsResult> {
681 const resolvedPaths = await this.packageManager.resolve();
682 const cliExtensionPaths = await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, {
683 temporary: true,
684 });
685 const enabledExtensions = resolvedPaths.extensions.filter((r) => r.enabled).map((r) => r.path);
686 const cliEnabledExtensions = cliExtensionPaths.extensions.filter((r) => r.enabled).map((r) => r.path);
687 // Built-in extensions wait for the final pass: project settings can disable them, and a loaded
688 // extension cannot be unloaded.
689 const extensionPaths = (
690 this.noExtensions ? cliEnabledExtensions : this.mergePaths(cliEnabledExtensions, enabledExtensions)
691 ).filter((path) => !path.startsWith(BUILTIN_PATH_PREFIX));
692 const metadataByPath = new Map(
693 [...resolvedPaths.extensions, ...cliExtensionPaths.extensions].map((resource) => [
694 resource.path,
695 resource.metadata,
696 ]),
697 );
698 const packageWarnings = collectExtensionPackageWarnings(extensionPaths, metadataByPath);
699 const extensionsResult = await loadExtensionsCached(extensionPaths, this.cwd, this.eventBus);
700 mergeExtensionWarnings(extensionsResult, packageWarnings);
701 if (!options.includeInlineFactories) {
702 return extensionsResult;
703 }
704
705 const inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime);
706 extensionsResult.extensions.push(...inlineExtensions.extensions);
707 extensionsResult.errors.push(...inlineExtensions.errors);
708 const replacementWarnings: Array<{ path: string; warning: string }> = [];
709 extensionsResult.extensions = omitReplacedExtensions(extensionsResult.extensions, replacementWarnings);
710 mergeExtensionWarnings(extensionsResult, replacementWarnings);
711 return extensionsResult;
712 }
713
714 private resolveExtensionLoadPath(path: string): string {
715 return isSyntheticPath(path) ? path : resolvePath(path, this.cwd, { normalizeUnicodeSpaces: true });
716 }
717
718 /** Load extension paths: files from disk and `builtin:<name>` paths from the built-in extensions. */
719 private async loadExtensionPaths(paths: string[], runtime?: ExtensionRuntime): Promise<LoadExtensionsResult> {
720 const isBuiltinPath = (path: string) => path.startsWith(BUILTIN_PATH_PREFIX);
721 const result = await loadExtensionsCached(
722 paths.filter((path) => !isBuiltinPath(path)),
723 this.cwd,
724 this.eventBus,
725 runtime,
726 );
727 for (const path of paths.filter(isBuiltinPath)) {
728 const builtin = this.builtinExtensions.get(path.slice(BUILTIN_PATH_PREFIX.length));
729 if (!builtin) {
730 result.errors.push({ path, error: `Unknown built-in extension: ${path}` });
731 continue;
732 }
733 try {
734 const extension = await loadExtensionFromFactory(
735 builtin.factory,
736 this.cwd,
737 this.eventBus,
738 result.runtime,
739 path,
740 );
741 extension.hidden = true;
742 extension.replaceable = builtin.replaceable === true;
743 result.extensions.push(extension);
744 } catch (error) {
745 result.errors.push({ path, error: error instanceof Error ? error.message : "failed to load extension" });
746 }
747 }
748 return result;
749 }
750
751 private async loadFinalExtensionSet(
752 extensionPaths: string[],
753 preTrustExtensions: LoadExtensionsResult | undefined,
754 ): Promise<LoadExtensionsResult> {
755 // Without a pre-trust pass nothing is preloaded, and inline extensions load here.
756 const preloaded = preTrustExtensions?.extensions ?? [];
757 const preloadedByPath = new Map(
758 preloaded
759 .filter((extension) => !extension.path.startsWith("<inline:"))
760 .map((extension) => [extension.resolvedPath, extension]),
761 );
762 const failedPreloadPaths = new Set(
763 (preTrustExtensions?.errors ?? []).map((error) => this.resolveExtensionLoadPath(error.path)),
764 );
765 const remainingPaths = extensionPaths.filter((path) => {
766 const resolvedPath = this.resolveExtensionLoadPath(path);
767 return !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath);
768 });
769 const remainingExtensions = await this.loadExtensionPaths(remainingPaths, preTrustExtensions?.runtime);
770 const loadedByPath = new Map(preloadedByPath);
771 for (const extension of remainingExtensions.extensions) {
772 loadedByPath.set(extension.resolvedPath, extension);
773 }
774
775 const inlineExtensions = preTrustExtensions
776 ? { extensions: preloaded.filter((extension) => extension.path.startsWith("<inline:")), errors: [] }
777 : await this.loadExtensionFactories(remainingExtensions.runtime);
778 const orderedExtensions = extensionPaths
779 .map((path) => loadedByPath.get(this.resolveExtensionLoadPath(path)))
780 .filter((extension): extension is Extension => extension !== undefined);
781 orderedExtensions.push(...inlineExtensions.extensions);
782
783 const replacementWarnings: Array<{ path: string; warning: string }> = [];
784 const extensionsResult: LoadExtensionsResult = {
785 extensions: omitReplacedExtensions(orderedExtensions, replacementWarnings),
786 errors: [...(preTrustExtensions?.errors ?? []), ...remainingExtensions.errors, ...inlineExtensions.errors],
787 warnings: [...(preTrustExtensions?.warnings ?? []), ...(remainingExtensions.warnings ?? [])],
788 runtime: remainingExtensions.runtime,
789 };
790 mergeExtensionWarnings(extensionsResult, replacementWarnings);
791 this.addExtensionConflictDiagnostics(extensionsResult);
792 return extensionsResult;
793 }
794
795 private addExtensionConflictDiagnostics(extensionsResult: LoadExtensionsResult): void {
796 // Detect extension conflicts (tools, commands, flags with same names from different extensions)
797 // Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order.
798 const conflicts = this.detectExtensionConflicts(extensionsResult.extensions);
799 for (const conflict of conflicts) {
800 extensionsResult.errors.push({ path: conflict.path, error: conflict.message });
801 }
802 }
803
804 private mapSkillPath(resource: ResolvedResource, metadataByPath: Map<string, PathMetadata>): string {
805 if (resource.metadata.source !== "auto" && resource.metadata.origin !== "package") {
806 return resource.path;
807 }
808 try {
809 const stats = statSync(resource.path);
810 if (!stats.isDirectory()) {
811 return resource.path;
812 }
813 } catch {
814 return resource.path;
815 }
816 const skillFile = join(resource.path, "SKILL.md");
817 if (existsSync(skillFile)) {
818 if (!metadataByPath.has(skillFile)) {
819 metadataByPath.set(skillFile, resource.metadata);
820 }
821 return skillFile;
822 }
823 return resource.path;
824 }
825
826 private normalizeExtensionPaths(
827 entries: Array<{ path: string; metadata: PathMetadata }>,
828 ): Array<{ path: string; metadata: PathMetadata }> {
829 return entries.map((entry) => {
830 const metadata = entry.metadata.baseDir
831 ? { ...entry.metadata, baseDir: this.resolveResourcePath(entry.metadata.baseDir) }
832 : entry.metadata;
833 return {
834 path: this.resolveResourcePath(entry.path),
835 metadata,
836 };
837 });
838 }
839
840 private updateSkillsFromPaths(skillPaths: string[], metadataByPath?: Map<string, PathMetadata>): void {
841 let skillsResult: { skills: Skill[]; diagnostics: ResourceDiagnostic[] };
842 if (this.noSkills && skillPaths.length === 0) {
843 skillsResult = { skills: [], diagnostics: [] };
844 } else {
845 skillsResult = loadSkills({
846 cwd: this.cwd,
847 agentDir: this.agentDir,
848 skillPaths,
849 includeDefaults: false,
850 });
851 }
852 const resolvedSkills = this.skillsOverride ? this.skillsOverride(skillsResult) : skillsResult;
853 this.skills = resolvedSkills.skills.map((skill) => ({
854 ...skill,
855 sourceInfo:
856 this.findSourceInfoForPath(skill.filePath, this.extensionSkillSourceInfos, metadataByPath) ??
857 skill.sourceInfo ??
858 this.getDefaultSourceInfoForPath(skill.filePath),
859 }));
860 this.skillDiagnostics = resolvedSkills.diagnostics;
861 }
862
863 private updatePromptsFromPaths(promptPaths: string[], metadataByPath?: Map<string, PathMetadata>): void {
864 let promptsResult: { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] };
865 if (this.noPromptTemplates && promptPaths.length === 0) {
866 promptsResult = { prompts: [], diagnostics: [] };
867 } else {
868 const loaded = loadPromptTemplates({
869 cwd: this.cwd,
870 agentDir: this.agentDir,
871 promptPaths,
872 includeDefaults: false,
873 });
874 const deduped = this.dedupePrompts(loaded.templates);
875 promptsResult = {
876 prompts: deduped.prompts,
877 diagnostics: [...loaded.diagnostics, ...deduped.diagnostics],
878 };
879 }
880 const resolvedPrompts = this.promptsOverride ? this.promptsOverride(promptsResult) : promptsResult;
881 this.prompts = resolvedPrompts.prompts.map((prompt) => ({
882 ...prompt,
883 sourceInfo:
884 this.findSourceInfoForPath(prompt.filePath, this.extensionPromptSourceInfos, metadataByPath) ??
885 prompt.sourceInfo ??
886 this.getDefaultSourceInfoForPath(prompt.filePath),
887 }));
888 this.promptDiagnostics = resolvedPrompts.diagnostics;
889 }
890
891 private updateThemesFromPaths(themePaths: string[], metadataByPath?: Map<string, PathMetadata>): void {
892 let themesResult: { themes: Theme[]; diagnostics: ResourceDiagnostic[] };
893 if (this.noThemes && themePaths.length === 0) {
894 themesResult = { themes: [], diagnostics: [] };
895 } else {
896 // Theme construction only needs trueColor, so skip the unrelated tmux hyperlink probe.
897 const colorMode = getTerminalColorMode({
898 ...detectCapabilities(() => false),
899 ...this.settingsManager.getTerminalCapabilityOverrides(),
900 });
901 const loaded = this.loadThemes(themePaths, false, colorMode);
902 const deduped = this.dedupeThemes(loaded.themes);
903 themesResult = { themes: deduped.themes, diagnostics: [...loaded.diagnostics, ...deduped.diagnostics] };
904 }
905 const resolvedThemes = this.themesOverride ? this.themesOverride(themesResult) : themesResult;
906 this.themes = resolvedThemes.themes.map((theme) => {
907 const sourcePath = theme.sourcePath;
908 theme.sourceInfo = sourcePath
909 ? (this.findSourceInfoForPath(sourcePath, this.extensionThemeSourceInfos, metadataByPath) ??
910 theme.sourceInfo ??
911 this.getDefaultSourceInfoForPath(sourcePath))
912 : theme.sourceInfo;
913 return theme;
914 });
915 this.themeDiagnostics = resolvedThemes.diagnostics;
916 }
917
918 private applyExtensionSourceInfo(extensions: Extension[], metadataByPath: Map<string, PathMetadata>): void {
919 for (const extension of extensions) {
920 extension.sourceInfo =
921 this.findSourceInfoForPath(extension.path, undefined, metadataByPath) ??
922 this.getDefaultSourceInfoForPath(extension.path);
923 for (const command of extension.commands.values()) {
924 command.sourceInfo = extension.sourceInfo;
925 }
926 for (const tool of extension.tools.values()) {
927 tool.sourceInfo = extension.sourceInfo;
928 }
929 }
930 }
931
932 private findSourceInfoForPath(
933 resourcePath: string,
934 extraSourceInfos?: Map<string, SourceInfo>,
935 metadataByPath?: Map<string, PathMetadata>,
936 ): SourceInfo | undefined {
937 if (!resourcePath) {
938 return undefined;
939 }
940
941 if (isSyntheticPath(resourcePath)) {
942 return this.getDefaultSourceInfoForPath(resourcePath);
943 }
944
945 const normalizedResourcePath = resolve(resourcePath);
946 if (extraSourceInfos) {
947 for (const [sourcePath, sourceInfo] of extraSourceInfos.entries()) {
948 const normalizedSourcePath = resolve(sourcePath);
949 if (
950 normalizedResourcePath === normalizedSourcePath ||
951 normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)
952 ) {
953 return { ...sourceInfo, path: resourcePath };
954 }
955 }
956 }
957
958 if (metadataByPath) {
959 const exact = metadataByPath.get(normalizedResourcePath) ?? metadataByPath.get(resourcePath);
960 if (exact) {
961 return createSourceInfo(resourcePath, exact);
962 }
963
964 for (const [sourcePath, metadata] of metadataByPath.entries()) {
965 const normalizedSourcePath = resolve(sourcePath);
966 if (
967 normalizedResourcePath === normalizedSourcePath ||
968 normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)
969 ) {
970 return createSourceInfo(resourcePath, metadata);
971 }
972 }
973 }
974
975 return undefined;
976 }
977
978 private getDefaultSourceInfoForPath(filePath: string): SourceInfo {
979 const syntheticSource = getSyntheticPathSource(filePath);
980 if (syntheticSource) {
981 return {
982 path: filePath,
983 source: syntheticSource,
984 scope: "temporary",
985 origin: "top-level",
986 };
987 }
988
989 const normalizedPath = resolve(filePath);
990 const agentRoots = [
991 join(this.agentDir, "skills"),
992 join(this.agentDir, "prompts"),
993 join(this.agentDir, "themes"),
994 join(this.agentDir, "extensions"),
995 ];
996 const projectRoots = [
997 join(this.cwd, CONFIG_DIR_NAME, "skills"),
998 join(this.cwd, CONFIG_DIR_NAME, "prompts"),
999 join(this.cwd, CONFIG_DIR_NAME, "themes"),
1000 join(this.cwd, CONFIG_DIR_NAME, "extensions"),
1001 ];
1002
1003 for (const root of agentRoots) {
1004 if (this.isUnderPath(normalizedPath, root)) {
1005 return { path: filePath, source: "local", scope: "user", origin: "top-level", baseDir: root };
1006 }
1007 }
1008
1009 for (const root of projectRoots) {
1010 if (this.isUnderPath(normalizedPath, root)) {
1011 return { path: filePath, source: "local", scope: "project", origin: "top-level", baseDir: root };
1012 }
1013 }
1014
1015 return {
1016 path: filePath,
1017 source: "local",
1018 scope: "temporary",
1019 origin: "top-level",
1020 baseDir: statSync(normalizedPath).isDirectory() ? normalizedPath : resolve(normalizedPath, ".."),
1021 };
1022 }
1023
1024 private mergePaths(primary: string[], additional: string[]): string[] {
1025 const merged: string[] = [];
1026 const seen = new Set<string>();
1027
1028 for (const p of [...primary, ...additional]) {
1029 const resolved = this.resolveResourcePath(p);
1030 const canonicalPath = canonicalizePath(resolved);
1031 if (seen.has(canonicalPath)) continue;
1032 seen.add(canonicalPath);
1033 merged.push(resolved);
1034 }
1035
1036 return merged;
1037 }
1038
1039 private resolveResourcePath(p: string): string {
1040 return isSyntheticPath(p) ? p : resolvePath(p, this.cwd, { trim: true });
1041 }
1042
1043 private loadThemes(
1044 paths: string[],
1045 includeDefaults: boolean,
1046 colorMode: TerminalColorMode,
1047 ): {
1048 themes: Theme[];
1049 diagnostics: ResourceDiagnostic[];
1050 } {
1051 const themes: Theme[] = [];
1052 const diagnostics: ResourceDiagnostic[] = [];
1053 if (includeDefaults) {
1054 const defaultDirs = [join(this.agentDir, "themes"), join(this.cwd, CONFIG_DIR_NAME, "themes")];
1055
1056 for (const dir of defaultDirs) {
1057 this.loadThemesFromDir(dir, themes, diagnostics, colorMode);
1058 }
1059 }
1060
1061 for (const p of paths) {
1062 const resolved = this.resolveResourcePath(p);
1063 if (!existsSync(resolved)) {
1064 diagnostics.push({ type: "warning", message: "theme path does not exist", path: resolved });
1065 continue;
1066 }
1067
1068 try {
1069 const stats = statSync(resolved);
1070 if (stats.isDirectory()) {
1071 this.loadThemesFromDir(resolved, themes, diagnostics, colorMode);
1072 } else if (stats.isFile() && resolved.endsWith(".json")) {
1073 this.loadThemeFromFile(resolved, themes, diagnostics, colorMode);
1074 } else {
1075 diagnostics.push({ type: "warning", message: "theme path is not a json file", path: resolved });
1076 }
1077 } catch (error) {
1078 const message = error instanceof Error ? error.message : "failed to read theme path";
1079 diagnostics.push({ type: "warning", message, path: resolved });
1080 }
1081 }
1082
1083 return { themes, diagnostics };
1084 }
1085
1086 private loadThemesFromDir(
1087 dir: string,
1088 themes: Theme[],
1089 diagnostics: ResourceDiagnostic[],
1090 colorMode: TerminalColorMode,
1091 ): void {
1092 if (!existsSync(dir)) {
1093 return;
1094 }
1095
1096 try {
1097 const entries = readdirSync(dir, { withFileTypes: true });
1098 for (const entry of entries) {
1099 let isFile = entry.isFile();
1100 if (entry.isSymbolicLink()) {
1101 try {
1102 isFile = statSync(join(dir, entry.name)).isFile();
1103 } catch {
1104 continue;
1105 }
1106 }
1107 if (!isFile) {
1108 continue;
1109 }
1110 if (!entry.name.endsWith(".json")) {
1111 continue;
1112 }
1113 this.loadThemeFromFile(join(dir, entry.name), themes, diagnostics, colorMode);
1114 }
1115 } catch (error) {
1116 const message = error instanceof Error ? error.message : "failed to read theme directory";
1117 diagnostics.push({ type: "warning", message, path: dir });
1118 }
1119 }
1120
1121 private loadThemeFromFile(
1122 filePath: string,
1123 themes: Theme[],
1124 diagnostics: ResourceDiagnostic[],
1125 colorMode: TerminalColorMode,
1126 ): void {
1127 try {
1128 themes.push(loadThemeFromPath(filePath, colorMode));
1129 } catch (error) {
1130 const message = error instanceof Error ? error.message : "failed to load theme";
1131 diagnostics.push({ type: "warning", message, path: filePath });
1132 }
1133 }
1134
1135 private async loadExtensionFactories(runtime: ExtensionRuntime): Promise<{
1136 extensions: Extension[];
1137 errors: Array<{ path: string; error: string }>;
1138 }> {
1139 const extensions: Extension[] = [];
1140 const errors: Array<{ path: string; error: string }> = [];
1141
1142 for (const [index, input] of this.extensionFactories.entries()) {
1143 const isNamed = typeof input !== "function";
1144 const factory = isNamed ? input.factory : input;
1145 const extensionPath = `<inline:${isNamed ? input.name : index + 1}>`;
1146 try {
1147 const extension = await loadExtensionFromFactory(factory, this.cwd, this.eventBus, runtime, extensionPath);
1148 extension.hidden = isNamed && input.hidden;
1149 extension.replaceable = isNamed && input.replaceable === true;
1150 extensions.push(extension);
1151 } catch (error) {
1152 const message = error instanceof Error ? error.message : "failed to load extension";
1153 errors.push({ path: extensionPath, error: message });
1154 }
1155 }
1156
1157 return { extensions, errors };
1158 }
1159
1160 private dedupePrompts(prompts: PromptTemplate[]): { prompts: PromptTemplate[]; diagnostics: ResourceDiagnostic[] } {
1161 const seen = new Map<string, PromptTemplate>();
1162 const diagnostics: ResourceDiagnostic[] = [];
1163
1164 for (const prompt of prompts) {
1165 const existing = seen.get(prompt.name);
1166 if (existing) {
1167 diagnostics.push({
1168 type: "collision",
1169 message: `name "/${prompt.name}" collision`,
1170 path: prompt.filePath,
1171 collision: {
1172 resourceType: "prompt",
1173 name: prompt.name,
1174 winnerPath: existing.filePath,
1175 loserPath: prompt.filePath,
1176 },
1177 });
1178 } else {
1179 seen.set(prompt.name, prompt);
1180 }
1181 }
1182
1183 return { prompts: Array.from(seen.values()), diagnostics };
1184 }
1185
1186 private dedupeThemes(themes: Theme[]): { themes: Theme[]; diagnostics: ResourceDiagnostic[] } {
1187 const seen = new Map<string, Theme>();
1188 const diagnostics: ResourceDiagnostic[] = [];
1189
1190 for (const t of themes) {
1191 const name = t.name ?? "unnamed";
1192 const existing = seen.get(name);
1193 if (existing) {
1194 diagnostics.push({
1195 type: "collision",
1196 message: `name "${name}" collision`,
1197 path: t.sourcePath,
1198 collision: {
1199 resourceType: "theme",
1200 name,
1201 winnerPath: existing.sourcePath ?? "<builtin>",
1202 loserPath: t.sourcePath ?? "<builtin>",
1203 },
1204 });
1205 } else {
1206 seen.set(name, t);
1207 }
1208 }
1209
1210 return { themes: Array.from(seen.values()), diagnostics };
1211 }
1212
1213 private discoverSystemPromptFile(): string | undefined {
1214 const projectPath = join(this.cwd, CONFIG_DIR_NAME, "SYSTEM.md");
1215 if (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) {
1216 return projectPath;
1217 }
1218
1219 const globalPath = join(this.agentDir, "SYSTEM.md");
1220 if (existsSync(globalPath)) {
1221 return globalPath;
1222 }
1223
1224 return undefined;
1225 }
1226
1227 private discoverAppendSystemPromptFile(): string | undefined {
1228 const projectPath = join(this.cwd, CONFIG_DIR_NAME, "APPEND_SYSTEM.md");
1229 if (this.settingsManager.isProjectTrusted() && existsSync(projectPath)) {
1230 return projectPath;
1231 }
1232
1233 const globalPath = join(this.agentDir, "APPEND_SYSTEM.md");
1234 if (existsSync(globalPath)) {
1235 return globalPath;
1236 }
1237
1238 return undefined;
1239 }
1240
1241 private isUnderPath(target: string, root: string): boolean {
1242 const normalizedRoot = resolve(root);
1243 if (target === normalizedRoot) {
1244 return true;
1245 }
1246 const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;
1247 return target.startsWith(prefix);
1248 }
1249
1250 private detectExtensionConflicts(extensions: Extension[]): Array<{ path: string; message: string }> {
1251 const conflicts: Array<{ path: string; message: string }> = [];
1252
1253 // Track which extension registered each tool and flag
1254 const toolOwners = new Map<string, string>();
1255 const flagOwners = new Map<string, string>();
1256
1257 for (const ext of extensions) {
1258 // Check tools
1259 for (const toolName of ext.tools.keys()) {
1260 const existingOwner = toolOwners.get(toolName);
1261 if (existingOwner && existingOwner !== ext.path) {
1262 conflicts.push({
1263 path: ext.path,
1264 message: `Tool "${toolName}" conflicts with ${existingOwner}`,
1265 });
1266 } else {
1267 toolOwners.set(toolName, ext.path);
1268 }
1269 }
1270
1271 // Check flags
1272 for (const flagName of ext.flags.keys()) {
1273 const existingOwner = flagOwners.get(flagName);
1274 if (existingOwner && existingOwner !== ext.path) {
1275 conflicts.push({
1276 path: ext.path,
1277 message: `Flag "--${flagName}" conflicts with ${existingOwner}`,
1278 });
1279 } else {
1280 flagOwners.set(flagName, ext.path);
1281 }
1282 }
1283 }
1284
1285 return conflicts;
1286 }
1287}