Open History to see the last commit
1/**
2 * Lenient `SKILL.md` frontmatter parsing (spec §7).
3 *
4 * Other clients emit malformed frontmatter — most commonly unquoted colons in
5 * descriptions — so the default is lenient. We hand-roll a tiny parser rather
6 * than pull in a YAML dependency: SKILL.md frontmatter is a flat key/value
7 * block (plus block scalars for `description` and simple lists for
8 * `allowedTools`), and taking `value = rest-of-line-after-first-colon` handles
9 * the unquoted-colon case in a single pass — no quote-and-retry needed.
10 *
11 * | Condition | Behavior |
12 * |----------------------|---------------------------------|
13 * | name/dir mismatch | warn, load |
14 * | name over 64 chars | warn, load |
15 * | invalid name chars | warn, load |
16 * | missing `description`| throw (caller skips) |
17 * | no frontmatter | throw (caller skips) |
18 *
19 * `strict: true` promotes every warning to a thrown error.
20 */
21import type { SkillMetadata } from './types'
22
23export interface ParseWarning {
24 code: 'name-dir-mismatch' | 'name-too-long' | 'name-invalid-chars'
25 message: string
26}
27
28export interface ParsedSkill {
29 metadata: SkillMetadata
30 /** frontmatter stripped. */
31 body: string
32 warnings: Array<ParseWarning>
33}
34
35export class SkillParseError extends Error {
36 override name = 'SkillParseError'
37}
38
39const NAME_RE = /^[a-z0-9-]+$/
40
41/** Split leading `---` frontmatter from the body. Returns null if absent. */
42function splitFrontmatter(
43 raw: string,
44): { frontmatter: string; body: string } | null {
45 // Tolerate a BOM and leading blank lines before the opening fence.
46 const text = raw.replace(/^/, '')
47 const match = /^\s*---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/.exec(
48 text,
49 )
50 if (!match) return null
51 return { frontmatter: match[1] ?? '', body: match[2] ?? '' }
52}
53
54/** Parse the flat frontmatter block into raw string/list/map values. */
55function parseBlock(frontmatter: string): Record<string, unknown> {
56 const lines = frontmatter.split(/\r?\n/)
57 const out: Record<string, unknown> = {}
58 let i = 0
59
60 const indentOf = (s: string) => s.length - s.trimStart().length
61
62 while (i < lines.length) {
63 const line = lines[i]
64 if (line === undefined) break
65 if (line.trim() === '' || line.trimStart().startsWith('#')) {
66 i++
67 continue
68 }
69 // Top-level keys are unindented.
70 if (indentOf(line) > 0) {
71 i++
72 continue
73 }
74 const colon = line.indexOf(':')
75 if (colon === -1) {
76 i++
77 continue
78 }
79 const key = line.slice(0, colon).trim()
80 const value = line.slice(colon + 1).trim()
81
82 // Block scalar: `>` (folded) or `|` (literal), with optional chomp/indent.
83 if (value === '>' || value === '|' || /^[>|][+-]?\d*$/.test(value)) {
84 const folded = value.startsWith('>')
85 const collected: Array<string> = []
86 i++
87 while (i < lines.length) {
88 const next = lines[i]
89 if (next === undefined) break
90 if (next.trim() !== '' && indentOf(next) === 0) break
91 collected.push(next)
92 i++
93 }
94 // Strip the common leading indentation of the block.
95 const nonEmpty = collected.filter((l) => l.trim() !== '')
96 const minIndent = nonEmpty.length
97 ? Math.min(...nonEmpty.map(indentOf))
98 : 0
99 const stripped = collected.map((l) => l.slice(minIndent))
100 out[key] = folded
101 ? stripped.join(' ').replace(/\s+/g, ' ').trim()
102 : stripped.join('\n').trim()
103 continue
104 }
105
106 // Empty value → indented children: a block list (`- x`) or a nested map
107 // (`k: v`), one level deep.
108 if (value === '') {
109 const items: Array<string> = []
110 const map: Record<string, string> = {}
111 let j = i + 1
112 while (j < lines.length) {
113 const next = lines[j]
114 if (next === undefined) break
115 if (next.trim() === '') {
116 j++
117 continue
118 }
119 if (indentOf(next) === 0) break
120 const t = next.trim()
121 if (t.startsWith('- ')) {
122 items.push(unquote(t.slice(2).trim()))
123 } else {
124 const c = t.indexOf(':')
125 if (c === -1) break
126 map[t.slice(0, c).trim()] = unquote(t.slice(c + 1).trim())
127 }
128 j++
129 }
130 if (items.length) out[key] = items
131 else if (Object.keys(map).length) out[key] = map
132 else out[key] = ''
133 i = Math.max(j, i + 1)
134 continue
135 }
136
137 // Inline list `[a, b]`.
138 if (value.startsWith('[') && value.endsWith(']')) {
139 out[key] = value
140 .slice(1, -1)
141 .split(',')
142 .map((s) => unquote(s.trim()))
143 .filter((s) => s !== '')
144 i++
145 continue
146 }
147
148 out[key] = unquote(value)
149 i++
150 }
151 return out
152}
153
154function unquote(s: string): string {
155 if (
156 (s.startsWith('"') && s.endsWith('"')) ||
157 (s.startsWith("'") && s.endsWith("'"))
158 ) {
159 return s.slice(1, -1)
160 }
161 return s
162}
163
164function asStringMap(value: unknown): Record<string, string> | undefined {
165 if (typeof value !== 'object' || value === null) return undefined
166 const out: Record<string, string> = {}
167 for (const [k, v] of Object.entries(value)) {
168 if (typeof v === 'string') out[k] = v
169 }
170 return Object.keys(out).length ? out : undefined
171}
172
173/**
174 * Parse a `SKILL.md`. Throws {@link SkillParseError} for cases the spec says to
175 * skip (no frontmatter, missing description). Non-fatal issues are returned as
176 * `warnings`; `strict` turns them into throws.
177 */
178export function parseSkill(
179 raw: string,
180 opts: { dirName?: string; strict?: boolean } = {},
181): ParsedSkill {
182 const split = splitFrontmatter(raw)
183 if (!split) {
184 throw new SkillParseError('SKILL.md has no frontmatter block')
185 }
186 const block = parseBlock(split.frontmatter)
187
188 const name = typeof block.name === 'string' ? block.name : undefined
189 const description =
190 typeof block.description === 'string' ? block.description : undefined
191
192 if (!description) {
193 throw new SkillParseError('SKILL.md is missing a `description`')
194 }
195
196 const warnings: Array<ParseWarning> = []
197 const effectiveName = name ?? opts.dirName ?? ''
198
199 if (name && opts.dirName && name !== opts.dirName) {
200 warnings.push({
201 code: 'name-dir-mismatch',
202 message: `skill name "${name}" does not match directory "${opts.dirName}"`,
203 })
204 }
205 if (effectiveName.length > 64) {
206 warnings.push({
207 code: 'name-too-long',
208 message: `skill name "${effectiveName}" exceeds 64 characters`,
209 })
210 }
211 if (effectiveName && !NAME_RE.test(effectiveName)) {
212 warnings.push({
213 code: 'name-invalid-chars',
214 message: `skill name "${effectiveName}" contains characters outside [a-z0-9-]`,
215 })
216 }
217
218 if (opts.strict && warnings.length) {
219 throw new SkillParseError(warnings.map((w) => w.message).join('; '))
220 }
221
222 const metadata: SkillMetadata = {
223 name: effectiveName,
224 description,
225 ...(typeof block.license === 'string' && { license: block.license }),
226 ...(typeof block.compatibility === 'string' && {
227 compatibility: block.compatibility,
228 }),
229 ...(Array.isArray(block.allowedTools) && {
230 allowedTools: block.allowedTools.filter(
231 (t): t is string => typeof t === 'string',
232 ),
233 }),
234 ...((): { metadata?: Record<string, string> } => {
235 const m = asStringMap(block.metadata)
236 return m ? { metadata: m } : {}
237 })(),
238 }
239
240 return { metadata, body: split.body.trim(), warnings }
241}
242
243/** Strip the frontmatter block, returning just the body. */
244export function stripFrontmatter(raw: string): string {
245 const split = splitFrontmatter(raw)
246 return split ? split.body.trim() : raw.trim()
247}