UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

205 lines (204 loc) • 7.96 kB
import { readFileSync, readdirSync, statSync } from "node:fs"; import { join } from "node:path"; import { readSkillFile } from "@sema-agent/primitives"; import { physicalPathOf } from "./physical-path.js"; import { isPhysicallyWithin } from "../tools/fs/path-containment.js"; import { assertNoRetiredKeys } from "./retired-keys.js"; import { thrownText } from "./thrown-value.js"; const SKILL_FILE = "SKILL.md"; const RESOURCE_DIRS = ["assets", "references", "scripts"]; const DEFAULT_MAX_ATTACHMENT_BYTES = 256 * 1024; function listRelativeFiles(base, dir, prefix, out, walk) { let entries; try { entries = readdirSync(join(base, dir), { withFileTypes: true }); } catch { return; } for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) { const rel = `${prefix}${e.name}`; const abs = join(base, dir, e.name); const resolved = resolveInsideSkill(abs, rel, walk); if (resolved === undefined) continue; if (resolved.stats.isDirectory()) { if (walk.visited.has(resolved.real)) continue; walk.visited.add(resolved.real); listRelativeFiles(base, join(dir, e.name), `${rel}/`, out, walk); } else if (resolved.stats.isFile()) { out.push(rel); } } } function skillPhysicalRoot(skillDir, skillName, warn) { try { return physicalPathOf(skillDir); } catch (err) { warn({ code: "read_failed", skill: skillName, detail: `the skill directory could not be resolved (${errText(err)}) — attachments skipped and no base directory is stated`, }); return undefined; } } function resolveInsideSkill(abs, rel, walk) { let real; let stats; try { real = physicalPathOf(abs); stats = statSync(abs); } catch (err) { walk.warn({ code: "attachment_skipped", skill: walk.skill, detail: `${rel}: could not be resolved (${errText(err)})` }); return undefined; } if (!isPhysicallyWithin(walk.realRoot, real)) { walk.warn({ code: "attachment_skipped", skill: walk.skill, detail: `${rel}: resolves outside the skill directory — skipped (attachments are collected from the declared skill directory only)`, }); return undefined; } return { real, stats }; } function readAttachments(skillDir, realRoot, skillName, budgetBytes, warn) { const walk = { realRoot, skill: skillName, warn, visited: new Set([realRoot]) }; const relPaths = []; for (const d of RESOURCE_DIRS) { let exists = true; try { statSync(join(skillDir, d)); } catch { exists = false; } if (!exists) continue; const resolved = resolveInsideSkill(join(skillDir, d), d, walk); if (resolved === undefined || !resolved.stats.isDirectory()) continue; walk.visited.add(resolved.real); listRelativeFiles(skillDir, d, `${d}/`, relPaths, walk); } relPaths.sort(); const files = []; let spent = 0; for (const rel of relPaths) { let bytes; try { bytes = readFileSync(join(skillDir, rel)); } catch (err) { warn({ code: "attachment_skipped", skill: skillName, detail: `${rel}: unreadable (${errText(err)})` }); continue; } if (!isDecodableText(bytes)) { warn({ code: "attachment_skipped", skill: skillName, detail: `${rel}: not text (attachment content is a string; binary is not carried)` }); continue; } if (spent + bytes.byteLength > budgetBytes) { warn({ code: "attachment_skipped", skill: skillName, detail: `${rel}: over the ${budgetBytes}-byte attachment budget for this skill` }); continue; } spent += bytes.byteLength; files.push({ path: rel, content: bytes.toString("utf8") }); } return files; } function isDecodableText(bytes) { if (bytes.includes(0)) return false; const decoded = bytes.toString("utf8"); return Buffer.byteLength(decoded, "utf8") === bytes.byteLength; } function errText(err) { return thrownText(err); } const RETIRED_SKILLS_DIRECTORY_OPTION_KEYS = Object.freeze({ deployedTools: "the loader copies a skill's `allowed-tools` / `disallowed-tools` into `SkillSpec.allowedTools` / `disallowedTools` as written and the run's grant table judges them (an entry naming a tool nothing mounts simply never matches) — drop the option", }); export function createSkillsFromDirectory(dir, options = {}) { assertNoRetiredKeys(options, RETIRED_SKILLS_DIRECTORY_OPTION_KEYS, "SkillsDirectoryOptions"); const warn = (w) => { options.onWarning?.(w); }; const budget = options.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES; let entries; let root; try { const st = statSync(dir); if (!st.isDirectory()) throw new Error("not a directory"); root = physicalPathOf(dir); entries = readdirSync(root, { withFileTypes: true }); } catch (err) { throw new Error(`skills directory could not be read: ${dir} (${errText(err)})`); } const containWithin = options.containWithin; if (containWithin !== undefined) { const isDir = typeof containWithin === "string" && statSync(containWithin, { throwIfNoEntry: false })?.isDirectory() === true; if (!isDir) throw new Error(`skills directory containment root is not a readable directory: ${String(containWithin)}`); } const outside = (skill, path, what) => { if (containWithin === undefined || isPhysicallyWithin(containWithin, path)) return false; warn({ code: "outside_root", skill, detail: `${what} resolves outside ${containWithin} — skipped` }); return true; }; const dirNames = []; for (const e of entries) { if (e.isDirectory()) { dirNames.push(e.name); continue; } if (!e.isSymbolicLink()) continue; try { if (statSync(join(root, e.name)).isDirectory()) dirNames.push(e.name); } catch (err) { warn({ code: "read_failed", skill: e.name, detail: `entry is a symbolic link that could not be resolved (${errText(err)}) — skipped` }); } } dirNames.sort(); const skills = []; for (const name of dirNames) { const skillDir = join(root, name); if (outside(name, skillDir, "its directory") || outside(name, join(skillDir, SKILL_FILE), SKILL_FILE)) continue; let text; try { text = readFileSync(join(skillDir, SKILL_FILE), "utf8"); } catch { warn({ code: "no_skill_file", skill: name, detail: `no ${SKILL_FILE} in this directory — skipped` }); continue; } const reading = readSkillFile(text, { directoryName: name }); if (reading.kind !== "read") { warn({ code: reading.reason, skill: name, detail: reading.detail }); continue; } const baseDir = skillPhysicalRoot(skillDir, name, warn); const files = baseDir === undefined ? [] : readAttachments(skillDir, baseDir, name, budget, warn); skills.push({ name: reading.name, description: reading.description, content: reading.body, ...(baseDir !== undefined ? { baseDir } : {}), ...(reading.allowedTools.length > 0 ? { allowedTools: [...reading.allowedTools] } : {}), ...(reading.disallowedTools.length > 0 ? { disallowedTools: [...reading.disallowedTools] } : {}), ...(files.length > 0 ? { files } : {}), }); } return skills; }