Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

Give ignore parsing, extension discovery and path helpers one owner (#2496)

Sebastian Müller9fb6cde3fd56
diff --git a/packages/coding-agent/.changes/single-owner-resource-discovery.md b/packages/coding-agent/.changes/single-owner-resource-discovery.md
new file mode 100644
index 0000000000..b2ad8ffe4e
--- /dev/null
+++ b/packages/coding-agent/.changes/single-owner-resource-discovery.md
@@ -0,0 +1,2 @@
+- Runtime extension discovery now applies the same rules as package resource discovery: entries matched by a `.gitignore`, `.ignore` or `.fdignore` file in the extensions directory, dot entries and `node_modules` are skipped, so a directory excluded from package discovery is no longer loaded at runtime.
+- Ignore-file parsing, extension entry-point resolution, resource path expansion and path containment checks now each have one implementation instead of two to four copies, so the loaders can no longer drift apart.
diff --git a/packages/coding-agent/src/core/extensions/discovery.ts b/packages/coding-agent/src/core/extensions/discovery.ts
new file mode 100644
index 0000000000..014e6592a5
--- /dev/null
+++ b/packages/coding-agent/src/core/extensions/discovery.ts
@@ -0,0 +1,95 @@
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { join, relative, resolve } from "node:path";
+import { toPosixPath } from "../../utils/paths.js";
+import { addIgnoreRules, createIgnoreMatcher } from "../ignore-rules.js";
+
+interface PiExtensionManifest {
+ extensions?: unknown;
+}
+
+function readManifestExtensions(packageJsonPath: string): string[] | undefined {
+ try {
+ const pkg = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as { pi?: PiExtensionManifest };
+ const declared = pkg.pi?.extensions;
+ if (!Array.isArray(declared)) return undefined;
+ return declared.filter((entry) => typeof entry === "string");
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Resolve the entry points of one extension directory:
+ * package.json "pi.extensions" first, then index.ts, then index.js.
+ * Returns null when the directory declares no entry point.
+ */
+export function resolveExtensionEntries(dir: string): string[] | null {
+ const packageJsonPath = join(dir, "package.json");
+ if (existsSync(packageJsonPath)) {
+ const declared = readManifestExtensions(packageJsonPath);
+ if (declared?.length) {
+ const entries = declared.map((extPath) => resolve(dir, extPath)).filter((extPath) => existsSync(extPath));
+ if (entries.length > 0) {
+ return entries;
+ }
+ }
+ }
+
+ const indexTs = join(dir, "index.ts");
+ if (existsSync(indexTs)) {
+ return [indexTs];
+ }
+ const indexJs = join(dir, "index.js");
+ if (existsSync(indexJs)) {
+ return [indexJs];
+ }
+
+ return null;
+}
+
+/**
+ * Collect extension entry points one level below dir: direct .ts/.js files and
+ * subdirectories that declare an entry point. Entries matched by the directory's
+ * ignore files, dot entries and node_modules are skipped.
+ */
+export function collectExtensionEntries(dir: string): string[] {
+ const entries: string[] = [];
+ if (!existsSync(dir)) return entries;
+
+ const ig = createIgnoreMatcher();
+ addIgnoreRules(ig, dir, dir);
+
+ try {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.name.startsWith(".")) continue;
+ if (entry.name === "node_modules") continue;
+
+ const fullPath = join(dir, entry.name);
+ let isDir = entry.isDirectory();
+ let isFile = entry.isFile();
+
+ if (entry.isSymbolicLink()) {
+ try {
+ const stats = statSync(fullPath);
+ isDir = stats.isDirectory();
+ isFile = stats.isFile();
+ } catch {
+ continue;
+ }
+ }
+
+ const relPath = toPosixPath(relative(dir, fullPath));
+ if (ig.ignores(isDir ? `${relPath}/` : relPath)) continue;
+
+ if (isFile && (entry.name.endsWith(".ts") || entry.name.endsWith(".js"))) {
+ entries.push(fullPath);
+ } else if (isDir) {
+ entries.push(...(resolveExtensionEntries(fullPath) ?? []));
+ }
+ }
+ } catch {
+ // Unreadable directory: keep whatever was discovered so far.
+ }
+
+ return entries;
+}
diff --git a/packages/coding-agent/src/core/extensions/loader.ts b/packages/coding-agent/src/core/extensions/loader.ts
index 2c7e81ad6b..abb0d18e04 100644
--- a/packages/coding-agent/src/core/extensions/loader.ts
+++ b/packages/coding-agent/src/core/extensions/loader.ts
@@ -5,15 +5,16 @@
import * as fs from "node:fs";
import { createRequire } from "node:module";
-import * as os from "node:os";
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import type { KeyId } from "@earendil-works/pi-tui";
import { CONFIG_DIR_NAME, getAgentDir, isBunBinary } from "../../config.js";
+import { resolveUserPath } from "../../utils/paths.js";
import { createEventBus, type EventBus } from "../event-bus.js";
import type { ExecOptions } from "../exec.js";
import { execCommand } from "../exec.js";
import { createSyntheticSourceInfo } from "../source-info.js";
+import { collectExtensionEntries, resolveExtensionEntries } from "./discovery.js";
import type {
Extension,
ExtensionAPI,
@@ -81,31 +82,6 @@ function getAliases(): Record<string, string> {
return _aliases;
}
-const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
-
-function normalizeUnicodeSpaces(str: string): string {
- return str.replace(UNICODE_SPACES, " ");
-}
-
-function expandPath(p: string): string {
- const normalized = normalizeUnicodeSpaces(p);
- if (normalized.startsWith("~/")) {
- return path.join(os.homedir(), normalized.slice(2));
- }
- if (normalized.startsWith("~")) {
- return path.join(os.homedir(), normalized.slice(1));
- }
- return normalized;
-}
-
-function resolvePath(extPath: string, cwd: string): string {
- const expanded = expandPath(extPath);
- if (path.isAbsolute(expanded)) {
- return expanded;
- }
- return path.resolve(cwd, expanded);
-}
-
type HandlerFn = (...args: unknown[]) => Promise<unknown>;
/**
@@ -377,7 +353,7 @@ async function loadExtension(
eventBus: EventBus,
runtime: ExtensionRuntime,
): Promise<{ extension: Extension | null; error: string | null }> {
- const resolvedPath = resolvePath(extensionPath, cwd);
+ const resolvedPath = resolveUserPath(extensionPath, cwd);
try {
const factory = await loadExtensionModule(resolvedPath);
@@ -441,111 +417,6 @@ export async function loadExtensions(paths: string[], cwd: string, eventBus?: Ev
};
}
-interface PiManifest {
- extensions?: string[];
- themes?: string[];
- skills?: string[];
- prompts?: string[];
-}
-
-function readPiManifest(packageJsonPath: string): PiManifest | null {
- try {
- const content = fs.readFileSync(packageJsonPath, "utf-8");
- const pkg = JSON.parse(content);
- if (pkg.pi && typeof pkg.pi === "object") {
- return pkg.pi as PiManifest;
- }
- return null;
- } catch {
- return null;
- }
-}
-
-function isExtensionFile(name: string): boolean {
- return name.endsWith(".ts") || name.endsWith(".js");
-}
-
-/**
- * Resolve extension entry points from a directory.
- *
- * Checks for:
- * 1. package.json with "pi.extensions" field -> returns declared paths
- * 2. index.ts or index.js -> returns the index file
- *
- * Returns resolved paths or null if no entry points found.
- */
-function resolveExtensionEntries(dir: string): string[] | null {
- const packageJsonPath = path.join(dir, "package.json");
- if (fs.existsSync(packageJsonPath)) {
- const manifest = readPiManifest(packageJsonPath);
- if (manifest?.extensions?.length) {
- const entries: string[] = [];
- for (const extPath of manifest.extensions) {
- const resolvedExtPath = path.resolve(dir, extPath);
- if (fs.existsSync(resolvedExtPath)) {
- entries.push(resolvedExtPath);
- }
- }
- if (entries.length > 0) {
- return entries;
- }
- }
- }
-
- const indexTs = path.join(dir, "index.ts");
- const indexJs = path.join(dir, "index.js");
- if (fs.existsSync(indexTs)) {
- return [indexTs];
- }
- if (fs.existsSync(indexJs)) {
- return [indexJs];
- }
-
- return null;
-}
-
-/**
- * Discover extensions in a directory.
- *
- * Discovery rules:
- * 1. Direct files: `extensions/*.ts` or `*.js` → load
- * 2. Subdirectory with index: `extensions/* /index.ts` or `index.js` → load
- * 3. Subdirectory with package.json: `extensions/* /package.json` with "pi" field → load what it declares
- *
- * No recursion beyond one level. Complex packages must use package.json manifest.
- */
-function discoverExtensionsInDir(dir: string): string[] {
- if (!fs.existsSync(dir)) {
- return [];
- }
-
- const discovered: string[] = [];
-
- try {
- const entries = fs.readdirSync(dir, { withFileTypes: true });
-
- for (const entry of entries) {
- const entryPath = path.join(dir, entry.name);
-
- if ((entry.isFile() || entry.isSymbolicLink()) && isExtensionFile(entry.name)) {
- discovered.push(entryPath);
- continue;
- }
-
- if (entry.isDirectory() || entry.isSymbolicLink()) {
- const entries = resolveExtensionEntries(entryPath);
- if (entries) {
- discovered.push(...entries);
- }
- }
- }
- } catch {
- return [];
- }
-
- return discovered;
-}
-
/**
* Discover and load extensions from standard locations.
*/
@@ -569,20 +440,20 @@ export async function discoverAndLoadExtensions(
};
const localExtDir = path.join(cwd, CONFIG_DIR_NAME, "extensions");
- addPaths(discoverExtensionsInDir(localExtDir));
+ addPaths(collectExtensionEntries(localExtDir));
const globalExtDir = path.join(agentDir, "extensions");
- addPaths(discoverExtensionsInDir(globalExtDir));
+ addPaths(collectExtensionEntries(globalExtDir));
for (const p of configuredPaths) {
- const resolved = resolvePath(p, cwd);
+ const resolved = resolveUserPath(p, cwd);
if (fs.existsSync(resolved) && fs.statSync(resolved).isDirectory()) {
const entries = resolveExtensionEntries(resolved);
if (entries) {
addPaths(entries);
continue;
}
- addPaths(discoverExtensionsInDir(resolved));
+ addPaths(collectExtensionEntries(resolved));
continue;
}
diff --git a/packages/coding-agent/src/core/ignore-rules.ts b/packages/coding-agent/src/core/ignore-rules.ts
new file mode 100644
index 0000000000..57ecaadf5c
--- /dev/null
+++ b/packages/coding-agent/src/core/ignore-rules.ts
@@ -0,0 +1,61 @@
+import { existsSync, readFileSync } from "node:fs";
+import { join, relative } from "node:path";
+import ignore from "ignore";
+import { toPosixPath } from "../utils/paths.js";
+
+export type IgnoreMatcher = ReturnType<typeof ignore>;
+
+const IGNORE_FILE_NAMES = [".gitignore", ".ignore", ".fdignore"];
+
+export function createIgnoreMatcher(): IgnoreMatcher {
+ return ignore();
+}
+
+function prefixIgnorePattern(line: string, prefix: string): string | null {
+ const trimmed = line.trim();
+ if (!trimmed) return null;
+ if (trimmed.startsWith("#") && !trimmed.startsWith("\\#")) return null;
+
+ let pattern = line;
+ let negated = false;
+
+ if (pattern.startsWith("!")) {
+ negated = true;
+ pattern = pattern.slice(1);
+ } else if (pattern.startsWith("\\!")) {
+ pattern = pattern.slice(1);
+ }
+
+ if (pattern.startsWith("/")) {
+ pattern = pattern.slice(1);
+ }
+
+ const prefixed = prefix ? `${prefix}${pattern}` : pattern;
+ return negated ? `!${prefixed}` : prefixed;
+}
+
+/**
+ * Add the ignore files of one directory to a matcher, rewriting their patterns
+ * so they match paths relative to rootDir.
+ */
+export function addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {
+ const relativeDir = relative(rootDir, dir);
+ const prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : "";
+
+ for (const filename of IGNORE_FILE_NAMES) {
+ const ignorePath = join(dir, filename);
+ if (!existsSync(ignorePath)) continue;
+ try {
+ const content = readFileSync(ignorePath, "utf-8");
+ const patterns = content
+ .split(/\r?\n/)
+ .map((line) => prefixIgnorePattern(line, prefix))
+ .filter((line): line is string => Boolean(line));
+ if (patterns.length > 0) {
+ ig.add(patterns);
+ }
+ } catch {
+ // Unreadable ignore file: skip it rather than failing discovery.
+ }
+ }
+}
diff --git a/packages/coding-agent/src/core/package-manager.ts b/packages/coding-agent/src/core/package-manager.ts
index fe9e294214..c9b36d4790 100644
--- a/packages/coding-agent/src/core/package-manager.ts
+++ b/packages/coding-agent/src/core/package-manager.ts
@@ -22,15 +22,16 @@ function getEnv(): NodeJS.ProcessEnv {
}
}
-import { basename, dirname, join, relative, resolve, sep } from "node:path";
+import { basename, dirname, join, relative, resolve } from "node:path";
import { globSync } from "glob";
-import ignore from "ignore";
import { minimatch } from "minimatch";
import { CONFIG_DIR_NAME, getBundledSkillsDir } from "../config.js";
import { shouldUseWindowsShell, spawnHidden, spawnSyncHidden } from "../utils/child-process.js";
import { type GitSource, parseGitUrl } from "../utils/git.js";
-import { canonicalizePath, isLocalPath } from "../utils/paths.js";
+import { canonicalizePath, isLocalPath, toPosixPath } from "../utils/paths.js";
import type { ResourceDiagnostic } from "./diagnostics.js";
+import { collectExtensionEntries, resolveExtensionEntries } from "./extensions/discovery.js";
+import { addIgnoreRules, createIgnoreMatcher, type IgnoreMatcher } from "./ignore-rules.js";
import { isStdoutTakenOver } from "./output-guard.js";
import type { PackageSource, SettingsManager } from "./settings-manager.js";
@@ -202,63 +203,10 @@ const FILE_PATTERNS: Record<ResourceType, RegExp> = {
themes: /\.json$/,
};
-const IGNORE_FILE_NAMES = [".gitignore", ".ignore", ".fdignore"];
-
-type IgnoreMatcher = ReturnType<typeof ignore>;
-
-function toPosixPath(p: string): string {
- return p.split(sep).join("/");
-}
-
function getHomeDir(): string {
return process.env.HOME || homedir();
}
-function prefixIgnorePattern(line: string, prefix: string): string | null {
- const trimmed = line.trim();
- if (!trimmed) return null;
- if (trimmed.startsWith("#") && !trimmed.startsWith("\\#")) return null;
-
- let pattern = line;
- let negated = false;
-
- if (pattern.startsWith("!")) {
- negated = true;
- pattern = pattern.slice(1);
- } else if (pattern.startsWith("\\!")) {
- pattern = pattern.slice(1);
- }
-
- if (pattern.startsWith("/")) {
- pattern = pattern.slice(1);
- }
-
- const prefixed = prefix ? `${prefix}${pattern}` : pattern;
- return negated ? `!${prefixed}` : prefixed;
-}
-
-function addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {
- const relativeDir = relative(rootDir, dir);
- const prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : "";
-
- for (const filename of IGNORE_FILE_NAMES) {
- const ignorePath = join(dir, filename);
- if (!existsSync(ignorePath)) continue;
- try {
- const content = readFileSync(ignorePath, "utf-8");
- const patterns = content
- .split(/\r?\n/)
- .map((line) => prefixIgnorePattern(line, prefix))
- .filter((line): line is string => Boolean(line));
- if (patterns.length > 0) {
- ig.add(patterns);
- }
- } catch {
- // Unreadable ignore file: skip it rather than failing resource loading.
- }
- }
-}
-
function isPattern(s: string): boolean {
return s.startsWith("!") || s.startsWith("+") || s.startsWith("-") || s.includes("*") || s.includes("?");
}
@@ -295,7 +243,7 @@ function collectFiles(
if (!existsSync(dir)) return files;
const root = rootDir ?? dir;
- const ig = ignoreMatcher ?? ignore();
+ const ig = ignoreMatcher ?? createIgnoreMatcher();
addIgnoreRules(ig, dir, root);
try {
@@ -347,7 +295,7 @@ function collectSkillEntries(
if (!existsSync(dir)) return entries;
const root = rootDir ?? dir;
- const ig = ignoreMatcher ?? ignore();
+ const ig = ignoreMatcher ?? createIgnoreMatcher();
addIgnoreRules(ig, dir, root);
try {
@@ -454,7 +402,7 @@ function collectAutoPromptEntries(dir: string): string[] {
const entries: string[] = [];
if (!existsSync(dir)) return entries;
- const ig = ignore();
+ const ig = createIgnoreMatcher();
addIgnoreRules(ig, dir, dir);
try {
@@ -491,7 +439,7 @@ function collectAutoThemeEntries(dir: string): string[] {
const entries: string[] = [];
if (!existsSync(dir)) return entries;
- const ig = ignore();
+ const ig = createIgnoreMatcher();
addIgnoreRules(ig, dir, dir);
try {
@@ -524,94 +472,9 @@ function collectAutoThemeEntries(dir: string): string[] {
return entries;
}
-function readPiManifestFile(packageJsonPath: string): PiManifest | null {
- try {
- const content = readFileSync(packageJsonPath, "utf-8");
- const pkg = JSON.parse(content) as { pi?: PiManifest };
- return pkg.pi ?? null;
- } catch {
- return null;
- }
-}
-
-function resolveExtensionEntries(dir: string): string[] | null {
- const packageJsonPath = join(dir, "package.json");
- if (existsSync(packageJsonPath)) {
- const manifest = readPiManifestFile(packageJsonPath);
- if (manifest?.extensions?.length) {
- const entries: string[] = [];
- for (const extPath of manifest.extensions) {
- const resolvedExtPath = resolve(dir, extPath);
- if (existsSync(resolvedExtPath)) {
- entries.push(resolvedExtPath);
- }
- }
- if (entries.length > 0) {
- return entries;
- }
- }
- }
-
- const indexTs = join(dir, "index.ts");
- const indexJs = join(dir, "index.js");
- if (existsSync(indexTs)) {
- return [indexTs];
- }
- if (existsSync(indexJs)) {
- return [indexJs];
- }
-
- return null;
-}
-
function collectAutoExtensionEntries(dir: string): string[] {
- const entries: string[] = [];
- if (!existsSync(dir)) return entries;
- const rootEntries = resolveExtensionEntries(dir);
- if (rootEntries) {
- return rootEntries;
- }
- const ig = ignore();
- addIgnoreRules(ig, dir, dir);
-
- try {
- const dirEntries = readdirSync(dir, { withFileTypes: true });
- for (const entry of dirEntries) {
- if (entry.name.startsWith(".")) continue;
- if (entry.name === "node_modules") continue;
-
- const fullPath = join(dir, entry.name);
- let isDir = entry.isDirectory();
- let isFile = entry.isFile();
-
- if (entry.isSymbolicLink()) {
- try {
- const stats = statSync(fullPath);
- isDir = stats.isDirectory();
- isFile = stats.isFile();
- } catch {
- continue;
- }
- }
-
- const relPath = toPosixPath(relative(dir, fullPath));
- const ignorePath = isDir ? `${relPath}/` : relPath;
- if (ig.ignores(ignorePath)) continue;
-
- if (isFile && (entry.name.endsWith(".ts") || entry.name.endsWith(".js"))) {
- entries.push(fullPath);
- } else if (isDir) {
- const resolvedEntries = resolveExtensionEntries(fullPath);
- if (resolvedEntries) {
- entries.push(...resolvedEntries);
- }
- }
- }
- } catch {
- // Ignore unreadable directories during extension discovery.
- }
-
- return entries;
+ if (!existsSync(dir)) return [];
+ return resolveExtensionEntries(dir) ?? collectExtensionEntries(dir);
}
/**
diff --git a/packages/coding-agent/src/core/prompt-templates.ts b/packages/coding-agent/src/core/prompt-templates.ts
index afe72c1d39..92ee8d6d02 100644
--- a/packages/coding-agent/src/core/prompt-templates.ts
+++ b/packages/coding-agent/src/core/prompt-templates.ts
@@ -1,8 +1,8 @@
import { existsSync, readdirSync, readFileSync, statSync } from "fs";
-import { homedir } from "os";
-import { basename, dirname, isAbsolute, join, resolve, sep } from "path";
+import { basename, dirname, join, resolve } from "path";
import { CONFIG_DIR_NAME } from "../config.js";
import { parseFrontmatter } from "../utils/frontmatter.js";
+import { isUnderPath, resolveUserPath } from "../utils/paths.js";
import { parseSlashCommand } from "./slash-commands.js";
import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.js";
@@ -174,19 +174,6 @@ export interface LoadPromptTemplatesOptions {
includeDefaults: boolean;
}
-function normalizePath(input: string): string {
- const trimmed = input.trim();
- if (trimmed === "~") return homedir();
- if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2));
- if (trimmed.startsWith("~")) return join(homedir(), trimmed.slice(1));
- return trimmed;
-}
-
-function resolvePromptPath(p: string, cwd: string): string {
- const normalized = normalizePath(p);
- return isAbsolute(normalized) ? normalized : resolve(cwd, normalized);
-}
-
/**
* Load all prompt templates from:
* 1. Global: agentDir/prompts/
@@ -204,15 +191,6 @@ export function loadPromptTemplates(options: LoadPromptTemplatesOptions): Prompt
const globalPromptsDir = options.agentDir ? join(options.agentDir, "prompts") : resolvedAgentDir;
const projectPromptsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, "prompts");
- const isUnderPath = (target: string, root: string): boolean => {
- const normalizedRoot = resolve(root);
- if (target === normalizedRoot) {
- return true;
- }
- const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;
- return target.startsWith(prefix);
- };
-
const getSourceInfo = (resolvedPath: string): SourceInfo => {
if (isUnderPath(resolvedPath, globalPromptsDir)) {
return createSyntheticSourceInfo(resolvedPath, {
@@ -241,7 +219,7 @@ export function loadPromptTemplates(options: LoadPromptTemplatesOptions): Prompt
// 3. Load explicit prompt paths
for (const rawPath of promptPaths) {
- const resolvedPath = resolvePromptPath(rawPath, resolvedCwd);
+ const resolvedPath = resolveUserPath(rawPath, resolvedCwd);
if (!existsSync(resolvedPath)) {
continue;
}
diff --git a/packages/coding-agent/src/core/resource-loader.ts b/packages/coding-agent/src/core/resource-loader.ts
index 5cb03a4bf5..e579bde6ae 100644
--- a/packages/coding-agent/src/core/resource-loader.ts
+++ b/packages/coding-agent/src/core/resource-loader.ts
@@ -1,6 +1,6 @@
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { homedir } from "node:os";
-import { join, resolve, sep } from "node:path";
+import { join, resolve } from "node:path";
import chalk from "chalk";
import { CONFIG_DIR_NAME, getBundledSkillsDir } from "../config.js";
import { loadThemeFromPath, type Theme } from "../modes/interactive/theme/theme.js";
@@ -8,7 +8,7 @@ import type { ResourceDiagnostic } from "./diagnostics.js";
export type { ResourceCollision, ResourceDiagnostic } from "./diagnostics.js";
-import { canonicalizePath, isLocalPath } from "../utils/paths.js";
+import { canonicalizePath, isLocalPath, isUnderPath } from "../utils/paths.js";
import { createEventBus, type EventBus } from "./event-bus.js";
import { createExtensionRuntime, loadExtensionFromFactory, loadExtensions } from "./extensions/loader.js";
import type { Extension, ExtensionFactory, ExtensionRuntime, LoadExtensionsResult } from "./extensions/types.js";
@@ -603,11 +603,7 @@ export class DefaultResourceLoader implements ResourceLoader {
const normalizedResourcePath = resolve(resourcePath);
if (extraSourceInfos) {
for (const [sourcePath, sourceInfo] of extraSourceInfos.entries()) {
- const normalizedSourcePath = resolve(sourcePath);
- if (
- normalizedResourcePath === normalizedSourcePath ||
- normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)
- ) {
+ if (isUnderPath(normalizedResourcePath, sourcePath)) {
return { ...sourceInfo, path: resourcePath };
}
}
@@ -620,11 +616,7 @@ export class DefaultResourceLoader implements ResourceLoader {
}
for (const [sourcePath, metadata] of metadataByPath.entries()) {
- const normalizedSourcePath = resolve(sourcePath);
- if (
- normalizedResourcePath === normalizedSourcePath ||
- normalizedResourcePath.startsWith(`${normalizedSourcePath}${sep}`)
- ) {
+ if (isUnderPath(normalizedResourcePath, sourcePath)) {
return createSourceInfo(resourcePath, metadata);
}
}
@@ -658,13 +650,13 @@ export class DefaultResourceLoader implements ResourceLoader {
];
for (const root of agentRoots) {
- if (this.isUnderPath(normalizedPath, root)) {
+ if (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)) {
+ if (isUnderPath(normalizedPath, root)) {
return { path: filePath, source: "local", scope: "project", origin: "top-level", baseDir: root };
}
}
@@ -889,15 +881,6 @@ export class DefaultResourceLoader implements ResourceLoader {
return undefined;
}
- private isUnderPath(target: string, root: string): boolean {
- const normalizedRoot = resolve(root);
- if (target === normalizedRoot) {
- return true;
- }
- const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;
- return target.startsWith(prefix);
- }
-
private detectExtensionConflicts(extensions: Extension[]): Array<{ path: string; message: string }> {
const conflicts: Array<{ path: string; message: string }> = [];
diff --git a/packages/coding-agent/src/core/skills.ts b/packages/coding-agent/src/core/skills.ts
index d8b2bd28cf..bcd4522135 100644
--- a/packages/coding-agent/src/core/skills.ts
+++ b/packages/coding-agent/src/core/skills.ts
@@ -1,12 +1,11 @@
import { getLogger } from "@earendil-works/pi-ai";
import { existsSync, readdirSync, readFileSync, statSync } from "fs";
-import ignore from "ignore";
-import { homedir } from "os";
-import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path";
+import { basename, dirname, join, relative, resolve } from "path";
import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";
import { parseFrontmatter } from "../utils/frontmatter.js";
-import { canonicalizePath } from "../utils/paths.js";
+import { canonicalizePath, isUnderPath, resolveUserPath, toPosixPath } from "../utils/paths.js";
import type { ResourceDiagnostic } from "./diagnostics.js";
+import { addIgnoreRules, createIgnoreMatcher, type IgnoreMatcher } from "./ignore-rules.js";
import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.js";
const log = getLogger("coding-agent.skills");
@@ -17,59 +16,6 @@ const MAX_NAME_LENGTH = 64;
/** Max description length per spec */
const MAX_DESCRIPTION_LENGTH = 1024;
-const IGNORE_FILE_NAMES = [".gitignore", ".ignore", ".fdignore"];
-
-type IgnoreMatcher = ReturnType<typeof ignore>;
-
-function toPosixPath(p: string): string {
- return p.split(sep).join("/");
-}
-
-function prefixIgnorePattern(line: string, prefix: string): string | null {
- const trimmed = line.trim();
- if (!trimmed) return null;
- if (trimmed.startsWith("#") && !trimmed.startsWith("\\#")) return null;
-
- let pattern = line;
- let negated = false;
-
- if (pattern.startsWith("!")) {
- negated = true;
- pattern = pattern.slice(1);
- } else if (pattern.startsWith("\\!")) {
- pattern = pattern.slice(1);
- }
-
- if (pattern.startsWith("/")) {
- pattern = pattern.slice(1);
- }
-
- const prefixed = prefix ? `${prefix}${pattern}` : pattern;
- return negated ? `!${prefixed}` : prefixed;
-}
-
-function addIgnoreRules(ig: IgnoreMatcher, dir: string, rootDir: string): void {
- const relativeDir = relative(rootDir, dir);
- const prefix = relativeDir ? `${toPosixPath(relativeDir)}/` : "";
-
- for (const filename of IGNORE_FILE_NAMES) {
- const ignorePath = join(dir, filename);
- if (!existsSync(ignorePath)) continue;
- try {
- const content = readFileSync(ignorePath, "utf-8");
- const patterns = content
- .split(/\r?\n/)
- .map((line) => prefixIgnorePattern(line, prefix))
- .filter((line): line is string => Boolean(line));
- if (patterns.length > 0) {
- ig.add(patterns);
- }
- } catch {
- // Unreadable ignore file: skip it rather than failing skill discovery.
- }
- }
-}
-
export interface SkillFrontmatter {
name?: string;
description?: string;
@@ -292,7 +238,7 @@ function loadSkillsFromDirInternal(
}
const root = rootDir ?? dir;
- const ig = ignoreMatcher ?? ignore();
+ const ig = ignoreMatcher ?? createIgnoreMatcher();
addIgnoreRules(ig, dir, root);
try {
@@ -493,19 +439,6 @@ export interface LoadSkillsOptions {
includeDefaults: boolean;
}
-function normalizePath(input: string): string {
- const trimmed = input.trim();
- if (trimmed === "~") return homedir();
- if (trimmed.startsWith("~/")) return join(homedir(), trimmed.slice(2));
- if (trimmed.startsWith("~")) return join(homedir(), trimmed.slice(1));
- return trimmed;
-}
-
-function resolveSkillPath(p: string, cwd: string): string {
- const normalized = normalizePath(p);
- return isAbsolute(normalized) ? normalized : resolve(cwd, normalized);
-}
-
/**
* Load skills from all configured locations.
* Returns skills and any validation diagnostics.
@@ -571,15 +504,6 @@ export function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {
const userSkillsDir = join(resolvedAgentDir, "skills");
const projectSkillsDir = resolve(cwd, CONFIG_DIR_NAME, "skills");
- const isUnderPath = (target: string, root: string): boolean => {
- const normalizedRoot = resolve(root);
- if (target === normalizedRoot) {
- return true;
- }
- const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;
- return target.startsWith(prefix);
- };
-
const getSource = (resolvedPath: string): "user" | "project" | "path" => {
if (!includeDefaults) {
if (isUnderPath(resolvedPath, userSkillsDir)) return "user";
@@ -589,7 +513,7 @@ export function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {
};
for (const rawPath of skillPaths) {
- const resolvedPath = resolveSkillPath(rawPath, cwd);
+ const resolvedPath = resolveUserPath(rawPath, cwd);
if (!existsSync(resolvedPath)) {
allDiagnostics.push({ type: "warning", message: "skill path does not exist", path: resolvedPath });
continue;
diff --git a/packages/coding-agent/src/core/tools/path-utils.ts b/packages/coding-agent/src/core/tools/path-utils.ts
index d2e466656e..b45717f312 100644
--- a/packages/coding-agent/src/core/tools/path-utils.ts
+++ b/packages/coding-agent/src/core/tools/path-utils.ts
@@ -1,12 +1,9 @@
import { accessSync, constants } from "node:fs";
-import * as os from "node:os";
-import { isAbsolute, posix, resolve as resolvePath, win32 } from "node:path";
+import { isAbsolute, resolve as resolvePath } from "node:path";
+import { expandTildePath } from "../../config.js";
+import { normalizeUnicodeSpaces } from "../../utils/paths.js";
-const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
const NARROW_NO_BREAK_SPACE = "\u202F";
-function normalizeUnicodeSpaces(str: string): string {
- return str.replace(UNICODE_SPACES, " ");
-}
function tryMacOSScreenshotPath(filePath: string): string {
return filePath.replace(/ (AM|PM)\./gi, `${NARROW_NO_BREAK_SPACE}$1.`);
@@ -37,14 +34,7 @@ function normalizeAtPrefix(filePath: string): string {
}
export function expandPath(filePath: string, platform: NodeJS.Platform = process.platform): string {
- const normalized = normalizeUnicodeSpaces(normalizeAtPrefix(filePath));
- if (normalized === "~") {
- return os.homedir();
- }
- if (normalized.startsWith("~/") || (platform === "win32" && normalized.startsWith("~\\"))) {
- return (platform === "win32" ? win32 : posix).join(os.homedir(), normalized.slice(2));
- }
- return normalized;
+ return expandTildePath(normalizeUnicodeSpaces(normalizeAtPrefix(filePath)), platform);
}
/**
diff --git a/packages/coding-agent/src/utils/paths.ts b/packages/coding-agent/src/utils/paths.ts
index ef36de7a9a..2fad718568 100644
--- a/packages/coding-agent/src/utils/paths.ts
+++ b/packages/coding-agent/src/utils/paths.ts
@@ -1,5 +1,37 @@
import { realpathSync } from "node:fs";
import { isAbsolute, relative, resolve as resolvePath, sep } from "node:path";
+import { expandTildePath } from "../config.js";
+
+const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
+
+/** Replace Unicode space variants that users paste with plain spaces. */
+export function normalizeUnicodeSpaces(str: string): string {
+ return str.replace(UNICODE_SPACES, " ");
+}
+
+/**
+ * Resolve a user-configured resource path (skill, prompt, extension) against a
+ * working directory, after trimming, Unicode space normalization and tilde expansion.
+ */
+export function resolveUserPath(input: string, cwd: string): string {
+ const expanded = expandTildePath(normalizeUnicodeSpaces(input.trim()));
+ return isAbsolute(expanded) ? expanded : resolvePath(cwd, expanded);
+}
+
+/** Convert a native path to posix separators, for ignore matching and display. */
+export function toPosixPath(path: string): string {
+ return path.split(sep).join("/");
+}
+
+/** True if an already resolved target path is the root directory or lives inside it. */
+export function isUnderPath(target: string, root: string): boolean {
+ const normalizedRoot = resolvePath(root);
+ if (target === normalizedRoot) {
+ return true;
+ }
+ const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`;
+ return target.startsWith(prefix);
+}
/**
* Resolve a path to its canonical (real) form, following symlinks.
diff --git a/packages/coding-agent/test/extensions-discovery.test.ts b/packages/coding-agent/test/extensions-discovery.test.ts
index 3b35f61a1c..1523c3beab 100644
--- a/packages/coding-agent/test/extensions-discovery.test.ts
+++ b/packages/coding-agent/test/extensions-discovery.test.ts
@@ -103,12 +103,16 @@ describe("extensions discovery", () => {
expected: ["my-package/custom.ts"],
},
{
- name: "package.json without pi field falls back to index.ts",
+ name: "package.json with an absent or unusable pi field does not stop discovery",
setup: () => {
write("my-package/index.ts");
write("my-package/package.json", JSON.stringify({ name: "my-package", version: "1.0.0" }));
+ write("malformed-package/index.ts");
+ write("malformed-package/package.json", JSON.stringify({ pi: { extensions: "index.ts" } }));
+ write("invalid-element-package/index.ts");
+ write("invalid-element-package/package.json", JSON.stringify({ pi: { extensions: [7] } }));
},
- expected: ["my-package/index.ts"],
+ expected: ["invalid-element-package/index.ts", "malformed-package/index.ts", "my-package/index.ts"],
},
{
name: "package.json paths that do not exist are skipped",
@@ -148,6 +152,26 @@ describe("extensions discovery", () => {
);
});
+ it("resolves a symlink named like a file through the entry point of its target directory", async () => {
+ const targetDir = path.join(tempDir, "target");
+ fs.mkdirSync(targetDir, { recursive: true });
+ fs.writeFileSync(path.join(targetDir, "index.ts"), extensionCode);
+ fs.symlinkSync(targetDir, path.join(extensionsDir, "foo.ts"), "dir");
+ const result = await discoverAndLoadExtensions([], tempDir, tempDir);
+ expect(result.errors).toHaveLength(0);
+ expect(result.extensions.map((extension) => path.relative(extensionsDir, extension.path))).toEqual([
+ path.join("foo.ts", "index.ts"),
+ ]);
+ });
+
+ it("silently skips a symlink whose target does not exist", async () => {
+ write("kept.ts");
+ fs.symlinkSync(path.join(tempDir, "missing.ts"), path.join(extensionsDir, "broken.ts"));
+ const result = await discoverAndLoadExtensions([], tempDir, tempDir);
+ expect(result.errors).toHaveLength(0);
+ expect(result.extensions.map((extension) => path.relative(extensionsDir, extension.path))).toEqual(["kept.ts"]);
+ });
+
it.each([
{
name: "code that fails to load",
@@ -178,6 +202,18 @@ describe("extensions discovery", () => {
if (error) expect(result.errors[0].error).toContain(error);
});
+ it("skips extensions excluded by the ignore files of the extensions directory", async () => {
+ write("kept.ts");
+ write("skipped.ts");
+ write("ignored-package/index.ts");
+ write(".gitignore", "skipped.ts\nignored-package/\n");
+
+ const result = await discoverAndLoadExtensions([], tempDir, tempDir);
+
+ expect(result.errors).toHaveLength(0);
+ expect(result.extensions.map((extension) => path.relative(extensionsDir, extension.path))).toEqual(["kept.ts"]);
+ });
+
it("loads explicitly configured paths outside the extensions directory", async () => {
const customPath = path.join(tempDir, "custom-location", "my-ext.ts");
fs.mkdirSync(path.dirname(customPath), { recursive: true });
diff --git a/packages/coding-agent/test/ignore-rules.test.ts b/packages/coding-agent/test/ignore-rules.test.ts
new file mode 100644
index 0000000000..4185e78b74
--- /dev/null
+++ b/packages/coding-agent/test/ignore-rules.test.ts
@@ -0,0 +1,71 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { addIgnoreRules, createIgnoreMatcher } from "../src/core/ignore-rules.js";
+
+describe("addIgnoreRules", () => {
+ let root: string;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "pi-ignore-rules-"));
+ });
+
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ const writeIgnoreFile = (dir: string, content: string, fileName = ".gitignore") => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, fileName), content);
+ };
+ const matcherFor = (...dirs: string[]) => {
+ const ig = createIgnoreMatcher();
+ for (const dir of dirs) addIgnoreRules(ig, dir, root);
+ return ig;
+ };
+
+ it.each([
+ { name: "an empty ignore file", content: "" },
+ { name: "a file of comments and blank lines", content: "# a comment\n\n \n\t\n" },
+ ])("ignores nothing for $name", ({ content }) => {
+ writeIgnoreFile(root, content);
+ const ig = matcherFor(root);
+ expect(ig.ignores("kept.ts")).toBe(false);
+ expect(ig.ignores("nested/deep.ts")).toBe(false);
+ });
+
+ it("treats a backslash-escaped hash as a literal file name", () => {
+ writeIgnoreFile(root, "\\#secret.ts\n");
+ const ig = matcherFor(root);
+ expect(ig.ignores("#secret.ts")).toBe(true);
+ expect(ig.ignores("secret.ts")).toBe(false);
+ });
+
+ it.each([".gitignore", ".ignore", ".fdignore"])("reads %s", (fileName) => {
+ writeIgnoreFile(root, "skipped.ts\n", fileName);
+ expect(matcherFor(root).ignores("skipped.ts")).toBe(true);
+ });
+
+ it("applies a negation rule after a broader pattern", () => {
+ writeIgnoreFile(root, "*.ts\n!kept.ts\n");
+ const ig = matcherFor(root);
+ expect(ig.ignores("dropped.ts")).toBe(true);
+ expect(ig.ignores("kept.ts")).toBe(false);
+ });
+
+ it("scopes a nested ignore file to its own directory", () => {
+ writeIgnoreFile(join(root, "nested"), "*.ts\n");
+ const ig = matcherFor(root, join(root, "nested"));
+ expect(ig.ignores("nested/skip.ts")).toBe(true);
+ expect(ig.ignores("top.ts")).toBe(false);
+ });
+
+ it("scopes a nested negation to the same directory", () => {
+ writeIgnoreFile(join(root, "nested"), "*.ts\n!kept.ts\n");
+ const ig = matcherFor(join(root, "nested"));
+ expect(ig.ignores("nested/skip.ts")).toBe(true);
+ expect(ig.ignores("nested/kept.ts")).toBe(false);
+ expect(ig.ignores("top.ts")).toBe(false);
+ });
+});
diff --git a/packages/coding-agent/test/utils-paths.test.ts b/packages/coding-agent/test/utils-paths.test.ts
new file mode 100644
index 0000000000..85879eb863
--- /dev/null
+++ b/packages/coding-agent/test/utils-paths.test.ts
@@ -0,0 +1,37 @@
+import { homedir, tmpdir } from "node:os";
+import { join, win32 } from "node:path";
+import { describe, expect, it } from "vitest";
+import { expandTildePath } from "../src/config.js";
+import { resolveUserPath } from "../src/utils/paths.js";
+
+const cwd = join(tmpdir(), "pi-paths-cwd");
+
+describe("resolveUserPath", () => {
+ it("keeps a tilde without a separator literal instead of expanding it", () => {
+ const result = resolveUserPath("~Documents/file.txt", cwd);
+ expect(result).toBe(join(cwd, "~Documents", "file.txt"));
+ });
+
+ it("expands a leading tilde that is followed by a separator", () => {
+ expect(resolveUserPath("~/Documents/file.txt", cwd)).toBe(join(homedir(), "Documents", "file.txt"));
+ });
+
+ it("expands the Windows backslash tilde spelling on Windows only", () => {
+ expect(expandTildePath("~\\Documents\\file.txt", "win32")).toBe(win32.join(homedir(), "Documents", "file.txt"));
+ expect(expandTildePath("~\\Documents\\file.txt", "linux")).toBe("~\\Documents\\file.txt");
+ });
+
+ it("passes an absolute path through unchanged", () => {
+ const absolute = join(cwd, "resources", "ext.ts");
+ expect(resolveUserPath(absolute, cwd)).toBe(absolute);
+ expect(resolveUserPath(absolute, join(cwd, "other"))).toBe(absolute);
+ });
+
+ it("trims surrounding whitespace and normalizes Unicode spaces", () => {
+ expect(resolveUserPath(" resources/ext.ts\n", cwd)).toBe(join(cwd, "resources", "ext.ts"));
+ expect(resolveUserPath("\u00A0skills\u3000dir\u00A0", cwd)).toBe(join(cwd, "skills dir"));
+ for (const space of ["\u00A0", "\u2000", "\u200A", "\u202F", "\u205F", "\u3000"]) {
+ expect(resolveUserPath(`my${space}folder`, cwd)).toBe(join(cwd, "my folder"));
+ }
+ });
+});