@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
1,421 lines • 69.9 kB
JavaScript
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
import { dirname, join, resolve, sep } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { detectCapabilities, getTerminalColorMode } from "@earendil-works/pi-tui";
import chalk from "chalk";
import { APP_NAME, CONFIG_DIR_NAME, findNodePackageDir, getAgentDir, getPackageDir, isBunBinary } from "../config.js";
import { loadThemeFromPath } from "../modes/interactive/theme/theme.js";
import { resolveInstallPath } from "../runtime-snapshot/marker.js";
import { ACCEPTED_SHIM_BANNERS, GENERATED_SHIM_BANNER } from "./generated-shim-banner.js";
export { loadProjectContextFiles };
import { canonicalizePath, isLocalPath, resolvePath } from "../utils/paths.js";
import { stripBom } from "../utils/text.js";
import { bundledBuiltinExtensions } from "./bundled-resources.js";
import { loadProjectContextFiles } from "./context-files.js";
import { createEventBus } from "./event-bus.js";
import { builtinExtensions, globalDefaultExtensionFactories, globalDefaultExtensionIds, } from "./extensions/builtin/index.js";
import { createMcpExtension } from "./extensions/builtin/mcp/index.js";
import { McpService } from "./extensions/builtin/mcp/service.js";
import { createExtensionRuntime, loadExtensionFromFactory, loadExtensions, } from "./extensions/loader.js";
import { EMPTY_SESSION_CONTEXT } from "./extensions/types.js";
import { dedupePathsByPackageIdentity, findNearestPackageIdentity } from "./package-identity.js";
import { DefaultPackageManager } from "./package-manager.js";
import { loadPromptTemplates } from "./prompt-templates.js";
import { memoizeResolvedPaths, resolvedPathsMemoKey } from "./resolved-paths-memo.js";
import { SettingsManager } from "./settings-manager.js";
import { ignoredSkillDiagnostics, loadSkills } from "./skills.js";
import { warnIfLargeSkillCatalog } from "./skills-prompt.js";
import { BUILTIN_PATH_PREFIX, createSourceInfo, getSyntheticPathSource, isSyntheticPath, } from "./source-info.js";
import { resetTimings, time } from "./timings.js";
const HOST_PROVIDED_EXTENSION_PACKAGES = new Set([
"@earendil-works/pi-agent-core",
"@earendil-works/pi-ai",
"@earendil-works/pi-coding-agent",
"@earendil-works/pi-tui",
"@mariozechner/pi-agent-core",
"@mariozechner/pi-ai",
"@mariozechner/pi-coding-agent",
"@mariozechner/pi-tui",
"@sinclair/typebox",
"typebox",
]);
function collectExtensionPackageWarnings(extensionPaths, metadataByPath) {
const warnings = [];
const packageRoots = new Set(extensionPaths
.map((extensionPath) => metadataByPath.get(extensionPath)?.packageRoot)
.filter((packageRoot) => packageRoot !== undefined));
for (const packageRoot of packageRoots) {
const packageJsonPath = join(packageRoot, "package.json");
if (!existsSync(packageJsonPath))
continue;
const manifest = JSON.parse(stripBom(readFileSync(packageJsonPath, "utf-8")));
if (typeof manifest.dependencies !== "object" ||
manifest.dependencies === null ||
Array.isArray(manifest.dependencies)) {
continue;
}
const hostDependencies = Object.keys(manifest.dependencies)
.filter((name) => HOST_PROVIDED_EXTENSION_PACKAGES.has(name))
.sort();
if (hostDependencies.length === 0)
continue;
warnings.push({
path: packageJsonPath,
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.`,
});
}
return warnings;
}
function mergeExtensionWarnings(result, warnings) {
result.warnings = [
...new Map([...(result.warnings ?? []), ...warnings].map((warning) => [warning.path, warning])).values(),
];
}
/** Built-in extensions supply the code of `builtin:<name>` extension paths (see `InlineExtension`). */
export function isBuiltinExtension(input) {
return typeof input !== "function" && input.builtin === true;
}
/**
* Leave out replaceable extensions (see `InlineExtension`) that share a tool, command, or flag name
* with another extension. For example, a third-party MCP extension that registers `/mcp` replaces
* the built-in MCP extension instead of both connecting the same servers.
*/
function omitReplacedExtensions(extensions, warnings) {
const names = (extension) => [
...[...extension.tools.keys()].map((name) => `tool:${name}`),
...[...extension.commands.keys()].map((name) => `command:${name}`),
...[...extension.flags.keys()].map((name) => `flag:${name}`),
];
const taken = new Map(extensions
.filter((extension) => !extension.replaceable)
.flatMap((extension) => names(extension).map((name) => [name, extension])));
return extensions.filter((extension) => {
if (!extension.replaceable)
return true;
const replacement = names(extension)
.map((name) => ({ name, extension: taken.get(name) }))
.find((value) => value.extension !== undefined);
if (!replacement)
return true;
if (extension.path.startsWith(BUILTIN_PATH_PREFIX)) {
const builtinName = extension.path.slice(BUILTIN_PATH_PREFIX.length);
const [kind, rawName] = replacement.name.split(":", 2);
const registeredName = kind === "command" ? `/${rawName}` : kind === "flag" ? `--${rawName}` : rawName;
warnings?.push({
path: extension.path,
warning: `Extension ${replacement.extension.path} registers ${kind} \`${registeredName}\`, so built-in extension \`${builtinName}\` was not loaded. To use \`${builtinName}\`, run \`${APP_NAME} 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.`,
});
}
return false;
});
}
function resolvePromptInput(input, description) {
if (!input) {
return undefined;
}
if (existsSync(input)) {
try {
return stripBom(readFileSync(input, "utf-8"));
}
catch (error) {
console.error(chalk.yellow(`Warning: Could not read ${description} file ${input}: ${error}`));
return input;
}
}
return input;
}
const GENERATED_GLOBAL_EXTENSION_BANNER = GENERATED_SHIM_BANNER;
const LEGACY_GENERATED_GLOBAL_EXTENSION_BANNERS = ACCEPTED_SHIM_BANNERS;
const VENDORED_BUILTIN_EXTENSION_PACKAGES = [
{ builtinId: "anthropic-bash", packageName: "pi-anthropic-bash" },
{ builtinId: "anthropic-web-search", packageName: "pi-anthropic-web-search" },
{ builtinId: "gpt-apply-patch", packageName: "pi-apply-patch" },
{ builtinId: "bash-timeout", packageName: "pi-bash-timeout" },
{ builtinId: "openai-web-search", packageName: "pi-openai-web-search" },
{ builtinId: "todowrite", packageName: "pi-todotools" },
{ builtinId: "codemode", packageName: "@code-yeongyu/senpi-codemode" },
];
function isGeneratedGlobalDefaultExtensionShim(content) {
return LEGACY_GENERATED_GLOBAL_EXTENSION_BANNERS.some((banner) => content.startsWith(banner));
}
/**
* The shim records an absolute path, and `getPackageDir()` derives from
* `import.meta.url`. A session launched through the npm bin symlink and one
* launched from the real checkout therefore spell the SAME build differently,
* so each rewrote the other's shim and every rewrite reloaded every other
* session. Canonicalizing collapses both spellings to one path.
*/
export function canonicalizeGlobalDefaultExtensionModulePath(modulePath) {
// A session running from its runtime snapshot names the snapshot's copy; the shim outlives
// that snapshot and is shared by every build's sessions, so it names the install instead.
const installPath = resolveInstallPath(modulePath, findNodePackageDir(dirname(modulePath)));
try {
return realpathSync(installPath);
}
catch {
return installPath;
}
}
function getGlobalDefaultExtensionModulePath(extensionId) {
const packageDir = getPackageDir();
const runningFromSource = fileURLToPath(import.meta.url).includes(`${sep}src${sep}core${sep}resource-loader.`);
const sourceRoot = runningFromSource ? "src" : "dist";
const extensionFile = runningFromSource ? `${extensionId}.ts` : `${extensionId}.js`;
const packageDirIsSourceRootPath = join(packageDir, "core", "extensions", "builtin", extensionFile);
if (!runningFromSource && existsSync(packageDirIsSourceRootPath)) {
return canonicalizeGlobalDefaultExtensionModulePath(packageDirIsSourceRootPath);
}
return canonicalizeGlobalDefaultExtensionModulePath(join(packageDir, sourceRoot, "core", "extensions", "builtin", extensionFile));
}
// A write-denied agent dir (a sandboxed review child, senpi#6287) is left as it is: a missing default
// extension shim is not seeded, so that default does not load, and a stale shim keeps loading whatever it
// points at. Startup survives either way, and each denied write is reported as an extension warning so a
// permission problem in a normal agent dir is visible; any other error is a real failure.
function seedWritable(write, path, denied) {
try {
write();
return true;
}
catch (error) {
const code = error.code;
if (code !== "EROFS" && code !== "EACCES" && code !== "EPERM")
throw error;
denied.push({
path,
warning: `Default extension shim not written (${code}); the extensions directory is not writable, so this default extension is not refreshed.`,
});
return false;
}
}
function buildGlobalDefaultExtensionShim(modulePath) {
return `${GENERATED_GLOBAL_EXTENSION_BANNER}export { default } from ${JSON.stringify(pathToFileURL(modulePath).href)};\n`;
}
function getGlobalDefaultExtensionShimPath(agentDir, extensionId) {
return join(agentDir, "extensions", `${extensionId}.js`);
}
function isGlobalDefaultExtensionShimLocation(extensionPath, agentDir) {
const resolvedExtensionPath = resolve(extensionPath);
return globalDefaultExtensionIds.some((extensionId) => resolvedExtensionPath === resolve(getGlobalDefaultExtensionShimPath(agentDir, extensionId)));
}
function findGeneratedGlobalDefaultExtensionId(extensionPath, agentDir) {
if (resolve(agentDir) !== resolve(getAgentDir())) {
return undefined;
}
const resolvedExtensionPath = resolve(extensionPath);
for (const extensionId of globalDefaultExtensionIds) {
if (resolvedExtensionPath === resolve(getGlobalDefaultExtensionShimPath(agentDir, extensionId))) {
return extensionId;
}
}
return undefined;
}
/** The module a generated shim re-exports, when it is a generated shim whose target no longer exists. */
// Exactly what `buildGlobalDefaultExtensionShim` writes: one export line after the banner, nothing else.
const GENERATED_SHIM_EXPORT_LINE = /^export \{ default \} from ("[^"\n]*");\n?$/;
/**
* The module a generated shim re-exports, when the file is exactly a generated shim (an accepted banner
* followed by the single export line and nothing else) and that module no longer exists. A file that
* carries the banner but also anything a person wrote is never treated as a shim.
*/
function deadGeneratedShimTarget(content) {
const banner = LEGACY_GENERATED_GLOBAL_EXTENSION_BANNERS.find((candidate) => content.startsWith(candidate));
if (banner === undefined)
return undefined;
const specifier = GENERATED_SHIM_EXPORT_LINE.exec(content.slice(banner.length))?.[1];
if (specifier === undefined)
return undefined;
let target;
try {
const parsed = JSON.parse(specifier);
target = parsed.startsWith("file:") ? fileURLToPath(parsed) : parsed;
}
catch {
return undefined;
}
return existsSync(target) ? undefined : target;
}
function removeDeadGeneratedShim(shimPath) {
let content;
try {
content = readFileSync(shimPath, "utf-8");
}
catch {
return;
}
if (deadGeneratedShimTarget(content) === undefined)
return;
try {
unlinkSync(shimPath);
}
catch {
// The loader skips a dead generated shim on its own; a failed removal only retries next start.
}
}
// A generated shim whose target is gone stands for "load the default extension" from an install that no
// longer exists. Importing it can only fail with "Cannot find module", so it is skipped without an error.
const skipDeadGeneratedShim = () => { };
function resolveGeneratedGlobalDefaultExtensionFactory(extensionPath, agentDir) {
if (isGlobalDefaultExtensionShimLocation(extensionPath, agentDir)) {
try {
if (deadGeneratedShimTarget(readFileSync(extensionPath, "utf-8")) !== undefined)
return skipDeadGeneratedShim;
}
catch {
// Unreadable: let the regular load report it.
}
}
const extensionId = findGeneratedGlobalDefaultExtensionId(extensionPath, agentDir);
if (!extensionId) {
return undefined;
}
try {
const expectedShim = buildGlobalDefaultExtensionShim(getGlobalDefaultExtensionModulePath(extensionId));
return readFileSync(extensionPath, "utf-8") === expectedShim
? globalDefaultExtensionFactories[extensionId]
: undefined;
}
catch {
return undefined;
}
}
export class DefaultResourceLoader {
constructor(options) {
this.contextDiagnostics = [];
this.deniedSeedWarnings = [];
this.userSkillRoots = [];
this.ignoredSkillFiles = [];
this.cwd = resolvePath(options.cwd);
this.agentDir = resolvePath(options.agentDir);
this.settingsManager = options.settingsManager ?? SettingsManager.create(this.cwd, this.agentDir);
this.extensionSession = {
sessionKind: options.sessionKind ?? "interactive",
sessionContext: options.sessionContext ?? EMPTY_SESSION_CONTEXT,
};
this.eventBus = options.eventBus ?? createEventBus();
const factories = options.extensionFactories ?? [];
const hostFactories = factories.flatMap((input) => typeof input !== "function" && input.host ? [{ id: input.name, factory: input.factory }] : []);
this.extensionFactories = factories.filter((input) => !(typeof input !== "function" && input.host) && !isBuiltinExtension(input));
this.builtinExtensions = new Map(factories.filter(isBuiltinExtension).map((input) => [input.name, input]));
this.packageManager = new DefaultPackageManager({
cwd: this.cwd,
agentDir: this.agentDir,
settingsManager: this.settingsManager,
builtinExtensions: [...this.builtinExtensions.keys()],
});
this.additionalExtensionPaths = options.additionalExtensionPaths ?? [];
this.additionalSkillPaths = options.additionalSkillPaths ?? [];
this.additionalPromptTemplatePaths = options.additionalPromptTemplatePaths ?? [];
this.additionalThemePaths = options.additionalThemePaths ?? [];
this.additionalHookPaths = options.additionalHookPaths ?? [];
this.builtinExtensionFactories =
options.mcpRegistry === undefined
? builtinExtensions
: builtinExtensions.map((extension) => extension.id === "mcp"
? {
...extension,
factory: (pi) => createMcpExtension(new McpService({ mcpRegistry: options.mcpRegistry }))(pi),
}
: extension);
this.builtinExtensionFactories = [...this.builtinExtensionFactories, ...hostFactories];
this.noExtensions = options.noExtensions ?? false;
this.noSkills = options.noSkills ?? false;
this.noPromptTemplates = options.noPromptTemplates ?? false;
this.noThemes = options.noThemes ?? false;
this.noContextFiles = options.noContextFiles ?? false;
this.systemPromptSource = options.systemPrompt;
this.appendSystemPromptSource = options.appendSystemPrompt;
this.extensionsOverride = options.extensionsOverride;
this.skillsOverride = options.skillsOverride;
this.promptsOverride = options.promptsOverride;
this.themesOverride = options.themesOverride;
this.agentsFilesOverride = options.agentsFilesOverride;
this.extensionsResult = { extensions: [], errors: [], runtime: createExtensionRuntime() };
this.skills = [];
this.skillDiagnostics = [];
this.prompts = [];
this.promptDiagnostics = [];
this.themes = [];
this.themeDiagnostics = [];
this.agentsFiles = [];
this.appendSystemPrompt = [];
this.appendSystemPromptSourcePaths = [];
this.lastSkillPaths = [];
this.extensionSkillSourceInfos = new Map();
this.extensionPromptSourceInfos = new Map();
this.extensionThemeSourceInfos = new Map();
this.resourceMetadataByPath = new Map();
this.lastPromptPaths = [];
this.lastThemePaths = [];
this.globalHookSourcePaths = [];
this.projectHookSourcePaths = [];
this.preSessionHookSourcePaths = [];
this.loadedHookSources = this.buildLoadedHookSources([]);
this.loaded = false;
}
getExtensions() {
return this.extensionsResult;
}
emitExtensionEvent(channel, data) {
this.eventBus.emit(channel, data);
}
onExtensionEvent(channel, handler) {
return this.eventBus.on(channel, handler);
}
getSkills() {
return { skills: this.skills, diagnostics: this.skillDiagnostics };
}
getPrompts() {
return { prompts: this.prompts, diagnostics: this.promptDiagnostics };
}
getThemes() {
return { themes: this.themes, diagnostics: this.themeDiagnostics };
}
getAgentsFiles() {
return { agentsFiles: this.agentsFiles, diagnostics: this.contextDiagnostics };
}
getSystemPrompt() {
return this.systemPrompt;
}
getSystemPromptSource() {
return this.systemPromptSourcePath ? { path: this.systemPromptSourcePath } : undefined;
}
getAppendSystemPrompt() {
return this.appendSystemPrompt;
}
getLoadedHookSources() {
return this.loadedHookSources;
}
getAppendSystemPromptSources() {
return this.appendSystemPromptSourcePaths.map((path) => ({ path }));
}
extendResources(paths) {
const skillPaths = this.normalizeExtensionPaths(paths.skillPaths ?? []);
const promptPaths = this.normalizeExtensionPaths(paths.promptPaths ?? []);
const themePaths = this.normalizeExtensionPaths(paths.themePaths ?? []);
const hookPaths = this.normalizeExtensionPaths(paths.hookPaths ?? []);
for (const entry of skillPaths) {
this.extensionSkillSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));
}
for (const entry of promptPaths) {
this.extensionPromptSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));
}
for (const entry of themePaths) {
this.extensionThemeSourceInfos.set(entry.path, createSourceInfo(entry.path, entry.metadata));
}
if (skillPaths.length > 0) {
this.lastSkillPaths = this.mergePaths(this.lastSkillPaths, skillPaths.map((entry) => entry.path));
this.updateSkillsFromPaths(this.lastSkillPaths, this.resourceMetadataByPath);
}
if (promptPaths.length > 0) {
this.lastPromptPaths = this.mergePaths(this.lastPromptPaths, promptPaths.map((entry) => entry.path));
this.updatePromptsFromPaths(this.lastPromptPaths, this.resourceMetadataByPath);
}
if (themePaths.length > 0) {
this.lastThemePaths = this.mergePaths(this.lastThemePaths, themePaths.map((entry) => entry.path));
this.updateThemesFromPaths(this.lastThemePaths, this.resourceMetadataByPath);
}
if (hookPaths.length > 0) {
const runtimeHookSourcePaths = this.mergePaths([...this.loadedHookSources.runtimeHookSourcePaths], hookPaths.map((entry) => entry.path));
this.loadedHookSources = this.buildLoadedHookSources(runtimeHookSourcePaths);
}
}
async loadProjectTrustExtensions(options = {}) {
// Force untrusted project settings for the bootstrap pass. This keeps project-local
// extensions/packages out while still loading user/global and temporary CLI extensions.
this.settingsManager.setProjectTrusted(false);
await this.settingsManager.reload();
return this.loadCurrentExtensionSet({ includeInlineFactories: true, ...options });
}
async reload(options) {
resetTimings("extensions");
// A re-load of this loader is the signal that disk may have changed - it
// must not read package resolution through the host memo (a package's own
// manifest is not in the key). The extension module cache needs no clearing:
// it drops its generation itself when a compiled source file changes, and
// clearing it here compiled an unevictable module graph on every reload.
const refresh = this.loaded;
this.ensureGlobalDefaultExtensions();
let preTrustExtensions;
if (options?.resolveProjectTrust) {
preTrustExtensions = await this.loadProjectTrustExtensions({ refresh });
const projectTrusted = await options.resolveProjectTrust({ extensionsResult: preTrustExtensions });
this.settingsManager.setProjectTrusted(projectTrusted);
}
// reload() preserves SettingsManager.projectTrusted and reloads settings for that trust state.
const settingsAreFresh = options?.settingsAlreadyReloadedFor === this.settingsManager && options?.resolveProjectTrust === undefined;
if (!settingsAreFresh) {
await this.settingsManager.reload();
}
const { resolvedPaths, cliExtensionPaths } = await this.resolvePackagePaths({ refresh });
this.userSkillRoots = [...(resolvedPaths.skillRoots ?? []), ...(cliExtensionPaths.skillRoots ?? [])]
.filter((selection) => selection.kind === "user")
.map((selection) => selection.selectedRoot);
this.ignoredSkillFiles = this.noSkills ? [] : [...(resolvedPaths.ignoredSkills ?? [])];
time("packageResolve", "extensions");
// Keep package metadata available for later extendResources() passes.
this.resourceMetadataByPath = new Map();
const metadataByPath = this.resourceMetadataByPath;
this.extensionSkillSourceInfos = new Map();
this.extensionPromptSourceInfos = new Map();
this.extensionThemeSourceInfos = new Map();
// Helper to extract enabled paths and store metadata
const getEnabledResources = (resources) => {
for (const r of resources) {
if (!metadataByPath.has(r.path)) {
metadataByPath.set(r.path, r.metadata);
}
}
return resources.filter((r) => r.enabled);
};
const getEnabledPaths = (resources) => getEnabledResources(resources).map((r) => r.path);
const enabledExtensions = getEnabledPaths(resolvedPaths.extensions);
const enabledSkillResources = getEnabledResources(resolvedPaths.skills);
const enabledPrompts = getEnabledPaths(resolvedPaths.prompts);
const enabledThemes = getEnabledPaths(resolvedPaths.themes);
const enabledHookResources = getEnabledResources(resolvedPaths.hooks);
const enabledSkills = enabledSkillResources.map((resource) => this.mapSkillPath(resource, metadataByPath));
// Add CLI paths metadata. Explicit -e/-s resources must keep CLI precedence
// even when they resolve through a package manifest. A package that declared
// itself part of the harness keeps the system scope and root it resolved to.
const cliMetadata = (resource) => resource.metadata.scope === "system"
? {
source: "cli",
scope: "system",
origin: "top-level",
baseDir: resource.metadata.baseDir,
skillProvenance: {
kind: "user",
selectedRoot: resource.metadata.skillProvenance?.selectedRoot ?? resource.path,
},
}
: {
source: "cli",
scope: "temporary",
origin: "top-level",
skillProvenance: {
kind: "user",
selectedRoot: resource.metadata.skillProvenance?.selectedRoot ?? resource.path,
},
};
for (const resources of [
cliExtensionPaths.extensions,
cliExtensionPaths.skills,
cliExtensionPaths.prompts,
cliExtensionPaths.themes,
cliExtensionPaths.hooks,
]) {
for (const r of resources) {
metadataByPath.set(r.path, cliMetadata(r));
}
}
const cliEnabledExtensions = getEnabledPaths(cliExtensionPaths.extensions);
const cliEnabledSkills = getEnabledPaths(cliExtensionPaths.skills);
const cliEnabledPrompts = getEnabledPaths(cliExtensionPaths.prompts);
const cliEnabledThemes = getEnabledPaths(cliExtensionPaths.themes);
const cliEnabledHooks = getEnabledPaths(cliExtensionPaths.hooks);
this.globalHookSourcePaths = enabledHookResources
.filter((resource) => resource.metadata.scope === "user")
.map((resource) => resource.path);
this.projectHookSourcePaths = enabledHookResources
.filter((resource) => resource.metadata.scope === "project")
.map((resource) => resource.path);
this.preSessionHookSourcePaths = this.mergePaths(cliEnabledHooks, this.additionalHookPaths);
this.loadedHookSources = this.buildLoadedHookSources([...this.loadedHookSources.runtimeHookSourcePaths]);
const extensionPaths = this.noExtensions
? cliEnabledExtensions
: this.mergePaths(cliEnabledExtensions, enabledExtensions);
// `builtin:<name>` paths name no file, so they never take part in package-identity dedupe.
const shadowedExtensionPaths = this.shadowVendoredBuiltinExtensionPaths(extensionPaths, metadataByPath);
const dedupedFilePaths = new Set(dedupePathsByPackageIdentity(shadowedExtensionPaths.filter((path) => !isSyntheticPath(path))));
const dedupedExtensionPaths = shadowedExtensionPaths.filter((path) => isSyntheticPath(path) || dedupedFilePaths.has(path));
const packageWarnings = collectExtensionPackageWarnings(dedupedExtensionPaths, metadataByPath);
const extensionsResult = await this.loadFinalExtensionSet(dedupedExtensionPaths, preTrustExtensions);
mergeExtensionWarnings(extensionsResult, packageWarnings);
mergeExtensionWarnings(extensionsResult, this.deniedSeedWarnings);
for (const p of this.additionalExtensionPaths) {
if (isLocalPath(p)) {
const resolved = this.resolveResourcePath(p);
if (!existsSync(resolved)) {
extensionsResult.errors.push({ path: resolved, error: `Extension path does not exist: ${resolved}` });
}
}
}
this.extensionsResult = this.extensionsOverride ? this.extensionsOverride(extensionsResult) : extensionsResult;
this.applyExtensionSourceInfo(this.extensionsResult.extensions, metadataByPath);
const skillPaths = dedupePathsByPackageIdentity(this.noSkills
? this.mergePaths(cliEnabledSkills, this.additionalSkillPaths)
: this.mergePaths([...cliEnabledSkills, ...enabledSkills], this.additionalSkillPaths));
this.lastSkillPaths = skillPaths;
this.updateSkillsFromPaths(skillPaths, metadataByPath);
time("skills", "extensions");
for (const p of this.additionalSkillPaths) {
if (isLocalPath(p)) {
const resolved = this.resolveResourcePath(p);
if (!existsSync(resolved) && !this.skillDiagnostics.some((d) => d.path === resolved)) {
this.skillDiagnostics.push({ type: "error", message: "Skill path does not exist", path: resolved });
}
}
}
const promptPaths = this.noPromptTemplates
? this.mergePaths(cliEnabledPrompts, this.additionalPromptTemplatePaths)
: this.mergePaths([...cliEnabledPrompts, ...enabledPrompts], this.additionalPromptTemplatePaths);
this.lastPromptPaths = promptPaths;
this.updatePromptsFromPaths(promptPaths, metadataByPath);
time("prompts", "extensions");
for (const p of this.additionalPromptTemplatePaths) {
if (isLocalPath(p)) {
const resolved = this.resolveResourcePath(p);
if (!existsSync(resolved) && !this.promptDiagnostics.some((d) => d.path === resolved)) {
this.promptDiagnostics.push({
type: "error",
message: "Prompt template path does not exist",
path: resolved,
});
}
}
}
const themePaths = this.noThemes
? this.mergePaths(cliEnabledThemes, this.additionalThemePaths)
: this.mergePaths([...cliEnabledThemes, ...enabledThemes], this.additionalThemePaths);
this.lastThemePaths = themePaths;
this.updateThemesFromPaths(themePaths, metadataByPath);
time("themes", "extensions");
for (const p of this.additionalThemePaths) {
const resolved = this.resolveResourcePath(p);
if (!existsSync(resolved) && !this.themeDiagnostics.some((d) => d.path === resolved)) {
this.themeDiagnostics.push({ type: "error", message: "Theme path does not exist", path: resolved });
}
}
const agentsFiles = {
agentsFiles: this.noContextFiles
? Object.assign([], { diagnostics: [] })
: loadProjectContextFiles({
cwd: this.cwd,
agentDir: this.agentDir,
...this.settingsManager.getSettings().contextFiles,
// senpi#5567: user settings only; a project's settings never redirect the global file.
globalPath: this.settingsManager.getGlobalContextFilePath(),
}),
};
const resolvedAgentsFiles = this.agentsFilesOverride ? this.agentsFilesOverride(agentsFiles) : agentsFiles;
this.agentsFiles = [...resolvedAgentsFiles.agentsFiles];
this.contextDiagnostics = agentsFiles.agentsFiles.diagnostics;
time("contextFiles", "extensions");
// SYSTEM.md / APPEND_SYSTEM.md file discovery was intentionally removed; the explicit
// options are the only static prompt source (see packages/coding-agent/changes.md).
this.systemPrompt = resolvePromptInput(this.systemPromptSource, "system prompt");
this.appendSystemPrompt = (this.appendSystemPromptSource ?? [])
.map((source) => resolvePromptInput(source, "append system prompt"))
.filter((source) => source !== undefined);
this.systemPromptSourcePath =
this.systemPromptSource && existsSync(this.systemPromptSource)
? resolvePath(this.systemPromptSource)
: undefined;
this.appendSystemPromptSourcePaths = (this.appendSystemPromptSource ?? [])
.filter((source) => existsSync(source))
.map((source) => resolvePath(source));
this.loaded = true;
}
ensureGlobalDefaultExtensions() {
if (resolve(this.agentDir) !== resolve(getAgentDir())) {
return;
}
const extensionsDir = join(this.agentDir, "extensions");
this.deniedSeedWarnings = [];
if (!seedWritable(() => mkdirSync(extensionsDir, { recursive: true }), extensionsDir, this.deniedSeedWarnings))
return;
for (const extensionId of globalDefaultExtensionIds) {
const modulePath = getGlobalDefaultExtensionModulePath(extensionId);
const targetPath = getGlobalDefaultExtensionShimPath(this.agentDir, extensionId);
if (!existsSync(modulePath)) {
// This engine has no on-disk builtin to point a shim at (a compiled binary). A shim an
// earlier install generated, whose target is gone, can only fail to load: remove it (#2765).
removeDeadGeneratedShim(targetPath);
continue;
}
const shim = buildGlobalDefaultExtensionShim(modulePath);
if (existsSync(targetPath)) {
const existing = readFileSync(targetPath, "utf-8");
if (existing === shim || !isGeneratedGlobalDefaultExtensionShim(existing)) {
continue;
}
seedWritable(() => writeFileSync(targetPath, shim, "utf-8"), targetPath, this.deniedSeedWarnings);
continue;
}
seedWritable(() => writeFileSync(targetPath, shim, "utf-8"), targetPath, this.deniedSeedWarnings);
}
}
resolvePackagePaths(options = {}) {
return memoizeResolvedPaths(resolvedPathsMemoKey({
agentDir: this.agentDir,
cwd: this.cwd,
projectTrusted: this.settingsManager.isProjectTrusted(),
globalSettings: this.settingsManager.getGlobalSettings(),
projectSettings: this.settingsManager.getProjectSettings(),
additionalExtensionPaths: this.additionalExtensionPaths,
}), async () => ({
resolvedPaths: await this.packageManager.resolve(),
cliExtensionPaths: await this.packageManager.resolveExtensionSources(this.additionalExtensionPaths, {
temporary: true,
}),
}), options);
}
buildGlobalDefaultExtensionLoadOptions() {
return {
factoryResolver: (_extensionPath, resolvedPath) => resolveGeneratedGlobalDefaultExtensionFactory(resolvedPath, this.agentDir),
...this.extensionSession,
};
}
async loadCurrentExtensionSet(options) {
const { resolvedPaths, cliExtensionPaths } = await this.resolvePackagePaths({ refresh: options.refresh });
const enabledExtensions = resolvedPaths.extensions.filter((r) => r.enabled).map((r) => r.path);
const cliEnabledExtensions = cliExtensionPaths.extensions.filter((r) => r.enabled).map((r) => r.path);
// Built-in extensions wait for the final pass: project settings can disable them, and a loaded
// extension cannot be unloaded.
const extensionPaths = (this.noExtensions ? cliEnabledExtensions : this.mergePaths(cliEnabledExtensions, enabledExtensions)).filter((path) => !path.startsWith(BUILTIN_PATH_PREFIX));
const metadataByPath = new Map([...resolvedPaths.extensions, ...cliExtensionPaths.extensions].map((resource) => [
resource.path,
resource.metadata,
]));
const packageWarnings = collectExtensionPackageWarnings(extensionPaths, metadataByPath);
const extensionsResult = await loadExtensions(extensionPaths, this.cwd, this.eventBus, undefined, this.buildGlobalDefaultExtensionLoadOptions());
mergeExtensionWarnings(extensionsResult, packageWarnings);
if (!options.includeInlineFactories) {
return extensionsResult;
}
const inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime);
extensionsResult.extensions.push(...inlineExtensions.extensions);
extensionsResult.errors.push(...inlineExtensions.errors);
const replacementWarnings = [];
extensionsResult.extensions = omitReplacedExtensions(extensionsResult.extensions, replacementWarnings);
mergeExtensionWarnings(extensionsResult, replacementWarnings);
return extensionsResult;
}
resolveExtensionLoadPath(path) {
return isSyntheticPath(path) ? path : resolvePath(path, this.cwd, { normalizeUnicodeSpaces: true });
}
/**
* Load extension paths: files from disk and `builtin:<name>` paths. A name resolves first against the
* caller-supplied built-in inline extensions, then against the fork builtin registry
* (`extensions/builtin/index.ts`), so `-e builtin:<id>` loads a registry builtin the settings disabled;
* one that is already active loads as `<builtin:id>` from `loadExtensionFactories()`, so naming it
* again is a no-op.
*/
async loadExtensionPaths(paths, runtime) {
const isBuiltinPath = (path) => path.startsWith(BUILTIN_PATH_PREFIX);
const result = await loadExtensions(paths.filter((path) => !isBuiltinPath(path)), this.cwd, this.eventBus, runtime, this.buildGlobalDefaultExtensionLoadOptions());
const builtinPaths = paths.filter(isBuiltinPath);
const activeRegistryIds = builtinPaths.length > 0 ? this.getActiveBuiltinExtensionIds() : new Set();
for (const path of builtinPaths) {
const name = path.slice(BUILTIN_PATH_PREFIX.length);
const registryBuiltin = this.builtinExtensionFactories.find((extension) => extension.id === name);
const builtin = this.builtinExtensions.get(name);
if (!builtin && registryBuiltin && activeRegistryIds.has(name))
continue;
const factory = builtin?.factory ?? registryBuiltin?.factory;
if (!factory) {
result.errors.push({ path, error: `Unknown built-in extension: ${path}` });
continue;
}
try {
const extension = await loadExtensionFromFactory(factory, this.cwd, this.eventBus, result.runtime, path, this.extensionSession);
extension.hidden = builtin !== undefined;
extension.replaceable = builtin?.replaceable === true;
result.extensions.push(extension);
}
catch (error) {
result.errors.push({ path, error: error instanceof Error ? error.message : "failed to load extension" });
}
}
return result;
}
async loadFinalExtensionSet(extensionPaths, preTrustExtensions) {
if (!preTrustExtensions) {
const extensionsResult = await this.loadExtensionPaths(extensionPaths);
const inlineExtensions = await this.loadExtensionFactories(extensionsResult.runtime);
extensionsResult.extensions.unshift(...inlineExtensions.extensions);
const replacementWarnings = [];
extensionsResult.extensions = omitReplacedExtensions(extensionsResult.extensions, replacementWarnings);
mergeExtensionWarnings(extensionsResult, replacementWarnings);
this.rebuildExtensionFlagDefaults(extensionsResult);
extensionsResult.errors.push(...inlineExtensions.errors);
this.addExtensionConflictDiagnostics(extensionsResult);
return extensionsResult;
}
const preloaded = preTrustExtensions.extensions;
const preloadedByPath = new Map(preloaded
.filter((extension) => !extension.path.startsWith("<inline:"))
.map((extension) => [extension.resolvedPath, extension]));
const failedPreloadPaths = new Set(preTrustExtensions.errors.map((error) => this.resolveExtensionLoadPath(error.path)));
const remainingPaths = extensionPaths.filter((path) => {
const resolvedPath = this.resolveExtensionLoadPath(path);
return !preloadedByPath.has(resolvedPath) && !failedPreloadPaths.has(resolvedPath);
});
const remainingExtensions = await this.loadExtensionPaths(remainingPaths, preTrustExtensions.runtime);
const loadedByPath = new Map(preloadedByPath);
for (const extension of remainingExtensions.extensions) {
loadedByPath.set(extension.resolvedPath, extension);
}
const bundledExtensionPaths = this.getBundledExtensionEntryPaths();
const factoryExtensions = preTrustExtensions.extensions.filter((extension) => extension.path.startsWith("<builtin:") ||
extension.path.startsWith("<inline:") ||
bundledExtensionPaths.has(extension.resolvedPath));
const orderedExtensions = extensionPaths
.map((path) => loadedByPath.get(this.resolveExtensionLoadPath(path)))
.filter((extension) => extension !== undefined);
orderedExtensions.unshift(...factoryExtensions);
const replacementWarnings = [];
const extensionsResult = {
extensions: omitReplacedExtensions(orderedExtensions, replacementWarnings),
errors: [...preTrustExtensions.errors, ...remainingExtensions.errors],
warnings: [...(preTrustExtensions.warnings ?? []), ...(remainingExtensions.warnings ?? [])],
runtime: preTrustExtensions.runtime,
eventBus: preTrustExtensions.eventBus ?? remainingExtensions.eventBus ?? this.eventBus,
};
mergeExtensionWarnings(extensionsResult, replacementWarnings);
this.rebuildExtensionFlagDefaults(extensionsResult);
this.addExtensionConflictDiagnostics(extensionsResult);
return extensionsResult;
}
addExtensionConflictDiagnostics(extensionsResult) {
// Detect extension conflicts (tools, commands, flags with same names from different extensions)
// Keep all extensions loaded. Conflicts are reported as diagnostics, and precedence is handled by load order.
const conflicts = this.detectExtensionConflicts(extensionsResult.extensions);
for (const conflict of conflicts) {
extensionsResult.errors.push({ path: conflict.path, error: conflict.message });
}
}
mapSkillPath(resource, metadataByPath) {
if (resource.metadata.source !== "auto" && resource.metadata.origin !== "package") {
return resource.path;
}
try {
const stats = statSync(resource.path);
if (!stats.isDirectory()) {
return resource.path;
}
}
catch {
return resource.path;
}
const skillFile = join(resource.path, "SKILL.md");
if (existsSync(skillFile)) {
if (!metadataByPath.has(skillFile)) {
metadataByPath.set(skillFile, resource.metadata);
}
return skillFile;
}
return resource.path;
}
normalizeExtensionPaths(entries) {
return entries.map((entry) => {
const metadata = entry.metadata.baseDir
? { ...entry.metadata, baseDir: this.resolveResourcePath(entry.metadata.baseDir) }
: entry.metadata;
return {
path: this.resolveResourcePath(entry.path),
metadata,
};
});
}
buildLoadedHookSources(runtimeHookSourcePaths) {
return {
agentDir: this.agentDir,
cwd: this.cwd,
globalHookSourcePaths: this.globalHookSourcePaths.map((path) => this.resolveResourcePath(path)),
globalHooksPath: this.resolveResourcePath(join(this.agentDir, "hooks.json")),
preSessionHookSourcePaths: this.preSessionHookSourcePaths.map((path) => this.resolveResourcePath(path)),
projectHookSourcePaths: this.projectHookSourcePaths.map((path) => this.resolveResourcePath(path)),
projectHooksPath: this.resolveResourcePath(join(this.cwd, CONFIG_DIR_NAME, "hooks.json")),
runtimeHookSourcePaths: runtimeHookSourcePaths.map((path) => this.resolveResourcePath(path)),
};
}
updateSkillsFromPaths(skillPaths, metadataByPath) {
let skillsResult;
if (this.noSkills && skillPaths.length === 0) {
skillsResult = { skills: [], diagnostics: [] };
}
else {
skillsResult = loadSkills({
cwd: this.cwd,
agentDir: this.agentDir,
skillPaths,
includeDefaults: false,
provenanceByPath: new Map(skillPaths.map((path) => [
path,
metadataByPath?.get(path)?.skillProvenance ?? { kind: "user", selectedRoot: path },
])),
userSkillRoots: [
...this.userSkillRoots,
...(this.settingsManager.getGlobalSettings().skills ?? [])
.filter((path) => !/^[!+-]/.test(path))
.map((path) => resolvePath(path, this.agentDir, { trim: true })),
],
});
}
const resolvedSkills = this.skillsOverride ? this.skillsOverride(skillsResult) : skillsResult;
this.skills = resolvedSkills.skills.map((skill) => ({
...skill,
sourceInfo: this.findSourceInfoForPath(skill.filePath, this.extensionSkillSourceInfos, metadataByPath) ??
skill.sourceInfo ??
this.getDefaultSourceInfoForPath(skill.filePath),
}));
this.skillDiagnostics = [
...resolvedSkills.diagnostics,
...ignoredSkillDiagnostics(this.ignoredSkillFiles, this.skills),
...warnIfLargeSkillCatalog(this.skills),
];
}
updatePromptsFromPaths(promptPaths, metadataByPath) {
let promptsResult;
if (this.noPromptTemplates && promptPaths.length === 0) {
promptsResult = { prompts: [], diagnostics: [] };
}
else {
const loaded = loadPromptTemplates({
cwd: this.cwd,
agentDir: this.agentDir,
promptPaths,
includeDefaults: false,
});
const deduped = this.dedupePrompts(loaded.templates);
promptsResult = {
prompts: deduped.prompts,
diagnostics: [...loaded.diagnostics, ...deduped.diagnostics],
};
}
const resolvedPrompts = this.promptsOverride ? this.promptsOverride(promptsResult) : promptsResult;
this.prompts = resolvedPrompts.prompts.map((prompt) => ({
...prompt,
sourceInfo: this.findSourceInfoForPath(prompt.filePath, this.extensionPromptSourceInfos, metadataByPath) ??
prompt.sourceInfo ??
this.getDefaultSourceInfoForPath(prompt.filePath),
}));
this.promptDiagnostics = resolvedPrompts.diagnostics;
}
updateThemesFromPaths(themePaths, metadataByPath) {
let themesResult;
if (this.noThemes && themePaths.length === 0) {
themesResult = { themes: [], diagnostics: [] };
}
else {
// Theme construction only needs trueColor, so skip the unrelated tmux hyperlink probe.
const colorMode = getTerminalColorMode({
...detectCapabilities(() => false),
...this.settingsManager.getTerminalCapabilityOverrides(),
});
const loaded = this.loadThemes(themePaths, false, colorMode);
const deduped = this.dedupeThemes(loaded.themes);
themesResult = { themes: deduped.themes, diagnostics: [...loaded.diagnostics, ...deduped.diagnostics] };
}
const resolvedThemes = this.themesOverride ? this.themesOverride(themesResult) : themesResult;
this.themes = resolvedThemes.themes.map((theme) => {
const sourcePath = theme.sourcePath;
theme.sourceInfo = sourcePath
? (this.findSourceInfoForPath(sourcePath, this.extensionThemeSourceInfos, metadataByPath) ??
theme.sourceInfo ??
this.getDefaultSourceInfoForPath(sourcePath))
: theme.sourceInfo;
return theme;
});
this.themeDiagnostics = resolvedThemes.diagnostics;
}
applyExtensionSourceInfo(extensions, metadataByPath) {
const bundledPackageRoots = this.getBundledExtensionPackageRoots();
for (const extension of extensions) {
extension.sourceInfo =
this.getHarnessExtensionSourceInfo(extension, bundledPackageRoots) ??
this.findSourceInfoForPath(extension.path, undefined, metadataByPath) ??
this.getDefaultSourceInfoForPath(extension.path);
for (const command of extension.commands.values()) {
command.sourceInfo = extension.sourceInfo;
}
for (const tool of extension.tools.values()) {
tool.sourceInfo = extension.sourceInfo;
}
}
}
findSourceInfoForPath(resourcePath, extraSourceInfos, metadataByPath) {
if (!resourcePath) {
return undefined;
}
if (isSyntheticPath(resourcePath)) {
return this.getDefaultSourceInfoForPath(resourcePath);
}
const normalizedResourcePath = resolve(resourcePath);
if (extraSourceInfos) {
for (const [sourcePath, sourceInfo] of extraSourceInfos.entries()) {
const normalizedSourcePath = resolve(sourcePath);
if (normalizedResourcePath === normalizedSourcePath ||
normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)) {
return { ...sourceInfo, path: resourcePath };
}
}
}
if (metadataByPath) {
const exact = metadataByPath.get(normalizedResourcePath) ?? metadataByPath.get(resourcePath);
if (exact) {
return createSourceInfo(resourcePath, exact);
}
for (const [sourcePath, metadata] of metadataByPath.entries()) {
const normalizedSourcePath = resolve(sourcePath);
if (normalizedResourcePath === normalizedSourcePath ||
normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)) {
return createSourceInfo(resourcePath, metadata);
}
}
}
return undefined;
}
getDefaultSourceInfoForPath(filePath) {
const source = getSyntheticPathSource(filePath);
if (source) {
return {
path: filePath,
source,
scope: source === "builtin" ? "system" : "temporary",
origin: "top-level",
};
}
const normalizedPath = resolve(filePath);
const agentRoots = [
join(this.agentDir, "skills"),
join(this.agentDir, "prompts"),
join(this.agentDir, "themes"),
join(this.agentDir, "extensions"),
];
const projectRoots = [
join(this.cwd, CONFIG_DIR_NAME, "skills"),
join(this.cwd, CONFIG_DIR_NAME, "prompts"),
join(this.cwd, CONFIG_DIR_NAME, "themes"),
join(this.cwd, CONFIG_DIR_NAME, "extensions"),
];
for (const root of agentRoots) {
if (this.isUnderPath(normalizedPath, root)) {
return { path: filePath, source: "local", scope: "user", origin: "top-level", baseDir: root };
}
}
for (const root of projectRoots) {
if (this.isUnderPath(normalizedPath, root)) {
return { path: filePath, source: "local", scope: "project", origin: "top-level", baseDir: root };
}
}
return {
path: filePath,
source: "local",
scope: "temporary",
origin: "top-level",
baseDir: statSync(normalizedPath).isDirectory() ? normalizedPath : resolve(normalizedPath, ".."),
};
}
mergePaths(primary, additional) {
const merged = [];
const seen = new Set();
for (const p of [...primary, ...additional]) {
const resolved = this.resolveResourcePath(p);
const canonicalPath = canonicalizePath(resolved);
if (seen.has(canonicalPath))
continue;
seen.add(canonicalPath);
merged.push(resolved);
}
return merged;
}
resolveResourcePath(p) {
return isSyntheticPath(p) ? p : resolvePath(p, this.cwd, { trim: true });
}
getActiveBuiltinExtensionIds() {
const enabledBuiltinExtensions = this.settingsManager.getEnabledBuiltinExtensions();
const enabledBuiltinExtensionSet = enabledBuiltinExtensions ? new Set(enabledBuiltinExtensions) : undefined;
const disabledBuiltinExtensions = new Set(this.settingsManager.getDisabledBuiltinExtensions());
const activeBuiltinExtensionIds = new Set();
for (const builtinExtension of this.builtinExtensionFactories) {
if (enabledBuiltinExtensionSet && !enabledBuiltinExtensionSet.has(builtinExtension.id)) {
continue;
}
if (disabledBuiltinExtensions.has(builtinExtension.id)) {
continue;
}
activeBuiltinExtensionIds.add(builtinExtension.id);
}
for (const bundledExtension of bundledBuiltinExtensions) {
if (enabledBuiltinExtensionSet && !enabledBuiltinExtensionSet.has(bundledExtension.id)) {
continue;
}
if (disabledBuiltinExtensions.has(bundledExtension.id)) {
continue;
}
activeBuiltinExtensionIds.add(bundledExtension.id);
}
return activeBuiltinExtensionIds;
}
getShadowedVendoredBuiltinPackageNames() {
const activeBuiltinExtensionIds = this.getActiveBuiltinExtensionIds();
const packageNames = new Set();
for (const { builtinId, packageName } of VENDORED_BUILTIN_EXTENSION_PACKAGES) {
if (activeBuiltinExtensionIds.has(builtinId)) {
packageNames.add(packageName);
}
}
return packageNames;
}
shadowVendoredBuiltinExtensionPaths(extensionPaths, metadataByPath) {
const shadowedPackageNames = this.getShadowedVendoredBuiltinPackageNames();
if (shadowedPackageNames.size === 0) {
return extensionPaths;
}
const filteredPaths = [];
for (const extensionPath of extensionPaths) {
if (isSyntheticPath(extensionPath)) {
filteredPaths.push(extensionPath);
continue;
}
const metadata = metadataByPath.get(extensionPath) ?? metadataByPath.get(resolve(extensionPath));
if (metadata?.source === "cli") {
filteredPaths.push(extensionPath);
continue;
}
const packageIdentity = findNearestPackageIdentity(extensionPath);
if (packageIdentity && shadowedPackageNames.has(packageIdentity.packageName)) {
continue;
}
filteredPaths.push(extensionPath);
}
return filteredPaths;
}
loadThemes(paths, includeDefaults, colorMode) {
const themes = [];
const diagnostics = [];
if (includeDefaults) {
const defaultDirs = [join(this.agentDir, "themes"), join(this.cwd, CONFIG_DIR_NAME, "themes")];
for (const dir of defaultDirs) {
this.loadThemesFromDir(dir, themes, diagnostics, colorMode);
}
}
for (const p of paths) {
const resolved = this.resolveResourcePath(p);
if (!existsSync(resolved)) {
diagnostics.push({ type: "warning", message: "theme path does not exist", path: resolved });
continue;
}
try {
const stats = statSync(resolved);
if (stats.isDirectory()) {
this.loadThemesFromDir(resolved, themes, diagnostics, colorMode);
}
else if (stats.isFile() && resolved.endsWith(".json")) {
this.loadThemeFromFile(resolved, themes, diagnostics, colorMode);
}
else {
diagnostics.push({ type: "warning", message: "theme path is not a json file", path: resolved });
}
}
catch (error) {
const message = error instanceof Error ? error.message : "failed to read theme path";
diagnostics.push({ type: "warning", message, path: resolved });
}
}
return { themes, diagnostics };
}
loadThemesFromDir(dir, themes, diagnostics, colorMode) {
if (!existsSync(dir)) {
return;
}
try {
const entries = readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
let isFile = entry.isFile();
if (entry.isSymbolicLink()) {
try {
isFile = statSync(join(dir, entry.name)).isFile();
}
catch {
continue;
}
}
if (!isFile) {
continue;
}
if (!entry.name.endsWith(".json")) {
continue;
}
this.loadThemeFromFile(join(dir, entry.name), themes, diagnostics, colorMode);
}
}
catch (error) {
const message = error instanceof Error ? error.message : "failed to read theme directory";
diagnostics.push({ type: "warning", message, path: dir });
}
}
loadThemeFromFile(filePath, themes, diagnostics, colorMode) {
try {
themes.push(loadThemeFromPath(filePath, colorMode));
}
catch (error) {
const message = error instanceof Error ? error.message : "failed to load theme";
diagnostics.push({ type: "warning", message, path: filePath });
}
}
async loadExtensionFactories(runtime) {
const extensions = [];
const errors = [];
const activeBuiltinExtensionIds = this.getActiveBuiltinExtensionIds();
for (const builtinExtension of this.builtinExtensionFactories) {
if (!activeBuiltinExtensionIds.has(builtinExtension.id)) {
continue;
}
const extensionPath = `<builtin:${builtinExtension.id}>`;
try {
const extension = await loadExtensionFromFactory(builtinExtension.factory, this.cwd, this.eventBus, runtime, extensionPath, this.extensionSession);
extensions.push(extension);
}
catch (error) {
const message = error instanceof Error ? error.message : "failed to load extension";
errors.push({ path: extensionPath, error: message });
}
}
for (const bundledExtension of bundledBuiltinExtensions) {
if (!activeBuiltinExtensionIds.has(bundledExtension.id)) {
continue;
}
try {
const packageJsonPath = bundledExtension.resolvePackage();
const entries = this.resolvePackageExtensionEntries(packageJsonPath);
if (entries.length === 0) {
errors.push({
path: `<builtin:${bundledExtension.id}>`,
error: `Bundled extension package does not declare pi.extensions: ${packageJsonPath}`,
});
continue;
}
const bundledResult = await loadExtensions(entries, this.cwd, this.eventBus, runtime, this.extensionSession);
for (const extension of bundledResult.extensions) {
if (isBunBinary)
extension.path = `<builtin:${bundledExtension.id}>`;
extensions.push(extension);
}
errors.push(...bundledResult.errors);
}
catch (error) {
const message = error instanceof Error ? error.message : "package resolution failed";
errors.push({
path: `<builtin:${bundledExtension.id}>`,
error: `Bundled extension unavailable: ${message}`,
});
}
}
for (const [index, input] of this.extensionFactories.entries()) {
const isNamed = typeof input !== "function";
const factory = isNamed ? input.factory : input;
const extensionPath = `<inline:${isNamed ? input.name : index + 1}>`;
try {
const extension = await loadExtensionFromFactory(factory, this.cwd, this.eventBus, runtime, extensionPath, this.extensionSession);
extension.hidden = isNamed && input.hidden;
extension.replaceable = isNamed && input.replaceable === true;
extensions.push(extension);
}
catch (error) {
const message = error instanceof Error ? error.message : "failed to load extension";
errors.push({ path: extensionPath, error: message });
}
}
return { extensions, errors };
}
getBundledExtensionEntryPaths() {
return new Set(this.getBundledExtensionPackageRoots().keys());
}
/**
* Source info for an extension file the harness itself provides: a bundled extension entry, or a
* global-default shim this loader generated under the agent extensions directory. A file at a shim
* path that no longer carries the generated banner is user-authored and gets no system scope.
*/
getHarnessExtensionSourceInfo(extension, bundledPackageRoots) {
const bundledPackageRoot = bundledPackageRoots.get(extension.resolvedPath);
if (bundledPackageRoot !== undefined) {
return {
path: extension.path,
source: "builtin",
scope: "system",
origin: "top-level",
baseDir: bundledPackageRoot,
};
}
if (this.isGeneratedGlobalDefaultExtensionShimPath(extension.resolvedPath)) {
return {
path: extension.path,
source: "builtin",
scope: "system",
origin: "top-level",
baseDir: join(this.agentDir, "extensions"),
};
}
return undefined;
}
isGeneratedGlobalDefaultExtensionShimPath(resolvedPath) {
const shimPath = resolve(resolvedPath);
const isShimPath = globalDefaultExtensionIds.some((extensionId) => resolve(getGlobalDefaultExtensionShimPath(this.agentDir, extensionId)) === shimPath);
if (!isShimPath) {
return false;
}
try {
return isGeneratedGlobalDefaultExtensionShim(readFileSync(shimPath, "utf-8"));
}
catch {
return false;
}
}
/** Resolved entry path of every active bundled extension mapped to the root of the package that ships it. */
getBundledExtensionPackageRoots() {
const packageRoots = new Map();
for (const bundledExtension of bundledBuiltinExtensions) {
try {
const packageJsonPath = bundledExtension.resolvePackage();
const packageRoot = resolve(packageJsonPath, "..");
for (const extensionPath of this.resolvePackageExtensionEntries(packageJsonPath)) {
packageRoots.set(this.resolveExtensionLoadPath(extensionPath), packageRoot);
}
}
catch {
// Bundled resolution errors are already reported by loadExtensionFactories().
}
}
return packageRoots;
}
resolvePackageExtensionEntries(packageJsonPath) {
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
const extensions = packageJson.pi?.extensions;
if (!Array.isArray(extensions)) {
return [];
}
const packageRoot = resolve(packageJsonPath, "..");
return extensions
.filter((extensionPath) => typeof extensionPath === "string")
.map((extensionPath) => resolve(packageRoot, extensionPath));
}
dedupePrompts(prompts) {
const seen = new Map();
const diagnostics = [];
for (const prompt of prompts) {
const existing = seen.get(prompt.name);
if (existing) {
diagnostics.push({
type: "collision",
message: `name "/${prompt.name}" collision`,
path: prompt.filePath,
collision: {
resourceType: "prompt",
name: prompt.name,
winnerPath: existing.filePath,
loserPath: prompt.filePath,
},
});
}
else {
seen.set(prompt.name, prompt);
}
}
return { prompts: Array.from(seen.values()), diagnostics };
}
dedupeThemes(themes) {
const seen = new Map();
const diagnostics = [];
for (const t of themes) {
const name = t.name ?? "unnamed";
const existing = seen.get(name);
if (existing) {
diagnostics.push({
type: "collision",
message: `name "${name}" collision`,
path: t.sourcePath,
collision: {
resourceType: "theme",
name,
winnerPath: existing.sourcePath ?? "<builtin>",
loserPath: t.sourcePath ?? "<builtin>",
},
});
}
else {
seen.set(name, t);
}
}
return { themes: Array.from(seen.values()), diagnostics };
}
isUnderPath(target, root) {
const normalizedRoot = resolve(root);
if (target === normalizedRoot) {
return true;
}
const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;
return target.startsWith(prefix);
}
isBuiltinExtensionPath(extensionPath) {
return extensionPath.startsWith("<builtin:");
}
shouldSuppressExtensionConflict(existingOwner, candidateOwner) {
if (this.isBuiltinExtensionPath(existingOwner) || this.isBuiltinExtensionPath(candidateOwner)) {
return true;
}
const existingPackageIdentity = findNearestPackageIdentity(existingOwner);
const candidatePackageIdentity = findNearestPackageIdentity(candidateOwner);
return existingPackageIdentity !== undefined && existingPackageIdentity.key === candidatePackageIdentity?.key;
}
rebuildExtensionFlagDefaults(extensionsResult) {
const rebuiltFlagValues = new Map();
const seenFlags = new Set();
for (const extension of extensionsResult.extensions) {
for (const [flagName, flag] of extension.flags) {
if (seenFlags.has(flagName)) {
continue;
}
seenFlags.add(flagName);
if (flag.default !== undefined) {
rebuiltFlagValues.set(flagName, flag.default);
}
}
}
extensionsResult.runtime.flagValues = rebuiltFlagValues;
}
detectExtensionConflicts(extensions) {
const conflicts = [];
// Track which extension registered each tool and flag
const toolOwners = new Map();
const flagOwners = new Map();
for (const ext of extensions) {
// Check tools
for (const toolName of ext.tools.keys()) {
const existingOwner = toolOwners.get(toolName);
if (existingOwner && existingOwner !== ext.path) {
if (this.shouldSuppressExtensionConflict(existingOwner, ext.path)) {
continue;
}
conflicts.push({
path: ext.path,
message: `Tool "${toolName}" conflicts with ${existingOwner}`,
});
}
else {
toolOwners.set(toolName, ext.path);
}
}
// Check flags
for (const flagName of ext.flags.keys()) {
const existingOwner = flagOwners.get(flagName);
if (existingOwner && existingOwner !== ext.path) {
if (this.shouldSuppressExtensionConflict(existingOwner, ext.path)) {
continue;
}
conflicts.push({
path: ext.path,
message: `Flag "--${flagName}" conflicts with ${existingOwner}`,
});
}
else {
flagOwners.set(flagName, ext.path);
}
}
}
return conflicts;
}
}
//# sourceMappingURL=resource-loader.js.map