UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

399 lines • 16.6 kB
import { homedir } from "node:os"; import { existsSync, readdirSync, realpathSync, statSync } from "fs"; import ignore from "ignore"; import { basename, dirname, join, relative, resolve, sep } from "path"; import { CONFIG_DIR_NAME, getAgentDir } from "../config.js"; import { parseFrontmatter } from "../utils/frontmatter.js"; import { canonicalizePath, resolvePath } from "../utils/paths.js"; import { authorizeSkillPath, BlockedSkillLinkError, buildSkillAllowedSet, insideSkillRoot, readSkillFileCheckedSync, skillProjectRoot, } from "./skill-access.js"; import { addIgnoreRules, shouldSkipSkillWalkDirectoryName } from "./skill-discovery.js"; import { readUserSkillSource } from "./skill-source-cache.js"; import { createSyntheticSourceInfo } from "./source-info.js"; export { formatSkillsForPrompt } from "./skills-prompt.js"; /** Max name length per spec */ const MAX_NAME_LENGTH = 64; /** Max description length per spec */ const MAX_DESCRIPTION_LENGTH = 1024; function toPosixPath(p) { return p.split(sep).join("/"); } /** * Validate skill name per Agent Skills spec. * Returns array of validation error messages (empty if valid). */ function validateName(name) { const errors = []; if (name.length > MAX_NAME_LENGTH) { errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`); } if (!/^[a-z0-9-]+$/.test(name)) { errors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`); } if (name.startsWith("-") || name.endsWith("-")) { errors.push(`name must not start or end with a hyphen`); } if (name.includes("--")) { errors.push(`name must not contain consecutive hyphens`); } return errors; } /** * Validate description per Agent Skills spec. */ function validateDescription(description) { const errors = []; if (typeof description !== "string" || description.trim() === "") { errors.push("description is required"); } else if (description.length > MAX_DESCRIPTION_LENGTH) { errors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`); } return errors; } function createSkillSourceInfo(filePath, baseDir, source) { switch (source) { case "user": return createSyntheticSourceInfo(filePath, { source: "local", scope: "user", baseDir, }); case "project": return createSyntheticSourceInfo(filePath, { source: "local", scope: "project", baseDir, }); case "path": return createSyntheticSourceInfo(filePath, { source: "local", baseDir, }); default: return createSyntheticSourceInfo(filePath, { source, baseDir }); } } /** * Load skills from a directory. * * Discovery rules: * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further * - otherwise, load direct .md children in the root * - recurse into subdirectories to find SKILL.md */ export function loadSkillsFromDir(options) { const { dir, source } = options; const provenance = options.provenance ?? { kind: source === "project" ? "project-auto" : "user", selectedRoot: dir, projectRoot: skillProjectRoot(dir), }; return loadSkillsFromDirInternal(dir, source, true, undefined, undefined, provenance, options.allowedSet); } function loadSkillsFromDirInternal(dir, source, includeRootFiles, ignoreMatcher, rootDir, provenance, allowedSet, ancestry = new Set()) { const skills = []; const diagnostics = []; if (!existsSync(dir)) { return { skills, diagnostics }; } let canonical; try { authorizeSkillPath(dir, provenance, allowedSet, true); canonical = realpathSync.native(dir); } catch (error) { if (error instanceof BlockedSkillLinkError) return { skills, diagnostics: [error.diagnostic] }; canonical = resolve(dir); } if (ancestry.has(canonical)) return { skills, diagnostics }; const descendants = new Set(ancestry); descendants.add(canonical); const root = rootDir ?? dir; const ig = ignoreMatcher ?? ignore(); try { const entries = readdirSync(dir, { withFileTypes: true }); addIgnoreRules(ig, dir, root, entries); for (const entry of entries) { if (entry.name !== "SKILL.md") { continue; } const fullPath = join(dir, entry.name); let isFile = entry.isFile(); if (entry.isSymbolicLink()) { try { isFile = statSync(fullPath).isFile(); } catch { continue; } } const relPath = toPosixPath(relative(root, fullPath)); if (!isFile || ig.ignores(relPath)) { continue; } const result = loadSkillFromFile(fullPath, source, provenance, allowedSet); if (result.skill) { skills.push(result.skill); } diagnostics.push(...result.diagnostics); return { skills, diagnostics }; } for (const entry of entries) { if (shouldSkipSkillWalkDirectoryName(entry.name)) { continue; } const fullPath = join(dir, entry.name); // For symlinks, check if they point to a directory and follow them let isDirectory = entry.isDirectory(); let isFile = entry.isFile(); const isLink = entry.isSymbolicLink(); if (isLink) { try { const stats = statSync(fullPath); isDirectory = stats.isDirectory(); isFile = stats.isFile(); } catch { // Broken symlink, skip it continue; } } // A linked entry belongs to another tree: the ignore files above it do not hide it, and a linked // directory gets its own ignore context, as in collectSkillEntries (senpi#5060, senpi#5069). const linkedDirectory = isLink && isDirectory; const relPath = toPosixPath(relative(root, fullPath)); const ignorePath = isDirectory ? `${relPath}/` : relPath; if (!isLink && ig.ignores(ignorePath)) { continue; } if (isDirectory) { const subResult = loadSkillsFromDirInternal(fullPath, source, false, linkedDirectory ? ignore() : ig, root, provenance, allowedSet, descendants); skills.push(...subResult.skills); diagnostics.push(...subResult.diagnostics); continue; } if (!isFile || !includeRootFiles || !entry.name.endsWith(".md")) { continue; } const result = loadSkillFromFile(fullPath, source, provenance, allowedSet); if (result.skill) { skills.push(result.skill); } diagnostics.push(...result.diagnostics); } } catch { } return { skills, diagnostics }; } function loadSkillFromFile(filePath, source, provenance, allowedSet, stats) { const diagnostics = []; const isDeclaredSkill = basename(filePath) === "SKILL.md"; let rawContent; try { rawContent = provenance === undefined || provenance.kind === "user" ? readUserSkillSource(filePath, stats ?? statSync(filePath)) : readSkillFileCheckedSync(filePath, provenance, allowedSet); } catch (error) { if (error instanceof BlockedSkillLinkError) return { skill: null, diagnostics: [error.diagnostic] }; const message = error instanceof Error ? error.message : "failed to read skill file"; diagnostics.push({ type: "warning", message, path: filePath }); return { skill: null, diagnostics }; } let frontmatter; try { ({ frontmatter } = parseFrontmatter(rawContent)); } catch (error) { if (isDeclaredSkill) { const message = error instanceof Error ? error.message : "failed to parse skill file"; diagnostics.push({ type: "warning", message, path: filePath }); } return { skill: null, diagnostics }; } const description = frontmatter.description; const hasDescription = typeof description === "string" && description.trim() !== ""; if (!isDeclaredSkill && !hasDescription) { return { skill: null, diagnostics }; } const skillDir = dirname(filePath); const parentDirName = basename(skillDir); // Validate description const descErrors = validateDescription(description); for (const error of descErrors) { diagnostics.push({ type: "warning", message: error, path: filePath }); } // Use name from frontmatter, or fall back to parent directory name const frontmatterName = typeof frontmatter.name === "string" ? frontmatter.name : undefined; const name = frontmatterName || parentDirName; // Validate name const nameErrors = validateName(name); for (const error of nameErrors) { diagnostics.push({ type: "warning", message: error, path: filePath }); } // Still load the skill even with warnings, unless description is missing or empty. if (!hasDescription) { return { skill: null, diagnostics }; } const argumentHint = frontmatter["argument-hint"]; const hasArgumentHint = typeof argumentHint === "string" && argumentHint.trim() !== ""; const requiresArguments = frontmatter["requires-arguments"]; return { skill: { name, provenance, allowedSet, description, filePath, baseDir: skillDir, sourceInfo: createSkillSourceInfo(filePath, skillDir, source), disableModelInvocation: frontmatter["disable-model-invocation"] === true, requiresArguments: typeof requiresArguments === "boolean" ? requiresArguments : hasArgumentHint, ...(hasArgumentHint && { argumentHint: argumentHint.trim() }), }, diagnostics, }; } /** * Load skills from all configured locations. * Returns skills and any validation diagnostics. */ export function loadSkills(options) { const { agentDir, skillPaths, includeDefaults } = options; // Resolve agentDir - if not provided, use default from config const resolvedCwd = resolvePath(options.cwd); const resolvedAgentDir = resolvePath(agentDir ?? getAgentDir()); const projectRoot = skillProjectRoot(resolvedCwd); const projectSkillsPath = resolve(resolvedCwd, CONFIG_DIR_NAME, "skills"); const allowedSet = buildSkillAllowedSet([ join(resolvedAgentDir, "skills"), join(homedir(), ".agents", "skills"), ...(options.userSkillRoots ?? []), ...skillPaths .map((path) => resolvePath(path, resolvedCwd, { trim: true })) .filter((path) => { const provenance = options.provenanceByPath?.get(path); return (provenance?.kind === "user" || (provenance === undefined && (includeDefaults || !insideSkillRoot(path, projectSkillsPath)))); }), ]); const skillMap = new Map(); const realPathSet = new Set(); const allDiagnostics = []; const collisionDiagnostics = []; function addSkills(result) { allDiagnostics.push(...result.diagnostics); for (const skill of result.skills) { // Resolve symlinks to detect duplicate files const realPath = canonicalizePath(skill.filePath); // Skip silently if we've already loaded this exact file (via symlink) if (realPathSet.has(realPath)) { continue; } const existing = skillMap.get(skill.name); if (existing) { collisionDiagnostics.push({ type: "collision", message: `name "${skill.name}" collision`, path: skill.filePath, collision: { resourceType: "skill", name: skill.name, winnerPath: existing.filePath, loserPath: skill.filePath, }, }); } else { skillMap.set(skill.name, skill); realPathSet.add(realPath); } } } if (includeDefaults) { const userRoot = join(resolvedAgentDir, "skills"); addSkills(loadSkillsFromDirInternal(userRoot, "user", true, undefined, undefined, { kind: "user", selectedRoot: userRoot }, allowedSet)); addSkills(loadSkillsFromDirInternal(projectSkillsPath, "project", true, undefined, undefined, { kind: "project-auto", selectedRoot: projectSkillsPath, projectRoot }, allowedSet)); } const userSkillsDir = join(resolvedAgentDir, "skills"); const projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, "skills"); const isUnderPath = (target, root) => { const normalizedRoot = resolve(root); if (target === normalizedRoot) { return true; } const prefix = normalizedRoot.endsWith(sep) ? normalizedRoot : `${normalizedRoot}${sep}`; return target.startsWith(prefix); }; const getSource = (resolvedPath) => { if (!includeDefaults) { if (isUnderPath(resolvedPath, userSkillsDir)) return "user"; if (isUnderPath(resolvedPath, projectSkillsDir)) return "project"; } return "path"; }; for (const rawPath of skillPaths) { const resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true }); let stats; try { stats = statSync(resolvedPath); } catch { allDiagnostics.push({ type: "warning", message: "skill path does not exist", path: resolvedPath }); continue; } try { const source = getSource(resolvedPath); const provenance = options.provenanceByPath?.get(resolvedPath) ?? { kind: source === "project" ? "project-auto" : "user", selectedRoot: resolvedPath, projectRoot, }; if (stats.isDirectory()) { addSkills(loadSkillsFromDirInternal(resolvedPath, source, true, undefined, undefined, provenance, allowedSet)); } else if (stats.isFile() && resolvedPath.endsWith(".md")) { const result = loadSkillFromFile(resolvedPath, source, provenance, allowedSet, stats); if (result.skill) { addSkills({ skills: [result.skill], diagnostics: result.diagnostics }); } else { allDiagnostics.push(...result.diagnostics); } } else { allDiagnostics.push({ type: "warning", message: "skill path is not a markdown file", path: resolvedPath }); } } catch (error) { const message = error instanceof Error ? error.message : "failed to read skill path"; allDiagnostics.push({ type: "warning", message, path: resolvedPath }); } } return { skills: Array.from(skillMap.values()), diagnostics: [...allDiagnostics, ...collisionDiagnostics], }; } /** * Warnings for skill folders an ignore file hid from discovery (senpi#5060). A folder whose name a loaded * skill already carries is skipped: another root supplied that skill, so nothing is missing. */ export function ignoredSkillDiagnostics(ignoredSkillFiles, loadedSkills) { const loadedNames = new Set(loadedSkills.map((skill) => skill.name)); return ignoredSkillFiles .filter((skillFile) => !loadedNames.has(basename(dirname(skillFile)))) .map((skillFile) => ({ type: "warning", category: "skill-ignored", path: skillFile, message: `Skill not loaded: ${dirname(skillFile)} is listed in an ignore file (.gitignore, .ignore or .fdignore) of the folder above it. Remove that entry to load the skill; to keep git ignoring it, list it in .git/info/exclude instead.`, })); } //# sourceMappingURL=skills.js.map