skillService.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
  2. import { basename, dirname, join, relative, resolve, sep } from 'node:path';
  3. import { randomUUID } from 'node:crypto';
  4. import { fromBuffer, type Entry, type ZipFile } from 'yauzl';
  5. import { getSkillsDir, isInsideDir, MAX_SKILL_NAME_LENGTH, SKILL_NAME_PATTERN } from './codexHome';
  6. import type { CodexRuntime, CodexSkillSummary, JsonValue } from './codexRuntime';
  7. /**
  8. * Skill 的文件层管理。Codex app-server 只给了 skills/list 与 skills/config/write(启停),
  9. * 没有安装/卸载接口,所以目录的增删由本模块负责,启停仍走原生 RPC。
  10. *
  11. * 目录布局:<CODEX_HOME>/skills/<kebab-name>/SKILL.md(+ 可选 agents/ scripts/ references/ assets/)。
  12. * Codex 会把内置 skill 实体化到同级的 .system/.curated/.experimental,这些一律不可删改。
  13. */
  14. const MAX_ENTRY_COUNT = 300;
  15. const MAX_FILE_BYTES = 2 * 1024 * 1024;
  16. const MAX_TOTAL_BYTES = 25 * 1024 * 1024;
  17. const MAX_SKILL_MD_BYTES = 64 * 1024;
  18. const SKILL_FILE_NAME = 'SKILL.md';
  19. const STAGING_PREFIX = '.staging-';
  20. const ALLOWED_EXTENSIONS = new Set([
  21. 'md', 'txt', 'json', 'yaml', 'yml', 'toml',
  22. 'py', 'js', 'mjs', 'cjs', 'ts', 'sh', 'ps1', 'bat',
  23. 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg', 'csv',
  24. ]);
  25. export interface SkillListItem extends CodexSkillSummary {
  26. /** 是否落在本模块可管理的用户目录里(内置 skill 为 false,不允许删除) */
  27. managed: boolean;
  28. }
  29. export interface SkillFileEntry {
  30. path: string;
  31. size: number;
  32. }
  33. export interface SkillReadResult {
  34. dir: string;
  35. content: string;
  36. files: SkillFileEntry[];
  37. }
  38. export interface SkillInstallOptions {
  39. /** 覆盖 frontmatter 里的 name;不传则用 frontmatter 的 name */
  40. name?: string | null;
  41. overwrite?: boolean;
  42. }
  43. export interface SkillTarget {
  44. path?: string | null;
  45. name?: string | null;
  46. }
  47. type SkillRuntime = Pick<CodexRuntime, 'listSkills' | 'setSkillEnabled'> &
  48. Partial<Pick<CodexRuntime, 'readConfig' | 'writeConfigValue'>>;
  49. export interface SkillServiceOptions {
  50. /** 默认取 <CODEX_HOME>/skills;单测注入临时目录 */
  51. skillsDir?: string;
  52. /** 非致命问题的上报口(诊断日志),避免异常被静默吞掉 */
  53. onDiagnostic?: (line: string) => void;
  54. }
  55. export class SkillService {
  56. readonly #runtime: SkillRuntime;
  57. readonly #skillsDir: string;
  58. readonly #options: SkillServiceOptions;
  59. constructor(runtime: SkillRuntime, options: SkillServiceOptions = {}) {
  60. this.#runtime = runtime;
  61. this.#options = options;
  62. this.#skillsDir = options.skillsDir ?? getSkillsDir();
  63. }
  64. get skillsDir(): string {
  65. return this.#skillsDir;
  66. }
  67. async list(options: { forceReload?: boolean } = {}): Promise<SkillListItem[]> {
  68. const skills = await this.#runtime.listSkills({ forceReload: options.forceReload ?? false });
  69. return skills.map((skill) => ({
  70. ...skill,
  71. managed: isManagedSkillPath(this.#skillsDir, skill.path),
  72. }));
  73. }
  74. async setEnabled(target: SkillTarget, enabled: boolean): Promise<boolean> {
  75. const selector = await this.#resolveSelector(target);
  76. return this.#runtime.setSkillEnabled(selector, enabled);
  77. }
  78. async read(target: SkillTarget): Promise<SkillReadResult> {
  79. const dir = await this.#resolveReadableDir(target);
  80. const content = await readFile(join(dir, SKILL_FILE_NAME), 'utf8');
  81. const files = await collectFiles(dir);
  82. return { dir, content, files };
  83. }
  84. /** 从一个已存在的目录安装(配合 osCtl.selectDirectory 选目录) */
  85. async installFromFolder(srcPath: string, options: SkillInstallOptions = {}): Promise<SkillListItem[]> {
  86. const source = resolve(srcPath);
  87. const sourceStat = await stat(source).catch(() => null);
  88. if (!sourceStat?.isDirectory()) throw new Error('源路径不是一个目录');
  89. const staging = await this.#createStagingDir();
  90. try {
  91. const manifest = await copyFolderChecked(source, staging);
  92. const name = await finalizeStagedSkill(staging, manifest, options);
  93. await this.#promoteStaging(staging, name, options.overwrite === true);
  94. } catch (error) {
  95. await rm(staging, { recursive: true, force: true }).catch(() => undefined);
  96. throw error;
  97. }
  98. return this.list({ forceReload: true });
  99. }
  100. /** 从 zip 字节安装(渲染进程读文件后把字节传过来,主进程不需要拿到本机路径) */
  101. async installFromZip(data: Uint8Array, options: SkillInstallOptions = {}): Promise<SkillListItem[]> {
  102. if (!data || data.byteLength === 0) throw new Error('zip 内容为空');
  103. if (data.byteLength > MAX_TOTAL_BYTES) throw new Error(`zip 超过 ${MAX_TOTAL_BYTES / 1024 / 1024} MiB 上限`);
  104. const staging = await this.#createStagingDir();
  105. try {
  106. const manifest = await extractZipChecked(data, staging);
  107. const root = await resolveZipRoot(staging, manifest);
  108. const name = await finalizeStagedSkill(root, manifest, options);
  109. await this.#promoteStaging(staging, name, options.overwrite === true, root);
  110. } catch (error) {
  111. await rm(staging, { recursive: true, force: true }).catch(() => undefined);
  112. throw error;
  113. }
  114. return this.list({ forceReload: true });
  115. }
  116. async remove(target: SkillTarget): Promise<SkillListItem[]> {
  117. const dir = await this.#resolveManagedDir(target);
  118. await rm(dir, { recursive: true, force: true });
  119. await this.#clearStaleConfig(dir, basename(dir));
  120. return this.list({ forceReload: true });
  121. }
  122. /**
  123. * 删掉目录后清掉 config.toml 里的 [[skills.config]] 残留条目。
  124. * 不清的话,将来装回同名 skill 会直接继承旧的 enabled=false,表现为「装了但不生效」。
  125. */
  126. async #clearStaleConfig(dir: string, name: string): Promise<void> {
  127. const runtime = this.#runtime;
  128. if (typeof runtime.readConfig !== 'function' || typeof runtime.writeConfigValue !== 'function') return;
  129. try {
  130. // 必须按方法调用,解构出来会丢 this 绑定
  131. const config = await runtime.readConfig();
  132. const skills = asRecord(config.skills);
  133. const entries = Array.isArray(skills?.config) ? (skills.config as unknown[]) : null;
  134. if (!entries) return;
  135. const kept = entries.filter((item) => !isStaleEntry(item, dir, name));
  136. if (kept.length === entries.length) return;
  137. await runtime.writeConfigValue('skills.config', kept as JsonValue[]);
  138. } catch (error) {
  139. // 目录已经删掉了,清理失败不该让删除整体失败,但一定要上报,否则表现为配置里有幽灵条目
  140. this.#options.onDiagnostic?.(
  141. `清理 skill 配置残留失败:${error instanceof Error ? error.message : String(error)}`,
  142. );
  143. }
  144. }
  145. /** 把 UI 传来的 path/name 收敛成一个「确实在用户 skills 目录内」的绝对路径 */
  146. async #resolveManagedDir(target: SkillTarget): Promise<string> {
  147. const skillsDir = this.#skillsDir;
  148. if (target.path) {
  149. const dir = resolve(toSkillDir(target.path));
  150. assertManagedSkillDir(skillsDir, dir);
  151. const manifest = await stat(join(dir, SKILL_FILE_NAME)).catch(() => null);
  152. if (!manifest?.isFile()) throw new Error('该目录下没有 SKILL.md');
  153. return dir;
  154. }
  155. if (target.name) {
  156. const name = normalizeSkillName(target.name);
  157. const dir = join(skillsDir, name);
  158. assertManagedSkillDir(skillsDir, dir);
  159. const manifest = await stat(join(dir, SKILL_FILE_NAME)).catch(() => null);
  160. if (!manifest?.isFile()) throw new Error(`未找到名为 ${name} 的 skill`);
  161. return dir;
  162. }
  163. throw new Error('必须提供 skill 的 path 或 name');
  164. }
  165. /**
  166. * 只读解析:内置(.system/.curated/.experimental)与暂存目录允许「查看」,只是不可删改。
  167. * 与 {@link #resolveManagedDir} 的区别就是不要求一级子目录、也不拦点号目录,
  168. * 边界仍然锁在 skills 目录内且必须有 SKILL.md。
  169. */
  170. async #resolveReadableDir(target: SkillTarget): Promise<string> {
  171. const skillsDir = this.#skillsDir;
  172. let dir: string;
  173. if (target.path) {
  174. dir = resolve(toSkillDir(target.path));
  175. } else if (target.name) {
  176. // 点号目录进不了 normalizeSkillName,所以按 name 只能查到用户自装 skill
  177. dir = join(skillsDir, normalizeSkillName(target.name));
  178. } else {
  179. throw new Error('必须提供 skill 的 path 或 name');
  180. }
  181. if (!isInsideDir(skillsDir, dir)) throw new Error('只能查看 skills 目录内的 skill');
  182. const manifest = await stat(join(dir, SKILL_FILE_NAME)).catch(() => null);
  183. if (!manifest?.isFile()) {
  184. throw new Error(target.path ? '该目录下没有 SKILL.md' : `未找到名为 ${target.name} 的 skill`);
  185. }
  186. return dir;
  187. }
  188. async #resolveSelector(target: SkillTarget): Promise<{ path?: string; name?: string }> {
  189. if (target.path) return { path: target.path };
  190. if (target.name) return { name: normalizeSkillName(target.name) };
  191. throw new Error('必须提供 skill 的 path 或 name');
  192. }
  193. async #createStagingDir(): Promise<string> {
  194. const staging = join(this.#skillsDir, `${STAGING_PREFIX}${randomUUID()}`);
  195. await mkdir(staging, { recursive: true });
  196. return staging;
  197. }
  198. /** staging → skills/<name>,用 rename 保证原子性 */
  199. async #promoteStaging(
  200. staging: string,
  201. name: string,
  202. overwrite: boolean,
  203. stagedRoot = staging,
  204. ): Promise<void> {
  205. const target = join(this.#skillsDir, name);
  206. const existing = await stat(target).catch(() => null);
  207. if (existing) {
  208. if (!overwrite) throw new Error(`skill「${name}」已存在,需显式覆盖`);
  209. await rm(target, { recursive: true, force: true });
  210. }
  211. await mkdir(this.#skillsDir, { recursive: true });
  212. await rename(stagedRoot, target);
  213. if (resolve(stagedRoot) !== resolve(staging)) {
  214. // zip 里带了一层外壳目录:搬完内层后清掉外壳
  215. await rm(staging, { recursive: true, force: true }).catch(() => undefined);
  216. }
  217. }
  218. }
  219. /**
  220. * Codex 的 skills/list 与 skills/config 都用 SKILL.md 文件路径标识一个 skill(见 scripts/codex-ipc-probe.json),
  221. * UI 把该 path 原样回传,这里先收敛成目录,否则 join(dir, 'SKILL.md') 会拼出不存在的路径。
  222. */
  223. function toSkillDir(pathOrFile: string): string {
  224. return basename(pathOrFile) === SKILL_FILE_NAME ? dirname(pathOrFile) : pathOrFile;
  225. }
  226. /** 内置目录(.system/.curated/.experimental)与暂存目录一律不可管理 */
  227. function isManagedSkillPath(skillsDir: string, skillPath: string): boolean {
  228. if (!isInsideDir(skillsDir, skillPath)) return false;
  229. const rel = relative(skillsDir, skillPath);
  230. const first = rel.split(sep)[0] ?? '';
  231. return Boolean(first) && !first.startsWith('.') && !rel.includes(`..${sep}`);
  232. }
  233. function assertManagedSkillDir(skillsDir: string, dir: string): void {
  234. if (!isInsideDir(skillsDir, dir)) throw new Error('只能管理用户 skills 目录内的 skill');
  235. const rel = relative(skillsDir, dir);
  236. const segments = rel.split(sep);
  237. // 先判内置/暂存目录,否则 .system/imagegen 会先撞上「一级子目录」的报错,信息不准
  238. if (segments[0]?.startsWith('.')) throw new Error('内置或暂存目录不可删改');
  239. if (segments.length !== 1 || !segments[0]) throw new Error('skill 必须是 skills 目录下的一级子目录');
  240. if (!SKILL_NAME_PATTERN.test(segments[0])) throw new Error('skill 目录名不合法');
  241. }
  242. export function normalizeSkillName(raw: string): string {
  243. const name = raw
  244. .trim()
  245. .toLowerCase()
  246. .replace(/[\s_]+/gu, '-')
  247. .replace(/[^a-z0-9-]/gu, '')
  248. .replace(/-{2,}/gu, '-')
  249. .replace(/^-|-$/gu, '');
  250. if (!name || name.length > MAX_SKILL_NAME_LENGTH) {
  251. throw new Error(`skill 名称非法(需为小写连字符命名,长度 ≤ ${MAX_SKILL_NAME_LENGTH})`);
  252. }
  253. if (!SKILL_NAME_PATTERN.test(name)) throw new Error('skill 名称只能是字母数字与连字符的组合');
  254. return name;
  255. }
  256. /** 校验并落定 staged skill:必须有合法 frontmatter,返回最终 skill 名 */
  257. async function finalizeStagedSkill(
  258. root: string,
  259. manifest: FileManifest,
  260. options: SkillInstallOptions,
  261. ): Promise<string> {
  262. if (manifest.totalBytes > MAX_TOTAL_BYTES) {
  263. throw new Error(`skill 内容超过 ${MAX_TOTAL_BYTES / 1024 / 1024} MiB 上限`);
  264. }
  265. const skillMd = join(root, SKILL_FILE_NAME);
  266. const skillStat = await stat(skillMd).catch(() => null);
  267. if (!skillStat?.isFile()) throw new Error('缺少 SKILL.md');
  268. if (skillStat.size > MAX_SKILL_MD_BYTES) throw new Error(`SKILL.md 超过 ${MAX_SKILL_MD_BYTES / 1024} KiB 上限`);
  269. const frontmatter = parseFrontmatter(await readFile(skillMd, 'utf8'));
  270. const rawName = options.name?.trim() || frontmatter.name;
  271. if (!rawName) throw new Error('SKILL.md 的 frontmatter 缺少 name');
  272. if (!frontmatter.description) throw new Error('SKILL.md 的 frontmatter 缺少 description');
  273. return normalizeSkillName(rawName);
  274. }
  275. interface FileManifest {
  276. entries: number;
  277. totalBytes: number;
  278. paths: string[];
  279. }
  280. function assertAllowedExtension(relPath: string): void {
  281. const ext = basename(relPath).split('.').pop()?.toLowerCase() ?? '';
  282. if (!basename(relPath).includes('.')) return;
  283. if (!ALLOWED_EXTENSIONS.has(ext)) throw new Error(`不允许的文件类型:${relPath}`);
  284. }
  285. /** 相对路径安全校验:拒绝绝对路径、`..`、盘符、UNC 与 macOS 垃圾目录。yauzl 也会拦一层,这里是第二道防线 */
  286. export function assertSafeRelativePath(relPath: string): string {
  287. if (!relPath || relPath.length > 512) throw new Error('条目路径非法');
  288. if (relPath.startsWith('__MACOSX/') || relPath.includes('/__MACOSX/')) {
  289. throw new Error('zip 含 __MACOSX 元数据目录');
  290. }
  291. const normalized = relPath.replace(/\\/gu, '/');
  292. if (/^[a-zA-Z]:/u.test(normalized) || normalized.startsWith('/') || normalized.startsWith('//')) {
  293. throw new Error('zip 含绝对路径条目');
  294. }
  295. const segments = normalized.split('/').filter(Boolean);
  296. if (!segments.length) throw new Error('zip 条目路径为空');
  297. for (const segment of segments) {
  298. if (segment === '..') throw new Error('zip 含路径穿越条目');
  299. if (segment === '.' || segment.startsWith(STAGING_PREFIX)) throw new Error('zip 条目路径非法');
  300. if (segment.length > 128) throw new Error('zip 条目路径过长');
  301. }
  302. return segments.join('/');
  303. }
  304. async function copyFolderChecked(source: string, staging: string): Promise<FileManifest> {
  305. const manifest: FileManifest = { entries: 0, totalBytes: 0, paths: [] };
  306. const walk = async (dir: string): Promise<void> => {
  307. for (const entry of await readdir(dir, { withFileTypes: true })) {
  308. const abs = join(dir, entry.name);
  309. const rel = relative(source, abs).split(sep).join('/');
  310. if (entry.isSymbolicLink()) throw new Error('源目录含符号链接,拒绝安装');
  311. if (entry.name.startsWith('.')) continue;
  312. if (entry.isDirectory()) {
  313. await mkdir(join(staging, rel), { recursive: true });
  314. await walk(abs);
  315. continue;
  316. }
  317. if (!entry.isFile()) throw new Error(`不支持的条目类型:${rel}`);
  318. assertSafeRelativePath(rel);
  319. assertAllowedExtension(rel);
  320. const info = await stat(abs);
  321. if (info.size > MAX_FILE_BYTES) throw new Error(`文件超过单文件 2 MiB 上限:${rel}`);
  322. manifest.entries += 1;
  323. manifest.totalBytes += info.size;
  324. manifest.paths.push(rel);
  325. if (manifest.entries > MAX_ENTRY_COUNT) throw new Error(`条目数超过 ${MAX_ENTRY_COUNT} 上限`);
  326. if (manifest.totalBytes > MAX_TOTAL_BYTES) throw new Error('内容总量超过上限');
  327. await mkdir(dirname(join(staging, rel)), { recursive: true });
  328. await writeFile(join(staging, rel), await readFile(abs));
  329. }
  330. };
  331. await walk(source);
  332. if (!manifest.entries) throw new Error('源目录是空的');
  333. return manifest;
  334. }
  335. function isSymlinkEntry(entry: Entry): boolean {
  336. // zip 的 Unix mode 存在 externalFileAttributes 高 16 位
  337. const mode = (entry.externalFileAttributes ?? 0) >>> 16;
  338. return (mode & 0o170000) === 0o120000;
  339. }
  340. async function extractZipChecked(data: Uint8Array, staging: string): Promise<FileManifest> {
  341. const manifest: FileManifest = { entries: 0, totalBytes: 0, paths: [] };
  342. const zip: ZipFile = await new Promise((resolvePromise, rejectPromise) => {
  343. fromBuffer(Buffer.from(data), { lazyEntries: true, autoClose: false }, (error, zipFile) => {
  344. // yauzl 的原文是英文且面向 zip 格式细节,页面会直接展示 message,这里包一层可读提示
  345. if (zipFile && !error) {
  346. resolvePromise(zipFile);
  347. return;
  348. }
  349. rejectPromise(new Error(`无法解析 zip 文件:${error?.message ?? '格式不正确'}`));
  350. });
  351. });
  352. try {
  353. await new Promise<void>((resolvePromise, reject) => {
  354. zip.once('error', reject);
  355. zip.once('end', () => resolvePromise());
  356. zip.on('entry', (entry: Entry) => {
  357. void handleEntry(entry).then(
  358. () => zip.readEntry(),
  359. (error: unknown) => reject(error instanceof Error ? error : new Error(String(error))),
  360. );
  361. });
  362. async function handleEntry(entry: Entry): Promise<void> {
  363. const rawName = entry.fileName.replace(/\\/gu, '/');
  364. if (isSymlinkEntry(entry)) throw new Error(`zip 含符号链接条目:${rawName}`);
  365. const isDir = rawName.endsWith('/');
  366. const rel = assertSafeRelativePath(isDir ? rawName.slice(0, -1) : rawName);
  367. if (isDir) {
  368. await mkdir(join(staging, rel), { recursive: true });
  369. return;
  370. }
  371. if (entry.uncompressedSize > MAX_FILE_BYTES) {
  372. throw new Error(`文件超过单文件 2 MiB 上限:${rel}`);
  373. }
  374. assertAllowedExtension(rel);
  375. manifest.entries += 1;
  376. if (manifest.entries > MAX_ENTRY_COUNT) throw new Error(`条目数超过 ${MAX_ENTRY_COUNT} 上限`);
  377. manifest.totalBytes += entry.uncompressedSize;
  378. if (manifest.totalBytes > MAX_TOTAL_BYTES) throw new Error('解压总量超过 25 MiB 上限');
  379. manifest.paths.push(rel);
  380. const buffer = await new Promise<Buffer>((resolveBuffer, rejectBuffer) => {
  381. zip.openReadStream(entry, (error, stream) => {
  382. if (error || !stream) {
  383. rejectBuffer(error ?? new Error(`无法读取 zip 条目:${rel}`));
  384. return;
  385. }
  386. const chunks: Buffer[] = [];
  387. let received = 0;
  388. stream.on('data', (chunk: Buffer) => {
  389. received += chunk.length;
  390. // 防 zip bomb:实际解压量超过声明值或超过单文件上限就立即中止
  391. if (received > MAX_FILE_BYTES || received > entry.uncompressedSize) {
  392. stream.destroy();
  393. rejectBuffer(new Error(`zip 条目解压量异常:${rel}`));
  394. return;
  395. }
  396. chunks.push(chunk);
  397. });
  398. stream.once('error', rejectBuffer);
  399. stream.once('end', () => resolveBuffer(Buffer.concat(chunks)));
  400. });
  401. });
  402. const destination = join(staging, rel);
  403. await mkdir(join(destination, '..'), { recursive: true });
  404. await writeFile(destination, buffer);
  405. }
  406. zip.readEntry();
  407. });
  408. } finally {
  409. zip.close();
  410. }
  411. if (!manifest.entries) throw new Error('zip 内没有可用文件');
  412. return manifest;
  413. }
  414. /** zip 常见形态是「一层外壳目录 + SKILL.md」,此时把内层当作 skill 根 */
  415. async function resolveZipRoot(staging: string, manifest: FileManifest): Promise<string> {
  416. if (manifest.paths.includes(SKILL_FILE_NAME)) return staging;
  417. const tops = new Set(manifest.paths.map((item) => item.split('/')[0]!));
  418. if (tops.size === 1) {
  419. const candidate = join(staging, [...tops][0]!);
  420. const inner = await stat(join(candidate, SKILL_FILE_NAME)).catch(() => null);
  421. if (inner?.isFile()) return candidate;
  422. }
  423. throw new Error('zip 根目录(或唯一的外壳目录)下没有 SKILL.md');
  424. }
  425. async function collectFiles(dir: string): Promise<SkillFileEntry[]> {
  426. const files: SkillFileEntry[] = [];
  427. const walk = async (current: string): Promise<void> => {
  428. for (const entry of await readdir(current, { withFileTypes: true })) {
  429. const abs = join(current, entry.name);
  430. if (entry.isDirectory()) {
  431. await walk(abs);
  432. continue;
  433. }
  434. if (!entry.isFile()) continue;
  435. const info = await stat(abs);
  436. files.push({ path: relative(dir, abs).split(sep).join('/'), size: info.size });
  437. }
  438. };
  439. await walk(dir);
  440. return files.sort((left, right) => left.path.localeCompare(right.path));
  441. }
  442. /** 只取 YAML frontmatter 里的 name / description 单行标量,够用且不引 YAML 依赖 */
  443. export function parseFrontmatter(content: string): { name: string | null; description: string | null } {
  444. const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---/u.exec(content);
  445. if (!match) return { name: null, description: null };
  446. const fields: Record<string, string> = {};
  447. for (const line of match[1]!.split(/\r?\n/u)) {
  448. const pair = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/u.exec(line.trim());
  449. if (!pair) continue;
  450. fields[pair[1]!.toLowerCase()] = stripQuotes(pair[2]!.trim());
  451. }
  452. return { name: fields.name || null, description: fields.description || null };
  453. }
  454. function stripQuotes(value: string): string {
  455. if (value.length >= 2 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) {
  456. return value.slice(1, -1);
  457. }
  458. return value.replace(/^>\s*|^\|\s*/u, '').trim();
  459. }
  460. /** 配置条目可能按 path(指向 SKILL.md)记录,也可能只按 name 记录 */
  461. function isStaleEntry(item: unknown, removedDir: string, removedName: string): boolean {
  462. const record = asRecord(item);
  463. if (!record) return false;
  464. const entryPath = readString(record.path);
  465. if (entryPath) {
  466. const target = resolve(entryPath);
  467. const dir = resolve(removedDir);
  468. return target === dir || target.startsWith(dir + sep) || dirname(target) === dir;
  469. }
  470. const entryName = readString(record.name);
  471. return Boolean(entryName) && entryName === removedName;
  472. }
  473. function asRecord(value: unknown): Record<string, unknown> | null {
  474. return value && typeof value === 'object' && !Array.isArray(value)
  475. ? (value as Record<string, unknown>)
  476. : null;
  477. }
  478. function readString(value: unknown): string | null {
  479. return typeof value === 'string' ? value : null;
  480. }