Commit e4cabd99 by sunqi02

feat: add skill_scanner module with scan_skills and update_skills_json

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 92f50e94
import logging
import re
import json
from pathlib import Path
from typing import Dict
from app.config.settings import SkillConfig
logger = logging.getLogger(__name__)
_FRONTMATTER_RE = re.compile(r'^---\s*\n(.*?)\n---\s*\n', re.DOTALL)
def _parse_frontmatter(content: str) -> tuple[dict, str]:
"""Parse YAML frontmatter. Returns (metadata_dict, body_text)."""
match = _FRONTMATTER_RE.match(content)
if not match:
return {}, content
raw = match.group(1)
body = content[match.end():]
metadata = {}
for line in raw.split('\n'):
line = line.strip()
if ':' in line:
key, _, value = line.partition(':')
key = key.strip()
value = value.strip().strip('"').strip("'")
metadata[key] = value
return metadata, body.strip()
def scan_skills(skills_dir: Path) -> Dict[str, SkillConfig]:
"""
遍历 skills_dir 下每个子目录的 SKILL.md,解析 frontmatter 和正文,
返回 {code: SkillConfig} 字典。
"""
skills: Dict[str, SkillConfig] = {}
if not skills_dir.exists():
logger.warning(f"skills 目录不存在: {skills_dir}")
return skills
for entry in sorted(skills_dir.iterdir()):
if not entry.is_dir():
continue
if entry.name.startswith('.') or entry.name.startswith('_'):
continue
skill_md = entry / "SKILL.md"
if not skill_md.exists():
logger.warning(f"跳过目录 {entry.name}: 缺少 SKILL.md")
continue
code = entry.name
try:
content = skill_md.read_text(encoding="utf-8")
meta, body = _parse_frontmatter(content)
if not meta:
logger.error(f"跳过 {code}: frontmatter 解析失败")
continue
skills[code] = SkillConfig(
code=code,
name=meta.get("name", code),
description=meta.get("description", ""),
instruction=body,
location=f"skills/{code}",
)
except Exception as e:
logger.error(f"跳过 {code}: 读取失败 - {e}")
return skills
def update_skills_json(skills_dir: Path, config_dir: Path) -> None:
"""全量扫描 skills 目录,覆盖写入 config/skills.json。"""
skills = scan_skills(skills_dir)
skills_data = {
"skills": {
code: skill.model_dump() for code, skill in skills.items()
}
}
config_dir.mkdir(parents=True, exist_ok=True)
output_path = config_dir / "skills.json"
output_path.write_text(
json.dumps(skills_data, ensure_ascii=False, indent=2),
encoding="utf-8",
)
logger.info(f"skills.json 已更新: {len(skills)} 个技能")
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!