Skip to content

The agent that grows with you

refactor(hermes_cli): skills_hub — phase-split do_browse/do_install, unify confirm/error/listing/preview helpers, table-driven slash usage

Teknium9d2f561752ec
diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.py
index b32ad59532a..819c191a6a9 100644
--- a/hermes_cli/skills_hub.py
+++ b/hermes_cli/skills_hub.py
@@ -14,19 +14,44 @@ from rich.console import Console
from rich.panel import Panel
from rich.table import Table
-# Lazy imports to avoid circular dependencies and slow startup.
-# tools.skills_hub and tools.skills_guard are imported inside functions.
+# tools.skills_hub / tools.skills_guard are imported inside functions (cycles + startup cost).
from hermes_constants import display_hermes_home
_console = Console()
+_VALID_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
+_VALID_CATEGORY_RE = re.compile(r"^[a-z][a-z0-9_/-]*$")
+_TRUST_STYLE = {"builtin": "bright_cyan", "trusted": "green", "community": "yellow", "local": "dim"}
+_TRUST_RANK = {"builtin": 3, "trusted": 2, "community": 1}
+# Browse per-source limits. When the centralized index is available,
+# parallel_search_sources skips the external API sources and serves everything
+# from "hermes-index", so that entry MUST cover the whole catalog or browse
+# silently caps the hub (it shipped at 50, then 5000 — both truncated). The
+# index is disk-cached and browse paginates client-side, so a ceiling above the
+# catalog size is right. The external limits only apply when the index is
+# unavailable (offline / first run before the cache populates).
+_BROWSE_LIMITS = {
+ "hermes-index": 1000000, "official": 200, "skills-sh": 200, "well-known": 50,
+ "github": 200, "clawhub": 500, "lobehub": 500, "browse-sh": 500,
+}
+# Programmatic (TUI gateway) browse keeps its own, lower caps.
+_BROWSE_API_LIMITS = {
+ "hermes-index": 5000, "official": 100, "skills-sh": 100, "well-known": 25,
+ "github": 100, "clawhub": 50, "lobehub": 50, "browse-sh": 500,
+}
+_EXTRA_META_LABELS = (
+ ("repo_url", "Repo"), ("detail_url", "Detail Page"), ("index_url", "Index"),
+ ("endpoint", "Endpoint"), ("install_command", "Install Command"),
+ ("installs", "Installs"), ("weekly_installs", "Weekly Installs"),
+)
-def _display_source(r) -> str:
- """Human-facing source label for a result row.
- GitHub-tap skills are stored under source="github"; surface their per-tap provider label
- (NVIDIA / OpenAI / ...) when present so the table reflects the real origin.
- """
+# ---------------------------------------------------------------------------
+# Small shared helpers
+# ---------------------------------------------------------------------------
+
+def _display_source(r) -> str:
+ """Source label for a result row: GitHub-tap rows surface their per-tap provider label."""
if r.source == "github":
provider = (getattr(r, "extra", None) or {}).get("provider")
if provider:
@@ -34,33 +59,127 @@ def _display_source(r) -> str:
return r.source
+def _trust_cell(trust_level: str, source: str, official_label: str = "official") -> str:
+ """Rich-styled trust cell; official-source rows show `official_label` instead of the level."""
+ label = official_label if source == "official" else trust_level
+ return f"[{_TRUST_STYLE.get(trust_level, 'dim')}]{label}[/]"
+
+
+def _truncate(text: str, width: int) -> str:
+ return text[:width] + ("..." if len(text) > width else "")
+
+
+def _identifier_column(table: Table, style: str) -> None:
+ # overflow="fold" keeps the full slug visible (wraps instead of ellipsis-truncating):
+ # browse.sh slugs end in a `-XXXXXX` hash that is part of the identifier users must
+ # copy into `hermes skills install`.
+ table.add_column("Identifier", style=style, overflow="fold", no_wrap=False)
+
+
+def _sources():
+ """Source router over all registries (authenticated GitHub when available)."""
+ from tools.skills_hub import GitHubAuth, create_source_router
+ return create_source_router(GitHubAuth())
+
+
+def _confirm() -> bool:
+ """Prompt `Confirm [y/N]:`; EOF/Ctrl-C counts as no."""
+ try:
+ answer = input("Confirm [y/N]: ").strip().lower()
+ except (EOFError, KeyboardInterrupt):
+ answer = "n"
+ return answer in {"y", "yes"}
+
+
+def _confirm_or_cancel(c: Console, *lines: str, cancel: str = "[dim]Cancelled.[/]\n") -> bool:
+ """Print `lines`, ask `_confirm()`; on refusal print `cancel` and return False."""
+ for line in lines:
+ c.print(line)
+ if _confirm():
+ return True
+ c.print(cancel)
+ return False
+
+
+def _clear_skills_cache() -> None:
+ """Invalidate the skills prompt cache so the change appears immediately."""
+ try:
+ from agent.prompt_builder import clear_skills_system_prompt_cache
+ clear_skills_system_prompt_cache(clear_snapshot=True)
+ except Exception:
+ pass
+
+
+def _finish_change(c: Console, invalidate_cache: bool) -> None:
+ """Apply-now (cache clear) or tell the user the change lands next session."""
+ if invalidate_cache:
+ _clear_skills_cache()
+ return
+ c.print("[dim]Change will take effect in your next session.[/]")
+ c.print("[dim]Use /reset to start a new session now, or --now to apply immediately (invalidates prompt cache).[/]\n")
+
+
+def _print_error(c: Console, message: str) -> None:
+ c.print(f"[bold red]Error:[/] {message}\n")
+
+
+def _print_listed(c: Console, label: str, items) -> None:
+ """`[dim]Label: a, b[/]` when `items` is non-empty."""
+ if items:
+ c.print(f"[dim]{label}: {', '.join(items)}[/]")
+
+
+def _skill_md_preview(bundle) -> Optional[str]:
+ """First 50 lines of the bundle's SKILL.md (None when absent)."""
+ if not bundle or "SKILL.md" not in bundle.files:
+ return None
+ content = bundle.files["SKILL.md"]
+ if isinstance(content, bytes):
+ content = content.decode("utf-8", errors="replace")
+ lines = content.split("\n")
+ preview = "\n".join(lines[:50])
+ if len(lines) > 50:
+ preview += f"\n\n... ({len(lines) - 50} more lines)"
+ return preview
+
+
+def _format_extra_metadata_lines(extra: Dict[str, Any]) -> list[str]:
+ lines: list[str] = []
+ if not extra:
+ return lines
+ for key, label in _EXTRA_META_LABELS:
+ value = extra.get(key)
+ if value is not None and (value or key == "installs"): # installs: 0 is still shown
+ lines.append(f"[bold]{label}:[/] {value}")
+ security = extra.get("security_audits")
+ if isinstance(security, dict) and security:
+ ordered = ", ".join(f"{name}={status}" for name, status in sorted(security.items()))
+ lines.append(f"[bold]Security:[/] {ordered}")
+ return lines
+
+
# ---------------------------------------------------------------------------
-# Shared do_* functions
+# Identifier / source resolution
# ---------------------------------------------------------------------------
def _resolve_short_name(name: str, sources, console: Console) -> str:
- """Resolve a short skill name (e.g. 'pptx') to a full identifier by searching all sources. If
- exactly one match is found, returns its identifier. If multiple matches exist, shows them and
- asks the user to use the full identifier. Returns empty string if nothing found or ambiguous.
+ """Resolve a short skill name (e.g. 'pptx') to a full identifier by searching all sources.
+
+ Exactly one exact match -> its identifier. Several -> the single official one wins,
+ otherwise they are listed and "" is returned. None -> suggestions (or an error) and "".
"""
from tools.skills_hub import unified_search
c = console or _console
c.print(f"[dim]Resolving '{name}'...[/]")
-
results = unified_search(name, sources, source_filter="all", limit=20)
-
- # Filter to exact name matches (case-insensitive)
exact = [r for r in results if r.name.lower() == name.lower()]
if len(exact) == 1:
c.print(f"[dim]Resolved to: {exact[0].identifier}[/]")
return exact[0].identifier
-
if len(exact) > 1:
- # Official catalog entries outrank community mirrors of the same
- # skill: `hermes skills install impeccable` should resolve to the
- # curated official/... entry, not stall on skills.sh duplicates.
+ # Official catalog entries outrank community mirrors of the same skill.
official = [r for r in exact if r.source == "official"]
if len(official) == 1:
c.print(f"[dim]Resolved to: {official[0].identifier} (official catalog)[/]")
@@ -69,105 +188,32 @@ def _resolve_short_name(name: str, sources, console: Console) -> str:
table = Table()
table.add_column("Source", style="dim")
table.add_column("Trust", style="dim")
- # overflow="fold" keeps the full slug visible (wraps instead of ellipsis-truncating)
- # so users can copy it for `hermes skills install`.
- table.add_column("Identifier", style="bold cyan", overflow="fold", no_wrap=False)
+ _identifier_column(table, "bold cyan")
for r in exact:
- trust_style = {"builtin": "bright_cyan", "trusted": "green", "community": "yellow"}.get(r.trust_level, "dim")
- trust_label = "official" if r.source == "official" else r.trust_level
- table.add_row(r.source, f"[{trust_style}]{trust_label}[/]", r.identifier)
+ table.add_row(r.source, _trust_cell(r.trust_level, r.source), r.identifier)
c.print(table)
c.print("[bold]Use the full identifier to install a specific one.[/]\n")
return ""
-
- # No exact match — check if there are partial matches to suggest
if results:
c.print(f"[yellow]No exact match for '{name}'. Did you mean one of these?[/]")
for r in results[:5]:
c.print(f" [cyan]{r.name}[/] — {r.identifier}")
c.print()
return ""
-
- c.print(f"[bold red]Error:[/] No skill named '{name}' found in any source.\n")
+ _print_error(c, f"No skill named '{name}' found in any source.")
return ""
-def _print_tier1_advisory(skill_dir, console) -> None:
- """Print the advisory SkillEvaluator Tier 1 report, if available.
-
- Never raises and never blocks the install: scanner missing, disabled via
- ``skills.tier1_advisory: false``, or erroring all degrade to silence. Secrets-class findings
- render red, the rest yellow.
- """
- try:
- from tools.skillevaluator_scan import (
- format_tier1_report, run_tier1_scan, tier1_advisory_enabled,
- )
- if not tier1_advisory_enabled():
- return
- report = run_tier1_scan(Path(skill_dir))
- if not report.available:
- return
- text = format_tier1_report(report)
- if not report.findings:
- console.print(f"[dim]{text}[/]")
- return
- style = "red" if report.secrets_findings else "yellow"
- console.print(Panel(
- text,
- title="SkillEvaluator Tier 1 (advisory)",
- border_style=style,
- ))
- if report.secrets_findings:
- console.print(
- "[bold red]Possible credentials detected above.[/] "
- "Review the flagged lines before using this skill.\n"
- )
- except Exception as exc: # advisory only — never break an install
- logging.getLogger(__name__).debug("Tier 1 advisory scan skipped: %s", exc)
-
-
-def _format_extra_metadata_lines(extra: Dict[str, Any]) -> list[str]:
- lines: list[str] = []
- if not extra:
- return lines
-
- if extra.get("repo_url"):
- lines.append(f"[bold]Repo:[/] {extra['repo_url']}")
- if extra.get("detail_url"):
- lines.append(f"[bold]Detail Page:[/] {extra['detail_url']}")
- if extra.get("index_url"):
- lines.append(f"[bold]Index:[/] {extra['index_url']}")
- if extra.get("endpoint"):
- lines.append(f"[bold]Endpoint:[/] {extra['endpoint']}")
- if extra.get("install_command"):
- lines.append(f"[bold]Install Command:[/] {extra['install_command']}")
- if extra.get("installs") is not None:
- lines.append(f"[bold]Installs:[/] {extra['installs']}")
- if extra.get("weekly_installs"):
- lines.append(f"[bold]Weekly Installs:[/] {extra['weekly_installs']}")
-
- security = extra.get("security_audits")
- if isinstance(security, dict) and security:
- ordered = ", ".join(f"{name}={status}" for name, status in sorted(security.items()))
- lines.append(f"[bold]Security:[/] {ordered}")
-
- return lines
-
-
def _resolve_source_meta_and_bundle(identifier: str, sources):
- """Resolve metadata and bundle from a single source adapter.
+ """Resolve (meta, bundle, source) from a single source adapter.
- Meta and bundle must come from the same adapter. Keeping catalog metadata from skills.sh while
- taking a ClawHub zip of a same-named skill is how ``hermes skills inspect
- owner/repo/skills/foo`` showed the requested identifier and the wrong SKILL.md.
+ Meta and bundle must come from the same adapter: pairing skills.sh catalog metadata with a
+ ClawHub zip of a same-named skill is how `inspect` once showed the wrong SKILL.md. Falls
+ back to the first adapter that at least produced metadata.
"""
first_meta = None
first_meta_source = None
-
for src in sources:
- meta = None
- bundle = None
try:
meta = src.inspect(identifier)
except Exception:
@@ -184,24 +230,17 @@ def _resolve_source_meta_and_bundle(identifier: str, sources):
meta = None
return meta, bundle, src
if first_meta is None and meta:
- first_meta = meta
- first_meta_source = src
-
+ first_meta, first_meta_source = meta, src
return first_meta, None, first_meta_source
-def _derive_category_from_install_path(install_path: str) -> str:
- path = Path(install_path)
- parent = str(path.parent)
- return "" if parent == "." else parent
-
-
-# ---------------------------------------------------------------------------
-# Interactive name/category resolution for URL-installed skills
-# ---------------------------------------------------------------------------
-
-_VALID_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
-_VALID_CATEGORY_RE = re.compile(r"^[a-z][a-z0-9_/-]*$")
+def _resolve_identifier(identifier: str, sources, c) -> tuple:
+ """Short-name resolution + (meta, bundle, source). identifier == "" means unresolved."""
+ if "/" not in identifier:
+ identifier = _resolve_short_name(identifier, sources, c)
+ if not identifier:
+ return "", None, None, None
+ return (identifier, *_resolve_source_meta_and_bundle(identifier, sources))
def _is_valid_installed_skill_name(name: str) -> bool:
@@ -215,66 +254,17 @@ def _is_valid_installed_skill_name(name: str) -> bool:
def _existing_categories() -> List[str]:
- """Return sorted subdirectory names under ``~/.hermes/skills/`` that look like category buckets
- (contain at least one ``SKILL.md`` somewhere below).
- """
+ """Sorted category buckets under ``~/.hermes/skills/`` (children without their own SKILL.md)."""
from tools.skills_hub import SKILLS_DIR, _category_skill_dirs
try:
- # _category_skill_dirs returns children containing any active
- # SKILL.md — including top-level skills themselves. Only children
- # WITHOUT their own SKILL.md are category buckets.
return sorted(
- name
- for name in set(_category_skill_dirs(SKILLS_DIR))
+ name for name in set(_category_skill_dirs(SKILLS_DIR))
if not (SKILLS_DIR / name / "SKILL.md").exists()
)
except (FileNotFoundError, OSError):
return []
-
-_TRUST_STYLE = {"builtin": "bright_cyan", "trusted": "green", "community": "yellow", "local": "dim"}
-
-
-def _trust_cell(trust_level: str, source: str, official_label: str = "official") -> str:
- """Rich-styled trust cell; official-source rows show `official_label` instead of the level."""
- label = official_label if source == "official" else trust_level
- return f"[{_TRUST_STYLE.get(trust_level, 'dim')}]{label}[/]"
-
-
-def _truncate(text: str, width: int) -> str:
- return text[:width] + ("..." if len(text) > width else "")
-
-
-def _sources():
- """Source router over all registries (authenticated GitHub when available)."""
- from tools.skills_hub import GitHubAuth, create_source_router
- return create_source_router(GitHubAuth())
-
-
-def _confirm() -> bool:
- """Prompt `Confirm [y/N]:`; EOF/Ctrl-C counts as no."""
- try:
- answer = input("Confirm [y/N]: ").strip().lower()
- except (EOFError, KeyboardInterrupt):
- answer = "n"
- return answer in {"y", "yes"}
-
-
-def _clear_skills_cache() -> None:
- """Invalidate the skills prompt cache so the change appears immediately."""
- try:
- from agent.prompt_builder import clear_skills_system_prompt_cache
- clear_skills_system_prompt_cache(clear_snapshot=True)
- except Exception:
- pass
-
-
-def _print_next_session_notice(c: Console) -> None:
- c.print("[dim]Change will take effect in your next session.[/]")
- c.print("[dim]Use /reset to start a new session now, or --now to apply immediately (invalidates prompt cache).[/]\n")
-
-
def _prompt_for_skill_name(c: Console, url: str, default: str = "") -> Optional[str]:
"""Prompt interactively for a skill name. Returns None on cancel/EOF."""
c.print()
@@ -289,7 +279,6 @@ def _prompt_for_skill_name(c: Console, url: str, default: str = "") -> Optional[
f"[dim](lowercase letters, digits, hyphens, underscores; starts with a letter)[/]"
)
from hermes_cli.cli_output import line_input
-
try:
answer = line_input("Name: ").strip()
except (EOFError, KeyboardInterrupt):
@@ -316,7 +305,6 @@ def _prompt_for_category(c: Console, existing: List[str]) -> str:
"[bold]Category[/] [dim](optional — press Enter to install flat at ~/.hermes/skills/<name>/)[/]"
)
from hermes_cli.cli_output import line_input
-
try:
answer = line_input("Category: ").strip()
except (EOFError, KeyboardInterrupt):
@@ -329,31 +317,26 @@ def _prompt_for_category(c: Console, existing: List[str]) -> str:
return answer
+# ---------------------------------------------------------------------------
+# search / browse / inspect
+# ---------------------------------------------------------------------------
+
def do_search(query: str, source: str = "all", limit: int = 10,
console: Optional[Console] = None, as_json: bool = False) -> None:
"""Search registries and display results as a Rich table.
- ``as_json=True`` writes a JSON array (``name``, ``identifier``, ``source``, ``trust_level``,
- ``description``) instead of the table: the scripting handle where the full identifier stays
- intact, even for slugs the table would wrap.
+ ``as_json=True`` writes a JSON array instead — the scripting handle where the full
+ identifier stays intact (no Rich status spinner contaminates stdout).
"""
from tools.skills_hub import unified_search
c = console or _console
-
sources = _sources()
if as_json:
- # Avoid Rich status spinner contaminating stdout — JSON consumers
- # expect a clean parseable stream.
results = unified_search(query, sources, source_filter=source, limit=limit)
payload = [
- {
- "name": r.name,
- "identifier": r.identifier,
- "source": r.source,
- "trust_level": r.trust_level,
- "description": r.description,
- }
+ {"name": r.name, "identifier": r.identifier, "source": r.source,
+ "trust_level": r.trust_level, "description": r.description}
for r in results
]
print(json.dumps(payload, indent=2))
@@ -362,7 +345,6 @@ def do_search(query: str, source: str = "all", limit: int = 10,
c.print(f"\n[bold]Searching for:[/] {query}")
with c.status("[bold]Searching registries..."):
results = unified_search(query, sources, source_filter=source, limit=limit)
-
if not results:
c.print("[dim]No skills found matching your query.[/]\n")
return
@@ -372,68 +354,43 @@ def do_search(query: str, source: str = "all", limit: int = 10,
table.add_column("Description", max_width=60)
table.add_column("Source", style="dim")
table.add_column("Trust", style="dim")
- # overflow="fold" keeps the full slug visible (wraps instead of
- # ellipsis-truncating). Browse.sh slugs end in a `-XXXXXX` hash that
- # is part of the actual identifier — truncating it makes copy-paste
- # into `hermes skills install` fail.
- table.add_column("Identifier", style="dim", overflow="fold", no_wrap=False)
-
+ _identifier_column(table, "dim")
for r in results:
- table.add_row(
- r.name,
- _truncate(r.description, 60),
- _display_source(r),
- _trust_cell(r.trust_level, r.source),
- r.identifier,
- )
-
+ table.add_row(r.name, _truncate(r.description, 60), _display_source(r),
+ _trust_cell(r.trust_level, r.source), r.identifier)
c.print(table)
c.print("[dim]Use: hermes skills inspect <identifier> to preview, "
"hermes skills install <identifier> to install "
"(--json for scripting)[/]\n")
-def do_browse(page: int = 1, page_size: int = 20, source: str = "all",
- console: Optional[Console] = None) -> None:
- """Browse all available skills across registries, paginated.
+def _rank_and_page(all_results, page: int, page_size: int):
+ """Dedupe by identifier (higher trust wins), sort official-first, slice one page.
- Official skills are always shown first, regardless of source filter.
+ identifier is unique per skill; name is not (browse-sh skills from different sites can
+ share a task name). Returns (deduped, page_items, page, total_pages, start).
"""
- from tools.skills_hub import parallel_search_sources
-
- # Clamp page_size to safe range
- page_size = max(1, min(page_size, 100))
-
- c = console or _console
+ seen: dict = {}
+ for r in all_results:
+ rank = _TRUST_RANK.get(r.trust_level, 0)
+ if r.identifier not in seen or rank > _TRUST_RANK.get(seen[r.identifier].trust_level, 0):
+ seen[r.identifier] = r
+ deduped = sorted(seen.values(), key=lambda r: (
+ -_TRUST_RANK.get(r.trust_level, 0), r.source != "official", r.name.lower(),
+ ))
+ total_pages = max(1, (len(deduped) + page_size - 1) // page_size)
+ page = max(1, min(page, total_pages))
+ start = (page - 1) * page_size
+ return deduped, deduped[start:start + page_size], page, total_pages, start
- sources = _sources()
- # Collect results from all (or filtered) sources in parallel.
- # Per-source limits are generous — parallelism + 30s timeout cap prevents hangs.
- _TRUST_RANK = {"builtin": 3, "trusted": 2, "community": 1}
- # NOTE: when the centralized index is available, parallel_search_sources
- # skips the external API sources and serves everything from "hermes-index".
- # That source MUST therefore carry a limit large enough to cover the whole
- # catalog, or browse silently caps the hub — it shipped at 50 (surfaced
- # ~136 of 88k skills), then 5000 (surfaced ~5.4k of 90k). The index is
- # disk-cached and browse paginates client-side, so a ceiling above the
- # current catalog size is the right call. The external-source limits below
- # only apply when the index is unavailable (offline / first run before the
- # cache populates).
- _PER_SOURCE_LIMIT = {
- "hermes-index": 1000000,
- "official": 200, "skills-sh": 200, "well-known": 50,
- "github": 200, "clawhub": 500,
- "lobehub": 500, "browse-sh": 500,
- }
+def _fetch_browse_results(c: Console, source: str):
+ """Parallel fetch from all (or filtered) sources with a live per-source progress spinner."""
+ from tools.skills_hub import parallel_search_sources
with c.status("[bold]Fetching skills from registries...") as status:
- # Live progress: tick off each source as it resolves so the wait is
- # visible instead of a frozen spinner. parallel_search_sources invokes
- # this callback from the collecting thread as each source completes;
- # the page itself is still rendered once, after the correctly-merged
- # and trust-sorted result set is final (browse's ordering contract is
- # computed over the whole set, so we never render a half-sorted page).
+ # parallel_search_sources invokes the callback from the collecting thread as each
+ # source completes; the page itself is rendered once over the final, fully sorted set.
_done: List[str] = []
def _on_source_done(sid: str, count: int) -> None:
@@ -443,58 +400,16 @@ def do_browse(page: int = 1, page_size: int = 20, source: str = "all",
f"[dim]done: {', '.join(_done)}[/]"
)
- all_results, source_counts, timed_out = parallel_search_sources(
- sources,
- query="",
- per_source_limits=_PER_SOURCE_LIMIT,
- source_filter=source,
- overall_timeout=30,
- on_source_done=_on_source_done,
+ return parallel_search_sources(
+ _sources(), query="", per_source_limits=_BROWSE_LIMITS, source_filter=source,
+ overall_timeout=30, on_source_done=_on_source_done,
)
- if not all_results:
- c.print("[dim]No skills found in the Skills Hub.[/]\n")
- return
-
- # Provider filter (nvidia/openai/...) narrows GitHub-tap skills by their
- # per-tap ``extra.provider`` label (the runtime index stores them all under
- # source="github"). Real source ids were already filtered upstream.
- from tools.skills_hub import _PROVIDER_FILTER_VALUES, _filter_results_by_provider
- if source.strip().lower() in _PROVIDER_FILTER_VALUES:
- all_results = _filter_results_by_provider(all_results, source)
- if not all_results:
- c.print(f"[dim]No skills found for provider '{source}'.[/]\n")
- return
-
- # Deduplicate by identifier, preferring higher trust.
- # identifier is always unique per skill; name is not (browse-sh skills from different
- # sites can share the same task name, e.g. "search-listings" on Airbnb and Booking.com).
- seen: dict = {}
- for r in all_results:
- rank = _TRUST_RANK.get(r.trust_level, 0)
- if r.identifier not in seen or rank > _TRUST_RANK.get(seen[r.identifier].trust_level, 0):
- seen[r.identifier] = r
- deduped = list(seen.values())
-
- # Sort: official first, then by trust level (desc), then alphabetically
- deduped.sort(key=lambda r: (
- -_TRUST_RANK.get(r.trust_level, 0),
- r.source != "official",
- r.name.lower(),
- ))
- # Paginate
+def _render_browse_page(c: Console, deduped, page_items, page: int, total_pages: int,
+ start: int, source: str, source_counts, timed_out) -> None:
total = len(deduped)
- total_pages = max(1, (total + page_size - 1) // page_size)
- page = max(1, min(page, total_pages))
- start = (page - 1) * page_size
- end = min(start + page_size, total)
- page_items = deduped[start:end]
-
- # Count official vs other
official_count = sum(1 for r in deduped if r.source == "official")
-
- # Build header
source_label = f"— {source}" if source != "all" else "— all sources"
loaded_label = f"{total} skills loaded"
if timed_out:
@@ -505,54 +420,132 @@ def do_browse(page: int = 1, page_size: int = 20, source: str = "all",
c.print(f"[bright_cyan]★ {official_count} official optional skill(s) from Nous Research[/]")
c.print()
- # Build table
table = Table(show_header=True, header_style="bold")
table.add_column("#", style="dim", width=4, justify="right")
table.add_column("Name", style="bold cyan", max_width=22)
table.add_column("Description", max_width=44)
table.add_column("Source", style="dim", width=12)
table.add_column("Trust", width=10)
- # The identifier is what you pass to `hermes skills install`. Browse used
- # to omit it entirely, so users couldn't act on what they saw without a
- # second `search`. overflow="fold" keeps long slugs copy-pasteable.
- table.add_column("Identifier", style="dim", overflow="fold", no_wrap=False)
-
+ _identifier_column(table, "dim")
for i, r in enumerate(page_items, start=start + 1):
- table.add_row(
- str(i),
- r.name,
- _truncate(r.description, 44),
- _display_source(r),
- _trust_cell(r.trust_level, r.source, official_label="★ official"),
- r.identifier,
- )
-
+ table.add_row(str(i), r.name, _truncate(r.description, 44), _display_source(r),
+ _trust_cell(r.trust_level, r.source, official_label="★ official"),
+ r.identifier)
c.print(table)
- # Navigation hints
nav_parts = []
if page > 1:
nav_parts.append(f"[cyan]--page {page - 1}[/] ← prev")
if page < total_pages:
nav_parts.append(f"[cyan]--page {page + 1}[/] → next")
-
if nav_parts:
c.print(f" {' | '.join(nav_parts)}")
-
- # Source summary
if source == "all" and source_counts:
parts = [f"{sid}: {ct}" for sid, ct in sorted(source_counts.items())]
c.print(f" [dim]Sources: {', '.join(parts)}[/]")
-
if timed_out:
c.print(f" [yellow]⚡ Slow sources skipped: {', '.join(timed_out)} "
f"— run again for cached results[/]")
-
c.print("[dim]Tip: 'hermes skills inspect <identifier>' to preview, "
"'hermes skills install <identifier>' to install, "
"'hermes skills search <query>' to search deeper[/]\n")
+def do_browse(page: int = 1, page_size: int = 20, source: str = "all",
+ console: Optional[Console] = None) -> None:
+ """Browse all available skills across registries, paginated; official skills first."""
+ page_size = max(1, min(page_size, 100))
+ c = console or _console
+ all_results, source_counts, timed_out = _fetch_browse_results(c, source)
+ if not all_results:
+ c.print("[dim]No skills found in the Skills Hub.[/]\n")
+ return
+ # Provider filter (nvidia/openai/...) narrows GitHub-tap skills by their per-tap
+ # ``extra.provider`` label (the runtime index stores them all under source="github").
+ from tools.skills_hub import _PROVIDER_FILTER_VALUES, _filter_results_by_provider
+ if source.strip().lower() in _PROVIDER_FILTER_VALUES:
+ all_results = _filter_results_by_provider(all_results, source)
+ if not all_results:
+ c.print(f"[dim]No skills found for provider '{source}'.[/]\n")
+ return
+ deduped, page_items, page, total_pages, start = _rank_and_page(all_results, page, page_size)
+ _render_browse_page(c, deduped, page_items, page, total_pages, start, source,
+ source_counts, timed_out)
+
+
+def browse_skills(page: int = 1, page_size: int = 20, source: str = "all") -> dict:
+ """Paginated hub browse for programmatic callers (e.g. TUI gateway)."""
+ from tools.skills_hub import parallel_search_sources
+
+ page_size = max(1, min(page_size, 100))
+ # The shared parallel walker carries the index-aware source-skip logic — querying
+ # hermes-index AND the external APIs at once would double-count every skill.
+ all_results, _counts, _timed_out = parallel_search_sources(
+ _sources(), query="", per_source_limits=_BROWSE_API_LIMITS,
+ source_filter=source, overall_timeout=30,
+ )
+ if not all_results:
+ return {"items": [], "page": 1, "total_pages": 1, "total": 0}
+ deduped, page_items, page, total_pages, _start = _rank_and_page(all_results, page, page_size)
+ return {
+ "items": [{"name": r.name, "description": r.description, "source": r.source,
+ "trust": r.trust_level, "identifier": r.identifier} for r in page_items],
+ "page": page, "total_pages": total_pages, "total": len(deduped),
+ }
+
+
+def do_inspect(identifier: str, console: Optional[Console] = None) -> None:
+ """Preview a skill's SKILL.md content without installing."""
+ c = console or _console
+ identifier, meta, bundle, _src = _resolve_identifier(identifier, _sources(), c)
+ if not identifier:
+ return
+ if not meta:
+ _print_error(c, f"Could not find '{identifier}' in any source.")
+ return
+
+ c.print()
+ info_lines = [
+ f"[bold]Name:[/] {meta.name}",
+ f"[bold]Description:[/] {meta.description}",
+ f"[bold]Source:[/] {meta.source}",
+ f"[bold]Trust:[/] {_trust_cell(meta.trust_level, meta.source)}",
+ f"[bold]Identifier:[/] {meta.identifier}",
+ ]
+ if meta.tags:
+ info_lines.append(f"[bold]Tags:[/] {', '.join(meta.tags)}")
+ info_lines.extend(_format_extra_metadata_lines(meta.extra))
+ c.print(Panel("\n".join(info_lines), title=f"Skill: {meta.name}"))
+ preview = _skill_md_preview(bundle)
+ if preview is not None:
+ c.print(Panel(preview, title="SKILL.md Preview", subtitle="hermes skills install <id> to install"))
+ c.print()
+
+
+def inspect_skill(identifier: str) -> Optional[dict]:
+ """Skill metadata (+ SKILL.md preview) for programmatic callers."""
+
+ class _Q:
+ def print(self, *a, **k):
+ pass
+
+ ident, meta, bundle, _ = _resolve_identifier(identifier, _sources(), _Q())
+ if not ident or not meta:
+ return None
+ out: dict = {
+ "name": meta.name, "description": meta.description, "source": meta.source,
+ "identifier": meta.identifier, "tags": list(meta.tags) if meta.tags else [],
+ }
+ preview = _skill_md_preview(bundle)
+ if preview is not None:
+ out["skill_md_preview"] = preview
+ return out
+
+
+# ---------------------------------------------------------------------------
+# install
+# ---------------------------------------------------------------------------
+
def _install_blocked(c: Console, bundle, message: str, verdict: str, detail: str,
q_path: Optional[Path] = None, lead: str = "") -> None:
"""Print the blocked-install line, drop the quarantine copy, append the audit row."""
@@ -567,100 +560,171 @@ def _resolve_url_bundle_name(c: Console, bundle, meta, identifier: str,
name_override: str, skip_confirm: bool) -> bool:
"""Give a URL-sourced bundle a name when SKILL.md has none.
- URL-sourced skills may arrive with an empty name when SKILL.md has no ``name:`` in
- frontmatter AND the URL path doesn't yield a valid identifier. Resolve by (1) --name
- override, (2) interactive prompt on a TTY, (3) refuse with an actionable error on
- non-interactive surfaces. Returns False when the install must abort.
+ Order: (1) --name override, (2) interactive prompt on a TTY, (3) refuse with an
+ actionable error on non-interactive surfaces. Returns False when the install must abort.
"""
bundle_meta = getattr(bundle, "metadata", {}) or {}
- if bundle.source == "url" and (not bundle.name or bundle_meta.get("awaiting_name")):
- if name_override and _is_valid_installed_skill_name(name_override):
- bundle.name = name_override.strip()
- bundle_meta["awaiting_name"] = False
- elif name_override:
- c.print(
- f"[bold red]Invalid --name:[/] {name_override!r}. "
- "Must be a lowercase identifier (letters, digits, hyphens, "
- "underscores; starts with a letter).\n"
- )
- return False
- elif skip_confirm:
- # Non-interactive surface (slash command / TUI / gateway). Can't
- # prompt — emit an actionable error.
- url = bundle_meta.get("url") or identifier
- c.print(
- f"[bold red]Cannot install from URL:[/] {url}\n"
- "[yellow]The SKILL.md has no `name:` in its frontmatter, "
- "and the URL path doesn't produce a valid identifier.[/]\n\n"
- "Retry with an explicit name:\n"
- f" [bold]/skills install {url} --name <your-name>[/]\n"
- f" [bold]hermes skills install {url} --name <your-name>[/]\n\n"
- "[dim]Or ask the SKILL.md's author to add a `name:` field to "
- "its YAML frontmatter.[/]\n"
- )
+ if bundle.source != "url" or (bundle.name and not bundle_meta.get("awaiting_name")):
+ return True
+ url = bundle_meta.get("url") or identifier
+ if name_override and _is_valid_installed_skill_name(name_override):
+ bundle.name = name_override.strip()
+ elif name_override:
+ c.print(
+ f"[bold red]Invalid --name:[/] {name_override!r}. "
+ "Must be a lowercase identifier (letters, digits, hyphens, "
+ "underscores; starts with a letter).\n"
+ )
+ return False
+ elif skip_confirm:
+ # Non-interactive surface (slash command / TUI / gateway): can't prompt.
+ c.print(
+ f"[bold red]Cannot install from URL:[/] {url}\n"
+ "[yellow]The SKILL.md has no `name:` in its frontmatter, "
+ "and the URL path doesn't produce a valid identifier.[/]\n\n"
+ "Retry with an explicit name:\n"
+ f" [bold]/skills install {url} --name <your-name>[/]\n"
+ f" [bold]hermes skills install {url} --name <your-name>[/]\n\n"
+ "[dim]Or ask the SKILL.md's author to add a `name:` field to "
+ "its YAML frontmatter.[/]\n"
+ )
+ return False
+ else:
+ chosen = _prompt_for_skill_name(c, url)
+ if not chosen:
+ c.print("[dim]Installation cancelled.[/]\n")
return False
- else:
- # Interactive TTY — prompt.
- url = bundle_meta.get("url") or identifier
- chosen = _prompt_for_skill_name(c, url)
- if not chosen:
- c.print("[dim]Installation cancelled.[/]\n")
- return False
- bundle.name = chosen
- bundle_meta["awaiting_name"] = False
- # Keep SkillMeta in sync so downstream "already installed" checks,
- # audit logs, and display all see the final name.
- if meta is not None:
- meta.name = bundle.name
- meta.path = bundle.name
+ bundle.name = chosen
+ bundle_meta["awaiting_name"] = False
+ # Keep SkillMeta in sync so "already installed" checks, audit logs and display agree.
+ if meta is not None:
+ meta.name = bundle.name
+ meta.path = bundle.name
return True
def _announce_blueprint(c: Console, skill_name: str) -> None:
"""Register an installed skill's ``metadata.hermes.blueprint`` as a Suggested Cron Job.
- A blueprint block marks a skill as a runnable automation. It is registered as a
- suggestion rather than auto-scheduled — installing never silently creates a recurring
- job; the user accepts it via /suggestions, the single surface every automation
- proposal flows through. Best-effort: never raises.
+ Registered as a suggestion, never auto-scheduled: installing must not silently create a
+ recurring job; the user accepts via /suggestions. Best-effort: never raises.
"""
try:
from tools.blueprints import BlueprintError, blueprint_spec_for_installed, register_blueprint_suggestion
-
try:
spec = blueprint_spec_for_installed(skill_name)
except BlueprintError as _rec_err:
c.print(f"[yellow]Blueprint block present but invalid:[/] {_rec_err}\n")
- spec = None
- if spec is not None:
- registered = register_blueprint_suggestion(spec)
- if registered is not None:
- c.print(
- f"[bold cyan]Blueprint:[/] '{skill_name}' is an automation "
- f"(schedule [bold]{spec.schedule}[/])."
- )
- c.print(
- "[dim]Added to your suggestions — run[/] [bold]/suggestions[/] "
- "[dim]to schedule or dismiss it.[/]\n"
- )
- else:
- # Dropped: already offered/dismissed (latched) or the pending
- # list is at its cap. Say so instead of silently doing nothing —
- # the user can still schedule it by hand.
- c.print(
- f"[bold cyan]Blueprint:[/] '{skill_name}' is an automation "
- f"(schedule [bold]{spec.schedule}[/]), but it wasn't added to "
- "your suggestions (already offered/dismissed, or the pending "
- "list is full — run [bold]/suggestions[/] to review)."
- )
- c.print(
- "[dim]You can still schedule it any time by asking the agent "
- "or via[/] [bold]hermes cron add[/][dim].[/]\n"
- )
+ return
+ if spec is None:
+ return
+ if register_blueprint_suggestion(spec) is not None:
+ c.print(
+ f"[bold cyan]Blueprint:[/] '{skill_name}' is an automation "
+ f"(schedule [bold]{spec.schedule}[/])."
+ )
+ c.print(
+ "[dim]Added to your suggestions — run[/] [bold]/suggestions[/] "
+ "[dim]to schedule or dismiss it.[/]\n"
+ )
+ else:
+ # Dropped: already offered/dismissed (latched) or the pending list is at its cap.
+ c.print(
+ f"[bold cyan]Blueprint:[/] '{skill_name}' is an automation "
+ f"(schedule [bold]{spec.schedule}[/]), but it wasn't added to "
+ "your suggestions (already offered/dismissed, or the pending "
+ "list is full — run [bold]/suggestions[/] to review)."
+ )
+ c.print(
+ "[dim]You can still schedule it any time by asking the agent "
+ "or via[/] [bold]hermes cron add[/][dim].[/]\n"
+ )
except Exception: # pragma: no cover - blueprint detection is best-effort
pass
+def _pinned_sources(c: Console, sources, source_id: Optional[str], identifier: str):
+ """Restrict `sources` to the adapter matching `source_id`; None when it is unknown."""
+ from tools.skills_hub import _source_matches
+ if not source_id:
+ return sources
+ pinned = [src for src in sources if _source_matches(src, source_id)]
+ if pinned:
+ return pinned
+ _print_error(c, f"no source adapter for '{source_id}'. "
+ f"Refusing to resolve '{identifier}' against other registries "
+ f"(that would change the skill's provenance).")
+ return None
+
+
+def _print_fetch_failure(c: Console, sources, identifier: str) -> None:
+ rate_limited = any(
+ getattr(src, "is_rate_limited", False)
+ or getattr(getattr(src, "github", None), "is_rate_limited", False)
+ for src in sources
+ )
+ c.print(f"[bold red]Error:[/] Could not fetch '{identifier}' from any source.")
+ if rate_limited:
+ c.print(
+ "[yellow]Hint:[/] GitHub API rate limit exhausted "
+ "(unauthenticated: 60 requests/hour).\n"
+ "Set [bold]GITHUB_TOKEN[/] in your .env or install the "
+ "[bold]gh[/] CLI and run [bold]gh auth login[/] "
+ "to raise the limit to 5,000/hr.\n"
+ )
+ else:
+ c.print()
+
+
+def _scan_quarantined(c: Console, q_path: Path, bundle, meta, identifier: str):
+ """Run the cached security scan on the quarantined bundle and print the report."""
+ from tools.skills_hub import HUB_DIR, source_url_for_bundle
+ from tools.skills_guard import scan_skill_cached, format_scan_report
+
+ c.print("[bold]Running security scan...[/]")
+ if bundle.source == "official":
+ scan_source = "official"
+ else:
+ scan_source = (getattr(bundle, "identifier", "") or getattr(meta, "identifier", "")
+ or identifier)
+ result, prov = scan_skill_cached(
+ q_path, source=scan_source, source_url=source_url_for_bundle(bundle),
+ cache_dir=HUB_DIR / "scan-cache",
+ )
+ c.print(format_scan_report(result))
+ freshness = "fresh" if prov["fresh"] else "cached"
+ c.print(f"[dim]Scan provenance: {freshness}; scanner "
+ f"{prov['scanner_version']}; hash {prov['bundle_hash']}[/]")
+ rules = ", ".join(prov["rules"]) or "none"
+ c.print(f"[dim]Source: {prov['source_url']}; scanned {prov['scanned_at']}; rules: {rules}[/]")
+ return result
+
+
+def _confirm_install(c: Console, bundle, category: str) -> bool:
+ """Source-appropriate disclaimer panel + `Install '<name>'?` prompt."""
+ files_at = f"Files will be at: [cyan]{display_hermes_home()}/skills/{category + '/' if category else ''}{bundle.name}/[/]"
+ c.print()
+ if bundle.source == "official":
+ c.print(Panel(
+ "[bold bright_cyan]This is an official optional skill maintained by Nous Research.[/]\n\n"
+ "It ships with hermes-agent but is not activated by default.\n"
+ "Installing will copy it to your skills directory where the agent can use it.\n\n"
+ + files_at,
+ title="Official Skill", border_style="bright_cyan",
+ ))
+ else:
+ c.print(Panel(
+ "[bold yellow]You are installing a third-party skill at your own risk.[/]\n\n"
+ "External skills can contain instructions that influence agent behavior,\n"
+ "shell commands, and scripts. Even after automated scanning, you should\n"
+ "review the installed files before use.\n\n"
+ + files_at,
+ title="Disclaimer", border_style="yellow",
+ ))
+ return _confirm_or_cancel(c, f"[bold]Install '{bundle.name}'?[/]",
+ cancel="[dim]Installation cancelled.[/]\n")
+
+
def do_install(identifier: str, category: str = "", force: bool = False,
console: Optional[Console] = None, skip_confirm: bool = False,
invalidate_cache: bool = True,
@@ -669,84 +733,41 @@ def do_install(identifier: str, category: str = "", force: bool = False,
"""Fetch, quarantine, scan, confirm, and install a skill.
``source_id`` pins resolution to a single source adapter (e.g. ``clawhub``). Callers that
- already know a skill's provenance -- notably ``do_update``, which reads it from the lockfile --
- should pass it so a bare, slash-less identifier cannot be fuzzy-resolved to a same-named skill
- in a different registry.
+ already know a skill's provenance (``do_update`` reads it from the lockfile) must pass it so
+ a bare identifier cannot be fuzzy-resolved to a same-named skill in another registry.
"""
- from tools.skills_hub import (
- ensure_hub_dirs, quarantine_bundle, install_from_quarantine, HubLockFile,
- _source_matches,
- )
- from tools.skills_guard import scan_skill_cached, should_allow_install, format_scan_report
+ from tools.skills_hub import ensure_hub_dirs, quarantine_bundle, install_from_quarantine, HubLockFile
+ from tools.skills_guard import should_allow_install
c = console or _console
ensure_hub_dirs()
-
- # Resolve which source adapter handles this identifier
- sources = _sources()
-
- if source_id:
- pinned = [src for src in sources if _source_matches(src, source_id)]
- if pinned:
- sources = pinned
- else:
- c.print(
- f"[bold red]Error:[/] no source adapter for '{source_id}'. "
- f"Refusing to resolve '{identifier}' against other registries "
- f"(that would change the skill's provenance).\n"
- )
- return
-
- # If identifier looks like a short name (no slashes), resolve it via search
+ sources = _pinned_sources(c, _sources(), source_id, identifier)
+ if sources is None:
+ return
if "/" not in identifier:
identifier = _resolve_short_name(identifier, sources, c)
if not identifier:
return
-
c.print(f"\n[bold]Fetching:[/] {identifier}")
-
meta, bundle, _matched_source = _resolve_source_meta_and_bundle(identifier, sources)
-
if not bundle:
- # Check if any source hit GitHub API rate limit
- rate_limited = any(
- getattr(src, "is_rate_limited", False)
- or getattr(getattr(src, "github", None), "is_rate_limited", False)
- for src in sources
- )
- c.print(f"[bold red]Error:[/] Could not fetch '{identifier}' from any source.")
- if rate_limited:
- c.print(
- "[yellow]Hint:[/] GitHub API rate limit exhausted "
- "(unauthenticated: 60 requests/hour).\n"
- "Set [bold]GITHUB_TOKEN[/] in your .env or install the "
- "[bold]gh[/] CLI and run [bold]gh auth login[/] "
- "to raise the limit to 5,000/hr.\n"
- )
- else:
- c.print()
+ _print_fetch_failure(c, sources, identifier)
return
-
if not _resolve_url_bundle_name(c, bundle, meta, identifier, name_override, skip_confirm):
return
- # URL-sourced skills: offer to pick a category interactively when the
- # caller didn't specify one (TTY only — non-interactive installs fall
- # through to flat install, matching all other sources).
+ # URL-sourced skills: pick a category interactively when none was given (TTY only;
+ # non-interactive installs fall through to flat install like every other source).
if bundle.source == "url" and not category and not skip_confirm:
category = _prompt_for_category(c, _existing_categories())
-
- # Auto-detect the full parent path for official skills. Optional skills
- # can be nested (e.g. "official/mlops/training/trl-fine-tuning"), so keep
- # every identifier segment between "official" and the final skill slug.
+ # Official skills can be nested ("official/mlops/training/trl-fine-tuning"): keep every
+ # identifier segment between "official" and the final slug as the category path.
if bundle.source == "official" and not category:
id_parts = bundle.identifier.split("/")
if len(id_parts) >= 3:
category = "/".join(id_parts[1:-1])
- # Check if already installed
- lock = HubLockFile()
- existing = lock.get_installed(bundle.name)
+ existing = HubLockFile().get_installed(bundle.name)
if existing:
c.print(f"[yellow]Warning:[/] '{bundle.name}' is already installed at {existing['install_path']}")
if not force:
@@ -756,7 +777,6 @@ def do_install(identifier: str, category: str = "", force: bool = False,
extra_metadata = dict(getattr(meta, "extra", {}) or {})
extra_metadata.update(getattr(bundle, "metadata", {}) or {})
- # Quarantine the bundle
try:
q_path = quarantine_bundle(bundle)
except ValueError as exc:
@@ -764,236 +784,80 @@ def do_install(identifier: str, category: str = "", force: bool = False,
return
c.print(f"[dim]Quarantined to {q_path.relative_to(q_path.parent.parent.parent)}[/]")
- # Scan
- c.print("[bold]Running security scan...[/]")
- if bundle.source == "official":
- scan_source = "official"
- else:
- scan_source = (
- getattr(bundle, "identifier", "")
- or getattr(meta, "identifier", "")
- or identifier
- )
- from tools.skills_hub import HUB_DIR, source_url_for_bundle
- result, scan_provenance = scan_skill_cached(
- q_path,
- source=scan_source,
- source_url=source_url_for_bundle(bundle),
- cache_dir=HUB_DIR / "scan-cache",
- )
- c.print(format_scan_report(result))
- freshness = "fresh" if scan_provenance["fresh"] else "cached"
- c.print(
- f"[dim]Scan provenance: {freshness}; scanner "
- f"{scan_provenance['scanner_version']}; hash {scan_provenance['bundle_hash']}[/]"
- )
- rules = ", ".join(scan_provenance["rules"]) or "none"
- c.print(
- f"[dim]Source: {scan_provenance['source_url']}; scanned "
- f"{scan_provenance['scanned_at']}; rules: {rules}[/]"
- )
-
- # Check install policy
+ result = _scan_quarantined(c, q_path, bundle, meta, identifier)
allowed, reason = should_allow_install(result, force=force)
if not allowed:
_install_blocked(c, bundle, reason, result.verdict, f"{len(result.findings)}_findings",
q_path=q_path, lead="\n")
- return
-
- # Advisory SkillEvaluator Tier 1 scan (optional second opinion).
- # Warn-and-continue by design: PII-class findings are informational
- # (known false-positive classes upstream), and the existing install
- # confirmation below is where the user decides. Never blocks.
- _print_tier1_advisory(q_path, c)
-
- if extra_metadata:
- metadata_lines = _format_extra_metadata_lines(extra_metadata)
- if metadata_lines:
- c.print(Panel("\n".join(metadata_lines), title="Upstream Metadata", border_style="blue"))
-
- # Confirm with user — show appropriate warning based on source
- # skip_confirm bypasses the prompt (needed in TUI mode where input() hangs)
- if not force and not skip_confirm:
- c.print()
- if bundle.source == "official":
- c.print(Panel(
- "[bold bright_cyan]This is an official optional skill maintained by Nous Research.[/]\n\n"
- "It ships with hermes-agent but is not activated by default.\n"
- "Installing will copy it to your skills directory where the agent can use it.\n\n"
- f"Files will be at: [cyan]{display_hermes_home()}/skills/{category + '/' if category else ''}{bundle.name}/[/]",
- title="Official Skill",
- border_style="bright_cyan",
- ))
- else:
- c.print(Panel(
- "[bold yellow]You are installing a third-party skill at your own risk.[/]\n\n"
- "External skills can contain instructions that influence agent behavior,\n"
- "shell commands, and scripts. Even after automated scanning, you should\n"
- "review the installed files before use.\n\n"
- f"Files will be at: [cyan]{display_hermes_home()}/skills/{category + '/' if category else ''}{bundle.name}/[/]",
- title="Disclaimer",
- border_style="yellow",
- ))
- c.print(f"[bold]Install '{bundle.name}'?[/]")
- if not _confirm():
- c.print("[dim]Installation cancelled.[/]\n")
- shutil.rmtree(q_path, ignore_errors=True)
- return
-
- # Install
- try:
- install_dir = install_from_quarantine(q_path, bundle.name, category, bundle, result)
- except ValueError as exc:
- _install_blocked(c, bundle, f"{exc}\n", "invalid_path", str(exc), q_path=q_path)
- return
- from tools.skills_hub import SKILLS_DIR
- c.print(f"[bold green]Installed:[/] {install_dir.resolve().relative_to(Path(SKILLS_DIR).resolve()).as_posix()}")
- c.print(f"[dim]Files: {', '.join(bundle.files.keys())}[/]\n")
-
- _announce_blueprint(c, bundle.name)
-
- if invalidate_cache:
- # Invalidate the skills prompt cache so the new skill appears immediately
- _clear_skills_cache()
- else:
- c.print("[dim]Skill will be available in your next session.[/]")
- c.print("[dim]Use /reset to start a new session now, or --now to activate immediately (invalidates prompt cache).[/]\n")
-
-
-def do_inspect(identifier: str, console: Optional[Console] = None) -> None:
- """Preview a skill's SKILL.md content without installing."""
- c = console or _console
- sources = _sources()
-
- if "/" not in identifier:
- identifier = _resolve_short_name(identifier, sources, c)
- if not identifier:
- return
-
- meta, bundle, _matched_source = _resolve_source_meta_and_bundle(identifier, sources)
-
- if not meta:
- c.print(f"[bold red]Error:[/] Could not find '{identifier}' in any source.\n")
- return
-
- c.print()
- trust_style = {"builtin": "bright_cyan", "trusted": "green", "community": "yellow"}.get(meta.trust_level, "dim")
- trust_label = "official" if meta.source == "official" else meta.trust_level
-
- info_lines = [
- f"[bold]Name:[/] {meta.name}",
- f"[bold]Description:[/] {meta.description}",
- f"[bold]Source:[/] {meta.source}",
- f"[bold]Trust:[/] [{trust_style}]{trust_label}[/]",
- f"[bold]Identifier:[/] {meta.identifier}",
- ]
- if meta.tags:
- info_lines.append(f"[bold]Tags:[/] {', '.join(meta.tags)}")
- info_lines.extend(_format_extra_metadata_lines(meta.extra))
-
- c.print(Panel("\n".join(info_lines), title=f"Skill: {meta.name}"))
-
- if bundle and "SKILL.md" in bundle.files:
- content = bundle.files["SKILL.md"]
- if isinstance(content, bytes):
- content = content.decode("utf-8", errors="replace")
- # Show first 50 lines as preview
- lines = content.split("\n")
- preview = "\n".join(lines[:50])
- if len(lines) > 50:
- preview += f"\n\n... ({len(lines) - 50} more lines)"
- c.print(Panel(preview, title="SKILL.md Preview", subtitle="hermes skills install <id> to install"))
-
- c.print()
-
+ return
+ # Advisory second opinion — warn-and-continue by design (PII-class findings are
+ # informational); the install confirmation below is where the user decides.
+ _print_tier1_advisory(q_path, c)
+ metadata_lines = _format_extra_metadata_lines(extra_metadata)
+ if metadata_lines:
+ c.print(Panel("\n".join(metadata_lines), title="Upstream Metadata", border_style="blue"))
-def browse_skills(page: int = 1, page_size: int = 20, source: str = "all") -> dict:
- """Paginated hub browse for programmatic callers (e.g. TUI gateway)."""
- from tools.skills_hub import parallel_search_sources
+ # skip_confirm bypasses the prompt (TUI mode, where input() hangs).
+ if not force and not skip_confirm and not _confirm_install(c, bundle, category):
+ shutil.rmtree(q_path, ignore_errors=True)
+ return
- page_size = max(1, min(page_size, 100))
- _TRUST_RANK = {"builtin": 3, "trusted": 2, "community": 1}
- # "hermes-index" must carry a high limit: when the index is available the
- # router skips external API sources and serves everything from it, so a
- # low cap here silently truncates the whole hub (see do_browse note).
- _PER_SOURCE_LIMIT = {"hermes-index": 5000, "official": 100, "skills-sh": 100,
- "well-known": 25, "github": 100, "clawhub": 50,
- "lobehub": 50, "browse-sh": 500}
- sources = _sources()
- # Delegate to the shared parallel walker so this inherits the index-aware
- # source-skip logic — querying hermes-index AND the external APIs at once
- # would double-count every skill.
- all_results, _counts, _timed_out = parallel_search_sources(
- sources, query="", per_source_limits=_PER_SOURCE_LIMIT,
- source_filter=source, overall_timeout=30,
- )
- if not all_results:
- return {"items": [], "page": 1, "total_pages": 1, "total": 0}
- seen: dict = {}
- for r in all_results:
- rank = _TRUST_RANK.get(r.trust_level, 0)
- if r.identifier not in seen or rank > _TRUST_RANK.get(seen[r.identifier].trust_level, 0):
- seen[r.identifier] = r
- deduped = list(seen.values())
- deduped.sort(key=lambda r: (-_TRUST_RANK.get(r.trust_level, 0), r.source != "official", r.name.lower()))
- total = len(deduped)
- total_pages = max(1, (total + page_size - 1) // page_size)
- page = max(1, min(page, total_pages))
- start = (page - 1) * page_size
- page_items = deduped[start : min(start + page_size, total)]
- return {
- "items": [{"name": r.name, "description": r.description, "source": r.source,
- "trust": r.trust_level, "identifier": r.identifier} for r in page_items],
- "page": page,
- "total_pages": total_pages,
- "total": total,
- }
+ try:
+ install_dir = install_from_quarantine(q_path, bundle.name, category, bundle, result)
+ except ValueError as exc:
+ _install_blocked(c, bundle, f"{exc}\n", "invalid_path", str(exc), q_path=q_path)
+ return
+ from tools.skills_hub import SKILLS_DIR
+ c.print(f"[bold green]Installed:[/] {install_dir.resolve().relative_to(Path(SKILLS_DIR).resolve()).as_posix()}")
+ c.print(f"[dim]Files: {', '.join(bundle.files.keys())}[/]\n")
+ _announce_blueprint(c, bundle.name)
+ if invalidate_cache:
+ _clear_skills_cache()
+ else:
+ c.print("[dim]Skill will be available in your next session.[/]")
+ c.print("[dim]Use /reset to start a new session now, or --now to activate immediately (invalidates prompt cache).[/]\n")
-def inspect_skill(identifier: str) -> Optional[dict]:
- """Skill metadata (+ SKILL.md preview) for programmatic callers."""
+def _print_tier1_advisory(skill_dir, console) -> None:
+ """Print the advisory SkillEvaluator Tier 1 report, if available.
- class _Q:
- def print(self, *a, **k):
- pass
+ Never raises and never blocks the install: scanner missing, disabled via
+ ``skills.tier1_advisory: false``, or erroring all degrade to silence. Secrets-class findings
+ render red, the rest yellow.
+ """
+ try:
+ from tools.skillevaluator_scan import format_tier1_report, run_tier1_scan, tier1_advisory_enabled
+ if not tier1_advisory_enabled():
+ return
+ report = run_tier1_scan(Path(skill_dir))
+ if not report.available:
+ return
+ text = format_tier1_report(report)
+ if not report.findings:
+ console.print(f"[dim]{text}[/]")
+ return
+ style = "red" if report.secrets_findings else "yellow"
+ console.print(Panel(text, title="SkillEvaluator Tier 1 (advisory)", border_style=style))
+ if report.secrets_findings:
+ console.print(
+ "[bold red]Possible credentials detected above.[/] "
+ "Review the flagged lines before using this skill.\n"
+ )
+ except Exception as exc: # advisory only — never break an install
+ logging.getLogger(__name__).debug("Tier 1 advisory scan skipped: %s", exc)
- c = _Q()
- sources = _sources()
- ident = identifier
- if "/" not in ident:
- ident = _resolve_short_name(ident, sources, c)
- if not ident:
- return None
- meta, bundle, _ = _resolve_source_meta_and_bundle(ident, sources)
- if not meta:
- return None
- out: dict = {
- "name": meta.name,
- "description": meta.description,
- "source": meta.source,
- "identifier": meta.identifier,
- "tags": list(meta.tags) if meta.tags else [],
- }
- if bundle and "SKILL.md" in bundle.files:
- content = bundle.files["SKILL.md"]
- if isinstance(content, bytes):
- content = content.decode("utf-8", errors="replace")
- lines = content.split("\n")
- preview = "\n".join(lines[:50])
- if len(lines) > 50:
- preview += f"\n\n... ({len(lines) - 50} more lines)"
- out["skill_md_preview"] = preview
- return out
+# ---------------------------------------------------------------------------
+# list / check / update / audit
+# ---------------------------------------------------------------------------
def do_list(source_filter: str = "all",
enabled_only: bool = False,
console: Optional[Console] = None) -> None:
"""List installed skills, distinguishing hub, builtin, and local skills.
- Enabled/disabled state is resolved against the currently active profile's config — ``hermes -p
- <profile> skills list`` reads that profile's ``skills.disabled`` list because ``-p`` swaps
- ``HERMES_HOME`` at process start. No explicit profile flag needed here.
+ Enabled/disabled state comes from the active profile's config: ``hermes -p <profile>``
+ swaps ``HERMES_HOME`` at process start, so no explicit profile flag is needed here.
"""
from tools.skills_hub import HubLockFile, ensure_hub_dirs
from tools.skills_sync import _read_manifest
@@ -1002,80 +866,49 @@ def do_list(source_filter: str = "all",
c = console or _console
ensure_hub_dirs()
- lock = HubLockFile()
- hub_installed = {e["name"]: e for e in lock.list_installed()}
+ hub_installed = {e["name"]: e for e in HubLockFile().list_installed()}
builtin_names = set(_read_manifest())
-
- # Pull ALL skills (including disabled ones) so we can annotate status.
- all_skills = _find_all_skills(skip_disabled=True)
+ all_skills = _find_all_skills(skip_disabled=True) # include disabled ones to annotate status
disabled_names = get_disabled_skill_names()
- title = "Installed Skills"
- if enabled_only:
- title += " (enabled only)"
-
- table = Table(title=title)
- table.add_column("Name", style="bold cyan")
- table.add_column("Category", style="dim")
- table.add_column("Source", style="dim")
- table.add_column("Trust", style="dim")
- table.add_column("Status", style="dim")
-
- hub_count = 0
- builtin_count = 0
- local_count = 0
- enabled_count = 0
- disabled_count = 0
+ table = Table(title="Installed Skills" + (" (enabled only)" if enabled_only else ""))
+ for col in ("Name", "Category", "Source", "Trust", "Status"):
+ table.add_column(col, style="bold cyan" if col == "Name" else "dim")
+ counts = {"hub": 0, "builtin": 0, "local": 0}
+ enabled_count = disabled_count = 0
for skill in sorted(all_skills, key=lambda s: (s.get("category") or "", s["name"])):
name = skill["name"]
- category = skill.get("category", "")
hub_entry = hub_installed.get(name)
-
if hub_entry:
- source_type = "hub"
- source_display = hub_entry.get("source", "hub")
+ source_type, source_display = "hub", hub_entry.get("source", "hub")
trust = hub_entry.get("trust_level", "community")
elif name in builtin_names:
- source_type = "builtin"
- source_display = "builtin"
- trust = "builtin"
+ source_type = source_display = trust = "builtin"
else:
- source_type = "local"
- source_display = "local"
- trust = "local"
-
+ source_type = source_display = trust = "local"
if source_filter != "all" and source_filter != source_type:
continue
-
is_enabled = name not in disabled_names
if enabled_only and not is_enabled:
continue
-
- if source_type == "hub":
- hub_count += 1
- elif source_type == "builtin":
- builtin_count += 1
- else:
- local_count += 1
-
+ counts[source_type] += 1
if is_enabled:
enabled_count += 1
status_cell = "[bold green]enabled[/]"
else:
disabled_count += 1
status_cell = "[dim red]disabled[/]"
-
- table.add_row(name, category, source_display, _trust_cell(trust, source_display), status_cell)
+ table.add_row(name, skill.get("category", ""), source_display,
+ _trust_cell(trust, source_display), status_cell)
c.print(table)
- summary = f"[dim]{hub_count} hub-installed, {builtin_count} builtin, {local_count} local"
+ summary = f"[dim]{counts['hub']} hub-installed, {counts['builtin']} builtin, {counts['local']} local"
if enabled_only:
summary += f" — {enabled_count} enabled shown"
else:
summary += f" — {enabled_count} enabled, {disabled_count} disabled"
- summary += "[/]\n"
- c.print(summary)
+ c.print(summary + "[/]\n")
def do_check(name: Optional[str] = None, console: Optional[Console] = None) -> None:
@@ -1087,30 +920,40 @@ def do_check(name: Optional[str] = None, console: Optional[Console] = None) -> N
if not results:
c.print("[dim]No hub-installed skills to check.[/]\n")
return
-
table = Table(title="Skill Updates")
table.add_column("Name", style="bold cyan")
table.add_column("Source", style="dim")
table.add_column("Status", style="dim")
-
for entry in results:
table.add_row(entry.get("name", ""), entry.get("source", ""), entry.get("status", ""))
-
c.print(table)
update_count = sum(1 for entry in results if entry.get("status") == "update_available")
c.print(f"[dim]{update_count} update(s) available across {len(results)} checked skill(s)[/]\n")
+def _has_local_edits(installed: dict) -> bool:
+ """True when the on-disk content no longer matches the install-time hash."""
+ from tools.skills_hub import SKILLS_DIR
+ from tools.skills_guard import content_hash
+
+ recorded_hash = installed.get("content_hash", "")
+ skill_path = SKILLS_DIR / installed.get("install_path", "")
+ if not (recorded_hash and skill_path.is_dir()):
+ return False
+ try:
+ return content_hash(skill_path) != recorded_hash
+ except OSError:
+ return False
+
+
def do_update(name: Optional[str] = None, console: Optional[Console] = None,
force: bool = False) -> None:
"""Update hub-installed skills with upstream changes.
- Skills whose on-disk content no longer matches the install-time hash were edited locally;
- updating would rmtree-replace the user's work, so they are skipped unless ``force=True``
- (destructive replacement must be an explicit caller choice, never a rerun default).
+ Locally edited skills are skipped unless ``force=True`` — updating would rmtree-replace the
+ user's work, so destructive replacement must be an explicit caller choice.
"""
- from tools.skills_hub import SKILLS_DIR, HubLockFile, check_for_skill_updates
- from tools.skills_guard import content_hash
+ from tools.skills_hub import HubLockFile, check_for_skill_updates
c = console or _console
lock = HubLockFile()
@@ -1122,46 +965,28 @@ def do_update(name: Optional[str] = None, console: Optional[Console] = None,
skipped_local: list[str] = []
for entry in updates:
installed = lock.get_installed(entry["name"])
- category = _derive_category_from_install_path(installed.get("install_path", "")) if installed else ""
- if installed and not force:
- recorded_hash = installed.get("content_hash", "")
- skill_path = SKILLS_DIR / installed.get("install_path", "")
- if recorded_hash and skill_path.is_dir():
- try:
- disk_hash = content_hash(skill_path)
- except OSError:
- disk_hash = recorded_hash
- if disk_hash != recorded_hash:
- skipped_local.append(entry["name"])
- c.print(
- f"[yellow]Skipping:[/] {entry['name']} — you have local edits "
- "(update would overwrite them)."
- )
- continue
+ category = ""
+ if installed:
+ parent = str(Path(installed.get("install_path", "")).parent)
+ category = "" if parent == "." else parent
+ if not force and _has_local_edits(installed):
+ skipped_local.append(entry["name"])
+ c.print(f"[yellow]Skipping:[/] {entry['name']} — you have local edits "
+ "(update would overwrite them).")
+ continue
c.print(f"[bold]Updating:[/] {entry['name']}")
- # Pin the update to the source registry recorded in the lockfile.
- # Without this, a bare (slash-less) identifier such as "reddit" falls
- # through to _resolve_short_name()'s fuzzy catalog search inside
- # do_install, which can match a same-named skill in a DIFFERENT
- # registry and install that instead -- overwriting the user's files
- # and rewriting the lock's `source`. An update must never change a
- # skill's provenance.
- do_install(
- entry["identifier"],
- category=category,
- force=True,
- console=c,
- source_id=entry.get("source", "") or None,
- )
+ # Pin to the lockfile's source registry: a bare identifier such as "reddit" would
+ # otherwise fuzzy-resolve inside do_install to a same-named skill in a DIFFERENT
+ # registry, overwriting the user's files and rewriting the lock's `source`.
+ do_install(entry["identifier"], category=category, force=True, console=c,
+ source_id=entry.get("source", "") or None)
updated_count = len(updates) - len(skipped_local)
if updated_count:
c.print(f"[bold green]Updated {updated_count} skill(s).[/]\n")
if skipped_local:
- c.print(
- f"[dim]{len(skipped_local)} skill(s) kept your local edits: "
- f"{', '.join(sorted(skipped_local))}.[/]"
- )
+ c.print(f"[dim]{len(skipped_local)} skill(s) kept your local edits: "
+ f"{', '.join(sorted(skipped_local))}.[/]")
c.print("[dim]Overwrite with: hermes skills update <name> --force[/]\n")
@@ -1169,47 +994,41 @@ def do_audit(name: Optional[str] = None, console: Optional[Console] = None,
deep: bool = False) -> None:
"""Re-run security scan on installed hub skills.
- When ``deep=True``, also runs an opt-in AST-level diagnostic on Python files (review aid only —
- not a security gate; skills_guard.py verdicts are unchanged).
+ ``deep=True`` adds an opt-in AST-level diagnostic on Python files (review aid only — not a
+ security gate; skills_guard verdicts are unchanged).
"""
from tools.skills_hub import HubLockFile, SKILLS_DIR
from tools.skills_guard import scan_skill, format_scan_report
c = console or _console
- lock = HubLockFile()
- installed = lock.list_installed()
-
+ installed = HubLockFile().list_installed()
if not installed:
c.print("[dim]No hub-installed skills to audit.[/]\n")
return
-
targets = installed
if name:
targets = [e for e in installed if e["name"] == name]
if not targets:
- c.print(f"[bold red]Error:[/] '{name}' is not a hub-installed skill.\n")
+ _print_error(c, f"'{name}' is not a hub-installed skill.")
return
-
c.print(f"\n[bold]Auditing {len(targets)} skill(s)...[/]\n")
-
if deep:
from tools.skills_ast_audit import ast_scan_path, format_ast_report
-
for entry in targets:
skill_path = SKILLS_DIR / entry["install_path"]
if not skill_path.exists():
c.print(f"[yellow]Warning:[/] {entry['name']} — path missing: {entry['install_path']}")
continue
-
- result = scan_skill(skill_path, source=entry.get("identifier", entry["source"]))
- c.print(format_scan_report(result))
-
+ c.print(format_scan_report(scan_skill(skill_path, source=entry.get("identifier", entry["source"]))))
if deep:
c.print(format_ast_report(ast_scan_path(skill_path), skill_name=entry["name"]))
-
c.print()
+# ---------------------------------------------------------------------------
+# uninstall / reset / bundled-skill management
+# ---------------------------------------------------------------------------
+
def do_uninstall(name: str, console: Optional[Console] = None,
skip_confirm: bool = False,
invalidate_cache: bool = True) -> None:
@@ -1217,23 +1036,15 @@ def do_uninstall(name: str, console: Optional[Console] = None,
from tools.skills_hub import uninstall_skill
c = console or _console
-
- # skip_confirm bypasses the prompt (needed in TUI mode where input() hangs)
- if not skip_confirm:
- c.print(f"\n[bold]Uninstall '{name}'?[/]")
- if not _confirm():
- c.print("[dim]Cancelled.[/]\n")
- return
-
+ # skip_confirm bypasses the prompt (TUI mode, where input() hangs)
+ if not skip_confirm and not _confirm_or_cancel(c, f"\n[bold]Uninstall '{name}'?[/]"):
+ return
success, msg = uninstall_skill(name)
if success:
c.print(f"[bold green]{msg}[/]\n")
- if invalidate_cache:
- _clear_skills_cache()
- else:
- _print_next_session_notice(c)
+ _finish_change(c, invalidate_cache)
else:
- c.print(f"[bold red]Error:[/] {msg}\n")
+ _print_error(c, msg)
def do_reset(name: str, restore: bool = False,
@@ -1244,32 +1055,21 @@ def do_reset(name: str, restore: bool = False,
from tools.skills_sync import reset_bundled_skill
c = console or _console
-
- if not skip_confirm and restore:
- c.print(f"\n[bold]Restore '{name}' from bundled source?[/]")
- c.print("[dim]This will DELETE your current copy and re-copy the bundled version.[/]")
- if not _confirm():
- c.print("[dim]Cancelled.[/]\n")
- return
-
+ if not skip_confirm and restore and not _confirm_or_cancel(
+ c, f"\n[bold]Restore '{name}' from bundled source?[/]",
+ "[dim]This will DELETE your current copy and re-copy the bundled version.[/]",
+ ):
+ return
result = reset_bundled_skill(name, restore=restore)
-
if not result["ok"]:
- c.print(f"[bold red]Error:[/] {result['message']}\n")
+ _print_error(c, result["message"])
return
-
c.print(f"[bold green]{result['message']}[/]")
synced = result.get("synced") or {}
- if synced.get("copied"):
- c.print(f"[dim]Copied: {', '.join(synced['copied'])}[/]")
- if synced.get("updated"):
- c.print(f"[dim]Updated: {', '.join(synced['updated'])}[/]")
+ _print_listed(c, "Copied", synced.get("copied"))
+ _print_listed(c, "Updated", synced.get("updated"))
c.print()
-
- if invalidate_cache:
- _clear_skills_cache()
- else:
- _print_next_session_notice(c)
+ _finish_change(c, invalidate_cache)
def do_list_modified(console: Optional[Console] = None,
@@ -1279,15 +1079,12 @@ def do_list_modified(console: Optional[Console] = None,
c = console or _console
modified = list_user_modified_bundled_skills()
-
if as_json:
c.print(json.dumps([m["name"] for m in modified]))
return
-
if not modified:
c.print("[dim]No user-modified bundled skills — everything tracks upstream.[/]\n")
return
-
c.print(f"\n[bold]{len(modified)} user-modified bundled skill(s)[/] "
"[dim](kept as-is by `hermes update`):[/]")
for entry in modified:
@@ -1298,35 +1095,36 @@ def do_list_modified(console: Optional[Console] = None,
c.print("[dim]Revert to stock: hermes skills reset <name> --restore[/]\n")
+def _print_diff_line(c: Console, line: str) -> None:
+ """Unified-diff line with light coloring."""
+ if line.startswith("+") and not line.startswith("+++"):
+ c.print(f"[green]{line}[/]")
+ elif line.startswith("-") and not line.startswith("---"):
+ c.print(f"[red]{line}[/]")
+ elif line.startswith("@@"):
+ c.print(f"[cyan]{line}[/]")
+ else:
+ c.print(line, highlight=False)
+
+
def do_diff(name: str, console: Optional[Console] = None) -> None:
"""Show how the user's copy of a bundled skill differs from the stock version."""
from tools.skills_sync import diff_bundled_skill
c = console or _console
result = diff_bundled_skill(name)
-
if not result["ok"]:
- c.print(f"[bold red]Error:[/] {result['message']}\n")
+ _print_error(c, result["message"])
return
-
if not result["modified"]:
c.print(f"[green]{result['message']}[/]\n")
return
-
c.print(f"\n[bold]{result['message']}[/]\n")
for entry in result["diffs"]:
status = entry["status"]
if status == "modified":
- # Render the unified diff with light coloring.
for line in entry["diff"].splitlines():
- if line.startswith("+") and not line.startswith("+++"):
- c.print(f"[green]{line}[/]")
- elif line.startswith("-") and not line.startswith("---"):
- c.print(f"[red]{line}[/]")
- elif line.startswith("@@"):
- c.print(f"[cyan]{line}[/]")
- else:
- c.print(line, highlight=False)
+ _print_diff_line(c, line)
elif status == "added":
c.print(f"[green]+ only in your copy:[/] {entry['path']}")
elif status == "removed":
@@ -1343,25 +1141,19 @@ def do_opt_out(remove: bool = False,
invalidate_cache: bool = True) -> None:
"""Opt the active profile out of bundled-skill seeding.
- Always writes the .no-bundled-skills marker (stop future seeding). With ``remove``, also deletes
- already-present bundled skills that are pristine (manifest-tracked AND unmodified); user-edited
- and non-bundled skills are never touched.
+ Always writes the .no-bundled-skills marker. With ``remove``, also deletes already-present
+ bundled skills that are pristine (manifest-tracked AND unmodified); user-edited and
+ non-bundled skills are never touched.
"""
- from tools.skills_sync import (
- set_bundled_skills_opt_out,
- remove_pristine_bundled_skills,
- )
+ from tools.skills_sync import set_bundled_skills_opt_out, remove_pristine_bundled_skills
c = console or _console
-
- # Write the marker first (the always-safe part).
- res = set_bundled_skills_opt_out(True)
+ res = set_bundled_skills_opt_out(True) # the marker first: always-safe
if not res["ok"]:
- c.print(f"[bold red]Error:[/] {res['message']}\n")
+ _print_error(c, res["message"])
return
c.print(f"[bold green]{res['message']}[/]")
c.print(f"[dim]Marker: {res['marker']}[/]")
-
if not remove:
c.print("[dim]Existing skills on disk were left in place. "
"Re-run with --remove to also delete unmodified bundled skills.[/]\n")
@@ -1375,25 +1167,19 @@ def do_opt_out(remove: bool = False,
c.print("[dim]No pristine bundled skills to remove "
"(nothing tracked, or all are user-modified/local).[/]\n")
return
-
c.print(f"\n[bold]Will remove {len(candidates)} unmodified bundled skill(s):[/]")
c.print(f"[dim]{', '.join(candidates)}[/]")
if kept:
c.print(f"[dim]Keeping {len(kept)} (user-modified or non-bundled).[/]")
-
- if not skip_confirm:
- c.print("[dim]This deletes the on-disk copies. User-edited and "
- "hub/local skills are NOT touched.[/]")
- if not _confirm():
- c.print("[dim]Marker kept; no skills deleted.[/]\n")
- return
-
+ if not skip_confirm and not _confirm_or_cancel(
+ c, "[dim]This deletes the on-disk copies. User-edited and hub/local skills are NOT touched.[/]",
+ cancel="[dim]Marker kept; no skills deleted.[/]\n",
+ ):
+ return
result = remove_pristine_bundled_skills(dry_run=False)
c.print(f"[bold green]{result['message']}[/]")
- if result["removed"]:
- c.print(f"[dim]Removed: {', '.join(result['removed'])}[/]")
+ _print_listed(c, "Removed", result["removed"])
c.print()
-
if invalidate_cache:
_clear_skills_cache()
@@ -1405,16 +1191,13 @@ def do_opt_in(sync: bool = False,
from tools.skills_sync import set_bundled_skills_opt_out, sync_skills
c = console or _console
-
res = set_bundled_skills_opt_out(False)
if not res["ok"]:
- c.print(f"[bold red]Error:[/] {res['message']}\n")
+ _print_error(c, res["message"])
return
c.print(f"[bold green]{res['message']}[/]")
-
if sync:
- synced = sync_skills(quiet=True)
- copied = len(synced.get("copied", []))
+ copied = len(sync_skills(quiet=True).get("copied", []))
c.print(f"[dim]Re-seeded {copied} bundled skill(s).[/]")
if invalidate_cache:
_clear_skills_cache()
@@ -1429,39 +1212,43 @@ def do_repair_official(name: str, restore: bool = False,
from tools.skills_sync import restore_official_optional_skill
c = console or _console
- if restore and not skip_confirm:
- c.print(f"\n[bold]Restore official optional skill '{name}' from repo source?[/]")
- c.print("[dim]Existing matching active copies will be moved to a restore backup before copying the official source.[/]")
- if not _confirm():
- c.print("[dim]Cancelled.[/]\n")
- return
-
+ if restore and not skip_confirm and not _confirm_or_cancel(
+ c, f"\n[bold]Restore official optional skill '{name}' from repo source?[/]",
+ "[dim]Existing matching active copies will be moved to a restore backup before copying the official source.[/]",
+ ):
+ return
result = restore_official_optional_skill(name, restore=restore)
if not result.get("ok"):
- c.print(f"[bold red]Error:[/] {result.get('message', 'Repair failed')}\n")
+ _print_error(c, result.get("message", "Repair failed"))
return
-
c.print(f"[bold green]{result['message']}[/]")
- if result.get("restored"):
- c.print(f"[dim]Restored: {', '.join(result['restored'])}[/]")
- if result.get("backfilled"):
- c.print(f"[dim]Backfilled provenance: {', '.join(result['backfilled'])}[/]")
+ _print_listed(c, "Restored", result.get("restored"))
+ _print_listed(c, "Backfilled provenance", result.get("backfilled"))
if result.get("backed_up"):
c.print(f"[dim]Backed up: {', '.join(result['backed_up'])}[/]")
c.print(f"[dim]Backup dir: {result.get('backup_dir')}[/]")
c.print()
-
if invalidate_cache:
_clear_skills_cache()
+# ---------------------------------------------------------------------------
+# taps / publish / snapshot
+# ---------------------------------------------------------------------------
+
+# action -> (TapsManager method, success line, failure line)
+_TAP_OPS = {
+ "add": ("add", "[bold green]Added tap:[/] {repo}\n", "[yellow]Tap already exists:[/] {repo}\n"),
+ "remove": ("remove", "[bold green]Removed tap:[/] {repo}\n", "[bold red]Error:[/] Tap not found: {repo}\n"),
+}
+
+
def do_tap(action: str, repo: str = "", console: Optional[Console] = None) -> None:
"""Manage taps (custom GitHub repo sources)."""
from tools.skills_hub import TapsManager
c = console or _console
mgr = TapsManager()
-
if action == "list":
taps = mgr.list_taps()
if not taps:
@@ -1475,29 +1262,29 @@ def do_tap(action: str, repo: str = "", console: Optional[Console] = None) -> No
table.add_row(label, t.get("path", "skills/"))
c.print(table)
c.print()
-
- elif action == "add":
- if not repo:
- c.print("[bold red]Error:[/] Repo required. Usage: hermes skills tap add owner/repo\n")
- return
- if mgr.add(repo):
- c.print(f"[bold green]Added tap:[/] {repo}\n")
- else:
- c.print(f"[yellow]Tap already exists:[/] {repo}\n")
-
- elif action == "remove":
+ elif action in _TAP_OPS:
+ method, ok_line, fail_line = _TAP_OPS[action]
if not repo:
- c.print("[bold red]Error:[/] Repo required. Usage: hermes skills tap remove owner/repo\n")
+ c.print(f"[bold red]Error:[/] Repo required. Usage: hermes skills tap {action} owner/repo\n")
return
- if mgr.remove(repo):
- c.print(f"[bold green]Removed tap:[/] {repo}\n")
- else:
- c.print(f"[bold red]Error:[/] Tap not found: {repo}\n")
-
+ c.print((ok_line if getattr(mgr, method)(repo) else fail_line).format(repo=repo))
else:
c.print(f"[bold red]Unknown tap action:[/] {action}. Use: list, add, remove\n")
+def _read_frontmatter(skill_md: str) -> dict:
+ """YAML frontmatter of a SKILL.md body ({} when absent/invalid)."""
+ import yaml
+ if skill_md.startswith("---"):
+ match = re.search(r'\n---\s*\n', skill_md[3:])
+ if match:
+ try:
+ return yaml.safe_load(skill_md[3:match.start() + 3]) or {}
+ except yaml.YAMLError:
+ pass
+ return {}
+
+
def do_publish(skill_path: str, target: str = "github", repo: str = "",
console: Optional[Console] = None) -> None:
"""Publish a local skill to a registry (GitHub PR or ClawHub submission)."""
@@ -1506,34 +1293,19 @@ def do_publish(skill_path: str, target: str = "github", repo: str = "",
c = console or _console
path = Path(skill_path)
-
- # Resolve relative to skills dir if not absolute
if not path.is_absolute():
path = SKILLS_DIR / path
if not path.exists() or not (path / "SKILL.md").exists():
- c.print(f"[bold red]Error:[/] No SKILL.md found at {path}\n")
+ _print_error(c, f"No SKILL.md found at {path}")
return
- # Validate the skill
- import yaml
- skill_md = (path / "SKILL.md").read_text(encoding="utf-8")
- skill_md = skill_md.lstrip("\ufeff") # tolerate UTF-8 BOM (Windows editors)
- fm = {}
- if skill_md.startswith("---"):
- match = re.search(r'\n---\s*\n', skill_md[3:])
- if match:
- try:
- fm = yaml.safe_load(skill_md[3:match.start() + 3]) or {}
- except yaml.YAMLError:
- pass
-
+ skill_md = (path / "SKILL.md").read_text(encoding="utf-8").lstrip("\ufeff") # tolerate BOM
+ fm = _read_frontmatter(skill_md)
name = fm.get("name", path.name)
- description = fm.get("description", "")
- if not description:
- c.print("[bold red]Error:[/] SKILL.md must have a 'description' in frontmatter.\n")
+ if not fm.get("description", ""):
+ _print_error(c, "SKILL.md must have a 'description' in frontmatter.")
return
- # Self-scan before publishing
c.print(f"[bold]Scanning '{name}' before publish...[/]")
result = scan_skill(path, source="self")
c.print(format_scan_report(result))
@@ -1546,20 +1318,17 @@ def do_publish(skill_path: str, target: str = "github", repo: str = "",
c.print("[bold red]Error:[/] --repo required for GitHub publish.\n"
"Usage: hermes skills publish <path> --to github --repo owner/repo\n")
return
-
auth = GitHubAuth()
if not auth.is_authenticated():
c.print("[bold red]Error:[/] GitHub authentication required.\n"
f"Set GITHUB_TOKEN in {display_hermes_home()}/.env or run 'gh auth login'.\n")
return
-
c.print(f"[bold]Publishing '{name}' to {repo}...[/]")
success, msg = _github_publish(path, name, repo, auth)
if success:
c.print(f"[bold green]{msg}[/]\n")
else:
- c.print(f"[bold red]Error:[/] {msg}\n")
-
+ _print_error(c, msg)
elif target == "clawhub":
c.print("[yellow]ClawHub publishing is not yet supported. "
"Submit manually at https://clawhub.ai/submit[/]\n")
@@ -1569,20 +1338,17 @@ def do_publish(skill_path: str, target: str = "github", repo: str = "",
def _github_publish(skill_path: Path, skill_name: str, target_repo: str,
auth) -> tuple:
- """Create a PR to a GitHub repo with the skill. Returns (success, message)."""
+ """Fork, branch, upload, and open a PR with the skill. Returns (success, message)."""
+ import base64
import httpx
headers = auth.get_headers()
+ api = "https://api.github.com/repos"
- # 1. Fork the repo
try:
- resp = httpx.post(
- f"https://api.github.com/repos/{target_repo}/forks",
- headers=headers, timeout=30,
- )
+ resp = httpx.post(f"{api}/{target_repo}/forks", headers=headers, timeout=30)
if resp.status_code in {200, 202}:
- fork = resp.json()
- fork_repo = fork["full_name"]
+ fork_repo = resp.json()["full_name"]
elif resp.status_code == 403:
return False, "GitHub token lacks permission to fork repos"
else:
@@ -1590,63 +1356,44 @@ def _github_publish(skill_path: Path, skill_name: str, target_repo: str,
except httpx.HTTPError as e:
return False, f"Network error forking repo: {e}"
- # 2. Get default branch
try:
- resp = httpx.get(
- f"https://api.github.com/repos/{target_repo}",
- headers=headers, timeout=15,
- )
+ resp = httpx.get(f"{api}/{target_repo}", headers=headers, timeout=15)
default_branch = resp.json().get("default_branch", "main")
except Exception:
default_branch = "main"
- # 3. Get the base tree SHA
try:
- resp = httpx.get(
- f"https://api.github.com/repos/{fork_repo}/git/refs/heads/{default_branch}",
- headers=headers, timeout=15,
- )
+ resp = httpx.get(f"{api}/{fork_repo}/git/refs/heads/{default_branch}",
+ headers=headers, timeout=15)
base_sha = resp.json()["object"]["sha"]
except Exception as e:
return False, f"Failed to get base branch: {e}"
- # 4. Create a new branch
branch_name = f"add-skill-{skill_name}"
try:
- httpx.post(
- f"https://api.github.com/repos/{fork_repo}/git/refs",
- headers=headers, timeout=15,
- json={"ref": f"refs/heads/{branch_name}", "sha": base_sha},
- )
+ httpx.post(f"{api}/{fork_repo}/git/refs", headers=headers, timeout=15,
+ json={"ref": f"refs/heads/{branch_name}", "sha": base_sha})
except Exception as e:
return False, f"Failed to create branch: {e}"
- # 5. Upload skill files
for f in skill_path.rglob("*"):
if not f.is_file():
continue
rel = str(f.relative_to(skill_path))
- upload_path = f"skills/{skill_name}/{rel}"
try:
- import base64
- content_b64 = base64.b64encode(f.read_bytes()).decode()
httpx.put(
- f"https://api.github.com/repos/{fork_repo}/contents/{upload_path}",
+ f"{api}/{fork_repo}/contents/skills/{skill_name}/{rel}",
headers=headers, timeout=15,
- json={
- "message": f"Add {skill_name} skill: {rel}",
- "content": content_b64,
- "branch": branch_name,
- },
+ json={"message": f"Add {skill_name} skill: {rel}",
+ "content": base64.b64encode(f.read_bytes()).decode(),
+ "branch": branch_name},
)
except Exception as e:
return False, f"Failed to upload {rel}: {e}"
- # 6. Create PR
try:
resp = httpx.post(
- f"https://api.github.com/repos/{target_repo}/pulls",
- headers=headers, timeout=15,
+ f"{api}/{target_repo}/pulls", headers=headers, timeout=15,
json={
"title": f"Add skill: {skill_name}",
"body": f"Submitting the `{skill_name}` skill via Hermes Skills Hub.\n\n"
@@ -1656,10 +1403,8 @@ def _github_publish(skill_path: Path, skill_name: str, target_repo: str,
},
)
if resp.status_code == 201:
- pr_url = resp.json().get("html_url", "")
- return True, f"PR created: {pr_url}"
- else:
- return False, f"Failed to create PR: {resp.status_code} {resp.text[:200]}"
+ return True, f"PR created: {resp.json().get('html_url', '')}"
+ return False, f"Failed to create PR: {resp.status_code} {resp.text[:200]}"
except httpx.HTTPError as e:
return False, f"Network error creating PR: {e}"
@@ -1669,12 +1414,8 @@ def do_snapshot_export(output_path: str, console: Optional[Console] = None) -> N
from tools.skills_hub import HubLockFile, TapsManager
c = console or _console
- lock = HubLockFile()
- taps = TapsManager()
-
- installed = lock.list_installed()
- tap_list = taps.list_taps()
-
+ installed = HubLockFile().list_installed()
+ tap_list = TapsManager().list_taps()
snapshot = {
"hermes_version": "0.1.0",
"exported_at": datetime.now(timezone.utc).isoformat(),
@@ -1690,15 +1431,14 @@ def do_snapshot_export(output_path: str, console: Optional[Console] = None) -> N
],
"taps": tap_list,
}
-
payload = json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n"
if output_path == "-":
sys.stdout.write(payload)
- else:
- out = Path(output_path)
- out.write_text(payload, encoding="utf-8")
- c.print(f"[bold green]Snapshot exported:[/] {out}")
- c.print(f"[dim]{len(installed)} skill(s), {len(tap_list)} tap(s)[/]\n")
+ return
+ out = Path(output_path)
+ out.write_text(payload, encoding="utf-8")
+ c.print(f"[bold green]Snapshot exported:[/] {out}")
+ c.print(f"[dim]{len(installed)} skill(s), {len(tap_list)} tap(s)[/]\n")
def do_snapshot_import(input_path: str, force: bool = False,
@@ -1709,16 +1449,14 @@ def do_snapshot_import(input_path: str, force: bool = False,
c = console or _console
inp = Path(input_path)
if not inp.exists():
- c.print(f"[bold red]Error:[/] File not found: {inp}\n")
+ _print_error(c, f"File not found: {inp}")
return
-
try:
snapshot = json.loads(inp.read_text(encoding="utf-8"))
except json.JSONDecodeError:
- c.print(f"[bold red]Error:[/] Invalid JSON in {inp}\n")
+ _print_error(c, f"Invalid JSON in {inp}")
return
- # Restore taps first
taps = snapshot.get("taps", [])
if taps:
mgr = TapsManager()
@@ -1728,23 +1466,18 @@ def do_snapshot_import(input_path: str, force: bool = False,
mgr.add(repo, tap.get("path", "skills/"))
c.print(f"[dim]Restored {len(taps)} tap(s)[/]")
- # Install skills
skills = snapshot.get("skills", [])
if not skills:
c.print("[dim]No skills in snapshot to install.[/]\n")
return
-
c.print(f"[bold]Importing {len(skills)} skill(s) from snapshot...[/]\n")
for entry in skills:
identifier = entry.get("identifier", "")
- category = entry.get("category", "")
if not identifier:
c.print(f"[yellow]Skipping entry with no identifier: {entry.get('name', '?')}[/]")
continue
-
c.print(f"[bold]--- {entry.get('name', identifier)} ---[/]")
- do_install(identifier, category=category, force=force, console=c)
-
+ do_install(identifier, category=entry.get("category", ""), force=force, console=c)
c.print("[bold green]Snapshot import complete.[/]\n")
@@ -1764,11 +1497,10 @@ def _snapshot_cli(args) -> None:
def _tap_cli(args) -> None:
tap_action = getattr(args, "tap_action", None)
- repo = getattr(args, "repo", "") or getattr(args, "name", "")
if not tap_action:
_console.print("Usage: hermes skills tap [list|add|remove]\n")
return
- do_tap(tap_action, repo=repo)
+ do_tap(tap_action, repo=getattr(args, "repo", "") or getattr(args, "name", ""))
# `hermes skills <action>` -> handler(args). Lambdas late-bind the do_* names so
@@ -1822,8 +1554,8 @@ def skills_command(args) -> None:
def _opt_value(args: List[str], flag: str, default: str, last: bool = False) -> str:
"""Value following `flag` in args (default if absent/trailing).
- `last=True` lets a repeated flag's final occurrence win (the historical
- behaviour of the install/publish/browse parsers); otherwise the first wins.
+ `last=True` lets a repeated flag's final occurrence win (the historical behaviour of the
+ install/publish/browse parsers); otherwise the first wins.
"""
found = default
for i, a in enumerate(args):
@@ -1842,19 +1574,8 @@ def _opt_int(args: List[str], flag: str, default: int) -> int:
return default
-def _slash_browse(args, c):
- do_browse(page=_opt_int(args, "--page", 1), page_size=_opt_int(args, "--size", 20),
- source=_opt_value(args, "--source", "all", last=True), console=c)
-
-
def _slash_search(args, c):
- if not args:
- c.print("[bold red]Usage:[/] /skills search <query> [--source skills-sh|github|official|nvidia|openai|anthropic|huggingface] [--limit N] [--json]\n")
- return
- source = "all"
- limit = 25
- as_json = False
- query_parts = []
+ source, limit, as_json, query_parts = "all", 25, False, []
i = 0
while i < len(args):
if args[i] == "--source" and i + 1 < len(args):
@@ -1872,77 +1593,7 @@ def _slash_search(args, c):
else:
query_parts.append(args[i])
i += 1
- do_search(" ".join(query_parts), source=source, limit=limit,
- console=c, as_json=as_json)
-
-
-def _slash_install(args, c):
- if not args:
- c.print("[bold red]Usage:[/] /skills install <identifier-or-url> [--name <name>] [--category <cat>] [--force] [--now]\n")
- return
- # Slash commands run inside prompt_toolkit where input() hangs, so
- # confirmation is always skipped — typing the command is implicit consent.
- # --now invalidates prompt cache immediately (costs more money);
- # default defers to next session to preserve cache.
- do_install(args[0], category=_opt_value(args, "--category", "", last=True),
- force="--force" in args, skip_confirm=True, invalidate_cache="--now" in args,
- name_override=_opt_value(args, "--name", "", last=True), console=c)
-
-
-def _slash_inspect(args, c):
- if not args:
- c.print("[bold red]Usage:[/] /skills inspect <identifier>\n")
- return
- do_inspect(args[0], console=c)
-
-
-def _slash_list(args, c):
- do_list(source_filter=_opt_value(args, "--source", "all"),
- enabled_only="--enabled-only" in args or "--enabled" in args, console=c)
-
-
-def _slash_update(args, c):
- pos = [a for a in args if not a.startswith("--")]
- do_update(name=pos[0] if pos else None, console=c, force="--force" in args)
-
-
-def _slash_audit(args, c):
- name = args[0] if args and not args[0].startswith("--") else None
- do_audit(name=name, console=c, deep="--deep" in args)
-
-
-def _slash_uninstall(args, c):
- if not args:
- c.print("[bold red]Usage:[/] /skills uninstall <name> [--now]\n")
- return
- # Slash commands run inside prompt_toolkit where input() hangs.
- do_uninstall(args[0], console=c, skip_confirm=True, invalidate_cache="--now" in args)
-
-
-def _slash_reset(args, c):
- if not args:
- c.print("[bold red]Usage:[/] /skills reset <name> [--restore] [--now]\n")
- c.print("[dim]Clears the bundled-skills manifest entry so future updates stop marking it as user-modified.[/]")
- c.print("[dim]Pass --restore to also replace the current copy with the bundled version.[/]\n")
- return
- # Slash commands can't prompt — --restore in slash mode is implicit consent.
- do_reset(args[0], restore="--restore" in args, console=c, skip_confirm=True,
- invalidate_cache="--now" in args)
-
-
-def _slash_diff(args, c):
- if not args:
- c.print("[bold red]Usage:[/] /skills diff <name>\n")
- return
- do_diff(args[0], console=c)
-
-
-def _slash_publish(args, c):
- if not args:
- c.print("[bold red]Usage:[/] /skills publish <skill-path> [--to github] [--repo owner/repo]\n")
- return
- do_publish(args[0], target=_opt_value(args, "--to", "github", last=True),
- repo=_opt_value(args, "--repo", "", last=True), console=c)
+ do_search(" ".join(query_parts), source=source, limit=limit, console=c, as_json=as_json)
def _slash_snapshot(args, c):
@@ -1961,21 +1612,42 @@ def _slash_tap(args, c):
do_tap(args[0], repo=args[1] if len(args) > 1 else "", console=c)
+def _first_positional(args):
+ return args[0] if args and not args[0].startswith("--") else None
+
+
+# Slash commands run inside prompt_toolkit where input() hangs, so install/uninstall/reset
+# always skip confirmation — typing the command is implicit consent. `--now` invalidates the
+# prompt cache immediately (costs more money); the default defers to the next session.
_SLASH_ACTIONS = {
- "browse": _slash_browse,
+ "browse": lambda args, c: do_browse(
+ page=_opt_int(args, "--page", 1), page_size=_opt_int(args, "--size", 20),
+ source=_opt_value(args, "--source", "all", last=True), console=c),
"search": _slash_search,
- "install": _slash_install,
- "inspect": _slash_inspect,
- "list": _slash_list,
+ "install": lambda args, c: do_install(
+ args[0], category=_opt_value(args, "--category", "", last=True),
+ force="--force" in args, skip_confirm=True, invalidate_cache="--now" in args,
+ name_override=_opt_value(args, "--name", "", last=True), console=c),
+ "inspect": lambda args, c: do_inspect(args[0], console=c),
+ "list": lambda args, c: do_list(
+ source_filter=_opt_value(args, "--source", "all"),
+ enabled_only="--enabled-only" in args or "--enabled" in args, console=c),
"check": lambda args, c: do_check(name=args[0] if args else None, console=c),
- "update": _slash_update,
- "audit": _slash_audit,
- "uninstall": _slash_uninstall,
- "reset": _slash_reset,
+ "update": lambda args, c: do_update(
+ name=next((a for a in args if not a.startswith("--")), None), console=c,
+ force="--force" in args),
+ "audit": lambda args, c: do_audit(name=_first_positional(args), console=c, deep="--deep" in args),
+ "uninstall": lambda args, c: do_uninstall(
+ args[0], console=c, skip_confirm=True, invalidate_cache="--now" in args),
+ "reset": lambda args, c: do_reset(
+ args[0], restore="--restore" in args, console=c, skip_confirm=True,
+ invalidate_cache="--now" in args),
"list-modified": lambda args, c: do_list_modified(console=c, as_json="--json" in args),
"modified": lambda args, c: do_list_modified(console=c, as_json="--json" in args),
- "diff": _slash_diff,
- "publish": _slash_publish,
+ "diff": lambda args, c: do_diff(args[0], console=c),
+ "publish": lambda args, c: do_publish(
+ args[0], target=_opt_value(args, "--to", "github", last=True),
+ repo=_opt_value(args, "--repo", "", last=True), console=c),
"snapshot": _slash_snapshot,
"tap": _slash_tap,
"help": lambda args, c: _print_skills_help(c),
@@ -1983,27 +1655,42 @@ _SLASH_ACTIONS = {
"-h": lambda args, c: _print_skills_help(c),
}
+# Actions that need at least one argument -> usage lines printed when called bare.
+_SLASH_USAGE = {
+ "search": ("[bold red]Usage:[/] /skills search <query> [--source skills-sh|github|official|nvidia|openai|anthropic|huggingface] [--limit N] [--json]\n",),
+ "install": ("[bold red]Usage:[/] /skills install <identifier-or-url> [--name <name>] [--category <cat>] [--force] [--now]\n",),
+ "inspect": ("[bold red]Usage:[/] /skills inspect <identifier>\n",),
+ "uninstall": ("[bold red]Usage:[/] /skills uninstall <name> [--now]\n",),
+ "reset": (
+ "[bold red]Usage:[/] /skills reset <name> [--restore] [--now]\n",
+ "[dim]Clears the bundled-skills manifest entry so future updates stop marking it as user-modified.[/]",
+ "[dim]Pass --restore to also replace the current copy with the bundled version.[/]\n",
+ ),
+ "diff": ("[bold red]Usage:[/] /skills diff <name>\n",),
+ "publish": ("[bold red]Usage:[/] /skills publish <skill-path> [--to github] [--repo owner/repo]\n",),
+}
+
def handle_skills_slash(cmd: str, console: Optional[Console] = None) -> None:
"""Parse and dispatch `/skills <subcommand> [args]` from the chat interface."""
c = console or _console
parts = cmd.strip().split()
-
- # Strip the leading "/skills" if present
if parts and parts[0].lower() == "/skills":
parts = parts[1:]
-
if not parts:
_print_skills_help(c)
return
-
- action = parts[0].lower()
+ action, args = parts[0].lower(), parts[1:]
handler = _SLASH_ACTIONS.get(action)
if handler is None:
c.print(f"[bold red]Unknown action:[/] {action}")
_print_skills_help(c)
return
- handler(parts[1:], c)
+ if not args and action in _SLASH_USAGE:
+ for line in _SLASH_USAGE[action]:
+ c.print(line)
+ return
+ handler(args, c)
def _print_skills_help(console: Console) -> None: