Skip to content

Agent Zero AI framework

Unify skills CLI with runtime helpers

Alessandro9b829a04258e
diff --git a/helpers/skills.py b/helpers/skills.py
index 1eeaa8504..a2a4e29cd 100644
--- a/helpers/skills.py
+++ b/helpers/skills.py
@@ -431,6 +431,7 @@ def find_skill(
agent:Agent|None=None,
include_content: bool = False,
include_hidden: bool = False,
+ validate: bool = True,
) -> Optional[Skill]:
target = _normalize_name(skill_name)
if not target:
@@ -440,7 +441,11 @@ def find_skill(
for root in roots:
for skill_md in discover_skill_md_files(Path(root)):
- s = skill_from_markdown(skill_md, include_content=include_content)
+ s = skill_from_markdown(
+ skill_md,
+ include_content=include_content,
+ validate=validate,
+ )
if not s:
continue
if _normalize_name(s.name) == target or _normalize_name(s.path.name) == target:
diff --git a/helpers/skills.py.dox.md b/helpers/skills.py.dox.md
index 902caf3fc..363edfca4 100644
--- a/helpers/skills.py.dox.md
+++ b/helpers/skills.py.dox.md
@@ -28,7 +28,7 @@
- `skill_from_markdown(skill_md_path: Path, include_content: bool=..., validate: bool=...) -> Optional[Skill]`
- `list_skills(agent: Agent | None=..., include_content: bool=..., include_hidden: bool=...) -> List[Skill]`: List skills, optionally filtered by agent scope.
- `delete_skill(skill_path: str) -> None`: Delete a skill directory.
-- `find_skill(skill_name: str, agent: Agent | None=..., include_content: bool=..., include_hidden: bool=...) -> Optional[Skill]`
+- `find_skill(skill_name: str, agent: Agent | None=..., include_content: bool=..., include_hidden: bool=..., validate: bool=...) -> Optional[Skill]`
- `load_skill_for_agent(skill_name: str, agent: Agent | None=...) -> str`: Load skill and format it as a complete string for agent context.
- `skill_instruction_name(message: Any) -> str`
- `_get_skill_files(skill_dir: Path) -> str`: Get file tree for skill directory.
@@ -59,6 +59,7 @@
- Loaded skill bodies live in chat history; hiding a skill changes catalog visibility but does not remove the loaded-skill ledger.
- `build_active_skills_prompt()` returns empty because selected skills are loaded through history, not prompt protocol.
- `search_skills()` normalizes query words, scores normal terms against skill names, and scores only long terms against tags/triggers; descriptions match only full query phrases so generic prose does not produce irrelevant suggestions.
+- `find_skill(validate=False)` lets validation tooling resolve a skill with incomplete metadata while preserving runtime validation by default.
- Invalid `SKILL.md` frontmatter emits a once-per-path scan warning with the skipped skill path/name and a line number when the parser can identify one directly.
- Observed side-effect areas: filesystem reads, filesystem deletion, plugin state, settings/state persistence, context data, secret handling.
- Imported dependency areas include: `__future__`, `dataclasses`, `helpers`, `os`, `pathlib`, `re`, `typing`.
diff --git a/helpers/skills_cli.py b/helpers/skills_cli.py
index a510b111d..435e2a759 100644
--- a/helpers/skills_cli.py
+++ b/helpers/skills_cli.py
@@ -11,155 +11,47 @@ Usage:
"""
import argparse
-import os
import sys
-import yaml
-import re
from pathlib import Path
-from typing import Optional, List, Dict, Any
-from dataclasses import dataclass, field
-from datetime import datetime
-# Add parent directory to path for imports
-sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+from helpers import files, skills as skills_runtime
-from helpers import files
+Skill = skills_runtime.Skill
-@dataclass
-class Skill:
- """Represents a skill loaded from SKILL.md"""
- name: str
- description: str
- path: Path
- version: str = "1.0.0"
- author: str = ""
- tags: List[str] = field(default_factory=list)
- trigger_patterns: List[str] = field(default_factory=list)
- content: str = ""
-
-def get_skills_dirs() -> List[Path]:
+def get_skills_dirs() -> list[Path]:
"""Get all skill directories"""
- base = Path(files.get_abs_path("usr", "skills"))
- roots = [
- Path(files.get_abs_path("skills")),
- base,
- base / "custom",
- base / "default",
- ]
- seen: set[Path] = set()
- ordered: List[Path] = []
- for root in roots:
- if root not in seen:
- seen.add(root)
- ordered.append(root)
- return ordered
-
-
-def parse_skill_file(skill_path: Path) -> Optional[Skill]:
+ return [Path(root) for root in skills_runtime.get_skill_roots()]
+
+
+def parse_skill_file(skill_path: Path) -> Skill | None:
"""Parse a SKILL.md file and return a Skill object"""
- try:
- content = skill_path.read_text(encoding="utf-8")
-
- # Parse YAML frontmatter
- if content.startswith("---"):
- parts = content.split("---", 2)
- if len(parts) >= 3:
- frontmatter = yaml.safe_load(parts[1])
- body = parts[2].strip()
-
- return Skill(
- name=frontmatter.get("name", skill_path.parent.name),
- description=frontmatter.get("description", ""),
- path=skill_path.parent,
- version=frontmatter.get("version", "1.0.0"),
- author=frontmatter.get("author", ""),
- tags=frontmatter.get("tags", []),
- trigger_patterns=frontmatter.get("trigger_patterns", []),
- content=body,
- )
-
- return None
- except Exception as e:
- print(f"Error parsing {skill_path}: {e}")
- return None
-
-
-def list_skills() -> List[Skill]:
- """List all available skills"""
- skills = []
- for skills_dir in get_skills_dirs():
- if not skills_dir.exists():
- continue
- for skill_dir in skills_dir.iterdir():
- if skill_dir.is_dir():
- skill_file = skill_dir / "SKILL.md"
- if skill_file.exists():
- skill = parse_skill_file(skill_file)
- if skill:
- skills.append(skill)
- return skills
-
-
-def find_skill(name: str) -> Optional[Skill]:
- """Find a skill by name"""
- for skill in list_skills():
- if skill.name == name or skill.path.name == name:
- return skill
- return None
+ return skills_runtime.skill_from_markdown(
+ skill_path,
+ include_content=True,
+ validate=False,
+ )
-def search_skills(query: str) -> List[Skill]:
- """Search skills by name, description, or tags"""
- query = query.lower()
- results = []
- for skill in list_skills():
- if (
- query in skill.name.lower()
- or query in skill.description.lower()
- or any(query in tag.lower() for tag in skill.tags)
- or any(query in trigger.lower() for trigger in skill.trigger_patterns)
- ):
- results.append(skill)
- return results
-
-
-def validate_skill(skill: Skill) -> List[str]:
- """Validate a skill and return list of issues"""
- issues = []
+def list_skills() -> list[Skill]:
+ """List all available skills"""
+ return skills_runtime.list_skills(include_content=True)
- # Required fields
- if not skill.name:
- issues.append("Missing required field: name")
- if not skill.description:
- issues.append("Missing required field: description")
- # Name format
- if skill.name:
- if not (1 <= len(skill.name) <= 64):
- issues.append("Name must be 1-64 characters")
- if not re.match(r"^[a-z0-9-]+$", skill.name):
- issues.append(f"Invalid name format: '{skill.name}' (use lowercase letters, numbers, and hyphens)")
- if skill.name.startswith("-") or skill.name.endswith("-"):
- issues.append("Name must not start or end with a hyphen")
- if "--" in skill.name:
- issues.append("Name must not contain consecutive hyphens")
+def find_skill(name: str) -> Skill | None:
+ """Find a skill by name"""
+ return skills_runtime.find_skill(name, include_content=True, validate=False)
- # Description length
- if skill.description and len(skill.description) < 20:
- issues.append("Description is too short (minimum 20 characters)")
- # Content
- if len(skill.content) < 100:
- issues.append("Skill content is too short (minimum 100 characters)")
+def search_skills(query: str) -> list[Skill]:
+ """Search skills by name, description, or tags"""
+ return skills_runtime.search_skills(query)
- # Check for associated files
- skill_dir = skill.path
- has_scripts = (skill_dir / "scripts").exists()
- has_docs = (skill_dir / "docs").exists()
- return issues
+def validate_skill(skill: Skill) -> list[str]:
+ """Validate a skill and return list of issues"""
+ return skills_runtime.validate_skill(skill)
def create_skill(name: str, description: str = "", author: str = "") -> Path:
@@ -184,7 +76,7 @@ description: "{description or 'Description of what this skill does and when to u
version: "1.0.0"
author: "{author or 'Your Name'}"
tags: ["custom"]
-trigger_patterns:
+triggers:
- "{name}"
---
@@ -234,7 +126,7 @@ Description of what to do next.
return skill_dir
-def print_skill_table(skills: List[Skill]):
+def print_skill_table(skills: list[Skill]):
"""Print skills in a formatted table"""
if not skills:
print("No skills found.")
@@ -330,7 +222,7 @@ Examples:
print(f"Author: {skill.author or 'Unknown'}")
print(f"Path: {skill.path}")
print(f"Tags: {', '.join(skill.tags) if skill.tags else 'None'}")
- print(f"Triggers: {', '.join(skill.trigger_patterns) if skill.trigger_patterns else 'None'}")
+ print(f"Triggers: {', '.join(skill.triggers) if skill.triggers else 'None'}")
print(f"\nDescription:")
print(f" {skill.description}")
print(f"\nContent Preview (first 500 chars):")
diff --git a/helpers/skills_cli.py.dox.md b/helpers/skills_cli.py.dox.md
index 02aa7922d..9243d6d6b 100644
--- a/helpers/skills_cli.py.dox.md
+++ b/helpers/skills_cli.py.dox.md
@@ -10,29 +10,31 @@
- `skills_cli.py` owns the runtime implementation.
- `skills_cli.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.
-- Classes:
-- `Skill` (no explicit base class)
+- Reuses `helpers.skills.Skill` rather than maintaining a CLI-specific model.
- Top-level functions:
-- `get_skills_dirs() -> List[Path]`: Get all skill directories
-- `parse_skill_file(skill_path: Path) -> Optional[Skill]`: Parse a SKILL.md file and return a Skill object
-- `list_skills() -> List[Skill]`: List all available skills
-- `find_skill(name: str) -> Optional[Skill]`: Find a skill by name
-- `search_skills(query: str) -> List[Skill]`: Search skills by name, description, or tags
-- `validate_skill(skill: Skill) -> List[str]`: Validate a skill and return list of issues
+- `get_skills_dirs() -> list[Path]`: Get all skill directories
+- `parse_skill_file(skill_path: Path) -> Skill | None`: Parse a SKILL.md file and return a Skill object
+- `list_skills() -> list[Skill]`: List all available skills
+- `find_skill(name: str) -> Skill | None`: Find a skill by name
+- `search_skills(query: str) -> list[Skill]`: Search skills by name, description, or tags
+- `validate_skill(skill: Skill) -> list[str]`: Validate a skill and return list of issues
- `create_skill(name: str, description: str=..., author: str=...) -> Path`: Create a new skill from template
-- `print_skill_table(skills: List[Skill])`: Print skills in a formatted table
+- `print_skill_table(skills: list[Skill])`: Print skills in a formatted table
- `main()`
## Runtime Contracts
- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together.
- Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change.
+- Skill discovery, parsing, search, and validation delegate to `helpers.skills` so CLI behavior matches the runtime contract.
+- CLI lookup disables eager validation so the `validate` command can report incomplete metadata through the canonical validator.
+- Created skills use the canonical `triggers` frontmatter field.
- Observed side-effect areas: filesystem reads, filesystem writes, settings/state persistence, secret handling.
-- Imported dependency areas include: `argparse`, `dataclasses`, `datetime`, `helpers`, `os`, `pathlib`, `re`, `sys`, `typing`, `yaml`.
+- Imported dependency areas include: `argparse`, `helpers`, `pathlib`, `sys`.
## Key Concepts
-- Important called helpers/classes observed in the source: `sys.path.insert`, `field`, `Path`, `get_skills_dirs`, `list_skills`, `query.lower`, `exists`, `custom_dir.mkdir`, `skill_dir.exists`, `skill_dir.mkdir`, `mkdir`, `skill_file.write_text`, `readme.write_text`, `argparse.ArgumentParser`, `parser.add_subparsers`, `subparsers.add_parser`, `list_parser.add_argument`, `create_parser.add_argument`, `show_parser.add_argument`, `validate_parser.add_argument`.
+- Important called helpers/classes observed in the source: `skills.get_skill_roots`, `skills.skill_from_markdown`, `skills.list_skills`, `skills.find_skill`, `skills.search_skills`, `skills.validate_skill`, `Path`, `custom_dir.mkdir`, `skill_dir.exists`, `skill_dir.mkdir`, `skill_file.write_text`, `readme.write_text`, `argparse.ArgumentParser`, `parser.add_subparsers`, `subparsers.add_parser`.
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
## Work Guidance
@@ -44,7 +46,7 @@
## Verification
- Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers.
-- No direct test reference was found by name search; choose the nearest behavioral test or perform a focused smoke check.
+- `tests/test_skills_cli.py` verifies that creation, parsing, discovery, lookup, search, and validation use the runtime skill contract.
## Child DOX Index
diff --git a/tests/test_skills_cli.py b/tests/test_skills_cli.py
new file mode 100644
index 000000000..1047648ee
--- /dev/null
+++ b/tests/test_skills_cli.py
@@ -0,0 +1,38 @@
+from helpers import skills, skills_cli
+
+
+def test_cli_uses_runtime_skill_contract(monkeypatch, tmp_path):
+ monkeypatch.setattr(
+ skills_cli.files,
+ "get_abs_path",
+ lambda *parts: str(tmp_path.joinpath(*parts)),
+ )
+ skill_dir = skills_cli.create_skill(
+ "cli-contract",
+ "Use this skill to verify the shared CLI and runtime contract.",
+ )
+ skills_root = tmp_path / "usr" / "skills"
+ monkeypatch.setattr(skills, "get_skill_roots", lambda agent=None: [str(skills_root)])
+
+ parsed = skills_cli.parse_skill_file(skill_dir / "SKILL.md")
+
+ assert isinstance(parsed, skills.Skill)
+ assert parsed.triggers == ["cli-contract"]
+ assert skills_cli.get_skills_dirs() == [skills_root]
+ assert [skill.name for skill in skills_cli.list_skills()] == ["cli-contract"]
+ assert skills_cli.find_skill("cli-contract").triggers == ["cli-contract"]
+ assert [skill.name for skill in skills_cli.search_skills("cli-contract")] == [
+ "cli-contract"
+ ]
+ assert skills_cli.validate_skill(parsed) == skills.validate_skill(parsed) == []
+
+ invalid_dir = skills_root / "invalid-skill"
+ invalid_dir.mkdir()
+ (invalid_dir / "SKILL.md").write_text(
+ "---\nname: invalid-skill\n---\n\n# Invalid skill\n",
+ encoding="utf-8",
+ )
+ invalid = skills_cli.find_skill("invalid-skill")
+
+ assert invalid is not None
+ assert skills_cli.validate_skill(invalid) == ["Missing required field: description"]