Open History to see the last commit
1/**
2 * Generic skill-directory walk, shared with `@tanstack/ai-sandbox`.
3 *
4 * The algorithm is identical to the one in `ai-sandbox/src/agents-file.ts`, but
5 * parameterized over an injected `list` function so it works over any backing
6 * store (`node:fs`, a `SandboxHandle.fs`, an in-memory tree). Taking only an
7 * injected function keeps this edge-safe, so it lives in the root barrel.
8 */
9
10/** A directory that contains `SKILL.md`. */
11export interface DiscoveredSkillDir {
12 name: string
13 dir: string
14}
15
16/** One entry as reported by an injected {@link ListDir}. */
17export interface WalkEntry {
18 name: string
19 path: string
20 type: 'file' | 'dir'
21}
22
23export type ListDir = (dir: string) => Promise<Array<WalkEntry>>
24
25export const SKILL_FILE = 'SKILL.md'
26export const MAX_SKILL_WALK_DEPTH = 6
27const SKIP_DIR_NAMES = new Set(['.git', 'node_modules'])
28
29function basenameOf(path: string): string {
30 const normalized = path.replace(/\\/g, '/')
31 const segments = normalized.split('/').filter((segment) => segment !== '')
32 return segments[segments.length - 1] ?? path
33}
34
35/**
36 * Find every skill folder under `root`. A skill folder is a directory that
37 * directly contains `SKILL.md`; the walk stops descending once found. Skips
38 * dot-directories, `.git`, and `node_modules`. Bounded by `maxDepth`. Errors
39 * from `list` are swallowed (an unreadable directory yields nothing).
40 *
41 * Unlike `ai-sandbox`'s `discoverSkillDirs`, this returns `[]` when nothing is
42 * found — the "fall back to the clone dir" behavior is a harness-projection
43 * concern and stays at that call site (it is wrong for a catalog).
44 */
45export async function walkSkillDirs(
46 list: ListDir,
47 root: string,
48 opts: { maxDepth?: number } = {},
49): Promise<Array<DiscoveredSkillDir>> {
50 const maxDepth = opts.maxDepth ?? MAX_SKILL_WALK_DEPTH
51 const found: Array<DiscoveredSkillDir> = []
52 await walk(list, root, found, 0, maxDepth)
53 return found
54}
55
56async function walk(
57 list: ListDir,
58 dir: string,
59 found: Array<DiscoveredSkillDir>,
60 depth: number,
61 maxDepth: number,
62): Promise<void> {
63 if (depth > maxDepth) return
64 let entries: Array<WalkEntry>
65 try {
66 entries = await list(dir)
67 } catch {
68 return
69 }
70 const hasSkill = entries.some(
71 (entry) =>
72 entry.type === 'file' &&
73 entry.name.toLowerCase() === SKILL_FILE.toLowerCase(),
74 )
75 if (hasSkill) {
76 found.push({ name: basenameOf(dir), dir })
77 return
78 }
79 for (const entry of entries) {
80 if (entry.type !== 'dir') continue
81 if (entry.name.startsWith('.') || SKIP_DIR_NAMES.has(entry.name)) continue
82 await walk(list, entry.path, found, depth + 1, maxDepth)
83 }
84}