#!/usr/bin/env python3 """Reference library CLI for Agent Skills validation and introspection. Adapted from the Agent Skills reference library (stdlib-only, no external deps): https://github.com/agentskills/agentskills/tree/main/skills-ref To check for upstream changes, compare the validation constants and rules in this file against skills-ref/src/skills_ref/ in that repo. Usage: skills-ref.py validate path/to/skill skills-ref.py read-properties path/to/skill skills-ref.py to-prompt path/to/skill-a path/to/skill-b skills-ref.py validate-all """ import argparse import html import json import re import sys import unicodedata from dataclasses import dataclass, field from pathlib import Path from typing import Optional # --- Constants (synced with upstream validator.py) --- MAX_SKILL_NAME_LENGTH = 64 MAX_DESCRIPTION_LENGTH = 1024 MAX_COMPATIBILITY_LENGTH = 500 ALLOWED_FIELDS = { "allowed-tools", "compatibility", "description", "license", "metadata", "name", } # --- Models (synced with upstream models.py) --- @dataclass class SkillProperties: """Properties parsed from a skill's SKILL.md frontmatter.""" name: str description: str license: Optional[str] = None compatibility: Optional[str] = None allowed_tools: Optional[str] = None metadata: dict[str, str] = field(default_factory=dict) def to_dict(self) -> dict: result = {"name": self.name, "description": self.description} if self.license is not None: result["license"] = self.license if self.compatibility is not None: result["compatibility"] = self.compatibility if self.allowed_tools is not None: result["allowed-tools"] = self.allowed_tools if self.metadata: result["metadata"] = self.metadata return result # --- Parser (synced with upstream parser.py, stdlib YAML) --- def find_skill_md(skill_dir: Path) -> Optional[Path]: """Find SKILL.md in a skill directory. Prefers uppercase.""" for name in ("SKILL.md", "skill.md"): path = skill_dir / name if path.exists(): return path return None def parse_frontmatter(content: str) -> tuple[dict, str]: """Parse YAML frontmatter from SKILL.md content. Returns (metadata_dict, markdown_body). Handles simple key: value pairs and one level of nested dicts (metadata). """ if not content.startswith("---"): raise ValueError("SKILL.md must start with YAML frontmatter (---)") parts = content.split("---", 2) if len(parts) < 3: raise ValueError("SKILL.md frontmatter not properly closed with ---") body = parts[2].strip() result: dict = {} current_key = None current_value_lines: list[str] = [] in_metadata = False metadata: dict[str, str] = {} def _save_current(): nonlocal current_key, current_value_lines, metadata, in_metadata if not current_key: return if current_key == "metadata": result["metadata"] = metadata else: val = "\n".join(current_value_lines).strip() if val: result[current_key] = val for line in parts[1].strip().splitlines(): m = re.match(r"^(\S[^:]*?):\s*(.*)", line) if m and not line.startswith(" ") and not line.startswith("\t"): _save_current() current_key = m.group(1).strip() current_value_lines = [m.group(2)] if m.group(2) else [] in_metadata = current_key == "metadata" metadata = {} elif in_metadata and (line.startswith(" ") or line.startswith("\t")): m2 = re.match(r"^\s+(\S[^:]*?):\s*(.*)", line) if m2: metadata[m2.group(1).strip()] = m2.group(2).strip() elif current_key: current_value_lines.append(line) _save_current() return result, body def read_properties(skill_dir: Path) -> SkillProperties: """Read skill properties from SKILL.md frontmatter.""" skill_md = find_skill_md(skill_dir) if skill_md is None: raise ValueError(f"SKILL.md not found in {skill_dir}") content = skill_md.read_text() metadata, _ = parse_frontmatter(content) if "name" not in metadata: raise ValueError("Missing required field in frontmatter: name") if "description" not in metadata: raise ValueError("Missing required field in frontmatter: description") name = metadata["name"] description = metadata["description"] if not isinstance(name, str) or not name.strip(): raise ValueError("Field 'name' must be a non-empty string") if not isinstance(description, str) or not description.strip(): raise ValueError("Field 'description' must be a non-empty string") return SkillProperties( name=name.strip(), description=description.strip(), license=metadata.get("license"), compatibility=metadata.get("compatibility"), allowed_tools=metadata.get("allowed-tools"), metadata=metadata.get("metadata", {}), ) # --- Validator (synced with upstream validator.py) --- def _validate_name(name: str, skill_dir: Path) -> list[str]: errors = [] if not name or not isinstance(name, str) or not name.strip(): return ["Field 'name' must be a non-empty string"] name = unicodedata.normalize("NFKC", name.strip()) if len(name) > MAX_SKILL_NAME_LENGTH: errors.append( f"Skill name '{name}' exceeds {MAX_SKILL_NAME_LENGTH} character limit " f"({len(name)} chars)" ) if name != name.lower(): errors.append(f"Skill name '{name}' must be lowercase") if name.startswith("-") or name.endswith("-"): errors.append("Skill name cannot start or end with a hyphen") if "--" in name: errors.append("Skill name cannot contain consecutive hyphens") if not all(c.isalnum() or c == "-" for c in name): errors.append( f"Skill name '{name}' contains invalid characters. " "Only letters, digits, and hyphens are allowed." ) dir_name = unicodedata.normalize("NFKC", skill_dir.name) if dir_name != name: errors.append( f"Directory name '{skill_dir.name}' must match skill name '{name}'" ) return errors def _validate_description(description: str) -> list[str]: if not description or not isinstance(description, str) or not description.strip(): return ["Field 'description' must be a non-empty string"] if len(description) > MAX_DESCRIPTION_LENGTH: return [ f"Description exceeds {MAX_DESCRIPTION_LENGTH} character limit " f"({len(description)} chars)" ] return [] def validate(skill_dir: Path) -> list[str]: """Validate a skill directory. Returns list of error messages.""" skill_dir = Path(skill_dir) if not skill_dir.exists(): return [f"Path does not exist: {skill_dir}"] if not skill_dir.is_dir(): return [f"Not a directory: {skill_dir}"] skill_md = find_skill_md(skill_dir) if skill_md is None: return ["Missing required file: SKILL.md"] try: content = skill_md.read_text() metadata, _ = parse_frontmatter(content) except ValueError as e: return [str(e)] errors = [] extra = set(metadata.keys()) - ALLOWED_FIELDS if extra: errors.append( f"Unexpected fields in frontmatter: {', '.join(sorted(extra))}. " f"Only {sorted(ALLOWED_FIELDS)} are allowed." ) if "name" not in metadata: errors.append("Missing required field in frontmatter: name") else: errors.extend(_validate_name(metadata["name"], skill_dir)) if "description" not in metadata: errors.append("Missing required field in frontmatter: description") else: errors.extend(_validate_description(metadata["description"])) if "compatibility" in metadata: comp = metadata["compatibility"] if not isinstance(comp, str): errors.append("Field 'compatibility' must be a string") elif len(comp) > MAX_COMPATIBILITY_LENGTH: errors.append( f"Compatibility exceeds {MAX_COMPATIBILITY_LENGTH} character limit " f"({len(comp)} chars)" ) return errors # --- Prompt generator (synced with upstream prompt.py) --- def to_prompt(skill_dirs: list[Path]) -> str: """Generate XML block for agent system prompts.""" if not skill_dirs: return "\n" lines = [""] for skill_dir in skill_dirs: skill_dir = Path(skill_dir).resolve() props = read_properties(skill_dir) skill_md_path = find_skill_md(skill_dir) lines.append("") lines.append("") lines.append(html.escape(props.name)) lines.append("") lines.append("") lines.append(html.escape(props.description)) lines.append("") lines.append("") lines.append(str(skill_md_path)) lines.append("") lines.append("") lines.append("") return "\n".join(lines) # --- CLI --- def cmd_validate(args: argparse.Namespace) -> int: """Validate a skill directory.""" skill_path = Path(args.skill_path) if skill_path.is_file() and skill_path.name.lower() == "skill.md": skill_path = skill_path.parent errors = validate(skill_path) if errors: print(f"Validation failed for {skill_path}:", file=sys.stderr) for error in errors: print(f" - {error}", file=sys.stderr) return 1 print(f"Valid skill: {skill_path}") return 0 def cmd_read_properties(args: argparse.Namespace) -> int: """Read and print skill properties as JSON.""" skill_path = Path(args.skill_path) if skill_path.is_file() and skill_path.name.lower() == "skill.md": skill_path = skill_path.parent try: props = read_properties(skill_path) print(json.dumps(props.to_dict(), indent=2)) return 0 except ValueError as e: print(f"Error: {e}", file=sys.stderr) return 1 def cmd_to_prompt(args: argparse.Namespace) -> int: """Generate XML for agent prompts.""" try: resolved = [] for p in args.skill_paths: path = Path(p) if path.is_file() and path.name.lower() == "skill.md": resolved.append(path.parent) else: resolved.append(path) print(to_prompt(resolved)) return 0 except ValueError as e: print(f"Error: {e}", file=sys.stderr) return 1 def cmd_validate_all(args: argparse.Namespace) -> int: """Validate all skills under skills///.""" skills_root = Path(args.skills_dir) if not skills_root.is_dir(): print(f"ERROR: {skills_root}/ directory not found", file=sys.stderr) return 1 total_errors = 0 skills_found = 0 for category_dir in sorted(skills_root.iterdir()): if not category_dir.is_dir(): continue for skill_dir in sorted(category_dir.iterdir()): if not skill_dir.is_dir(): continue skills_found += 1 errors = validate(skill_dir) if errors: print(f"FAIL: {skill_dir}", file=sys.stderr) for error in errors: print(f" - {error}", file=sys.stderr) total_errors += len(errors) else: print(f" OK: {skill_dir}") if total_errors > 0: print( f"\nFAILED: {total_errors} error(s) in {skills_found} skill(s)", file=sys.stderr, ) return 1 print(f"\nOK: {skills_found} skill(s) validated") return 0 def main() -> int: parser = argparse.ArgumentParser( description="Reference library CLI for Agent Skills." ) subparsers = parser.add_subparsers(dest="command", required=True) # validate p_validate = subparsers.add_parser( "validate", help="Validate a skill directory" ) p_validate.add_argument("skill_path", help="Path to skill directory or SKILL.md") # read-properties p_read = subparsers.add_parser( "read-properties", help="Read skill properties as JSON" ) p_read.add_argument("skill_path", help="Path to skill directory or SKILL.md") # to-prompt p_prompt = subparsers.add_parser( "to-prompt", help="Generate XML for agent prompts" ) p_prompt.add_argument( "skill_paths", nargs="+", help="Paths to skill directories" ) # validate-all (bonus: batch validate all skills in the repo) p_all = subparsers.add_parser( "validate-all", help="Validate all skills under a root directory" ) p_all.add_argument( "skills_dir", nargs="?", default="skills", help="Root directory containing category subdirs (default: skills)" ) args = parser.parse_args() commands = { "validate": cmd_validate, "read-properties": cmd_read_properties, "to-prompt": cmd_to_prompt, "validate-all": cmd_validate_all, } return commands[args.command](args) if __name__ == "__main__": sys.exit(main())