@useavalon/caelence-agent 0.1.1-canary.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,15 @@
1
- import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
- import { dirname, join } from "node:path";
1
+ import {
2
+ cpSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readdirSync,
6
+ readFileSync,
7
+ rmSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { dirname, join, resolve } from "node:path";
3
11
  import { errorMessage } from "../core/errors.ts";
12
+ import { harnessHome } from "../desktop/secrets.ts";
4
13
  import { listBundledSkills, parseSkillMarkdown, SKILL_CATALOG_REF_FILE } from "./loader.ts";
5
14
 
6
15
  /** Bare names that install more than one catalog folder. */
@@ -29,8 +38,25 @@ export function bundledPackStepNames(): Set<string> {
29
38
  }
30
39
 
31
40
  const SEARCH_URL = trimTrailingSlashes(process.env.SKILLS_API_URL?.trim() || "https://skills.sh");
32
- const MAX_FILES = 40;
41
+ const MAX_FILES = 80;
33
42
  const MAX_FILE_BYTES = 512 * 1024;
43
+ const GENERIC_SKILL_TOKENS = new Set([
44
+ "skill",
45
+ "skills",
46
+ "frontend",
47
+ "backend",
48
+ "design",
49
+ "ui",
50
+ "web",
51
+ "app",
52
+ "v1",
53
+ "v2",
54
+ "v3",
55
+ "agent",
56
+ "code",
57
+ "kit",
58
+ ]);
59
+ const YAML_NAME_SCAN_LIMIT = 40;
34
60
 
35
61
  function trimTrailingSlashes(value: string): string {
36
62
  let end = value.length;
@@ -45,6 +71,54 @@ function isRepoToken(value: string): boolean {
45
71
  return /^[A-Za-z0-9_.-]+$/.test(value);
46
72
  }
47
73
 
74
+ /** GitHub logins cannot be a registry host like smithery.ai. */
75
+ function isGithubLogin(value: string): boolean {
76
+ if (/\.(ai|com|cn|io|dev|app|org|net|sh|co)$/i.test(value)) return false;
77
+ return isRepoToken(value);
78
+ }
79
+
80
+ function slugifySkillId(value: string): string {
81
+ return value
82
+ .trim()
83
+ .toLowerCase()
84
+ .replace(/[^a-z0-9]+/g, "-")
85
+ .replace(/^-|-$/g, "");
86
+ }
87
+
88
+ /** `owner/repo@skill` and `owner/repo/skill` are the same catalog row. */
89
+ export function normalizeCatalogKey(value: string): string {
90
+ return value.trim().replaceAll("@", "/").toLowerCase();
91
+ }
92
+
93
+ export function catalogRefsMatch(left: string, right: string): boolean {
94
+ return normalizeCatalogKey(left) === normalizeCatalogKey(right);
95
+ }
96
+
97
+ export function skillNameFromCatalogId(id: string): string {
98
+ const value = id.trim();
99
+ if (!value) return "";
100
+ const bundled = /^bundled[@/](.+)$/i.exec(value);
101
+ if (bundled?.[1]) return bundled[1];
102
+ const at = value.lastIndexOf("@");
103
+ if (at > 0) return value.slice(at + 1);
104
+ const slash = value.lastIndexOf("/");
105
+ if (slash >= 0) return value.slice(slash + 1);
106
+ return value;
107
+ }
108
+
109
+ export function isBundledCatalogId(id: string): boolean {
110
+ const value = id.trim();
111
+ if (!value) return false;
112
+ if (/^bundled[@/]/i.test(value)) return true;
113
+ return !value.includes("/") && !value.includes("@");
114
+ }
115
+
116
+ export function skillInstallDirName(yamlName: string, catalogRef?: string): string {
117
+ const nameSlug = slugifySkillId(yamlName);
118
+ if (!catalogRef || catalogRef.startsWith("bundled@")) return nameSlug;
119
+ return slugifySkillId(catalogRef.replaceAll("@", "/")) || nameSlug;
120
+ }
121
+
48
122
  function parseGithubPath(pathname: string): ParsedSkillSource | undefined {
49
123
  const parts = pathname.split("/").filter(Boolean);
50
124
  const owner = parts[0];
@@ -122,15 +196,17 @@ function parseOwnerRepo(value: string): ParsedSkillSource | undefined {
122
196
  if (slash > 0) {
123
197
  const owner = left.slice(0, slash);
124
198
  const repo = left.slice(slash + 1);
125
- if (isRepoToken(owner) && isRepoToken(repo) && skill) {
199
+ if (isGithubLogin(owner) && isRepoToken(repo) && skill) {
126
200
  return { owner, repo, skill, ref: "HEAD" };
127
201
  }
202
+ } else if (isGithubLogin(left) && skill) {
203
+ return parseOwnerRepo(`${left}/${skill}`);
128
204
  }
129
205
  }
130
206
  const parts = value.split("/");
131
207
  const owner = parts[0];
132
208
  const repo = parts[1];
133
- if (!owner || !repo || !isRepoToken(owner) || !isRepoToken(repo)) return undefined;
209
+ if (!owner || !repo || !isGithubLogin(owner) || !isRepoToken(repo)) return undefined;
134
210
  const path = trimTrailingSlashes(parts.slice(2).join("/"));
135
211
  return {
136
212
  owner,
@@ -150,6 +226,11 @@ export function parseSkillSource(
150
226
  }
151
227
  const parsed = parseOwnerRepo(value);
152
228
  if (parsed) return parsed;
229
+ if (/^[A-Za-z0-9_.-]+\.[A-Za-z]{2,}(?:[@/]|$)/.test(value)) {
230
+ return {
231
+ error: `${value} is listed on skills.sh but is not a GitHub repo, so it cannot be added.`,
232
+ };
233
+ }
153
234
  return {
154
235
  error: "Use a bundled name, owner/repo, owner/repo@skill, or a GitHub / skills.sh URL.",
155
236
  };
@@ -171,7 +252,7 @@ export function bundledInstallNames(name: string): string[] | undefined {
171
252
  if (pack) return [...pack];
172
253
  for (const packName of catalogPackNames()) {
173
254
  const members = BUNDLED_PACKS[packName] ?? [];
174
- if (members.some((member) => member === key)) return [...members];
255
+ if (members.includes(key)) return [...members];
175
256
  }
176
257
  const found = listBundledSkills().find((skill) => skill.name.toLowerCase() === key);
177
258
  return found ? [found.name] : undefined;
@@ -226,7 +307,240 @@ export function formatBundledHits(hits: RegistryHit[]): string {
226
307
 
227
308
  export function skillCatalogRef(hit: RegistryHit): string {
228
309
  if (hit.source === "bundled") return `bundled@${hit.name}`;
229
- return `${hit.source}@${hit.name}`;
310
+ if (hit.id.includes("/")) return hit.id;
311
+ if (hit.source.includes("/")) return `${hit.source}@${hit.name}`;
312
+ return hit.source ? `${hit.source}/${hit.name}` : hit.name;
313
+ }
314
+
315
+ /** skills.sh rows we can fetch from GitHub. Hosts like smithery.ai are listings only. */
316
+ export function isInstallableSkillsShHit(hit: { source: string }): boolean {
317
+ if (hit.source === "bundled") return true;
318
+ const slash = hit.source.indexOf("/");
319
+ if (slash <= 0) return false;
320
+ const owner = hit.source.slice(0, slash);
321
+ const repo = hit.source.slice(slash + 1);
322
+ return Boolean(owner && repo && !repo.includes("/") && isGithubLogin(owner) && isRepoToken(repo));
323
+ }
324
+
325
+ const githubFolderCache = new Map<string, string[]>();
326
+ const missingCatalogKeys = new Set<string>();
327
+ let githubFolderDiskLoaded = false;
328
+ let missingCatalogDiskLoaded = false;
329
+
330
+ function githubFoldersPath(env: Record<string, string | undefined> = process.env): string {
331
+ return resolve(harnessHome(env), "github-skill-folders.json");
332
+ }
333
+
334
+ function missingCatalogPath(env: Record<string, string | undefined> = process.env): string {
335
+ return resolve(harnessHome(env), "skills-sh-missing.json");
336
+ }
337
+
338
+ function loadGithubFolderDisk(env: Record<string, string | undefined> = process.env): void {
339
+ if (githubFolderDiskLoaded) return;
340
+ githubFolderDiskLoaded = true;
341
+ try {
342
+ if (!existsSync(githubFoldersPath(env))) return;
343
+ const parsed = JSON.parse(readFileSync(githubFoldersPath(env), "utf8")) as unknown;
344
+ if (!parsed || typeof parsed !== "object") return;
345
+ for (const [source, folders] of Object.entries(parsed as Record<string, unknown>)) {
346
+ if (githubFolderCache.has(source) || !Array.isArray(folders)) continue;
347
+ githubFolderCache.set(
348
+ source,
349
+ folders.filter(
350
+ (folder): folder is string => typeof folder === "string" && folder.length > 0,
351
+ ),
352
+ );
353
+ }
354
+ } catch {
355
+ // Ignore a broken cache file.
356
+ }
357
+ }
358
+
359
+ function saveGithubFolderDisk(env: Record<string, string | undefined> = process.env): void {
360
+ try {
361
+ mkdirSync(harnessHome(env), { recursive: true });
362
+ writeFileSync(
363
+ githubFoldersPath(env),
364
+ `${JSON.stringify(Object.fromEntries(githubFolderCache), null, "\t")}\n`,
365
+ );
366
+ } catch {
367
+ // Memory cache is enough if the home dir is not writable.
368
+ }
369
+ }
370
+
371
+ function loadMissingCatalogDisk(env: Record<string, string | undefined> = process.env): void {
372
+ if (missingCatalogDiskLoaded) return;
373
+ missingCatalogDiskLoaded = true;
374
+ try {
375
+ if (!existsSync(missingCatalogPath(env))) return;
376
+ const parsed = JSON.parse(readFileSync(missingCatalogPath(env), "utf8")) as unknown;
377
+ if (!Array.isArray(parsed)) return;
378
+ for (const id of parsed) {
379
+ if (typeof id === "string" && id.trim()) missingCatalogKeys.add(normalizeCatalogKey(id));
380
+ }
381
+ } catch {
382
+ // Ignore a broken cache file.
383
+ }
384
+ }
385
+
386
+ function saveMissingCatalogDisk(env: Record<string, string | undefined> = process.env): void {
387
+ try {
388
+ mkdirSync(harnessHome(env), { recursive: true });
389
+ writeFileSync(
390
+ missingCatalogPath(env),
391
+ `${JSON.stringify([...missingCatalogKeys], null, "\t")}\n`,
392
+ );
393
+ } catch {
394
+ // Memory cache is enough if the home dir is not writable.
395
+ }
396
+ }
397
+
398
+ function rememberGithubSkillFolders(
399
+ source: string,
400
+ folders: string[],
401
+ env: Record<string, string | undefined> = process.env,
402
+ ): void {
403
+ loadGithubFolderDisk(env);
404
+ githubFolderCache.set(source, folders);
405
+ saveGithubFolderDisk(env);
406
+ }
407
+
408
+ export function rememberMissingCatalogSkill(
409
+ id: string,
410
+ env: Record<string, string | undefined> = process.env,
411
+ ): void {
412
+ const key = normalizeCatalogKey(id);
413
+ if (!key || isBundledCatalogId(id)) return;
414
+ loadMissingCatalogDisk(env);
415
+ missingCatalogKeys.add(key);
416
+ saveMissingCatalogDisk(env);
417
+ }
418
+
419
+ export function isMissingCatalogSkill(
420
+ id: string,
421
+ env: Record<string, string | undefined> = process.env,
422
+ ): boolean {
423
+ loadMissingCatalogDisk(env);
424
+ return missingCatalogKeys.has(normalizeCatalogKey(id));
425
+ }
426
+
427
+ export function clearGithubSkillFolderCache(
428
+ env: Record<string, string | undefined> = process.env,
429
+ ): void {
430
+ githubFolderCache.clear();
431
+ missingCatalogKeys.clear();
432
+ githubFolderDiskLoaded = false;
433
+ missingCatalogDiskLoaded = false;
434
+ for (const path of [githubFoldersPath(env), missingCatalogPath(env)]) {
435
+ try {
436
+ if (existsSync(path)) rmSync(path);
437
+ } catch {
438
+ // Ignore an unwritable cache file.
439
+ }
440
+ }
441
+ }
442
+
443
+ async function githubSkillFolders(
444
+ source: string,
445
+ fetchFn: FetchLike,
446
+ ): Promise<string[] | undefined> {
447
+ loadGithubFolderDisk();
448
+ if (githubFolderCache.has(source)) return githubFolderCache.get(source);
449
+ const parsed = parseSkillSource(source);
450
+ if (!parsed || "error" in parsed || "url" in parsed) return undefined;
451
+ try {
452
+ const treeUrl = `https://api.github.com/repos/${parsed.owner}/${parsed.repo}/git/trees/${parsed.ref}?recursive=1`;
453
+ const res = await fetchFn(treeUrl, {
454
+ headers: {
455
+ accept: "application/vnd.github+json",
456
+ "user-agent": "caelence-harness",
457
+ },
458
+ });
459
+ if (!res.ok) return undefined;
460
+ const data = (await res.json()) as { tree?: Array<{ path?: string; type?: string }> };
461
+ if (!Array.isArray(data.tree)) return undefined;
462
+ const folders = uniqueSkillFolders(
463
+ productionSkillFiles(
464
+ data.tree
465
+ .map((node) => node.path ?? "")
466
+ .filter((path) => path.endsWith("/SKILL.md") || path === "SKILL.md"),
467
+ ),
468
+ parsed.repo,
469
+ );
470
+ rememberGithubSkillFolders(source, folders);
471
+ return folders;
472
+ } catch {
473
+ return undefined;
474
+ }
475
+ }
476
+
477
+ function catalogHitName(hit: RegistryHit): string {
478
+ return (hit.name || skillNameFromCatalogId(hit.id)).trim().toLowerCase();
479
+ }
480
+
481
+ function meaningfulSkillTokens(name: string): string[] {
482
+ return name
483
+ .toLowerCase()
484
+ .split(/[^a-z0-9]+/)
485
+ .filter((token) => token.length > 2 && !GENERIC_SKILL_TOKENS.has(token));
486
+ }
487
+
488
+ function yamlNameLikeness(wanted: string, folder: string): number {
489
+ const key = folder.toLowerCase();
490
+ if (key === wanted) return 1000;
491
+ let score = 0;
492
+ if (wanted.endsWith("-v1") && key.endsWith("-v1")) score += 4;
493
+ for (const token of meaningfulSkillTokens(wanted)) {
494
+ if (key === token || key.endsWith(`-${token}`) || key.startsWith(`${token}-`)) score += 12;
495
+ else if (key.includes(token)) score += 8;
496
+ }
497
+ return score;
498
+ }
499
+
500
+ /** Folder name, single-skill repo, or a non-generic token shared with a folder. */
501
+ export function catalogNameFitsGithubFolders(wanted: string, folders: string[]): boolean {
502
+ const name = wanted.trim().toLowerCase();
503
+ if (!name || folders.length === 0) return false;
504
+ if (folders.some((folder) => folder.toLowerCase() === name)) return true;
505
+ if (folders.length === 1) return true;
506
+ const tokens = meaningfulSkillTokens(name);
507
+ if (tokens.length === 0) return false;
508
+ return folders.some((folder) => yamlNameLikeness(name, folder) > 0);
509
+ }
510
+
511
+ function catalogHitIsInstallable(hit: RegistryHit, folders: string[] | undefined): boolean {
512
+ if (
513
+ isMissingCatalogSkill(skillCatalogRef(hit)) ||
514
+ isMissingCatalogSkill(`${hit.source}/${hit.name}`)
515
+ ) {
516
+ return false;
517
+ }
518
+ if (!folders) return true;
519
+ return catalogNameFitsGithubFolders(catalogHitName(hit), folders);
520
+ }
521
+
522
+ /** Drop skills.sh rows we already know are missing from that GitHub repo. */
523
+ export function dropUninstallableCatalogHits(hits: RegistryHit[]): RegistryHit[] {
524
+ loadGithubFolderDisk();
525
+ loadMissingCatalogDisk();
526
+ return hits.filter((hit) => catalogHitIsInstallable(hit, githubFolderCache.get(hit.source)));
527
+ }
528
+
529
+ /** Drop skills.sh rows whose named skill is not in that GitHub repo. */
530
+ export async function filterGithubCatalogHits(
531
+ hits: RegistryHit[],
532
+ fetchFn: FetchLike,
533
+ ): Promise<RegistryHit[]> {
534
+ const sources = [
535
+ ...new Set(hits.map((hit) => hit.source).filter((source) => source.includes("/"))),
536
+ ];
537
+ const foldersBySource = new Map<string, string[] | undefined>();
538
+ await Promise.all(
539
+ sources.map(async (source) => {
540
+ foldersBySource.set(source, await githubSkillFolders(source, fetchFn));
541
+ }),
542
+ );
543
+ return hits.filter((hit) => catalogHitIsInstallable(hit, foldersBySource.get(hit.source)));
230
544
  }
231
545
 
232
546
  /** True when this loaded skill is the catalog row, not another skill with the same name. */
@@ -234,17 +548,42 @@ export function skillIsCatalogHit(
234
548
  skill: { name: string; source: string; catalogRef?: string },
235
549
  hit: RegistryHit,
236
550
  ): boolean {
237
- const ref = skillCatalogRef(hit);
238
- if (skill.catalogRef) return skill.catalogRef === ref || skill.catalogRef === hit.id;
551
+ const keys = [
552
+ skillCatalogRef(hit),
553
+ hit.id,
554
+ `${hit.source}/${hit.name}`,
555
+ `${hit.source}@${hit.name}`,
556
+ ];
557
+ if (skill.catalogRef) {
558
+ return keys.some((key) => catalogRefsMatch(skill.catalogRef ?? "", key));
559
+ }
239
560
  if (skill.source === "user") {
240
561
  return (
241
562
  skill.name.toLowerCase() === hit.name.toLowerCase() &&
242
563
  (hit.source === "user" || hit.source === "project")
243
564
  );
244
565
  }
566
+ if (hit.source !== "bundled") return false;
245
567
  return skill.name.toLowerCase() === hit.name.toLowerCase();
246
568
  }
247
569
 
570
+ export function findSkillForCatalogId<
571
+ T extends { name: string; source: string; catalogRef?: string },
572
+ >(skills: readonly T[], id: string): T | undefined {
573
+ const wanted = id.trim();
574
+ if (!wanted) return undefined;
575
+ const byRef = skills.find(
576
+ (skill) => skill.catalogRef && catalogRefsMatch(skill.catalogRef, wanted),
577
+ );
578
+ if (byRef) return byRef;
579
+ const name = skillNameFromCatalogId(wanted).toLowerCase();
580
+ if (!name) return undefined;
581
+ if (isBundledCatalogId(wanted)) {
582
+ return skills.find((skill) => skill.name.toLowerCase() === name);
583
+ }
584
+ return undefined;
585
+ }
586
+
248
587
  export async function searchSkillCatalog(
249
588
  query: string,
250
589
  fetchFn: FetchLike = fetch,
@@ -316,21 +655,22 @@ export async function searchSkillsSh(
316
655
  ): Promise<RegistryHit[]> {
317
656
  const q = query.trim();
318
657
  if (!q) return [];
319
- const limit = String(Math.min(Math.max(options.limit ?? 10, 1), 20));
320
- const url = `${SEARCH_URL}/api/search?${new URLSearchParams({ q, limit }).toString()}`;
658
+ const want = Math.min(Math.max(options.limit ?? 10, 1), 20);
659
+ const url = `${SEARCH_URL}/api/search?${new URLSearchParams({ q, limit: String(want) }).toString()}`;
321
660
  const res = await fetchFn(url, { headers: { accept: "application/json" } });
322
661
  if (!res.ok) throw new Error(`skills.sh search failed (${res.status})`);
323
662
  const data = (await res.json()) as {
324
663
  skills?: Array<{ id?: string; name?: string; source?: string; installs?: number }>;
325
664
  };
326
- return (data.skills ?? [])
665
+ const mapped = (data.skills ?? [])
327
666
  .map((row) => ({
328
667
  id: String(row.id ?? row.name ?? ""),
329
668
  name: String(row.name ?? row.id ?? ""),
330
669
  source: String(row.source ?? ""),
331
670
  ...(typeof row.installs === "number" ? { installs: row.installs } : {}),
332
671
  }))
333
- .filter((row) => row.name && row.source);
672
+ .filter((row) => row.name && row.source && isInstallableSkillsShHit(row));
673
+ return filterGithubCatalogHits(mapped, fetchFn);
334
674
  }
335
675
 
336
676
  export function formatRegistryHits(hits: RegistryHit[]): string {
@@ -360,11 +700,9 @@ export async function installSkillFromSource(input: {
360
700
  if ("url" in parsed)
361
701
  return installFromDirectUrl(parsed.url, input.destRoot, input.fetchFn ?? fetch);
362
702
  const skill = input.skill?.trim() || parsed.skill;
363
- const catalogRef = input.source.includes("@")
364
- ? input.source
365
- : skill
366
- ? `${parsed.owner}/${parsed.repo}@${skill}`
367
- : `${parsed.owner}/${parsed.repo}`;
703
+ let catalogRef = `${parsed.owner}/${parsed.repo}`;
704
+ if (input.source.includes("@")) catalogRef = input.source;
705
+ else if (skill) catalogRef = `${parsed.owner}/${parsed.repo}@${skill}`;
368
706
  return installFromGithub({
369
707
  ...parsed,
370
708
  skill,
@@ -389,23 +727,126 @@ async function installFromDirectUrl(
389
727
  return writeSkillDir(destRoot, parsed.name, { "SKILL.md": markdown });
390
728
  }
391
729
 
730
+ const NOISE_SKILL_DIRS = new Set([
731
+ "node_modules",
732
+ "examples",
733
+ "example",
734
+ "test",
735
+ "tests",
736
+ "__tests__",
737
+ "fixtures",
738
+ ]);
739
+
740
+ function isNoiseSkillPath(path: string): boolean {
741
+ return path.split("/").some((part) => NOISE_SKILL_DIRS.has(part));
742
+ }
743
+
392
744
  function skillFolderName(path: string, repo: string): string {
393
745
  return dirname(path) === "." ? repo : (dirname(path).split("/").pop() ?? path);
394
746
  }
395
747
 
748
+ function uniqueSkillFolders(paths: string[], repo: string): string[] {
749
+ const seen = new Set<string>();
750
+ const folders: string[] = [];
751
+ for (const path of paths) {
752
+ const folder = skillFolderName(path, repo);
753
+ const key = folder.toLowerCase();
754
+ if (seen.has(key)) continue;
755
+ seen.add(key);
756
+ folders.push(folder);
757
+ }
758
+ return folders.toSorted((a, b) => a.localeCompare(b));
759
+ }
760
+
761
+ function productionSkillFiles(skillFiles: string[]): string[] {
762
+ const filtered = skillFiles.filter((path) => !isNoiseSkillPath(path));
763
+ return filtered.length > 0 ? filtered : skillFiles;
764
+ }
765
+
396
766
  function skillPathMatches(path: string, wanted: string, input: ParsedSkillSource): boolean {
397
767
  const folder = skillFolderName(path, input.repo);
398
768
  if (folder.toLowerCase() !== wanted) return false;
769
+ const prefix = trimTrailingSlashes(input.path?.toLowerCase() ?? "");
770
+ if (!prefix.includes("/")) return true;
399
771
  const lower = path.toLowerCase();
400
- if (input.path) {
401
- const prefix = input.path.toLowerCase().replace(/\/+$/, "");
402
- return lower === `${prefix}/skill.md` || lower.startsWith(`${prefix}/`);
403
- }
404
- return lower === `${wanted}/skill.md` || lower.endsWith(`/${wanted}/skill.md`);
772
+ return lower === `${prefix}/skill.md` || lower.startsWith(`${prefix}/`);
405
773
  }
406
774
 
407
775
  function pickSkillMd(matches: string[]): string {
408
- return [...matches].sort((a, b) => a.length - b.length || a.localeCompare(b))[0] ?? "";
776
+ const rank = (path: string): number => {
777
+ const lower = path.toLowerCase();
778
+ if (lower === "skill.md") return 0;
779
+ if (/^skills\/[^/]+\/skill\.md$/.test(lower)) return 1;
780
+ if (/^\.github\/skills\/[^/]+\/skill\.md$/.test(lower)) return 2;
781
+ if (/^\.cursor\/skills\/[^/]+\/skill\.md$/.test(lower)) return 3;
782
+ if (/^\.claude\/skills\/[^/]+\/skill\.md$/.test(lower)) return 4;
783
+ if (!path.startsWith(".")) return 5;
784
+ return 6;
785
+ };
786
+ const ranked = matches.toSorted(
787
+ (a, b) => rank(a) - rank(b) || a.length - b.length || a.localeCompare(b),
788
+ );
789
+ return ranked[0] ?? "";
790
+ }
791
+
792
+ function isSkillPayloadFile(path: string, skillMd: string): boolean {
793
+ return path.endsWith(".md") || path.endsWith(".txt") || path === skillMd;
794
+ }
795
+
796
+ function selectSkillPayloadFiles(files: string[], skillMd: string): string[] {
797
+ const unique = [...new Set(files.filter((path) => isSkillPayloadFile(path, skillMd)))];
798
+ const rank = (path: string): number => {
799
+ const base = path.split("/").pop() ?? "";
800
+ const lower = path.toLowerCase();
801
+ if (path === skillMd) return 0;
802
+ if (/^license(\.txt|\.md)?$/i.test(base)) return 1;
803
+ if (lower.includes("/reference/") || lower.includes("/references/")) return 2;
804
+ return 3;
805
+ };
806
+ return unique
807
+ .toSorted((a, b) => rank(a) - rank(b) || a.length - b.length || a.localeCompare(b))
808
+ .slice(0, MAX_FILES);
809
+ }
810
+
811
+ async function yamlNameForSkillMd(
812
+ path: string,
813
+ input: ParsedSkillSource & { fetchFn: FetchLike },
814
+ ): Promise<string> {
815
+ const raw = `https://raw.githubusercontent.com/${input.owner}/${input.repo}/${input.ref}/${path}`;
816
+ const file = await input.fetchFn(raw, { headers: { "user-agent": "caelence-harness" } });
817
+ if (!file.ok) return "";
818
+ const markdown = await file.text();
819
+ return parseSkillMarkdown(markdown, "SKILL.md", ".").name.trim().toLowerCase();
820
+ }
821
+
822
+ async function resolveGithubSkillMatches(input: {
823
+ files: string[];
824
+ wanted?: string;
825
+ input: ParsedSkillSource & { fetchFn: FetchLike };
826
+ }): Promise<string[]> {
827
+ const { files, wanted } = input;
828
+ const repo = input.input.repo;
829
+ if (!wanted) return files;
830
+ const byFolder = files.filter((path) => skillPathMatches(path, wanted, input.input));
831
+ if (byFolder.length > 0) return byFolder;
832
+ const folders = uniqueSkillFolders(files, repo);
833
+ const ranked = [...folders].sort(
834
+ (a, b) => yamlNameLikeness(wanted, b) - yamlNameLikeness(wanted, a) || a.localeCompare(b),
835
+ );
836
+ for (const folder of ranked.slice(0, YAML_NAME_SCAN_LIMIT)) {
837
+ const candidates = files.filter(
838
+ (path) => skillFolderName(path, repo).toLowerCase() === folder.toLowerCase(),
839
+ );
840
+ const md = pickSkillMd(candidates);
841
+ if (!md) continue;
842
+ const yamlName = await yamlNameForSkillMd(md, input.input);
843
+ if (yamlName === wanted) return candidates;
844
+ }
845
+ if (folders.length === 1) {
846
+ const only = folders[0]?.toLowerCase();
847
+ return files.filter((path) => skillFolderName(path, repo).toLowerCase() === only);
848
+ }
849
+ return [];
409
850
  }
410
851
 
411
852
  async function installFromGithub(
@@ -426,40 +867,50 @@ async function installFromGithub(
426
867
  if (!res.ok)
427
868
  return { error: `GitHub tree failed (${res.status}) for ${input.owner}/${input.repo}` };
428
869
  const data = (await res.json()) as { tree?: Array<{ path?: string; type?: string }> };
429
- const skillFiles = (data.tree ?? [])
430
- .map((node) => node.path ?? "")
431
- .filter((path) => path.endsWith("/SKILL.md") || path === "SKILL.md")
432
- .filter(
433
- (path) => !path.split("/").some((part) => part === "node_modules" || part === "examples"),
434
- );
435
- if (skillFiles.length === 0) return { error: `No SKILL.md in ${input.owner}/${input.repo}` };
870
+ const catalogFiles = productionSkillFiles(
871
+ (data.tree ?? [])
872
+ .map((node) => node.path ?? "")
873
+ .filter((path) => path.endsWith("/SKILL.md") || path === "SKILL.md"),
874
+ );
875
+ if (catalogFiles.length === 0) return { error: `No SKILL.md in ${input.owner}/${input.repo}` };
436
876
 
437
877
  const wanted = input.skill?.toLowerCase() || input.path?.split("/").pop()?.toLowerCase();
438
- const matches = wanted
439
- ? skillFiles.filter((path) => skillPathMatches(path, wanted, input))
440
- : skillFiles;
878
+ const matches = await resolveGithubSkillMatches({
879
+ files: catalogFiles,
880
+ wanted,
881
+ input,
882
+ });
883
+ const choices = uniqueSkillFolders(catalogFiles, input.repo);
884
+ rememberGithubSkillFolders(`${input.owner}/${input.repo}`, choices);
441
885
 
442
886
  if (matches.length === 0) {
887
+ const ref =
888
+ input.catalogRef?.trim() || (wanted ? `${input.owner}/${input.repo}@${wanted}` : "");
889
+ if (ref) rememberMissingCatalogSkill(ref);
443
890
  return {
444
891
  error: `No skill ${JSON.stringify(input.skill)} in ${input.owner}/${input.repo}.`,
445
- choices: skillFiles.map((path) => skillFolderName(path, input.repo)),
892
+ choices,
446
893
  };
447
894
  }
448
- if (matches.length > 1 && !wanted) {
895
+ if (!wanted && uniqueSkillFolders(matches, input.repo).length > 1) {
449
896
  return {
450
897
  error: "Repo has several skills. Add @name.",
451
- choices: matches.map((path) => skillFolderName(path, input.repo)),
898
+ choices,
452
899
  };
453
900
  }
454
901
 
455
902
  const skillMd = pickSkillMd(matches);
456
903
  const root = dirname(skillMd) === "." ? "" : dirname(skillMd);
457
- const files = (data.tree ?? [])
458
- .map((node) => node.path ?? "")
459
- .filter(
460
- (path) => path && (root ? path === root || path.startsWith(`${root}/`) : path === "SKILL.md"),
461
- );
462
- if (files.length > MAX_FILES) return { error: `Skill has more than ${MAX_FILES} files.` };
904
+ const files = selectSkillPayloadFiles(
905
+ (data.tree ?? [])
906
+ .map((node) => node.path ?? "")
907
+ .filter(
908
+ (path) =>
909
+ path && (root ? path === root || path.startsWith(`${root}/`) : path === "SKILL.md"),
910
+ ),
911
+ skillMd,
912
+ );
913
+ if (files.length === 0) return { error: "Skill has no installable files." };
463
914
 
464
915
  const downloaded = await downloadSkillFiles(input, files, skillMd, root);
465
916
  if ("error" in downloaded) return downloaded;
@@ -505,7 +956,7 @@ function writeSkillDir(
505
956
  .replace(/[^a-z0-9-]+/g, "-")
506
957
  .replace(/^-|-$/g, "");
507
958
  if (!slug) return { error: "Skill name is empty." };
508
- const dest = join(destRoot, slug);
959
+ const dest = join(destRoot, skillInstallDirName(slug, catalogRef));
509
960
  try {
510
961
  rmSync(dest, { recursive: true, force: true });
511
962
  mkdirSync(dest, { recursive: true });
@@ -521,19 +972,57 @@ function writeSkillDir(
521
972
  } catch (err) {
522
973
  return { error: errorMessage(err) };
523
974
  }
524
- return { name: slug, rel: `${slug}/SKILL.md` };
975
+ return { name: slug, rel: `${skillInstallDirName(slug, catalogRef)}/SKILL.md` };
976
+ }
977
+
978
+ function catalogRefInDir(dir: string): string {
979
+ const path = join(dir, SKILL_CATALOG_REF_FILE);
980
+ if (!existsSync(path)) return "";
981
+ try {
982
+ return readFileSync(path, "utf8").trim();
983
+ } catch {
984
+ return "";
985
+ }
986
+ }
987
+
988
+ function catalogDirMatches(
989
+ stored: string,
990
+ wanted: string,
991
+ precise: boolean,
992
+ wantedName: string,
993
+ ): boolean {
994
+ if (!stored) return false;
995
+ if (precise) return catalogRefsMatch(stored, wanted);
996
+ return skillNameFromCatalogId(stored).toLowerCase() === wantedName;
997
+ }
998
+
999
+ function collectInstalledSkillDirs(destRoot: string, wanted: string): string[] {
1000
+ const precise = wanted.includes("/") || wanted.includes("@");
1001
+ const wantedName = skillNameFromCatalogId(wanted).toLowerCase();
1002
+ const folders = new Set<string>();
1003
+ const bySlug = join(destRoot, skillInstallDirName(wantedName, precise ? wanted : undefined));
1004
+ const byName = join(destRoot, slugifySkillId(wantedName));
1005
+ if (existsSync(bySlug)) folders.add(bySlug);
1006
+ if (existsSync(byName)) folders.add(byName);
1007
+ if (!existsSync(destRoot)) return [...folders];
1008
+ for (const entry of readdirSync(destRoot, { withFileTypes: true })) {
1009
+ if (!entry.isDirectory()) continue;
1010
+ const dir = join(destRoot, entry.name);
1011
+ if (catalogDirMatches(catalogRefInDir(dir), wanted, precise, wantedName)) folders.add(dir);
1012
+ }
1013
+ return [...folders];
525
1014
  }
526
1015
 
527
1016
  export function removeInstalledSkill(
528
1017
  destRoot: string,
529
1018
  name: string,
530
1019
  ): { removed: boolean; reason?: string } {
531
- const slug = name.trim().toLowerCase();
532
- if (!slug) return { removed: false, reason: "Name is empty." };
533
- const dest = join(destRoot, slug);
534
- if (!existsSync(dest)) return { removed: false, reason: "Not installed." };
1020
+ const wanted = name.trim();
1021
+ if (!wanted) return { removed: false, reason: "Name is empty." };
1022
+ const folders = collectInstalledSkillDirs(destRoot, wanted);
1023
+ if (folders.length === 0) return { removed: false, reason: "Not installed." };
535
1024
  try {
536
- rmSync(dest, { recursive: true, force: true });
1025
+ for (const dir of folders) rmSync(dir, { recursive: true, force: true });
537
1026
  return { removed: true };
538
1027
  } catch (err) {
539
1028
  return { removed: false, reason: errorMessage(err) };