registry.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. import { constants as fsConstants, promises as fs, readdirSync, statSync } from 'node:fs';
  2. import path from 'node:path';
  3. import { fileURLToPath, pathToFileURL } from 'node:url';
  4. import yaml from 'js-yaml';
  5. import { subscribeToSkillDirectory } from './directory-watcher.js';
  6. import type {
  7. SkillCatalogRender,
  8. SkillDiagnostic,
  9. SkillEntry,
  10. SkillLoser,
  11. SkillRefreshMetrics,
  12. SkillRegistryDump,
  13. SkillRegistryWatchOptions,
  14. SkillRegistryWatcher,
  15. SkillRenderMetrics,
  16. SkillRenderOptions,
  17. SkillSnapshot,
  18. SkillSourceKind,
  19. SkillSourceRoot,
  20. SkillViewEntry,
  21. } from './types.js';
  22. interface CachedSkillFile {
  23. key: string;
  24. entry?: SkillEntry;
  25. diagnostics: SkillDiagnostic[];
  26. }
  27. interface CanonicalRoot extends SkillSourceRoot {
  28. canonicalPath: string;
  29. }
  30. interface SkillFileStat {
  31. size: number;
  32. mtimeMs: number;
  33. dev: number;
  34. ino: number;
  35. }
  36. interface SkillWatchTarget {
  37. targetPath: string;
  38. dev: number;
  39. ino: number;
  40. }
  41. interface ActiveSkillWatcher extends SkillWatchTarget {
  42. watcher: { close(): void };
  43. }
  44. interface SkillFileCandidate {
  45. fileLocation: string;
  46. contentDir: string;
  47. entryDir: string;
  48. allowOutsideRoot: boolean;
  49. }
  50. /**
  51. * Resolve template variables in skill content.
  52. * Currently only supports {{DATA_DIR}} → actual data directory path.
  53. * Windows paths are normalized to forward slashes for cross-platform consistency.
  54. */
  55. export function resolveSkillContentVariables(content: string): string {
  56. const dataDir = process.env.MINIMAX_DATA_DIR;
  57. if (!dataDir || !content.includes('{{DATA_DIR}}')) return content;
  58. // Normalize Windows backslashes to forward slashes
  59. const normalizedDir = dataDir.replace(/\\/g, '/');
  60. return content.split('{{DATA_DIR}}').join(normalizedDir);
  61. }
  62. const SOURCE_RANK: Record<SkillSourceKind, number> = {
  63. project: 0,
  64. workspace: 1,
  65. agent: 2,
  66. global: 3,
  67. user: 3,
  68. builtin: 4,
  69. };
  70. const DEFAULT_RENDER_BUDGET_CHARS = 20_000;
  71. const DEFAULT_EXTERNAL_DESCRIPTION_CHARS = 120;
  72. const WATCH_DEBOUNCE_MS = 200;
  73. const WATCH_MAX_WAIT_MS = 1000;
  74. const OPEN_SKILL_FILE_FLAGS =
  75. fsConstants.O_RDONLY | (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0);
  76. export class SkillRegistry {
  77. private readonly cache = new Map<string, CachedSkillFile>();
  78. private snapshot?: SkillSnapshot;
  79. private version = 0;
  80. constructor(private readonly roots: SkillSourceRoot[]) {}
  81. async refresh(): Promise<SkillSnapshot> {
  82. const canonicalRoots = await canonicalizeRoots(this.roots);
  83. const diagnostics: SkillDiagnostic[] = [];
  84. const entries: SkillEntry[] = [];
  85. const seenCacheLocations = new Set<string>();
  86. const metrics: SkillRefreshMetrics = {
  87. rootsScanned: canonicalRoots.length,
  88. filesSeen: 0,
  89. filesRead: 0,
  90. filesReused: 0,
  91. diagnostics: 0,
  92. entries: 0,
  93. winners: 0,
  94. losers: 0,
  95. };
  96. for (const root of canonicalRoots) {
  97. const candidates = await listSkillFiles(root, diagnostics);
  98. for (const candidate of candidates) {
  99. const cacheLocation = `${root.id}:${candidate.entryDir}`;
  100. seenCacheLocations.add(cacheLocation);
  101. metrics.filesSeen += 1;
  102. const stat = await statSkillFile(root, candidate, diagnostics);
  103. if (!stat) {
  104. this.cache.delete(cacheLocation);
  105. continue;
  106. }
  107. const cacheKey = `${candidate.fileLocation}:${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}`;
  108. const cached = this.cache.get(cacheLocation);
  109. let parsed: CachedSkillFile;
  110. if (cached?.key === cacheKey) {
  111. metrics.filesReused += 1;
  112. parsed = cached;
  113. } else {
  114. metrics.filesRead += 1;
  115. parsed = await parseSkillFile(root, candidate, stat, cacheKey);
  116. this.cache.set(cacheLocation, parsed);
  117. }
  118. diagnostics.push(...parsed.diagnostics);
  119. if (parsed.entry) {
  120. entries.push(parsed.entry);
  121. }
  122. }
  123. }
  124. for (const cachedLocation of this.cache.keys()) {
  125. if (!seenCacheLocations.has(cachedLocation)) {
  126. this.cache.delete(cachedLocation);
  127. }
  128. }
  129. const { winners, losers } = resolvePrecedence(entries);
  130. metrics.entries = entries.length;
  131. metrics.winners = winners.length;
  132. metrics.losers = losers.length;
  133. metrics.diagnostics = diagnostics.length;
  134. this.snapshot = {
  135. version: ++this.version,
  136. generatedAt: Date.now(),
  137. roots: canonicalRoots.map(({ canonicalPath: _canonicalPath, ...root }) => root),
  138. entries: sortEntries(entries),
  139. winners,
  140. losers,
  141. diagnostics,
  142. metrics,
  143. };
  144. return this.snapshot;
  145. }
  146. getSnapshot(): SkillSnapshot | undefined {
  147. return this.snapshot;
  148. }
  149. getAvailableSkills(): SkillViewEntry[] {
  150. return this.requireSnapshot().winners;
  151. }
  152. getByLocationUri(locationUri: string): SkillEntry {
  153. const normalizedLocationUri = normalizeLocationUri(locationUri);
  154. const entry = this.requireSnapshot().entries.find(
  155. (candidate) => candidate.locationUri === normalizedLocationUri,
  156. );
  157. if (!entry) {
  158. throw new Error(`Unknown skill location_uri: ${locationUri}`);
  159. }
  160. return entry;
  161. }
  162. readByLocationUri(locationUri: string): string {
  163. return this.getByLocationUri(locationUri).content;
  164. }
  165. watch(options: SkillRegistryWatchOptions): SkillRegistryWatcher {
  166. const watchers = new Map<string, ActiveSkillWatcher>();
  167. let closed = false;
  168. let refreshInFlight = false;
  169. let debounceTimer: ReturnType<typeof setTimeout> | undefined;
  170. let maxWaitTimer: ReturnType<typeof setTimeout> | undefined;
  171. const pendingRoots = new Map<string, SkillSourceRoot>();
  172. const clearFlushTimers = () => {
  173. if (debounceTimer) {
  174. clearTimeout(debounceTimer);
  175. debounceTimer = undefined;
  176. }
  177. if (maxWaitTimer) {
  178. clearTimeout(maxWaitTimer);
  179. maxWaitTimer = undefined;
  180. }
  181. };
  182. const closeWatchers = () => {
  183. for (const activeWatcher of watchers.values()) {
  184. activeWatcher.watcher.close();
  185. }
  186. watchers.clear();
  187. };
  188. const watchKey = (watchTarget: SkillWatchTarget, root: SkillSourceRoot) =>
  189. `${path.resolve(watchTarget.targetPath)}\0${root.id}`;
  190. const desiredWatchTargets = () => {
  191. const targets = new Map<string, { root: SkillSourceRoot; target: SkillWatchTarget }>();
  192. const rootsById = new Map(this.roots.map((root) => [root.id, root]));
  193. const collectPath = (targetPath: string, root: SkillSourceRoot) => {
  194. const target = existingWatchTarget(targetPath);
  195. if (!target) return;
  196. targets.set(watchKey(target, root), { root, target });
  197. };
  198. for (const root of this.roots) {
  199. collectPath(root.rootPath, root);
  200. for (const skillDir of listWatchableSkillDirs(root.rootPath)) {
  201. collectPath(skillDir, root);
  202. }
  203. }
  204. for (const entry of this.snapshot?.entries ?? []) {
  205. const root = rootsById.get(entry.rootId);
  206. if (root) collectPath(entry.skillDir, root);
  207. }
  208. return targets;
  209. };
  210. const closeStaleWatchers = (
  211. desiredTargets: Map<string, { root: SkillSourceRoot; target: SkillWatchTarget }>,
  212. ) => {
  213. for (const [key, activeWatcher] of watchers) {
  214. const desired = desiredTargets.get(key);
  215. if (
  216. desired &&
  217. activeWatcher.dev === desired.target.dev &&
  218. activeWatcher.ino === desired.target.ino
  219. ) {
  220. continue;
  221. }
  222. activeWatcher.watcher.close();
  223. watchers.delete(key);
  224. }
  225. };
  226. const watchTarget = (target: SkillWatchTarget, root: SkillSourceRoot) => {
  227. const key = watchKey(target, root);
  228. const existingWatcher = watchers.get(key);
  229. if (existingWatcher?.dev === target.dev && existingWatcher.ino === target.ino) return;
  230. existingWatcher?.watcher.close();
  231. try {
  232. const watcher = subscribeToSkillDirectory(target, {
  233. onChange: () => scheduleChange(root),
  234. onError: () => {
  235. watchers.delete(key);
  236. scheduleChange(root);
  237. },
  238. });
  239. watchers.set(key, { ...target, watcher });
  240. } catch {
  241. // Missing roots or skill directories are expected while users edit skills.
  242. }
  243. };
  244. const armWatchers = () => {
  245. if (closed) return;
  246. const desiredTargets = desiredWatchTargets();
  247. closeStaleWatchers(desiredTargets);
  248. for (const { root, target } of desiredTargets.values()) {
  249. watchTarget(target, root);
  250. }
  251. };
  252. const flushChanges = async () => {
  253. clearFlushTimers();
  254. while (pendingRoots.size > 0 && !closed) {
  255. const roots = [...pendingRoots.values()];
  256. pendingRoots.clear();
  257. await this.refresh().catch(() => undefined);
  258. armWatchers();
  259. for (const root of roots) {
  260. await Promise.resolve(options.onChange(root)).catch(() => undefined);
  261. }
  262. }
  263. refreshInFlight = false;
  264. if (pendingRoots.size > 0 && !closed) {
  265. scheduleFlush();
  266. }
  267. };
  268. const runScheduledFlush = () => {
  269. if (closed || refreshInFlight || pendingRoots.size === 0) return;
  270. refreshInFlight = true;
  271. void flushChanges();
  272. };
  273. const scheduleFlush = () => {
  274. if (closed || refreshInFlight) return;
  275. if (debounceTimer) clearTimeout(debounceTimer);
  276. debounceTimer = setTimeout(runScheduledFlush, WATCH_DEBOUNCE_MS);
  277. maxWaitTimer ??= setTimeout(runScheduledFlush, WATCH_MAX_WAIT_MS);
  278. };
  279. const scheduleChange = (root: SkillSourceRoot) => {
  280. if (closed) return;
  281. pendingRoots.set(root.id, root);
  282. scheduleFlush();
  283. };
  284. armWatchers();
  285. return {
  286. rearm() {
  287. armWatchers();
  288. },
  289. close() {
  290. closed = true;
  291. clearFlushTimers();
  292. closeWatchers();
  293. },
  294. };
  295. }
  296. dump(renderMetrics?: SkillRenderMetrics): SkillRegistryDump {
  297. const snapshot = this.requireSnapshot();
  298. return dumpSkillRegistry(snapshot, renderMetrics);
  299. }
  300. private requireSnapshot(): SkillSnapshot {
  301. if (!this.snapshot) {
  302. throw new Error('Skill registry has not been refreshed');
  303. }
  304. return this.snapshot;
  305. }
  306. }
  307. export async function createSkillRegistry(roots: SkillSourceRoot[]): Promise<SkillRegistry> {
  308. const registry = new SkillRegistry(roots);
  309. await registry.refresh();
  310. return registry;
  311. }
  312. export function renderAvailableSkillsCatalog(
  313. input: SkillSnapshot | SkillViewEntry[],
  314. options: SkillRenderOptions = {},
  315. ): SkillCatalogRender {
  316. const winners = Array.isArray(input) ? input : input.winners;
  317. const budgetChars = options.budgetChars ?? DEFAULT_RENDER_BUDGET_CHARS;
  318. const externalDescriptionChars =
  319. options.externalDescriptionChars ?? DEFAULT_EXTERNAL_DESCRIPTION_CHARS;
  320. const metrics: SkillRenderMetrics = {
  321. total: winners.length,
  322. rendered: 0,
  323. compacted: 0,
  324. dropped: 0,
  325. charsUsed: 0,
  326. budgetChars,
  327. };
  328. const lines: string[] = [];
  329. for (const entry of winners) {
  330. const compact = entry.sourceExternal;
  331. const description = compact
  332. ? truncate(entry.firstDescriptionLine || entry.description, externalDescriptionChars)
  333. : entry.description;
  334. const rendered = `- ${entry.name}: ${description}\n location_uri: ${entry.locationUri}`;
  335. const projectedLength = joinCatalog(lines, rendered).length;
  336. if (projectedLength > budgetChars) {
  337. metrics.dropped = winners.length - metrics.rendered;
  338. break;
  339. }
  340. lines.push(rendered);
  341. metrics.rendered += 1;
  342. if (compact) {
  343. metrics.compacted += 1;
  344. }
  345. }
  346. const catalog = lines.join('\n');
  347. metrics.charsUsed = catalog.length;
  348. if (metrics.dropped === 0) {
  349. metrics.dropped = metrics.total - metrics.rendered;
  350. }
  351. return { catalog, metrics };
  352. }
  353. export function dumpSkillRegistry(
  354. snapshot: SkillSnapshot,
  355. renderMetrics?: SkillRenderMetrics,
  356. ): SkillRegistryDump {
  357. return {
  358. version: snapshot.version,
  359. generated_at: snapshot.generatedAt,
  360. roots: snapshot.roots.map((root) => ({ ...root, canonicalPath: path.resolve(root.rootPath) })),
  361. entries: snapshot.entries.map(({ content: _content, ...entry }) => entry),
  362. winners: snapshot.winners.map((winner) => winner.locationUri),
  363. losers: snapshot.losers.map((loser) => ({
  364. locationUri: loser.entry.locationUri,
  365. name: loser.entry.name,
  366. reason: loser.reason,
  367. winnerLocationUri: loser.winnerLocationUri,
  368. })),
  369. diagnostics: snapshot.diagnostics,
  370. refresh_metrics: snapshot.metrics,
  371. render_metrics: renderMetrics,
  372. };
  373. }
  374. async function canonicalizeRoots(roots: SkillSourceRoot[]): Promise<CanonicalRoot[]> {
  375. return Promise.all(
  376. roots.map(async (root) => ({
  377. ...root,
  378. canonicalPath: await canonicalRootPath(root),
  379. })),
  380. );
  381. }
  382. async function canonicalRootPath(root: SkillSourceRoot): Promise<string> {
  383. try {
  384. const stat = await fs.lstat(root.rootPath);
  385. if (stat.isSymbolicLink() && !allowsDirectorySymlinkOutsideRoot(root)) {
  386. return path.resolve(root.rootPath);
  387. }
  388. } catch {
  389. return path.resolve(root.rootPath);
  390. }
  391. return canonicalPath(root.rootPath);
  392. }
  393. async function canonicalPath(filePath: string): Promise<string> {
  394. try {
  395. return await fs.realpath(filePath);
  396. } catch {
  397. return path.resolve(filePath);
  398. }
  399. }
  400. function existingWatchTarget(targetPath: string): SkillWatchTarget | undefined {
  401. const resolvedTarget = path.resolve(targetPath);
  402. try {
  403. const targetStat = statSync(resolvedTarget);
  404. if (targetStat.isDirectory()) {
  405. return {
  406. targetPath: resolvedTarget,
  407. dev: targetStat.dev,
  408. ino: targetStat.ino,
  409. };
  410. }
  411. const parentPath = path.dirname(resolvedTarget);
  412. const parentStat = statSync(parentPath);
  413. return {
  414. targetPath: parentPath,
  415. dev: parentStat.dev,
  416. ino: parentStat.ino,
  417. };
  418. } catch {
  419. return undefined;
  420. }
  421. }
  422. function allowsDirectorySymlinkOutsideRoot(root: SkillSourceRoot): boolean {
  423. return ['agent', 'global', 'user', 'builtin'].includes(root.kind);
  424. }
  425. async function listSkillFiles(
  426. root: CanonicalRoot,
  427. diagnostics: SkillDiagnostic[],
  428. ): Promise<SkillFileCandidate[]> {
  429. let children;
  430. try {
  431. children = await fs.readdir(root.canonicalPath, { withFileTypes: true });
  432. } catch (error) {
  433. diagnostics.push({
  434. level: 'warning',
  435. code: 'root_unreadable',
  436. rootId: root.id,
  437. message: `Unable to read skill root: ${error instanceof Error ? error.message : String(error)}`,
  438. });
  439. return [];
  440. }
  441. const files: SkillFileCandidate[] = [];
  442. for (const child of children) {
  443. if (!child.isDirectory() && !child.isSymbolicLink()) continue;
  444. const entryDir = path.join(root.canonicalPath, child.name);
  445. let contentDir = entryDir;
  446. let allowOutsideRoot = false;
  447. if (child.isSymbolicLink()) {
  448. try {
  449. if (!(await fs.stat(entryDir)).isDirectory()) {
  450. diagnostics.push({
  451. level: 'warning',
  452. code: 'skill_directory_link_not_directory',
  453. rootId: root.id,
  454. locationUri: locationUriFromFilePath(entryDir),
  455. message: 'Skill directory link target is not a directory',
  456. });
  457. continue;
  458. }
  459. contentDir = await fs.realpath(entryDir);
  460. allowOutsideRoot = allowsDirectorySymlinkOutsideRoot(root);
  461. } catch (error) {
  462. diagnostics.push({
  463. level: 'warning',
  464. code: 'skill_directory_link_unreadable',
  465. rootId: root.id,
  466. locationUri: locationUriFromFilePath(entryDir),
  467. message: `Unable to resolve skill directory link: ${error instanceof Error ? error.message : String(error)}`,
  468. });
  469. continue;
  470. }
  471. }
  472. const skillFile = path.join(contentDir, 'SKILL.md');
  473. try {
  474. const stat = await fs.lstat(skillFile);
  475. if (stat.isSymbolicLink()) {
  476. diagnostics.push({
  477. level: 'warning',
  478. code: 'skill_symlink_rejected',
  479. rootId: root.id,
  480. locationUri: locationUriFromFilePath(skillFile),
  481. message: 'SKILL.md symlinks are not allowed inside bounded skill roots',
  482. });
  483. continue;
  484. }
  485. if (stat.isFile()) {
  486. const fileLocation = await fs.realpath(skillFile);
  487. if (allowOutsideRoot || isInsideRoot(root, fileLocation)) {
  488. files.push({ fileLocation, contentDir, entryDir, allowOutsideRoot });
  489. } else {
  490. diagnostics.push({
  491. level: 'warning',
  492. code: 'skill_outside_root',
  493. rootId: root.id,
  494. locationUri: locationUriFromFilePath(fileLocation),
  495. message: 'Resolved SKILL.md path is outside its bounded skill root',
  496. });
  497. }
  498. }
  499. } catch (error) {
  500. if (errorCode(error) !== 'ENOENT') {
  501. diagnostics.push({
  502. level: 'warning',
  503. code: 'skill_file_unreadable',
  504. rootId: root.id,
  505. locationUri: locationUriFromFilePath(skillFile),
  506. message: `Unable to inspect SKILL.md: ${error instanceof Error ? error.message : String(error)}`,
  507. });
  508. }
  509. }
  510. }
  511. return files.sort(
  512. (left, right) =>
  513. left.fileLocation.localeCompare(right.fileLocation) ||
  514. left.entryDir.localeCompare(right.entryDir),
  515. );
  516. }
  517. async function statSkillFile(
  518. root: CanonicalRoot,
  519. candidate: SkillFileCandidate,
  520. diagnostics: SkillDiagnostic[],
  521. ): Promise<SkillFileStat | undefined> {
  522. const { fileLocation, allowOutsideRoot } = candidate;
  523. let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
  524. try {
  525. const pathStat = await fs.lstat(fileLocation);
  526. if (pathStat.isSymbolicLink()) {
  527. diagnostics.push({
  528. level: 'warning',
  529. code: 'skill_symlink_rejected',
  530. rootId: root.id,
  531. locationUri: locationUriFromFilePath(fileLocation),
  532. message: 'SKILL.md symlinks are not allowed inside bounded skill roots',
  533. });
  534. return undefined;
  535. }
  536. if (!pathStat.isFile()) {
  537. diagnostics.push({
  538. level: 'warning',
  539. code: 'skill_file_not_file',
  540. rootId: root.id,
  541. locationUri: locationUriFromFilePath(fileLocation),
  542. message: 'Skill path is no longer a file',
  543. });
  544. return undefined;
  545. }
  546. handle = await fs.open(fileLocation, OPEN_SKILL_FILE_FLAGS);
  547. const fileStat = await handle.stat();
  548. if (!fileStat.isFile()) {
  549. diagnostics.push({
  550. level: 'warning',
  551. code: 'skill_file_not_file',
  552. rootId: root.id,
  553. locationUri: locationUriFromFilePath(fileLocation),
  554. message: 'Skill path is no longer a file',
  555. });
  556. return undefined;
  557. }
  558. const canonicalFileLocation = await canonicalPath(fileLocation);
  559. if (!allowOutsideRoot && !isInsideRoot(root, canonicalFileLocation)) {
  560. diagnostics.push({
  561. level: 'warning',
  562. code: 'skill_outside_root',
  563. rootId: root.id,
  564. locationUri: locationUriFromFilePath(canonicalFileLocation),
  565. message: 'Resolved SKILL.md path is outside its bounded skill root',
  566. });
  567. return undefined;
  568. }
  569. return {
  570. size: fileStat.size,
  571. mtimeMs: fileStat.mtimeMs,
  572. dev: fileStat.dev,
  573. ino: fileStat.ino,
  574. };
  575. } catch (error) {
  576. const code = errorCode(error);
  577. diagnostics.push({
  578. level: 'warning',
  579. code: code === 'ELOOP' ? 'skill_symlink_rejected' : 'skill_stat_failed',
  580. rootId: root.id,
  581. locationUri: locationUriFromFilePath(fileLocation),
  582. message:
  583. code === 'ELOOP'
  584. ? 'SKILL.md symlinks are not allowed inside bounded skill roots'
  585. : `Unable to stat SKILL.md during refresh: ${error instanceof Error ? error.message : String(error)}`,
  586. });
  587. return undefined;
  588. } finally {
  589. await handle?.close().catch(() => undefined);
  590. }
  591. }
  592. function isInsideRoot(root: CanonicalRoot, fileLocation: string): boolean {
  593. return (
  594. fileLocation === root.canonicalPath ||
  595. fileLocation.startsWith(`${root.canonicalPath}${path.sep}`)
  596. );
  597. }
  598. async function parseSkillFile(
  599. root: CanonicalRoot,
  600. candidate: SkillFileCandidate,
  601. stat: SkillFileStat,
  602. key: string,
  603. ): Promise<CachedSkillFile> {
  604. const { fileLocation, contentDir, entryDir } = candidate;
  605. const diagnostics: SkillDiagnostic[] = [];
  606. const readResult = await readStableSkillFile(root, fileLocation, stat);
  607. diagnostics.push(...readResult.diagnostics);
  608. const content = readResult.content;
  609. if (content === undefined) {
  610. return { key, diagnostics };
  611. }
  612. const { frontmatter, displayNames, descriptions, body } = parseFrontmatter(
  613. content,
  614. diagnostics,
  615. root.id,
  616. fileLocation,
  617. );
  618. const title = stringValue(frontmatter.title) ?? firstHeading(body);
  619. const description = stringValue(frontmatter.description) ?? firstDescription(body);
  620. const name = stringValue(frontmatter.name) ?? path.basename(path.dirname(fileLocation));
  621. if (!title) {
  622. diagnostics.push({
  623. level: 'warning',
  624. code: 'missing_title',
  625. rootId: root.id,
  626. locationUri: locationUriFromFilePath(fileLocation),
  627. message: 'Skill is missing frontmatter title and markdown heading',
  628. });
  629. }
  630. if (!description) {
  631. diagnostics.push({
  632. level: 'warning',
  633. code: 'missing_description',
  634. rootId: root.id,
  635. locationUri: locationUriFromFilePath(fileLocation),
  636. message: 'Skill is missing frontmatter description and body description',
  637. });
  638. }
  639. if (!name) {
  640. diagnostics.push({
  641. level: 'error',
  642. code: 'missing_name',
  643. rootId: root.id,
  644. locationUri: locationUriFromFilePath(fileLocation),
  645. message: 'Skill name could not be inferred',
  646. });
  647. return { key, diagnostics };
  648. }
  649. return {
  650. key,
  651. diagnostics,
  652. entry: {
  653. id: `${root.id}:${name}:${locationUriFromFilePath(fileLocation)}`,
  654. name,
  655. title: title || name,
  656. description: resolveSkillContentVariables(description || ''),
  657. firstDescriptionLine: firstNonEmptyLine(resolveSkillContentVariables(description || '')),
  658. content: resolveSkillContentVariables(content),
  659. locationUri: locationUriFromFilePath(fileLocation),
  660. skillDir: contentDir,
  661. entryDir,
  662. rootId: root.id,
  663. rootKind: root.kind,
  664. rootScope: root.scope,
  665. rootPriority: root.priority ?? 0,
  666. sourceExternal: root.external ?? isExternalUserHomeSource(root),
  667. frontmatter,
  668. ...(displayNames ? { displayNames } : {}),
  669. ...(descriptions ? { descriptions } : {}),
  670. size: stat.size,
  671. mtimeMs: stat.mtimeMs,
  672. },
  673. };
  674. }
  675. async function readStableSkillFile(
  676. root: CanonicalRoot,
  677. fileLocation: string,
  678. expectedStat: SkillFileStat,
  679. ): Promise<{ content?: string; diagnostics: SkillDiagnostic[] }> {
  680. let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
  681. try {
  682. handle = await fs.open(fileLocation, OPEN_SKILL_FILE_FLAGS);
  683. const openedStat = await handle.stat();
  684. if (!openedStat.isFile()) {
  685. return {
  686. diagnostics: [
  687. {
  688. level: 'warning',
  689. code: 'skill_file_not_file',
  690. rootId: root.id,
  691. locationUri: locationUriFromFilePath(fileLocation),
  692. message: 'Skill path is no longer a file',
  693. },
  694. ],
  695. };
  696. }
  697. if (!sameSkillFileStat(expectedStat, openedStat)) {
  698. return {
  699. diagnostics: [
  700. {
  701. level: 'warning',
  702. code: 'skill_changed_during_read',
  703. rootId: root.id,
  704. locationUri: locationUriFromFilePath(fileLocation),
  705. message: 'SKILL.md changed between stat and read; retry on next refresh',
  706. },
  707. ],
  708. };
  709. }
  710. return { content: await handle.readFile({ encoding: 'utf8' }), diagnostics: [] };
  711. } catch (error) {
  712. const code = errorCode(error);
  713. if (code === 'ELOOP') {
  714. return {
  715. diagnostics: [
  716. {
  717. level: 'warning',
  718. code: 'skill_symlink_rejected',
  719. rootId: root.id,
  720. locationUri: locationUriFromFilePath(fileLocation),
  721. message: 'SKILL.md symlinks are not allowed inside bounded skill roots',
  722. },
  723. ],
  724. };
  725. }
  726. return {
  727. diagnostics: [
  728. {
  729. level: 'error',
  730. code: 'skill_read_failed',
  731. rootId: root.id,
  732. locationUri: locationUriFromFilePath(fileLocation),
  733. message: `Unable to read SKILL.md: ${error instanceof Error ? error.message : String(error)}`,
  734. },
  735. ],
  736. };
  737. } finally {
  738. await handle?.close().catch(() => undefined);
  739. }
  740. }
  741. function sameSkillFileStat(expected: SkillFileStat, actual: SkillFileStat): boolean {
  742. return (
  743. expected.dev === actual.dev &&
  744. expected.ino === actual.ino &&
  745. expected.size === actual.size &&
  746. expected.mtimeMs === actual.mtimeMs
  747. );
  748. }
  749. function listWatchableSkillDirs(rootPath: string): string[] {
  750. try {
  751. return readdirSync(rootPath, { withFileTypes: true })
  752. .filter((child) => child.isDirectory())
  753. .map((child) => path.join(rootPath, child.name))
  754. .sort();
  755. } catch {
  756. return [];
  757. }
  758. }
  759. function errorCode(error: unknown): string | undefined {
  760. if (typeof error !== 'object' || error === null || !('code' in error)) {
  761. return undefined;
  762. }
  763. const code = (error as { code?: unknown }).code;
  764. return typeof code === 'string' ? code : undefined;
  765. }
  766. function parseFrontmatter(
  767. content: string,
  768. diagnostics: SkillDiagnostic[],
  769. rootId: string,
  770. fileLocation: string,
  771. ): {
  772. frontmatter: Record<string, string | number | boolean>;
  773. displayNames?: Record<string, string>;
  774. descriptions?: Record<string, string>;
  775. body: string;
  776. } {
  777. const startMatch = /^---\r?\n/.exec(content);
  778. if (!startMatch) {
  779. return { frontmatter: {}, body: content };
  780. }
  781. const frontmatterStart = startMatch[0].length;
  782. const closingMatch = /(?:^|\r?\n)---(?:\r?\n|$)/.exec(content.slice(frontmatterStart));
  783. if (!closingMatch || closingMatch.index === undefined) {
  784. diagnostics.push({
  785. level: 'error',
  786. code: 'frontmatter_unclosed',
  787. rootId,
  788. locationUri: locationUriFromFilePath(fileLocation),
  789. message: 'Frontmatter starts with --- but never closes',
  790. });
  791. return { frontmatter: {}, body: '' };
  792. }
  793. const closingPrefixLength = closingMatch[0].startsWith('\r\n')
  794. ? 2
  795. : closingMatch[0].startsWith('\n')
  796. ? 1
  797. : 0;
  798. const frontmatterEnd = frontmatterStart + closingMatch.index + closingPrefixLength;
  799. const delimiterEnd = frontmatterEnd + 3;
  800. const bodyStart = content.startsWith('\r\n', delimiterEnd)
  801. ? delimiterEnd + 2
  802. : content.startsWith('\n', delimiterEnd)
  803. ? delimiterEnd + 1
  804. : delimiterEnd;
  805. const rawFrontmatter = content.slice(frontmatterStart, frontmatterEnd).trim();
  806. const body = content.slice(bodyStart);
  807. let parsed: unknown;
  808. try {
  809. parsed = yaml.load(rawFrontmatter);
  810. } catch (error) {
  811. diagnostics.push({
  812. level: 'warning',
  813. code: 'frontmatter_invalid_yaml',
  814. rootId,
  815. locationUri: locationUriFromFilePath(fileLocation),
  816. message: `Invalid frontmatter YAML: ${error instanceof Error ? error.message : String(error)}`,
  817. });
  818. return { frontmatter: {}, body };
  819. }
  820. if (parsed === undefined || parsed === null) {
  821. return { frontmatter: {}, body };
  822. }
  823. if (typeof parsed !== 'object' || Array.isArray(parsed)) {
  824. diagnostics.push({
  825. level: 'warning',
  826. code: 'frontmatter_not_mapping',
  827. rootId,
  828. locationUri: locationUriFromFilePath(fileLocation),
  829. message: 'Frontmatter YAML must be a mapping',
  830. });
  831. return { frontmatter: {}, body };
  832. }
  833. const frontmatter: Record<string, string | number | boolean> = {};
  834. for (const [key, value] of Object.entries(parsed)) {
  835. const scalar = frontmatterScalar(value);
  836. if (scalar !== undefined) {
  837. frontmatter[key] = scalar;
  838. }
  839. }
  840. const record = parsed as Record<string, unknown>;
  841. const displayNames = normalizeLocaleTextMap(record.displayNames);
  842. const descriptions = normalizeLocaleTextMap(record.descriptions);
  843. return {
  844. frontmatter,
  845. ...(displayNames ? { displayNames } : {}),
  846. ...(descriptions ? { descriptions } : {}),
  847. body,
  848. };
  849. }
  850. /**
  851. * Normalize a nested `{ <locale>: <text> }` frontmatter map. Non-object inputs
  852. * yield `undefined`; non-string or blank locale values are dropped so a
  853. * malformed optional translation cannot break skill loading. Returns
  854. * `undefined` when no valid entry remains so callers can omit the field.
  855. */
  856. function normalizeLocaleTextMap(value: unknown): Record<string, string> | undefined {
  857. if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
  858. const out: Record<string, string> = {};
  859. for (const [locale, text] of Object.entries(value as Record<string, unknown>)) {
  860. if (typeof text === 'string' && text.trim() !== '') {
  861. out[locale] = text;
  862. }
  863. }
  864. return Object.keys(out).length > 0 ? out : undefined;
  865. }
  866. function frontmatterScalar(value: unknown): string | number | boolean | undefined {
  867. if (typeof value === 'string' || typeof value === 'boolean') return value;
  868. if (typeof value === 'number' && Number.isFinite(value)) return value;
  869. return undefined;
  870. }
  871. function stringValue(value: string | number | boolean | undefined): string | undefined {
  872. return typeof value === 'string' && value.trim() ? value.trim() : undefined;
  873. }
  874. function firstHeading(body: string): string | undefined {
  875. const match = body.match(/^#\s+(.+)$/m);
  876. return match?.[1]?.trim();
  877. }
  878. function firstDescription(body: string): string | undefined {
  879. const lines = body.split(/\r?\n/);
  880. let pastHeading = false;
  881. const description: string[] = [];
  882. for (const rawLine of lines) {
  883. const line = rawLine.trim();
  884. if (!pastHeading && line.startsWith('# ')) {
  885. pastHeading = true;
  886. continue;
  887. }
  888. if (!line) {
  889. if (description.length > 0) {
  890. break;
  891. }
  892. continue;
  893. }
  894. if (line.startsWith('#')) {
  895. if (description.length > 0) {
  896. break;
  897. }
  898. continue;
  899. }
  900. description.push(line);
  901. }
  902. return description.join('\n').trim() || undefined;
  903. }
  904. function firstNonEmptyLine(value: string): string {
  905. return (
  906. value
  907. .split(/\r?\n/)
  908. .find((line) => line.trim())
  909. ?.trim() ?? ''
  910. );
  911. }
  912. function isExternalUserHomeSource(root: CanonicalRoot): boolean {
  913. if (!['global', 'user'].includes(root.kind)) {
  914. return false;
  915. }
  916. return homeDirectories().some(
  917. (home) => root.canonicalPath === home || root.canonicalPath.startsWith(`${home}${path.sep}`),
  918. );
  919. }
  920. function homeDirectories(): string[] {
  921. const driveHome =
  922. process.env.HOMEDRIVE && process.env.HOMEPATH
  923. ? `${process.env.HOMEDRIVE}${process.env.HOMEPATH}`
  924. : undefined;
  925. const homes = [process.env.HOME, process.env.USERPROFILE, driveHome]
  926. .filter((value): value is string => Boolean(value))
  927. .map((value) => path.resolve(value));
  928. return Array.from(new Set(homes));
  929. }
  930. function resolvePrecedence(entries: SkillEntry[]): {
  931. winners: SkillViewEntry[];
  932. losers: SkillLoser[];
  933. } {
  934. const byName = new Map<string, SkillEntry[]>();
  935. for (const entry of entries) {
  936. const group = byName.get(entry.name) ?? [];
  937. group.push(entry);
  938. byName.set(entry.name, group);
  939. }
  940. const winners: SkillViewEntry[] = [];
  941. const losers: SkillLoser[] = [];
  942. for (const group of byName.values()) {
  943. const sorted = sortEntries(group);
  944. const [winner, ...shadowed] = sorted;
  945. if (!winner) {
  946. continue;
  947. }
  948. const winnerLosers: SkillLoser[] = shadowed.map((entry) => ({
  949. entry,
  950. reason: `Shadowed by ${winner.rootKind} source ${winner.locationUri}`,
  951. winnerLocationUri: winner.locationUri,
  952. }));
  953. losers.push(...winnerLosers);
  954. winners.push({ ...winner, losers: winnerLosers });
  955. }
  956. return { winners: sortEntries(winners) as SkillViewEntry[], losers: sortLosers(losers) };
  957. }
  958. function sortEntries<T extends SkillEntry>(entries: T[]): T[] {
  959. return [...entries].sort((left, right) => {
  960. const rank = SOURCE_RANK[left.rootKind] - SOURCE_RANK[right.rootKind];
  961. if (rank !== 0) {
  962. return rank;
  963. }
  964. const priority = right.rootPriority - left.rootPriority;
  965. if (priority !== 0) {
  966. return priority;
  967. }
  968. const name = left.name.localeCompare(right.name);
  969. if (name !== 0) {
  970. return name;
  971. }
  972. return left.locationUri.localeCompare(right.locationUri);
  973. });
  974. }
  975. function sortLosers(losers: SkillLoser[]): SkillLoser[] {
  976. return [...losers].sort((left, right) =>
  977. left.entry.locationUri.localeCompare(right.entry.locationUri),
  978. );
  979. }
  980. function locationUriFromFilePath(filePath: string): string {
  981. return pathToFileURL(filePath).href.replace(/^file:/u, 'files:');
  982. }
  983. function normalizeLocationUri(locationUri: string): string {
  984. if (!locationUri.startsWith('files://')) {
  985. throw new Error(`Unsupported skill location_uri: ${locationUri}`);
  986. }
  987. return locationUriFromFilePath(fileURLToPath(locationUri.replace(/^files:/u, 'file:')));
  988. }
  989. function truncate(value: string, maxChars: number): string {
  990. if (value.length <= maxChars) {
  991. return value;
  992. }
  993. return `${value.slice(0, Math.max(0, maxChars - 1)).trimEnd()}…`;
  994. }
  995. function joinCatalog(existing: string[], next: string): string {
  996. return existing.length === 0 ? next : `${existing.join('\n')}\n${next}`;
  997. }