Files
orchestration_engine/execution_engine/skills/agent_skills.py

153 lines
5.1 KiB
Python

"""Agent Skills discovery and frontmatter validation.
A Skill is a directory holding a SKILL.md whose YAML frontmatter follows the
Agent Skills specification (https://agentskills.io/specification).
"""
from __future__ import annotations
import hashlib
import re
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
import yaml
SKILL_FILE = "SKILL.md"
_NAME_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
_FRONTMATTER_PATTERN = re.compile(
r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\Z)", re.DOTALL
)
_ALLOWED_FIELDS = {
"name",
"description",
"license",
"compatibility",
"metadata",
"allowed-tools",
}
class SkillFormatError(ValueError):
"""A SKILL.md does not conform to the Agent Skills specification."""
@dataclass(frozen=True)
class SkillMeta:
"""The level-1 metadata of a Skill, plus where it lives."""
name: str
description: str
path: Path
def split_frontmatter(text: str, source: Path) -> tuple[dict, str]:
"""Split a markdown document into its YAML frontmatter mapping and body."""
match = _FRONTMATTER_PATTERN.match(text)
if not match:
raise SkillFormatError(f"{source}: missing YAML frontmatter delimited by '---'")
try:
frontmatter = yaml.safe_load(match.group(1))
except yaml.YAMLError as exc:
raise SkillFormatError(
f"{source}: frontmatter is not valid YAML: {exc}"
) from exc
if not isinstance(frontmatter, dict):
raise SkillFormatError(f"{source}: frontmatter must be a mapping")
return frontmatter, text[match.end() :]
def read_skill(skill_dir: Path) -> SkillMeta:
"""Parse and validate the SKILL.md in `skill_dir`."""
skill_file = skill_dir / SKILL_FILE
frontmatter, _ = split_frontmatter(
skill_file.read_text(encoding="utf-8"), skill_file
)
unknown = set(frontmatter) - _ALLOWED_FIELDS
if unknown:
raise SkillFormatError(
f"{skill_file}: unsupported frontmatter fields: {', '.join(sorted(unknown))}"
)
name = frontmatter.get("name")
if not isinstance(name, str) or not name:
raise SkillFormatError(f"{skill_file}: 'name' is required")
if len(name) > 64:
raise SkillFormatError(f"{skill_file}: 'name' must be at most 64 characters")
if not _NAME_PATTERN.match(name):
raise SkillFormatError(
f"{skill_file}: 'name' must use lowercase letters, digits and single hyphens, "
"without leading or trailing hyphens"
)
if name != skill_dir.name:
raise SkillFormatError(
f"{skill_file}: 'name' {name!r} must match its directory {skill_dir.name!r}"
)
description = frontmatter.get("description")
if not isinstance(description, str) or not description.strip():
raise SkillFormatError(
f"{skill_file}: 'description' is required and must be non-empty"
)
if len(description) > 1024:
raise SkillFormatError(
f"{skill_file}: 'description' must be at most 1024 characters"
)
compatibility = frontmatter.get("compatibility")
if compatibility is not None and (
not isinstance(compatibility, str) or not 1 <= len(compatibility) <= 500
):
raise SkillFormatError(
f"{skill_file}: 'compatibility' must be 1-500 characters"
)
metadata = frontmatter.get("metadata")
if metadata is not None and (
not isinstance(metadata, dict)
or not all(
isinstance(key, str) and isinstance(value, str)
for key, value in metadata.items()
)
):
raise SkillFormatError(
f"{skill_file}: 'metadata' must map string keys to string values"
)
for field in ("license", "allowed-tools"):
if field in frontmatter and not isinstance(frontmatter[field], str):
raise SkillFormatError(f"{skill_file}: '{field}' must be a string")
return SkillMeta(name=name, description=description, path=skill_dir)
def skill_version(skill_dir: Path) -> str:
"""A short content hash of every file in the Skill, to say which Skill was loaded."""
digest = hashlib.sha256()
for path in sorted(p for p in skill_dir.rglob("*") if p.is_file()):
digest.update(path.relative_to(skill_dir).as_posix().encode())
digest.update(path.read_bytes())
return digest.hexdigest()[:12]
def discover_skills(directories: Iterable[Path]) -> dict[str, SkillMeta]:
"""Index every Skill that is an immediate child of one of `directories`.
Raises SkillFormatError on an invalid Skill or a name defined twice.
"""
skills: dict[str, SkillMeta] = {}
for directory in directories:
for child in sorted(directory.iterdir()):
if not (child / SKILL_FILE).is_file():
continue
skill = read_skill(child)
if skill.name in skills:
raise SkillFormatError(
f"Skill {skill.name!r} is defined in both {skills[skill.name].path} and {skill.path}"
)
skills[skill.name] = skill
return skills