skill-files.ts 1.3 KB

123456789101112131415161718192021222324252627
  1. // SKILL.md 读取工具:Claude 插件、Codex 官方技能、第三方技能共用
  2. /** 读取 SKILL.md 头部的 YAML 字段(只处理单层键值,支持 > / | 多行写法) */
  3. export function frontmatter(md: string): Record<string, string> {
  4. const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(md)
  5. const out: Record<string, string> = {}
  6. const lines = m?.[1]?.split(/\r?\n/) ?? []
  7. for (let i = 0; i < lines.length; i++) {
  8. const kv = /^([A-Za-z_-]+):\s*(.*)$/.exec(lines[i]!)
  9. if (!kv) continue
  10. let value = kv[2]!.trim()
  11. if (/^[>|][+-]?$/.test(value)) {
  12. const block: string[] = []
  13. while (i + 1 < lines.length && (/^\s+\S/.test(lines[i + 1]!) || lines[i + 1] === '')) block.push(lines[++i]!.trim())
  14. value = block.join(value.startsWith('>') ? ' ' : '\n').trim()
  15. }
  16. out[kv[1]!] = value.replace(/^["']|["']$/g, '').trim()
  17. }
  18. return out
  19. }
  20. /** SKILL.md 中声明的版本号:frontmatter 顶层的 version,或 metadata 下的 version */
  21. export function declaredVersion(md: string): string | null {
  22. const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(md)?.[1] ?? ''
  23. const v = /^version:\s*(.+)$/m.exec(fm) ?? /^metadata:[^\n]*\n(?:[ \t]+[^\n]*\n)*?[ \t]+version:\s*(.+)$/m.exec(fm)
  24. return v ? v[1]!.trim().replace(/^["']|["']$/g, '').slice(0, 40) || null : null
  25. }