Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

index.ts

281 lines9.3 KB

1/**
2 * `skillDirectory` — a filesystem-backed {@link SkillSource}. Lives behind the
3 * `/node` subpath because it imports `node:fs`; the root export stays edge-safe
4 * (Workers, browsers), mirroring `@tanstack/ai-code-mode-snippets/storage`.
5 */
6import { readFile, readdir, realpath, stat } from 'node:fs/promises'
7import { basename, join, relative, sep } from 'node:path'
8import { walkSkillDirs } from '../walk'
9import { parseSkill, stripFrontmatter } from '../parse'
10import { assertSafeResourcePath, stableHash } from '../util'
11import type { Dirent } from 'node:fs'
12import type { ListDir } from '../walk'
13import type { GeneratedCatalog, GeneratedSkill } from '../static/index'
14import type { SkillMetadata, SkillScriptRef, SkillSource } from '../types'
15​
16const RESOURCE_DIRS = ['references', 'assets']
17const SCRIPT_DIR = 'scripts'
18​
19export interface SkillDirectoryOptions {
20 maxDepth?: number
21 /** default true — promote parse warnings to errors (see spec §7). */
22 strict?: boolean
24​
25const nodeLister: ListDir = async (dir) => {
26 const ents = await readdir(dir, { withFileTypes: true })
27 return ents.map((e) => ({
28 name: e.name,
29 path: join(dir, e.name),
30 type: e.isDirectory() ? 'dir' : 'file',
31 }))
33​
34/** Recursively collect file paths under `dir`, relative to `root`. */
35async function collectFiles(dir: string, root: string): Promise<Array<string>> {
36 let ents: Array<Dirent>
37 try {
38 ents = await readdir(dir, { withFileTypes: true })
39 } catch {
40 return []
41 }
42 const out: Array<string> = []
43 for (const e of ents) {
44 const full = join(dir, e.name)
45 if (e.isDirectory()) out.push(...(await collectFiles(full, root)))
46 else out.push(relative(root, full).replace(/\\/g, '/'))
47 }
48 return out
50​
51function posixRel(path: string): string {
52 return path.replace(/\\/g, '/')
54​
55function hasPrefix(rel: string, prefixes: Array<string>): boolean {
56 const n = posixRel(rel)
57 return prefixes.some((p) => n === p || n.startsWith(`${p}/`))
59​
60async function resolveInside(dir: string, rel: string): Promise<string> {
61 const full = join(dir, rel)
62 const rootReal = await realpath(dir)
63 const fullReal = await realpath(full)
64 const prefix = rootReal.endsWith(sep) ? rootReal : rootReal + sep
65 if (fullReal !== rootReal && !fullReal.startsWith(prefix)) {
66 throw new Error(`unsafe resource path: "${rel}"`)
67 }
68 return fullReal
70​
71export function skillDirectory(
72 root: string | Array<string>,
73 options: SkillDirectoryOptions = {},
74): SkillSource {
75 const roots = Array.isArray(root) ? root : [root]
76 const { maxDepth, strict = true } = options
77​
78 /** Fresh scan of every root → parsed skill name → skill directory. First wins. */
79 const scan = async (): Promise<Map<string, string>> => {
80 const map = new Map<string, string>()
81 for (const r of roots) {
82 const dirs = await walkSkillDirs(nodeLister, r, { maxDepth })
83 for (const d of dirs) {
84 const raw = await readFile(join(d.dir, 'SKILL.md'), 'utf8').catch(
85 () => undefined,
86 )
87 if (raw === undefined) continue
88 try {
89 const parsed = parseSkill(raw, {
90 dirName: basename(d.dir),
91 strict,
92 })
93 if (!map.has(parsed.metadata.name)) {
94 map.set(parsed.metadata.name, d.dir)
95 }
96 } catch {
97 // Skip unparseable skills (same policy as list()).
98 }
99 }
100 }
101 return map
102 }
103​
104 const dirOf = async (name: string): Promise<string> => {
105 const dir = (await scan()).get(name)
106 if (!dir)
107 throw new Error(`no skill named "${name}" under ${roots.join(', ')}`)
108 return dir
109 }
110​
111 return {
112 revision: async () => {
113 const map = await scan()
114 const parts: Array<string> = []
115 for (const [name, dir] of [...map].sort()) {
116 const s = await stat(join(dir, 'SKILL.md')).catch(() => undefined)
117 parts.push(`${name}:${s?.mtimeMs ?? 0}:${s?.size ?? 0}`)
118 }
119 return stableHash(parts.join('|'))
120 },
121 list: async () => {
122 const map = await scan()
123 const out: Array<SkillMetadata> = []
124 for (const [, dir] of map) {
125 const raw = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(
126 () => undefined,
127 )
128 if (raw === undefined) continue
129 try {
130 out.push(parseSkill(raw, { dirName: basename(dir), strict }).metadata)
131 } catch {
132 // Lenient: an unparseable skill is skipped, not fatal (spec §7).
133 // strict mode still throws inside parseSkill for warnings, but a
134 // genuinely broken file (no description) is always skipped.
135 }
136 }
137 return out
138 },
139 load: async (name) => readFile(join(await dirOf(name), 'SKILL.md'), 'utf8'),
140 listResources: async (name) => {
141 const dir = await dirOf(name)
142 const files: Array<string> = []
143 for (const sub of RESOURCE_DIRS) {
144 files.push(...(await collectFiles(join(dir, sub), dir)))
145 }
146 return files
147 },
148 readResource: async (name, path) => {
149 assertSafeResourcePath(path)
150 if (!hasPrefix(path, RESOURCE_DIRS)) {
151 throw new Error(
152 `resource path must be under references/ or assets/: "${path}"`,
153 )
154 }
155 const dir = await dirOf(name)
156 const fullReal = await resolveInside(dir, path)
157 if (hasPrefix(path, ['references'])) {
158 return readFile(fullReal, 'utf8')
159 }
160 return readFile(fullReal)
161 },
162 listScripts: async (name) => {
163 const dir = await dirOf(name)
164 const files = await collectFiles(join(dir, SCRIPT_DIR), dir)
165 return files.map(
166 (p): SkillScriptRef => ({
167 path: p,
168 executable: false,
169 reason: 'no-runtime',
170 }),
171 )
172 },
173 readScript: async (name, path) => {
174 assertSafeResourcePath(path)
175 if (!hasPrefix(path, [SCRIPT_DIR])) {
176 throw new Error(`script path must be under scripts/: "${path}"`)
177 }
178 const dir = await dirOf(name)
179 const fullReal = await resolveInside(dir, path)
180 const bytes = await readFile(fullReal)
181 return new Uint8Array(bytes)
182 },
183 }
185​
186/**
187 * Read a skill directory tree into a plain {@link GeneratedCatalog} — the shape
188 * `staticSkills` consumes. Used by the Vite plugin and directly available for
189 * custom build scripts.
190 */
191export async function generateCatalog(
192 root: string | Array<string>,
193 options: SkillDirectoryOptions = {},
194): Promise<GeneratedCatalog> {
195 const roots = Array.isArray(root) ? root : [root]
196 const skills: Array<GeneratedSkill> = []
197 const seen = new Set<string>()
198 for (const r of roots) {
199 for (const { dir } of await walkSkillDirs(nodeLister, r, {
200 maxDepth: options.maxDepth,
201 })) {
202 const raw = await readFile(join(dir, 'SKILL.md'), 'utf8').catch(
203 () => undefined,
204 )
205 if (raw === undefined) continue
206 let meta
207 try {
208 meta = parseSkill(raw, {
209 dirName: basename(dir),
210 strict: options.strict ?? true,
211 }).metadata
212 } catch {
213 continue
214 }
215 if (seen.has(meta.name)) continue
216 seen.add(meta.name)
217 const resources: Record<string, string> = {}
218 for (const sub of RESOURCE_DIRS) {
219 for (const rel of await collectFiles(join(dir, sub), dir)) {
220 resources[rel] = await readFile(join(dir, rel), 'utf8').catch(
221 () => '',
222 )
223 }
224 }
225 skills.push({
226 name: meta.name,
227 description: meta.description,
228 body: stripFrontmatter(raw),
229 ...(meta.compatibility && { compatibility: meta.compatibility }),
230 ...(Object.keys(resources).length && { resources }),
231 })
232 }
233 }
234 skills.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
235 const revision = stableHash(
236 skills.map((s) => `${s.name}:${stableHash(s.body)}`).join('|'),
237 )
238 return { revision, skills }
240​
241/** Structural Vite plugin (no `vite` type dependency). */
242export interface SkillsCatalogPlugin {
243 name: string
244 resolveId: (id: string) => string | undefined
245 load: (
246 this: { addWatchFile?: (id: string) => void },
247 id: string,
248 ) => Promise<string | undefined>
250​
251/**
252 * Vite plugin that globs `SKILL.md` under `dir` at build time and serves a
253 * virtual module (default id `virtual:tanstack-skills`) exporting the catalog
254 * `as const`. Consumers then wrap it with `staticSkills` for a literal-union of
255 * skill names. The catalog is embedded as JSON, so the bundle hash tracks it.
256 */
257export function skillsCatalogPlugin(
258 options: { dir?: string; virtualId?: string; maxDepth?: number } = {},
259): SkillsCatalogPlugin {
260 const virtualId = options.virtualId ?? 'virtual:tanstack-skills'
261 const resolved = `\0${virtualId}`
262 const dir = options.dir ?? 'skills'
263 return {
264 name: 'tanstack-skills-catalog',
265 resolveId: (id) => (id === virtualId ? resolved : undefined),
266 async load(this: { addWatchFile?: (id: string) => void }, id: string) {
267 if (id !== resolved) return undefined
268 const catalog = await generateCatalog(dir, { maxDepth: options.maxDepth })
269 if (typeof this.addWatchFile === 'function') {
270 for (const r of Array.isArray(dir) ? dir : [dir]) {
271 for (const d of await walkSkillDirs(nodeLister, r, {
272 maxDepth: options.maxDepth,
273 })) {
274 this.addWatchFile(join(d.dir, 'SKILL.md'))
275 }
276 }
277 }
278 return `export const catalog = ${JSON.stringify(catalog)} as const\n`
279 },
280 }