skills_hub.py 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731
  1. #!/usr/bin/env python3
  2. """Skills Hub CLI — Unified interface for the Hermes Skills Hub."""
  3. import json
  4. import logging
  5. import re
  6. import shutil
  7. import sys
  8. from datetime import datetime, timezone, UTC
  9. from pathlib import Path
  10. from typing import Any, Dict, List, Optional
  11. from rich.console import Console
  12. from rich.panel import Panel
  13. from rich.table import Table
  14. # tools.skills_hub / tools.skills_guard are imported inside functions (cycles + startup cost).
  15. from hermes_constants import display_hermes_home
  16. _console = Console()
  17. _VALID_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
  18. _VALID_CATEGORY_RE = re.compile(r"^[a-z][a-z0-9_/-]*$")
  19. _TRUST_STYLE = {"builtin": "bright_cyan", "trusted": "green", "community": "yellow", "local": "dim"}
  20. _TRUST_RANK = {"builtin": 3, "trusted": 2, "community": 1}
  21. # Browse per-source limits. With the centralized index available, parallel_search_sources
  22. # serves everything from "hermes-index", so that entry MUST exceed the whole catalog or browse
  23. # silently caps the hub (50 and 5000 both truncated). The index is disk-cached and browse
  24. # paginates client-side. The external limits only apply when the index is unavailable.
  25. _BROWSE_LIMITS = {
  26. "hermes-index": 1000000, "official": 200, "skills-sh": 200, "well-known": 50,
  27. "github": 200, "clawhub": 500, "lobehub": 500, "browse-sh": 500}
  28. # Programmatic (TUI gateway) browse keeps its own, lower caps.
  29. _BROWSE_API_LIMITS = {
  30. "hermes-index": 5000, "official": 100, "skills-sh": 100, "well-known": 25,
  31. "github": 100, "clawhub": 50, "lobehub": 50, "browse-sh": 500}
  32. _EXTRA_META_LABELS = (
  33. ("repo_url", "Repo"), ("detail_url", "Detail Page"), ("index_url", "Index"),
  34. ("endpoint", "Endpoint"), ("install_command", "Install Command"),
  35. ("installs", "Installs"), ("weekly_installs", "Weekly Installs"))
  36. # --- Small shared helpers ---
  37. def _display_source(r) -> str:
  38. """Source label for a result row: GitHub-tap rows surface their per-tap provider label."""
  39. return ((r.extra or {}).get("provider") if r.source == "github" else None) or r.source
  40. def _trust_cell(trust_level: str, source: str, official_label: str = "official") -> str:
  41. """Rich-styled trust cell; official-source rows show `official_label` instead of the level."""
  42. label = official_label if source == "official" else trust_level
  43. return f"[{_TRUST_STYLE.get(trust_level, 'dim')}]{label}[/]"
  44. def _row(r, *fields) -> dict:
  45. """`{field: getattr(r, field)}` projection of a result/meta object, in the given order."""
  46. return {f: getattr(r, f) for f in fields}
  47. def _truncate(text: str, width: int) -> str:
  48. return text[:width] + ("..." if len(text) > width else "")
  49. def _ident_col(style: str) -> tuple:
  50. # overflow="fold" keeps the full slug visible (wraps instead of ellipsis-truncating):
  51. # browse.sh slugs end in a `-XXXXXX` hash that is part of the identifier users must
  52. # copy into `hermes skills install`.
  53. return "Identifier", {"style": style, "overflow": "fold", "no_wrap": False}
  54. def _table(*columns, **table_kw) -> Table:
  55. """Rich table from (header, add_column-kwargs) pairs; a bare header is a dim column."""
  56. table = Table(**table_kw)
  57. for col in columns:
  58. header, kw = col if isinstance(col, tuple) else (col, {"style": "dim"})
  59. table.add_column(header, **kw)
  60. return table
  61. def _try(fn, *args):
  62. """`fn(*args)`, or None when it raises (adapter probes are best-effort)."""
  63. try:
  64. return fn(*args)
  65. except Exception:
  66. return None
  67. def _sources():
  68. """Source router over all registries (authenticated GitHub when available)."""
  69. from tools.skills_hub_github import GitHubAuth
  70. from tools.skills_hub_search import create_source_router
  71. return create_source_router(GitHubAuth())
  72. def _confirm() -> bool:
  73. """Prompt `Confirm [y/N]:`; EOF/Ctrl-C counts as no."""
  74. try:
  75. return input("Confirm [y/N]: ").strip().lower() in {"y", "yes"}
  76. except (EOFError, KeyboardInterrupt):
  77. return False
  78. def _confirm_or_cancel(c: Console, *lines: str, cancel: str = "[dim]Cancelled.[/]\n") -> bool:
  79. """Print `lines`, ask `_confirm()`; on refusal print `cancel` and return False."""
  80. for line in lines:
  81. c.print(line)
  82. if _confirm():
  83. return True
  84. c.print(cancel)
  85. return False
  86. def _clear_skills_cache() -> None:
  87. """Invalidate the skills prompt cache so the change appears immediately."""
  88. try:
  89. from agent.prompt_builder import clear_skills_system_prompt_cache
  90. clear_skills_system_prompt_cache(clear_snapshot=True)
  91. except Exception:
  92. pass
  93. def _finish_change(c: Console, invalidate_cache: bool, what: str = "Change will take effect",
  94. verb: str = "apply", notice: bool = True) -> None:
  95. """Apply-now (cache clear) or, when `notice`, tell the user the change lands next session."""
  96. if invalidate_cache:
  97. _clear_skills_cache()
  98. return
  99. if not notice:
  100. return
  101. c.print(f"[dim]{what} in your next session.[/]")
  102. c.print(f"[dim]Use /reset to start a new session now, or --now to {verb} immediately (invalidates prompt cache).[/]\n")
  103. def _print_error(c: Console, message: str) -> None:
  104. # One unwrapped line: the Desktop Hub toasts a failed action's last 3 log lines, and an 80-column
  105. # wrap left only the tail of the message there (the subject was cut off).
  106. c.print(f"[bold red]Error:[/] {message}\n", soft_wrap=True)
  107. def _print_listed(c: Console, label: str, items) -> None:
  108. """`[dim]Label: a, b[/]` when `items` is non-empty."""
  109. if items:
  110. c.print(f"[dim]{label}: {', '.join(items)}[/]")
  111. def _report_pair(c: Console, success: bool, msg: str) -> bool:
  112. """`(success, message)` result: green message + blank line, or red error."""
  113. if success:
  114. c.print(f"[bold green]{msg}[/]\n")
  115. else:
  116. _print_error(c, msg)
  117. return success
  118. def _report_ok(c: Console, result: dict, fallback: str = "") -> bool:
  119. """skills_sync-style `{ok, message}` result: green message on success, red error otherwise."""
  120. if result.get("ok"):
  121. c.print(f"[bold green]{result['message']}[/]")
  122. return True
  123. _print_error(c, result.get("message", fallback))
  124. return False
  125. def _skill_md_preview(bundle) -> Optional[str]:
  126. """First 50 lines of the bundle's SKILL.md (None when absent)."""
  127. if not bundle or "SKILL.md" not in bundle.files:
  128. return None
  129. content = bundle.files["SKILL.md"]
  130. if isinstance(content, bytes):
  131. content = content.decode("utf-8", errors="replace")
  132. lines = content.split("\n")
  133. more = f"\n\n... ({len(lines) - 50} more lines)" if len(lines) > 50 else ""
  134. return "\n".join(lines[:50]) + more
  135. def _format_extra_metadata_lines(extra: dict[str, Any]) -> list[str]:
  136. lines: list[str] = []
  137. for key, label in _EXTRA_META_LABELS:
  138. value = extra.get(key)
  139. if value is not None and (value or key == "installs"): # installs: 0 is still shown
  140. lines.append(f"[bold]{label}:[/] {value}")
  141. security = extra.get("security_audits")
  142. if isinstance(security, dict) and security:
  143. ordered = ", ".join(f"{name}={status}" for name, status in sorted(security.items()))
  144. lines.append(f"[bold]Security:[/] {ordered}")
  145. return lines
  146. # --- Identifier / source resolution ---
  147. def _slug_key(text: str) -> str:
  148. """Separator-insensitive comparison key ("Blender Bpy Enhanced" == "blender-bpy-enhanced")."""
  149. return re.sub(r"[^a-z0-9]+", "", str(text or "").lower())
  150. def _identifier_slug(identifier: str) -> str:
  151. """Trailing path segment of an identifier ("skills-sh/org/repo/blender-animation" -> the slug)."""
  152. return str(identifier or "").split("/")[-1]
  153. def _exact_name_hits(results, name: str):
  154. """Results that ARE `name`: display name as written first, then — only when that finds nothing —
  155. the separator-insensitive form of the display name or of the identifier's trailing slug. Catalogs
  156. that carry a prettified title (ClawHub rows read "Blender Bpy Enhanced") or a path-shaped
  157. identifier ("@org/my-skill") match by neither, so `hermes skills install my-skill` refused with
  158. "No exact match" while printing that very slug on the suggestion line."""
  159. query = str(name or "").strip().lower()
  160. hits = [r for r in results if str(r.name or "").strip().lower() == query]
  161. if hits:
  162. return hits
  163. key = _slug_key(query)
  164. if not key:
  165. return []
  166. return [r for r in results if key in (_slug_key(r.name), _slug_key(_identifier_slug(r.identifier)))]
  167. def _resolve_short_name(name: str, sources, console: Console, attempt: Optional[dict] = None) -> str:
  168. """Short name -> full identifier via search; "" when ambiguous/missing (one exact match wins,
  169. several -> the single official one, else they are listed). ``attempt`` (an install's metric
  170. record) gets ``failure_class`` ``ambiguous`` / ``not_found`` when it returns ""."""
  171. attempt = attempt if attempt is not None else {}
  172. from tools.skills_hub_search import unified_search
  173. c = console or _console
  174. c.print(f"[dim]Resolving '{name}'...[/]")
  175. results = unified_search(name, sources, source_filter="all", limit=20)
  176. exact = _exact_name_hits(results, name)
  177. if len(exact) == 1:
  178. c.print(f"[dim]Resolved to: {exact[0].identifier}[/]")
  179. attempt["registry"] = exact[0].source # the adapter that served it overrides this
  180. return exact[0].identifier
  181. if len(exact) > 1:
  182. official = [r for r in exact if r.source == "official"] # outranks community mirrors
  183. if len(official) == 1:
  184. c.print(f"[dim]Resolved to: {official[0].identifier} (official catalog)[/]")
  185. attempt["registry"] = "official"
  186. return official[0].identifier
  187. c.print(f"\n[yellow]Multiple skills named '{name}' found:[/]")
  188. table = _table("Source", "Trust", _ident_col("bold cyan"))
  189. for r in exact:
  190. table.add_row(r.source, _trust_cell(r.trust_level, r.source), r.identifier)
  191. c.print(table)
  192. c.print("[bold]Use the full identifier to install a specific one.[/]\n")
  193. attempt["failure_class"] = "ambiguous"
  194. return ""
  195. if results:
  196. c.print(f"[yellow]No exact match for '{name}'. Did you mean one of these?[/]")
  197. for r in results[:5]:
  198. c.print(f" [cyan]{r.name}[/] — {r.identifier}")
  199. c.print()
  200. attempt["failure_class"] = "not_found"
  201. return ""
  202. _print_error(c, f"No skill named '{name}' found in any source.")
  203. attempt["failure_class"] = "not_found"
  204. return ""
  205. def _resolve_source_meta_and_bundle(identifier: str, sources):
  206. """(meta, bundle, source) from ONE adapter — mixing skills.sh metadata with a ClawHub zip of
  207. a same-named skill once showed the wrong SKILL.md. Falls back to the first meta-only hit.
  208. """
  209. first_meta = None
  210. first_meta_source = None
  211. for src in sources:
  212. meta = _try(src.inspect, identifier)
  213. bundle = _try(src.fetch, identifier)
  214. if bundle:
  215. if meta is None:
  216. meta = _try(src.inspect, identifier)
  217. return meta, bundle, src
  218. if first_meta is None and meta:
  219. first_meta, first_meta_source = meta, src
  220. return first_meta, None, first_meta_source
  221. def _full_identifier(identifier: str, sources, c, attempt: Optional[dict] = None) -> str:
  222. """Identifiers without a slash are short names; "" when they cannot be resolved."""
  223. return identifier if "/" in identifier else _resolve_short_name(identifier, sources, c, attempt)
  224. def _resolve_identifier(identifier: str, sources, c) -> tuple:
  225. """Short-name resolution + (meta, bundle, source). identifier == "" means unresolved."""
  226. from tools.skills_hub import skills_hub_http_session
  227. with skills_hub_http_session():
  228. identifier = _full_identifier(identifier, sources, c)
  229. if not identifier:
  230. return "", None, None, None
  231. return (identifier, *_resolve_source_meta_and_bundle(identifier, sources))
  232. def _is_valid_installed_skill_name(name: str) -> bool:
  233. """Accept identifier-shaped names, reject empty / sentinel-y values."""
  234. candidate = name.strip().lower() if isinstance(name, str) else ""
  235. return bool(candidate not in {"", "skill", "readme", "index", "unnamed-skill"}
  236. and _VALID_NAME_RE.match(candidate))
  237. def _existing_categories() -> list[str]:
  238. """Sorted category buckets under ``~/.hermes/skills/`` (children without their own SKILL.md)."""
  239. from tools.skills_hub import SKILLS_DIR
  240. from tools.skills_hub_install import _category_skill_dirs
  241. try:
  242. return sorted(name for name in set(_category_skill_dirs(SKILLS_DIR))
  243. if not (SKILLS_DIR / name / "SKILL.md").exists())
  244. except OSError: # FileNotFoundError is an OSError
  245. return []
  246. def _line_input(prompt: str) -> Optional[str]:
  247. """Stripped interactive line; None on EOF/Ctrl-C."""
  248. from hermes_cli.cli_output import line_input
  249. try:
  250. return line_input(prompt).strip()
  251. except (EOFError, KeyboardInterrupt):
  252. return None
  253. def _prompt_for_skill_name(c: Console, url: str, default: str = "") -> Optional[str]:
  254. """Prompt interactively for a skill name. Returns None on cancel/EOF."""
  255. c.print()
  256. c.print(f"[yellow]The SKILL.md at {url} doesn't declare a `name:` in its frontmatter,[/]\n"
  257. "[yellow]and the URL path doesn't produce a valid identifier either.[/]")
  258. c.print(f"[bold]Enter a skill name{f' [{default}]' if default else ''}:[/] "
  259. "[dim](lowercase letters, digits, hyphens, underscores; starts with a letter)[/]")
  260. answer = _line_input("Name: ")
  261. if answer is None:
  262. return None
  263. answer = answer or default
  264. if not _is_valid_installed_skill_name(answer):
  265. c.print(f"[bold red]Invalid name:[/] {answer!r}. Aborting install.\n")
  266. return None
  267. return answer
  268. def _prompt_for_category(c: Console, existing: list[str]) -> str:
  269. """Prompt interactively for a category. Empty/None input means flat install."""
  270. c.print()
  271. if existing:
  272. c.print("[bold]Pick a category[/] "
  273. "[dim](reuse an existing bucket, type a new one, or press Enter to install flat)[/]")
  274. c.print(f"[dim]Existing: {', '.join(existing)}[/]")
  275. else:
  276. c.print("[bold]Category[/] "
  277. f"[dim](optional — press Enter to install flat at {display_hermes_home()}/skills/<name>/)[/]")
  278. answer = _line_input("Category: ")
  279. if answer and not _VALID_CATEGORY_RE.match(answer):
  280. c.print(f"[dim]Invalid category {answer!r} — installing flat.[/]")
  281. return ""
  282. return answer or ""
  283. # --- search / browse / inspect ---
  284. def do_search(query: str, source: str = "all", limit: int = 10, console: Optional[Console] = None,
  285. as_json: bool = False) -> None:
  286. """Search registries -> Rich table, or a clean JSON array (``as_json``) for scripting."""
  287. from tools.skills_hub_search import unified_search
  288. c = console or _console
  289. sources = _sources()
  290. if as_json:
  291. results = unified_search(query, sources, source_filter=source, limit=limit)
  292. print(json.dumps([_row(r, "name", "identifier", "source", "trust_level", "description")
  293. for r in results], indent=2))
  294. return
  295. c.print(f"\n[bold]Searching for:[/] {query}")
  296. with c.status("[bold]Searching registries..."):
  297. results = unified_search(query, sources, source_filter=source, limit=limit)
  298. if not results:
  299. c.print("[dim]No skills found matching your query.[/]\n")
  300. return
  301. table = _table(("Name", {"style": "bold cyan"}), ("Description", {"max_width": 60}), "Source",
  302. "Trust", _ident_col("dim"), title=f"Skills Hub — {len(results)} result(s)")
  303. for r in results:
  304. table.add_row(r.name, _truncate(r.description, 60), _display_source(r),
  305. _trust_cell(r.trust_level, r.source), r.identifier)
  306. c.print(table)
  307. c.print("[dim]Use: hermes skills inspect <identifier> to preview, "
  308. "hermes skills install <identifier> to install "
  309. "(--json for scripting)[/]\n")
  310. def _rank_and_page(all_results, page: int, page_size: int):
  311. """Dedupe by identifier (higher trust wins; names are NOT unique across browse-sh sites),
  312. sort official-first, slice one page -> (deduped, page_items, page, total_pages, start)."""
  313. rank = lambda r: _TRUST_RANK.get(r.trust_level, 0)
  314. seen: dict = {}
  315. for r in all_results:
  316. if r.identifier not in seen or rank(r) > rank(seen[r.identifier]):
  317. seen[r.identifier] = r
  318. deduped = sorted(seen.values(),
  319. key=lambda r: (-rank(r), r.source != "official", r.name.lower()))
  320. total_pages = max(1, (len(deduped) + page_size - 1) // page_size)
  321. page = max(1, min(page, total_pages))
  322. start = (page - 1) * page_size
  323. return deduped, deduped[start:start + page_size], page, total_pages, start
  324. def _fetch_browse_results(c: Console, source: str):
  325. """Parallel fetch from all (or filtered) sources with a live per-source progress spinner."""
  326. from tools.skills_hub_search import parallel_search_sources
  327. with c.status("[bold]Fetching skills from registries...") as status:
  328. # parallel_search_sources invokes the callback from the collecting thread as each
  329. # source completes; the page itself is rendered once over the final, fully sorted set.
  330. _done: list[str] = []
  331. def _on_source_done(sid: str, count: int) -> None:
  332. _done.append(f"{sid} ({count})")
  333. status.update(
  334. f"[bold]Fetching skills from registries...[/] [dim]done: {', '.join(_done)}[/]")
  335. return parallel_search_sources(
  336. _sources(), query="", per_source_limits=_BROWSE_LIMITS, source_filter=source,
  337. overall_timeout=30, on_source_done=_on_source_done)
  338. def _render_browse_page(c: Console, deduped, page_items, page: int, total_pages: int,
  339. start: int, source: str, source_counts, timed_out) -> None:
  340. official_count = sum(1 for r in deduped if r.source == "official")
  341. loaded_label = f"{len(deduped)} skills loaded" + (
  342. f", {len(timed_out)} source(s) still loading" if timed_out else "")
  343. c.print(f"\n[bold]Skills Hub — Browse — {source if source != 'all' else 'all sources'}[/]"
  344. f" [dim]({loaded_label}, page {page}/{total_pages})[/]")
  345. if official_count > 0 and page == 1:
  346. c.print(f"[bright_cyan]★ {official_count} official optional skill(s) from Nous Research[/]")
  347. c.print()
  348. table = _table(("#", {"style": "dim", "width": 4, "justify": "right"}),
  349. ("Name", {"style": "bold cyan", "max_width": 22}),
  350. ("Description", {"max_width": 44}), ("Source", {"style": "dim", "width": 12}),
  351. ("Trust", {"width": 10}),
  352. _ident_col("dim"), show_header=True, header_style="bold")
  353. for i, r in enumerate(page_items, start=start + 1):
  354. table.add_row(str(i), r.name, _truncate(r.description, 44), _display_source(r),
  355. _trust_cell(r.trust_level, r.source, official_label="★ official"),
  356. r.identifier)
  357. c.print(table)
  358. nav_parts = ([f"[cyan]--page {page - 1}[/] ← prev"] if page > 1 else []) + (
  359. [f"[cyan]--page {page + 1}[/] → next"] if page < total_pages else [])
  360. if nav_parts:
  361. c.print(f" {' | '.join(nav_parts)}")
  362. if source == "all" and source_counts:
  363. c.print(f" [dim]Sources: {', '.join(f'{sid}: {ct}' for sid, ct in sorted(source_counts.items()))}[/]")
  364. if timed_out:
  365. c.print(f" [yellow]⚡ Slow sources skipped: {', '.join(timed_out)} "
  366. f"— run again for cached results[/]")
  367. c.print("[dim]Tip: 'hermes skills inspect <identifier>' to preview, "
  368. "'hermes skills install <identifier>' to install, "
  369. "'hermes skills search <query>' to search deeper[/]\n")
  370. def do_browse(page: int = 1, page_size: int = 20, source: str = "all",
  371. console: Optional[Console] = None) -> None:
  372. """Browse all available skills across registries, paginated; official skills first."""
  373. page_size = max(1, min(page_size, 100))
  374. c = console or _console
  375. all_results, source_counts, timed_out = _fetch_browse_results(c, source)
  376. from tools.skills_hub_github import _provider_filter_of
  377. if not all_results:
  378. # Provider narrowing happens inside parallel_search_sources; keep the
  379. # provider-specific empty message.
  380. if _provider_filter_of(source):
  381. c.print(f"[dim]No skills found for provider '{source}'.[/]\n")
  382. else:
  383. c.print("[dim]No skills found in the Skills Hub.[/]\n")
  384. return
  385. deduped, page_items, page, total_pages, start = _rank_and_page(all_results, page, page_size)
  386. _render_browse_page(c, deduped, page_items, page, total_pages, start, source,
  387. source_counts, timed_out)
  388. def browse_skills(page: int = 1, page_size: int = 20, source: str = "all") -> dict:
  389. """Paginated hub browse for programmatic callers (e.g. TUI gateway)."""
  390. from tools.skills_hub_search import parallel_search_sources
  391. page_size = max(1, min(page_size, 100))
  392. # The shared parallel walker carries the index-aware source-skip logic — querying
  393. # hermes-index AND the external APIs at once would double-count every skill.
  394. all_results, _counts, _timed_out = parallel_search_sources(
  395. _sources(), query="", per_source_limits=_BROWSE_API_LIMITS,
  396. source_filter=source, overall_timeout=30)
  397. if not all_results:
  398. return {"items": [], "page": 1, "total_pages": 1, "total": 0}
  399. deduped, page_items, page, total_pages, _start = _rank_and_page(all_results, page, page_size)
  400. return {
  401. "items": [{**_row(r, "name", "description", "source"), "trust": r.trust_level,
  402. "identifier": r.identifier} for r in page_items],
  403. "page": page, "total_pages": total_pages, "total": len(deduped)}
  404. def do_inspect(identifier: str, console: Optional[Console] = None) -> None:
  405. """Preview a skill's SKILL.md content without installing."""
  406. c = console or _console
  407. identifier, meta, bundle, _src = _resolve_identifier(identifier, _sources(), c)
  408. if not identifier:
  409. return
  410. if not meta:
  411. _print_error(c, f"Could not find '{identifier}' in any source.")
  412. return
  413. c.print()
  414. info_lines = [f"[bold]Name:[/] {meta.name}", f"[bold]Description:[/] {meta.description}",
  415. f"[bold]Source:[/] {meta.source}",
  416. f"[bold]Trust:[/] {_trust_cell(meta.trust_level, meta.source)}",
  417. f"[bold]Identifier:[/] {meta.identifier}"]
  418. if meta.tags:
  419. info_lines.append(f"[bold]Tags:[/] {', '.join(meta.tags)}")
  420. info_lines.extend(_format_extra_metadata_lines(meta.extra))
  421. c.print(Panel("\n".join(info_lines), title=f"Skill: {meta.name}"))
  422. preview = _skill_md_preview(bundle)
  423. if preview is not None:
  424. c.print(Panel(preview, title="SKILL.md Preview", subtitle="hermes skills install <id> to install"))
  425. c.print()
  426. def inspect_skill(identifier: str) -> Optional[dict]:
  427. """Skill metadata (+ SKILL.md preview) for programmatic callers."""
  428. ident, meta, bundle, _ = _resolve_identifier(identifier, _sources(), Console(quiet=True))
  429. if not ident or not meta:
  430. return None
  431. out = {**_row(meta, "name", "description", "source", "identifier"),
  432. "tags": list(meta.tags) if meta.tags else []}
  433. preview = _skill_md_preview(bundle)
  434. if preview is not None:
  435. out["skill_md_preview"] = preview
  436. return out
  437. # --- install ---
  438. def _install_blocked(c: Console, bundle, message: str, verdict: str, detail: str,
  439. q_path: Optional[Path] = None, lead: str = "", label: str = "Installation blocked:") -> None:
  440. """Print the blocked-install line, drop the quarantine copy, append the audit row."""
  441. c.print(f"{lead}[bold red]{label}[/] {message}")
  442. if q_path is not None:
  443. shutil.rmtree(q_path, ignore_errors=True)
  444. from tools.skills_hub import append_audit_log
  445. append_audit_log("BLOCKED", bundle.name, bundle.source, bundle.trust_level, verdict, detail)
  446. def _scan_block_message(result, identifier: str) -> str:
  447. """User-facing sentence for a scan-blocked install (the audit row keeps the scanner's raw reason).
  448. Says what happened (not installed), why in plain words (high-risk patterns), whether ``--force``
  449. can help, and the read-only next step (``hermes skills inspect``). The hard-block rule mirrors
  450. ``tools.skills_guard.should_allow_install``: a dangerous verdict on a non-official source."""
  451. n = len(result.findings)
  452. findings = f"{n} high-risk pattern(s)" if n else "high-risk patterns"
  453. hard_block = result.verdict == "dangerous" and result.trust_level in ("community", "trusted")
  454. policy = ("Hermes never installs unverified skills with high-risk findings, even with --force."
  455. if hard_block else "Re-run with --force to install anyway.")
  456. return (f"the security scan found {findings} in '{identifier}' (listed above). "
  457. f"{policy} Review the findings or ask the author to fix them; to read the skill without "
  458. f"installing, run `hermes skills inspect {identifier}`.")
  459. def _invalid_path(c: Console, bundle, exc: ValueError, q_path: Optional[Path] = None) -> None:
  460. _install_blocked(c, bundle, f"{exc}\n", "invalid_path", str(exc), q_path=q_path)
  461. def _resolve_url_bundle_name(c: Console, bundle, meta, identifier: str,
  462. name_override: str, skip_confirm: bool) -> bool:
  463. """Name a URL-sourced bundle whose SKILL.md has none: --name override, else TTY prompt,
  464. else an actionable refusal on non-interactive surfaces. False => abort the install."""
  465. bundle_meta = bundle.metadata
  466. if bundle.source != "url" or (bundle.name and not bundle_meta.get("awaiting_name")):
  467. return True
  468. url = bundle_meta.get("url") or identifier
  469. if name_override and _is_valid_installed_skill_name(name_override):
  470. bundle.name = name_override.strip()
  471. elif name_override:
  472. c.print(f"[bold red]Invalid --name:[/] {name_override!r}. Must be a lowercase identifier "
  473. "(letters, digits, hyphens, underscores; starts with a letter).\n")
  474. return False
  475. elif skip_confirm:
  476. # Non-interactive surface (slash command / TUI / gateway): can't prompt.
  477. c.print(f"[bold red]Cannot install from URL:[/] {url}\n"
  478. "[yellow]The SKILL.md has no `name:` in its frontmatter, "
  479. "and the URL path doesn't produce a valid identifier.[/]\n\n"
  480. "Retry with an explicit name:\n"
  481. f" [bold]/skills install {url} --name <your-name>[/]\n"
  482. f" [bold]hermes skills install {url} --name <your-name>[/]\n\n"
  483. "[dim]Or ask the SKILL.md's author to add a `name:` field to "
  484. "its YAML frontmatter.[/]\n")
  485. return False
  486. else:
  487. chosen = _prompt_for_skill_name(c, url)
  488. if not chosen:
  489. c.print("[dim]Installation cancelled.[/]\n")
  490. return False
  491. bundle.name = chosen
  492. bundle_meta["awaiting_name"] = False
  493. # Keep SkillMeta in sync so "already installed" checks, audit logs and display agree.
  494. if meta is not None:
  495. meta.name = bundle.name
  496. meta.path = bundle.name
  497. return True
  498. def _announce_blueprint(c: Console, skill_name: str) -> None:
  499. """Offer an installed skill's ``metadata.hermes.blueprint`` via /suggestions — never
  500. auto-scheduled (installing must not silently create a recurring job). Never raises."""
  501. try:
  502. from tools.blueprints import BlueprintError, blueprint_spec_for_installed, register_blueprint_suggestion
  503. try:
  504. spec = blueprint_spec_for_installed(skill_name)
  505. except BlueprintError as _rec_err:
  506. c.print(f"[yellow]Blueprint block present but invalid:[/] {_rec_err}\n")
  507. return
  508. if spec is None:
  509. return
  510. lead = (f"[bold cyan]Blueprint:[/] '{skill_name}' is an automation "
  511. f"(schedule [bold]{spec.schedule}[/])")
  512. if register_blueprint_suggestion(spec) is not None:
  513. c.print(f"{lead}.")
  514. c.print("[dim]Added to your suggestions — run[/] [bold]/suggestions[/] "
  515. "[dim]to schedule or dismiss it.[/]\n")
  516. else:
  517. # Dropped: already offered/dismissed (latched) or the pending list is at its cap.
  518. c.print(f"{lead}, but it wasn't added to your suggestions (already offered/dismissed, "
  519. "or the pending list is full — run [bold]/suggestions[/] to review).")
  520. c.print("[dim]You can still schedule it any time by asking the agent "
  521. "or via[/] [bold]hermes cron add[/][dim].[/]\n")
  522. except Exception: # pragma: no cover - blueprint detection is best-effort
  523. pass
  524. def _pinned_sources(c: Console, sources, source_id: Optional[str], identifier: str):
  525. """Restrict `sources` to the adapter matching `source_id`; None when it is unknown."""
  526. from tools.skills_hub_install import _source_matches
  527. pinned = [src for src in sources if _source_matches(src, source_id)] if source_id else sources
  528. if pinned:
  529. return pinned
  530. _print_error(c, f"no source adapter for '{source_id}'. "
  531. f"Refusing to resolve '{identifier}' against other registries "
  532. f"(that would change the skill's provenance).")
  533. return None
  534. def _hub_rate_limited(sources) -> bool:
  535. return any(getattr(src, "is_rate_limited", False)
  536. or getattr(getattr(src, "github", None), "is_rate_limited", False)
  537. for src in sources)
  538. def _hub_rejected_credentials(sources) -> list:
  539. """Credentials GitHub refused with 401 (the fetch already fell through past them, #98725)."""
  540. return next((r for src in sources
  541. if isinstance(r := getattr(getattr(src, "auth", None), "rejected", None), list) and r), [])
  542. def _print_fetch_failure(c: Console, sources, identifier: str, meta=None, source=None) -> str:
  543. """Explain a resolved identifier no adapter served; returns the extension-install failure class."""
  544. rate_limited = _hub_rate_limited(sources)
  545. rejected = _hub_rejected_credentials(sources)
  546. # Index hit but files gone: a stale index entry, not a user typo — name it so users stop
  547. # re-trying spellings (#3259). Only when no adapter was rate limited or refused a credential:
  548. # those fetches also yield meta-without-bundle, and calling that "stale" would send users away
  549. # from a skill that exists.
  550. if meta is not None and not rate_limited and not rejected:
  551. src_id = getattr(source, "source_id", lambda: "the registry")()
  552. c.print(f"[bold red]Error:[/] '{identifier}' is listed in the {src_id} index, "
  553. f"but its files no longer exist upstream.")
  554. c.print("[dim]Stale index entry: the skill was likely renamed or removed by "
  555. "its author. Try `hermes skills search` for an alternative.[/]\n")
  556. return "stale_index"
  557. c.print(f"[bold red]Error:[/] Could not download '{identifier}'.")
  558. if rejected:
  559. c.print(f"[yellow]Hint:[/] GitHub rejected {' and '.join(rejected)} (401 Bad credentials). "
  560. f"Replace or remove the token in {display_hermes_home()}/.env, or re-run [bold]gh auth login[/].")
  561. if rate_limited:
  562. c.print("[yellow]Hint:[/] GitHub API rate limit exhausted "
  563. "(unauthenticated: 60 requests/hour).\n"
  564. "Set [bold]GITHUB_TOKEN[/] in your .env or install the [bold]gh[/] CLI and run "
  565. "[bold]gh auth login[/] to raise the limit to 5,000/hr.\n")
  566. else:
  567. c.print(f"Check the name with [bold]hermes skills search {identifier.rsplit('/', 1)[-1]}[/] "
  568. "and check your internet connection. If it keeps failing, run [bold]hermes doctor[/].\n")
  569. return "rate_limited" if rate_limited else "auth_rejected" if rejected else "fetch_failed"
  570. def _scan_quarantined(c: Console, q_path: Path, bundle, meta, identifier: str):
  571. """Run the cached security scan on the quarantined bundle and print the report."""
  572. from tools.skills_hub import HUB_DIR
  573. from tools.skills_hub_models import source_url_for_bundle
  574. from tools.skills_guard import scan_skill_cached, format_scan_report
  575. c.print("[bold]Running security scan...[/]")
  576. scan_source = ("official" if bundle.source == "official"
  577. else bundle.identifier or getattr(meta, "identifier", "") or identifier)
  578. result, prov = scan_skill_cached(
  579. q_path, source=scan_source, source_url=source_url_for_bundle(bundle),
  580. cache_dir=HUB_DIR / "scan-cache")
  581. c.print(format_scan_report(result))
  582. c.print(f"[dim]Scan provenance: {'fresh' if prov['fresh'] else 'cached'}; scanner "
  583. f"{prov['scanner_version']}; hash {prov['bundle_hash']}[/]")
  584. c.print(f"[dim]Source: {prov['source_url']}; scanned {prov['scanned_at']}; "
  585. f"rules: {', '.join(prov['rules']) or 'none'}[/]")
  586. return result
  587. _INSTALL_PANELS = {
  588. "official": (
  589. "[bold bright_cyan]This is an official optional skill maintained by Nous Research.[/]\n\n"
  590. "It ships with hermes-agent but is not activated by default.\n"
  591. "Installing will copy it to your skills directory where the agent can use it.\n\n",
  592. "Official Skill", "bright_cyan"),
  593. "external": (
  594. "[bold yellow]You are installing a third-party skill at your own risk.[/]\n\n"
  595. "External skills can contain instructions that influence agent behavior,\n"
  596. "shell commands, and scripts. Even after automated scanning, you should\n"
  597. "review the installed files before use.\n\n",
  598. "Disclaimer", "yellow")}
  599. def _confirm_install(c: Console, bundle, category: str) -> bool:
  600. """Source-appropriate disclaimer panel + `Install '<name>'?` prompt."""
  601. files_at = f"Files will be at: [cyan]{display_hermes_home()}/skills/{category + '/' if category else ''}{bundle.name}/[/]"
  602. body, title, style = _INSTALL_PANELS["official" if bundle.source == "official" else "external"]
  603. c.print()
  604. c.print(Panel(body + files_at, title=title, border_style=style))
  605. return _confirm_or_cancel(c, f"[bold]Install '{bundle.name}'?[/]",
  606. cancel="[dim]Installation cancelled.[/]\n")
  607. _SKILL_METRIC_SOURCES = {"official": "catalog", "url": "url", "bundled": "bundled"}
  608. def _install_bundled(c: Console, name: str, invalidate_cache: bool) -> tuple:
  609. """``_install_skill`` for a name Hermes ships: point at the active copy, or restore it from the
  610. bundled source. The hub copy of a built-in is either a stranger's same-named skill or this
  611. repo's files rescanned as community content and refused, so neither is fetched."""
  612. from types import SimpleNamespace
  613. from tools.skills_sync_bundled_ops import ensure_bundled_skill
  614. result = ensure_bundled_skill(name)
  615. if not result["ok"]:
  616. _print_error(c, result["message"])
  617. return None, "failed", False
  618. if result["action"] == "hub_shadowed": # not the built-in, so exit 1; the hub install stays (no install event)
  619. _print_error(c, result["message"])
  620. return None, None, False
  621. if result["action"] == "present":
  622. where = f" at {result['path']}" if result["path"] else ""
  623. c.print(f"[green]'{name}' is a built-in skill and is already available{where}.[/]\n")
  624. return None, None, None
  625. c.print(f"[bold green]Restored built-in skill:[/] {name} [dim]({result['path']})[/]\n")
  626. _finish_change(c, invalidate_cache, "Skill will be available", "activate")
  627. return SimpleNamespace(name=name, source="bundled"), "success", True
  628. def _registry_prefixes() -> tuple:
  629. """Identifier prefixes each adapter accepts, from the adapters themselves (``<SOURCE_ID>/``, the
  630. skills.sh spellings, ``well-known:``), so a fetch no adapter answered still names the registry
  631. it was meant for. Bare owner/repo/path stays unresolved."""
  632. from tools.skills_hub_clawhub import ClawHubSource
  633. from tools.skills_hub_official import OptionalSkillSource
  634. from tools.skills_hub_skillssh import SkillsShSource
  635. from tools.skills_hub_sources import BrowseShSource, LobeHubSource, UrlSource, WellKnownSkillSource
  636. return (
  637. *((f"{cls.SOURCE_ID}/", cls.SOURCE_ID) for cls in (OptionalSkillSource, ClawHubSource, LobeHubSource, BrowseShSource)),
  638. *((prefix, SkillsShSource.SOURCE_ID) for prefix in SkillsShSource._ID_PREFIX_ALIASES),
  639. (f"{WellKnownSkillSource.SOURCE_ID}:", WellKnownSkillSource.SOURCE_ID),
  640. ("http://", UrlSource.SOURCE_ID), ("https://", UrlSource.SOURCE_ID),
  641. )
  642. def _registry_from_identifier(identifier: str) -> str:
  643. lowered = identifier.lower()
  644. if lowered.startswith(("http://", "https://")) and "/.well-known/skills/" in lowered:
  645. return "well-known"
  646. return next((sid for prefix, sid in _registry_prefixes() if lowered.startswith(prefix)), "unresolved")
  647. def _record_skill_install(identifier: str, bundle, outcome: str, attempt: Optional[dict] = None,
  648. error: Optional[BaseException] = None) -> None:
  649. """One shared-metrics extension install: official optional skills are the catalog, URL skills
  650. stay anonymous, every other registry is the hub. ``attempt`` carries the failure class the
  651. failing exit named and the hub adapter id (``registry``); a raised ``error`` is classified by
  652. its type inside the metrics guard."""
  653. from hermes_cli.observability.shared_metrics_events import record_extension_install
  654. attempt = attempt or {}
  655. origin = getattr(bundle, "source", None) or attempt.get("origin") or (
  656. "official" if identifier.startswith("official/")
  657. else "url" if identifier.startswith(("http://", "https://")) else "hub")
  658. source = _SKILL_METRIC_SOURCES.get(origin, "hub")
  659. name = None if source == "url" else (getattr(bundle, "name", None) or identifier)
  660. record_extension_install(kind="skill", source=source, name=name, outcome=outcome,
  661. failure_class=attempt.get("failure_class"), registry=attempt.get("registry"),
  662. error=error)
  663. def do_install(identifier: str, category: str = "", force: bool = False,
  664. console: Optional[Console] = None, skip_confirm: bool = False,
  665. invalidate_cache: bool = True, name_override: str = "",
  666. source_id: Optional[str] = None) -> Optional[bool]:
  667. """Fetch, quarantine, scan, confirm, and install a skill. ``source_id`` pins resolution to one
  668. adapter; callers that know the provenance (``do_update``) must pass it so a bare identifier
  669. cannot resolve to a same-named skill elsewhere.
  670. A first install is recorded once as an extension install; updates and ``--force`` reinstalls
  671. of an installed skill run through here too and are not installs, nor is a cancelled prompt.
  672. Returns True when the skill was installed, False when the install failed (unresolved name,
  673. fetch, scan block, bad path), None for a no-op the user owns (already installed, declined).
  674. The CLI router turns False into a non-zero exit — the Desktop Hub toasts failures off that
  675. exit code, so an exit-0 failure reads as "the button did nothing" (only the action log).
  676. """
  677. from tools.skills_hub import HubLockFile
  678. fresh = not HubLockFile().get_installed(identifier.rstrip("/").rsplit("/", 1)[-1])
  679. attempt: dict = {}
  680. try:
  681. bundle, outcome, installed = _install_skill(identifier, category, force, console or _console,
  682. skip_confirm, invalidate_cache, name_override, source_id,
  683. attempt=attempt)
  684. except Exception as exc:
  685. if fresh:
  686. _record_skill_install(identifier, None, "failed", attempt, error=exc)
  687. raise
  688. if fresh and outcome:
  689. _record_skill_install(identifier, bundle, outcome, attempt)
  690. return installed
  691. def _install_skill(identifier: str, category: str, force: bool, c: Console, skip_confirm: bool,
  692. invalidate_cache: bool, name_override: str, source_id: Optional[str],
  693. attempt: Optional[dict] = None) -> tuple:
  694. """``do_install``'s body: ``(bundle, outcome, installed)``. ``outcome`` is the extension-install
  695. event (None when this was no new install); ``installed`` is ``do_install``'s return value.
  696. ``attempt`` collects the metric's ``registry`` (adapter id) and, on a failed exit, its
  697. ``failure_class``."""
  698. attempt = attempt if attempt is not None else {}
  699. attempt["registry"] = "none"
  700. from tools.skills_hub import HubLockFile, ensure_hub_dirs, skills_hub_http_session
  701. from tools.skills_hub_install import install_from_quarantine, quarantine_bundle
  702. from tools.skills_guard import should_allow_install
  703. ensure_hub_dirs()
  704. from tools.skills_sync_bundled_ops import bundled_skill_for_install
  705. if not source_id and not name_override and (builtin := bundled_skill_for_install(identifier)):
  706. # Read only when the restore fails or raises: either way it was a bundled install, not a hub one.
  707. attempt.update(failure_class="filesystem_error", origin="bundled")
  708. return _install_bundled(c, builtin, invalidate_cache)
  709. attempt["registry"] = "unresolved"
  710. sources = _pinned_sources(c, _sources(), source_id, identifier)
  711. if sources is None:
  712. attempt["failure_class"] = "not_found"
  713. return None, "failed", False
  714. # One pooled guarded client for the whole resolve + fetch fan-out (tree, SKILL.md, N support files).
  715. with skills_hub_http_session():
  716. identifier = _full_identifier(identifier, sources, c, attempt)
  717. if not identifier:
  718. # Search fans out to every adapter and swallows their errors: a name that resolved to
  719. # nothing while GitHub was refusing us is the refusal, not a missing skill.
  720. if _hub_rate_limited(sources):
  721. attempt["failure_class"] = "rate_limited"
  722. elif _hub_rejected_credentials(sources):
  723. attempt["failure_class"] = "auth_rejected"
  724. return None, "failed", False
  725. c.print(f"\n[bold]Fetching:[/] {identifier}")
  726. meta, bundle, _matched_source = _resolve_source_meta_and_bundle(identifier, sources)
  727. if _matched_source is not None:
  728. attempt["registry"] = _matched_source.source_id() or "other"
  729. elif attempt.get("registry") == "unresolved":
  730. attempt["registry"] = _registry_from_identifier(identifier)
  731. if not bundle:
  732. attempt["failure_class"] = _print_fetch_failure(c, sources, identifier, meta=meta, source=_matched_source)
  733. return None, "failed", False
  734. if not _resolve_url_bundle_name(c, bundle, meta, identifier, name_override, skip_confirm):
  735. attempt["failure_class"] = "invalid_name"
  736. return bundle, "failed", False
  737. # URL-sourced skills: pick a category interactively when none was given (TTY only;
  738. # non-interactive installs fall through to flat install like every other source).
  739. if bundle.source == "url" and not category and not skip_confirm:
  740. category = _prompt_for_category(c, _existing_categories())
  741. # Official skills can be nested ("official/mlops/training/trl-fine-tuning"): keep every
  742. # identifier segment between "official" and the final slug as the category path.
  743. if bundle.source == "official" and not category:
  744. category = "/".join(bundle.identifier.split("/")[1:-1])
  745. existing = HubLockFile().get_installed(bundle.name)
  746. if existing:
  747. c.print(f"[yellow]Warning:[/] '{bundle.name}' is already installed at {existing['install_path']}")
  748. if not force:
  749. c.print("Use --force to reinstall.\n")
  750. return bundle, None, None
  751. failed = None if existing else "failed"
  752. extra_metadata = {**(getattr(meta, "extra", {}) or {}), **bundle.metadata}
  753. try:
  754. q_path = quarantine_bundle(bundle)
  755. except ValueError as exc:
  756. _invalid_path(c, bundle, exc)
  757. attempt["failure_class"] = "invalid_bundle"
  758. return bundle, failed, False
  759. c.print(f"[dim]Quarantined to {q_path.relative_to(q_path.parent.parent.parent)}[/]")
  760. result = _scan_quarantined(c, q_path, bundle, meta, identifier)
  761. allowed, _reason = should_allow_install(result, force=force)
  762. if not allowed:
  763. _install_blocked(c, bundle, _scan_block_message(result, identifier), result.verdict,
  764. f"{len(result.findings)}_findings", q_path=q_path, lead="\n", label="Not installed:")
  765. attempt["failure_class"] = "scan_blocked"
  766. return bundle, failed, False
  767. # Advisory second opinion — warn-and-continue by design (PII-class findings are
  768. # informational); the install confirmation below is where the user decides.
  769. _print_tier1_advisory(q_path, c)
  770. metadata_lines = _format_extra_metadata_lines(extra_metadata)
  771. if metadata_lines:
  772. c.print(Panel("\n".join(metadata_lines), title="Upstream Metadata", border_style="blue"))
  773. # skip_confirm bypasses the prompt (TUI mode, where input() hangs).
  774. if not force and not skip_confirm and not _confirm_install(c, bundle, category):
  775. shutil.rmtree(q_path, ignore_errors=True)
  776. return bundle, None, None
  777. try:
  778. install_dir = install_from_quarantine(q_path, bundle.name, category, bundle, result)
  779. except ValueError as exc:
  780. _invalid_path(c, bundle, exc, q_path)
  781. attempt["failure_class"] = "invalid_bundle"
  782. return bundle, failed, False
  783. from tools.skills_hub import SKILLS_DIR
  784. c.print(f"[bold green]Installed:[/] {install_dir.resolve().relative_to(Path(SKILLS_DIR).resolve()).as_posix()}")
  785. c.print(f"[dim]Files: {', '.join(bundle.files.keys())}[/]\n")
  786. _announce_blueprint(c, bundle.name)
  787. _finish_change(c, invalidate_cache, "Skill will be available", "activate")
  788. return bundle, None if existing else "success", True
  789. def _print_tier1_advisory(skill_dir, console) -> None:
  790. """Advisory SkillEvaluator Tier 1 report. Never raises/blocks: scanner missing, disabled via
  791. ``skills.tier1_advisory: false``, or erroring all degrade to silence. Secrets render red."""
  792. try:
  793. from tools.skillevaluator_scan import (format_tier1_report, run_tier1_scan,
  794. tier1_advisory_enabled)
  795. if not tier1_advisory_enabled():
  796. return
  797. report = run_tier1_scan(Path(skill_dir))
  798. if not report.available:
  799. return
  800. text = format_tier1_report(report)
  801. if not report.findings:
  802. console.print(f"[dim]{text}[/]")
  803. return
  804. console.print(Panel(text, title="SkillEvaluator Tier 1 (advisory)",
  805. border_style="red" if report.secrets_findings else "yellow"))
  806. if report.secrets_findings:
  807. console.print("[bold red]Possible credentials detected above.[/] "
  808. "Review the flagged lines before using this skill.\n")
  809. except Exception as exc: # advisory only — never break an install
  810. logging.getLogger(__name__).debug("Tier 1 advisory scan skipped: %s", exc)
  811. # --- list / check / update / audit ---
  812. def do_list(source_filter: str = "all", enabled_only: bool = False,
  813. console: Optional[Console] = None) -> None:
  814. """List installed skills (hub / builtin / local). Enabled state comes from the active
  815. profile's config — ``-p`` swaps HERMES_HOME at process start, so no profile flag here."""
  816. from tools.skills_hub import HubLockFile, ensure_hub_dirs
  817. from tools.skills_sync import _read_manifest
  818. from tools.skills_tool import _skill_catalog
  819. from agent.skill_utils import TIER_CREATE_DIR, TIER_EXTERNAL, TIER_PROJECT, get_disabled_skill_names
  820. from agent.skill_commands import skill_command_collision_note
  821. c = console or _console
  822. ensure_hub_dirs()
  823. hub_installed = {e["name"]: e for e in HubLockFile().list_installed()}
  824. builtin_names = set(_read_manifest())
  825. # Rows are what skill_view loads: shadowed copies hidden, same-tier duplicates under their exact path.
  826. all_skills = [{**s, "name": s["load_name"]} for s in _skill_catalog(skip_disabled=True) if s["load_name"]]
  827. root_labels = {TIER_PROJECT: "project", TIER_CREATE_DIR: "create_dir", TIER_EXTERNAL: "external"}
  828. disabled_names = get_disabled_skill_names()
  829. table = _table(("Name", {"style": "bold cyan"}), "Category", "Source", "Trust", "Status",
  830. title="Installed Skills" + (" (enabled only)" if enabled_only else ""))
  831. counts = {"hub": 0, "builtin": 0, "local": 0}
  832. enabled_count = disabled_count = 0
  833. for skill in sorted(all_skills, key=lambda s: (s.get("category") or "", s["name"])):
  834. name = skill["name"]
  835. hub_entry = hub_installed.get(name)
  836. if hub_entry:
  837. source_type, source_display = "hub", hub_entry.get("source", "hub")
  838. trust = hub_entry.get("trust_level", "community")
  839. else:
  840. source_type = source_display = trust = "builtin" if name in builtin_names else "local"
  841. source_display = root_labels.get(skill["tier"], source_display)
  842. is_enabled = name not in disabled_names
  843. if source_filter not in ("all", source_type) or (enabled_only and not is_enabled):
  844. continue
  845. counts[source_type] += 1
  846. enabled_count += is_enabled
  847. disabled_count += not is_enabled
  848. status = "[bold green]enabled[/]" if is_enabled else "[dim red]disabled[/]"
  849. # Name taken by a built-in: the skill loads but has no /<name> (see agent.skill_commands).
  850. if note := skill_command_collision_note(name):
  851. status += f"\n[yellow]{note}[/]"
  852. table.add_row(name, skill.get("category", ""), source_display,
  853. _trust_cell(trust, source_display), status)
  854. c.print(table)
  855. tail = (f"{enabled_count} enabled shown" if enabled_only
  856. else f"{enabled_count} enabled, {disabled_count} disabled")
  857. c.print(f"[dim]{counts['hub']} hub-installed, {counts['builtin']} builtin, "
  858. f"{counts['local']} local — {tail}[/]\n")
  859. def do_check(name: Optional[str] = None, console: Optional[Console] = None) -> None:
  860. """Check hub-installed skills for upstream updates."""
  861. from tools.skills_hub_install import check_for_skill_updates
  862. c = console or _console
  863. results = check_for_skill_updates(name=name)
  864. if not results:
  865. c.print("[dim]No hub-installed skills to check.[/]\n")
  866. return
  867. table = _table(("Name", {"style": "bold cyan"}), "Source", "Status", title="Skill Updates")
  868. for entry in results:
  869. table.add_row(entry.get("name", ""), entry.get("source", ""), entry.get("status", ""))
  870. c.print(table)
  871. update_count = sum(1 for entry in results if entry.get("status") == "update_available")
  872. c.print(f"[dim]{update_count} update(s) available across {len(results)} checked skill(s)[/]\n")
  873. orphaned = [entry.get("name", "") for entry in results if entry.get("status") == "orphaned"]
  874. if orphaned:
  875. c.print(f"[yellow]Orphaned:[/] {', '.join(orphaned)} — lock-file entries whose local "
  876. "directory is missing or replaced by a non-directory. For missing directories, "
  877. "remove the stale entry with: hermes skills uninstall <name>\n")
  878. def _has_local_edits(installed: dict) -> bool:
  879. """True when the on-disk content no longer matches the install-time hash."""
  880. from tools.skills_hub import SKILLS_DIR
  881. from tools.skills_guard import content_hash
  882. recorded_hash = installed.get("content_hash", "")
  883. skill_path = SKILLS_DIR / installed.get("install_path", "")
  884. try:
  885. return (bool(recorded_hash) and skill_path.is_dir()
  886. and content_hash(skill_path) != recorded_hash)
  887. except OSError:
  888. return False
  889. def do_update(name: Optional[str] = None, console: Optional[Console] = None,
  890. force: bool = False) -> Optional[bool]:
  891. """Update hub-installed skills. Locally edited ones are skipped unless ``force`` — the
  892. update rmtree-replaces the user's work, so that must be an explicit choice. Returns False
  893. when any update failed (e.g. the new version is refused by the scan gate), else None.
  894. Skills whose on-disk content no longer matches the hash recorded at install time have been edited
  895. locally; updating them would silently destroy the user's work (``do_install(force=True)``
  896. rmtree-replaces the directory). Those are skipped by default and only overwritten when ``force=True``.
  897. Mirrors the user-modified protection bundled skills already get from ``hermes update`` (ported from
  898. paperclipai/paperclip#10978's explicit-merge-mode rule: destructive replacement must be an explicit
  899. caller choice, never a rerun default).
  900. """
  901. from tools.skills_hub import HubLockFile
  902. from tools.skills_hub_install import check_for_skill_updates
  903. c = console or _console
  904. lock = HubLockFile()
  905. updates = [entry for entry in check_for_skill_updates(name=name) if entry.get("status") == "update_available"]
  906. if not updates:
  907. c.print("[dim]No updates available.[/]\n")
  908. return
  909. skipped_local: list[str] = []
  910. failed: list[str] = []
  911. for entry in updates:
  912. installed = lock.get_installed(entry["name"])
  913. category = ""
  914. if installed:
  915. parent = str(Path(installed.get("install_path", "")).parent)
  916. category = "" if parent == "." else parent
  917. if not force and _has_local_edits(installed):
  918. skipped_local.append(entry["name"])
  919. c.print(f"[yellow]Skipping:[/] {entry['name']} — you have local edits "
  920. "(update would overwrite them).")
  921. continue
  922. c.print(f"[bold]Updating:[/] {entry['name']}")
  923. # Pin to the lockfile's source registry: a bare identifier such as "reddit" would
  924. # otherwise fuzzy-resolve inside do_install to a same-named skill in a DIFFERENT
  925. # registry, overwriting the user's files and rewriting the lock's `source`.
  926. if do_install(entry["identifier"], category=category, force=True, console=c,
  927. source_id=entry.get("source", "") or None) is False:
  928. failed.append(entry["name"])
  929. updated = len(updates) - len(skipped_local) - len(failed)
  930. if updated:
  931. c.print(f"[bold green]Updated {updated} skill(s).[/]\n")
  932. if skipped_local:
  933. c.print(f"[dim]{len(skipped_local)} skill(s) kept your local edits: "
  934. f"{', '.join(sorted(skipped_local))}.[/]")
  935. c.print("[dim]Overwrite with: hermes skills update <name> --force[/]\n")
  936. if failed:
  937. c.print(f"[bold red]Not updated:[/] {', '.join(sorted(failed))} (see the messages above).\n")
  938. return False
  939. return None
  940. def do_audit(name: Optional[str] = None, console: Optional[Console] = None,
  941. deep: bool = False) -> None:
  942. """Re-scan installed hub skills; ``deep`` adds an AST diagnostic (review aid, not a gate)."""
  943. from tools.skills_hub import HubLockFile, SKILLS_DIR
  944. from tools.skills_guard import scan_skill, format_scan_report
  945. c = console or _console
  946. installed = HubLockFile().list_installed()
  947. if not installed:
  948. c.print("[dim]No hub-installed skills to audit.[/]\n")
  949. return
  950. targets = [e for e in installed if e["name"] == name] if name else installed
  951. if not targets:
  952. _print_error(c, f"'{name}' is not a hub-installed skill.")
  953. return
  954. c.print(f"\n[bold]Auditing {len(targets)} skill(s)...[/]\n")
  955. if deep:
  956. from tools.skills_ast_audit import ast_scan_path, format_ast_report
  957. for entry in targets:
  958. skill_path = SKILLS_DIR / entry["install_path"]
  959. if not skill_path.exists():
  960. c.print(f"[yellow]Warning:[/] {entry['name']} — path missing: {entry['install_path']}")
  961. continue
  962. c.print(format_scan_report(scan_skill(skill_path, source=entry.get("identifier", entry["source"]))))
  963. if deep:
  964. c.print(format_ast_report(ast_scan_path(skill_path), skill_name=entry["name"]))
  965. c.print()
  966. # --- uninstall / reset / bundled-skill management ---
  967. def do_uninstall(name: str, console: Optional[Console] = None, skip_confirm: bool = False,
  968. invalidate_cache: bool = True) -> Optional[bool]:
  969. """Remove a hub-installed skill with confirmation. True when removed, False when the removal
  970. was refused (not a hub skill, unsafe path), None when the user declined the prompt."""
  971. from tools.skills_hub_install import uninstall_skill
  972. c = console or _console
  973. # skip_confirm bypasses the prompt (TUI mode, where input() hangs)
  974. if not skip_confirm and not _confirm_or_cancel(c, f"\n[bold]Uninstall '{name}'?[/]"):
  975. return None
  976. if not _report_pair(c, *uninstall_skill(name)):
  977. return False
  978. _finish_change(c, invalidate_cache)
  979. return True
  980. def do_reset(name: str, restore: bool = False, console: Optional[Console] = None,
  981. skip_confirm: bool = False, invalidate_cache: bool = True) -> None:
  982. """Reset a bundled skill's manifest tracking (+ optionally restore from bundled)."""
  983. from tools.skills_sync_bundled_ops import reset_bundled_skill
  984. c = console or _console
  985. if not skip_confirm and restore and not _confirm_or_cancel(
  986. c, f"\n[bold]Restore '{name}' from bundled source?[/]",
  987. "[dim]This will DELETE your current copy and re-copy the bundled version.[/]"):
  988. return
  989. result = reset_bundled_skill(name, restore=restore)
  990. if not _report_ok(c, result):
  991. return
  992. synced = result.get("synced") or {}
  993. _print_listed(c, "Copied", synced.get("copied"))
  994. _print_listed(c, "Updated", synced.get("updated"))
  995. c.print()
  996. _finish_change(c, invalidate_cache)
  997. def do_list_modified(console: Optional[Console] = None, as_json: bool = False) -> None:
  998. """List bundled skills the user has edited (which `hermes update` keeps)."""
  999. from tools.skills_sync_bundled_ops import list_user_modified_bundled_skills
  1000. c = console or _console
  1001. modified = list_user_modified_bundled_skills()
  1002. if as_json:
  1003. c.print(json.dumps([m["name"] for m in modified]))
  1004. return
  1005. if not modified:
  1006. c.print("[dim]No user-modified bundled skills — everything tracks upstream.[/]\n")
  1007. return
  1008. c.print(f"\n[bold]{len(modified)} user-modified bundled skill(s)[/] "
  1009. "[dim](kept as-is by `hermes update`):[/]")
  1010. for entry in modified:
  1011. c.print(f" [yellow]~[/] {entry['name']}")
  1012. c.print()
  1013. c.print("[dim]See changes: hermes skills diff <name>[/]")
  1014. c.print("[dim]Resume updates: hermes skills reset <name> (keep your copy, re-baseline)[/]")
  1015. c.print("[dim]Revert to stock: hermes skills reset <name> --restore[/]\n")
  1016. def _print_diff_line(c: Console, line: str) -> None:
  1017. """Unified-diff line with light coloring (file headers +++/--- stay plain)."""
  1018. for prefix, style in (("+", "green"), ("-", "red"), ("@@", "cyan")):
  1019. if line.startswith(prefix) and not line.startswith(prefix * 3):
  1020. c.print(f"[{style}]{line}[/]")
  1021. return
  1022. c.print(line, highlight=False)
  1023. _DIFF_STATUS_LINE = {
  1024. "added": "[green]+ only in your copy:[/] {path}", "removed": "[red]- only in stock:[/] {path}",
  1025. "binary": "[yellow]~ {path}:[/] binary file differs"}
  1026. def do_diff(name: str, console: Optional[Console] = None) -> None:
  1027. """Show how the user's copy of a bundled skill differs from the stock version."""
  1028. from tools.skills_sync_bundled_ops import diff_bundled_skill
  1029. c = console or _console
  1030. result = diff_bundled_skill(name)
  1031. if not result["ok"]:
  1032. _print_error(c, result["message"])
  1033. return
  1034. if not result["modified"]:
  1035. c.print(f"[green]{result['message']}[/]\n")
  1036. return
  1037. c.print(f"\n[bold]{result['message']}[/]\n")
  1038. for entry in result["diffs"]:
  1039. if entry["status"] == "modified":
  1040. for line in entry["diff"].splitlines():
  1041. _print_diff_line(c, line)
  1042. else:
  1043. line = _DIFF_STATUS_LINE.get(entry["status"], _DIFF_STATUS_LINE["binary"])
  1044. c.print(line.format(**entry))
  1045. c.print()
  1046. c.print(f"[dim]Revert with: hermes skills reset {name} --restore[/]\n")
  1047. def do_opt_out(remove: bool = False, console: Optional[Console] = None, skip_confirm: bool = False,
  1048. invalidate_cache: bool = True) -> None:
  1049. """Write the .no-bundled-skills marker; with ``remove`` also delete pristine (tracked AND
  1050. unmodified) bundled skills. User-edited and non-bundled skills are never touched."""
  1051. from tools.skills_sync_bundled_ops import set_bundled_skills_opt_out, remove_pristine_bundled_skills
  1052. c = console or _console
  1053. res = set_bundled_skills_opt_out(True) # the marker first: always-safe
  1054. if not _report_ok(c, res):
  1055. return
  1056. c.print(f"[dim]Marker: {res['marker']}[/]")
  1057. if not remove:
  1058. c.print("[dim]Existing skills on disk were left in place. "
  1059. "Re-run with --remove to also delete unmodified bundled skills.[/]\n")
  1060. return
  1061. # Destructive step: preview, confirm, then delete.
  1062. preview = remove_pristine_bundled_skills(dry_run=True)
  1063. candidates = preview["removed"]
  1064. if not candidates:
  1065. c.print("[dim]No pristine bundled skills to remove "
  1066. "(nothing tracked, or all are user-modified/local).[/]\n")
  1067. return
  1068. c.print(f"\n[bold]Will remove {len(candidates)} unmodified bundled skill(s):[/]")
  1069. c.print(f"[dim]{', '.join(candidates)}[/]")
  1070. if preview["skipped"]:
  1071. c.print(f"[dim]Keeping {len(preview['skipped'])} (user-modified or non-bundled).[/]")
  1072. if not skip_confirm and not _confirm_or_cancel(
  1073. c, "[dim]This deletes the on-disk copies. User-edited and hub/local skills are NOT touched.[/]",
  1074. cancel="[dim]Marker kept; no skills deleted.[/]\n"):
  1075. return
  1076. result = remove_pristine_bundled_skills(dry_run=False)
  1077. c.print(f"[bold green]{result['message']}[/]")
  1078. _print_listed(c, "Removed", result["removed"])
  1079. c.print()
  1080. _finish_change(c, invalidate_cache, notice=False)
  1081. def do_opt_in(sync: bool = False, console: Optional[Console] = None,
  1082. invalidate_cache: bool = True) -> None:
  1083. """Remove the opt-out marker so bundled-skill seeding resumes."""
  1084. from tools.skills_sync import sync_skills
  1085. from tools.skills_sync_bundled_ops import set_bundled_skills_opt_out
  1086. c = console or _console
  1087. if not _report_ok(c, set_bundled_skills_opt_out(False)):
  1088. return
  1089. if sync:
  1090. copied = len(sync_skills(quiet=True).get("copied", []))
  1091. c.print(f"[dim]Re-seeded {copied} bundled skill(s).[/]")
  1092. _finish_change(c, invalidate_cache, notice=False)
  1093. c.print()
  1094. def do_repair_official(name: str, restore: bool = False, console: Optional[Console] = None,
  1095. skip_confirm: bool = False, invalidate_cache: bool = True) -> None:
  1096. """Backfill or restore official optional skills from repo source."""
  1097. from tools.skills_sync_optional import restore_official_optional_skill
  1098. c = console or _console
  1099. if restore and not skip_confirm and not _confirm_or_cancel(
  1100. c, f"\n[bold]Restore official optional skill '{name}' from repo source?[/]",
  1101. "[dim]Existing matching active copies will be moved to a restore backup before copying the official source.[/]",
  1102. ):
  1103. return
  1104. result = restore_official_optional_skill(name, restore=restore)
  1105. if not _report_ok(c, result, "Repair failed"):
  1106. return
  1107. _print_listed(c, "Restored", result.get("restored"))
  1108. _print_listed(c, "Backfilled provenance", result.get("backfilled"))
  1109. if result.get("backed_up"):
  1110. c.print(f"[dim]Backed up: {', '.join(result['backed_up'])}[/]")
  1111. c.print(f"[dim]Backup dir: {result.get('backup_dir')}[/]")
  1112. c.print()
  1113. _finish_change(c, invalidate_cache, notice=False)
  1114. # --- taps / publish / snapshot ---
  1115. # action -> (TapsManager method, success line, failure line)
  1116. _TAP_OPS = {
  1117. "add": ("add", "[bold green]Added tap:[/] {repo}\n", "[yellow]Tap already exists:[/] {repo}\n"),
  1118. "remove": ("remove", "[bold green]Removed tap:[/] {repo}\n", "[bold red]Error:[/] Tap not found: {repo}\n"),
  1119. }
  1120. def do_tap(action: str, repo: str = "", console: Optional[Console] = None) -> None:
  1121. """Manage taps (custom GitHub repo sources)."""
  1122. from tools.skills_hub import TapsManager
  1123. c = console or _console
  1124. mgr = TapsManager()
  1125. if action == "list":
  1126. taps = mgr.list_taps()
  1127. if not taps:
  1128. c.print("[dim]No custom taps configured. Using default sources only.[/]\n")
  1129. return
  1130. table = _table(("Repo", {"style": "bold cyan"}), "Path", title="Configured Taps")
  1131. for t in taps:
  1132. table.add_row(t.get("repo") or t.get("name") or t.get("path", "unknown"),
  1133. t.get("path", "skills/"))
  1134. c.print(table)
  1135. c.print()
  1136. elif action in _TAP_OPS:
  1137. method, ok_line, fail_line = _TAP_OPS[action]
  1138. if not repo:
  1139. _print_error(c, f"Repo required. Usage: hermes skills tap {action} owner/repo")
  1140. return
  1141. c.print((ok_line if getattr(mgr, method)(repo) else fail_line).format(repo=repo))
  1142. else:
  1143. c.print(f"[bold red]Unknown tap action:[/] {action}. Use: list, add, remove\n")
  1144. def _read_frontmatter(skill_md: str) -> dict:
  1145. """YAML frontmatter of a SKILL.md body ({} when absent/invalid)."""
  1146. import hermes_yaml as yaml
  1147. match = re.search(r'\n---\s*\n', skill_md[3:]) if skill_md.startswith("---") else None
  1148. try:
  1149. return (yaml.safe_load(skill_md[3:match.start() + 3]) or {}) if match else {}
  1150. except yaml.YAMLError:
  1151. return {}
  1152. def do_publish(skill_path: str, target: str = "github", repo: str = "",
  1153. console: Optional[Console] = None) -> None:
  1154. """Publish a local skill to a registry (GitHub PR or ClawHub submission)."""
  1155. from tools.skills_hub import SKILLS_DIR
  1156. from tools.skills_hub_github import GitHubAuth
  1157. from tools.skills_guard import scan_skill, format_scan_report
  1158. c = console or _console
  1159. path = Path(skill_path)
  1160. if not path.is_absolute():
  1161. path = SKILLS_DIR / path
  1162. if not (path / "SKILL.md").exists():
  1163. _print_error(c, f"No SKILL.md found at {path}")
  1164. return
  1165. skill_md = (path / "SKILL.md").read_text(encoding="utf-8-sig").lstrip("\ufeff") # tolerate BOM
  1166. fm = _read_frontmatter(skill_md)
  1167. name = fm.get("name", path.name)
  1168. if not fm.get("description", ""):
  1169. _print_error(c, "SKILL.md must have a 'description' in frontmatter.")
  1170. return
  1171. c.print(f"[bold]Scanning '{name}' before publish...[/]")
  1172. result = scan_skill(path, source="self")
  1173. c.print(format_scan_report(result))
  1174. if result.verdict == "dangerous":
  1175. c.print("[bold red]Cannot publish a skill with DANGEROUS verdict.[/]\n")
  1176. return
  1177. if target == "github":
  1178. if not repo:
  1179. _print_error(c, "--repo required for GitHub publish.\n"
  1180. "Usage: hermes skills publish <path> --to github --repo owner/repo")
  1181. return
  1182. auth = GitHubAuth()
  1183. if not auth.is_authenticated():
  1184. _print_error(c, "GitHub authentication required.\n"
  1185. f"Set GITHUB_TOKEN in {display_hermes_home()}/.env "
  1186. "or run 'gh auth login'.")
  1187. return
  1188. c.print(f"[bold]Publishing '{name}' to {repo}...[/]")
  1189. _report_pair(c, *_github_publish(path, name, repo, auth))
  1190. elif target == "clawhub":
  1191. c.print("[yellow]ClawHub publishing is not yet supported. "
  1192. "Submit manually at https://clawhub.ai/submit[/]\n")
  1193. else:
  1194. c.print(f"[bold red]Unknown target:[/] {target}. Use 'github' or 'clawhub'.\n")
  1195. def _github_publish(skill_path: Path, skill_name: str, target_repo: str, auth) -> tuple:
  1196. """Fork, branch, upload, and open a PR with the skill. Returns (success, message)."""
  1197. import base64
  1198. import httpx
  1199. headers = auth.get_headers()
  1200. api = "https://api.github.com/repos"
  1201. def call(method: str, path: str, timeout: int = 15, **kw):
  1202. return getattr(httpx, method)(f"{api}/{path}", headers=headers, timeout=timeout, **kw)
  1203. try:
  1204. resp = call("post", f"{target_repo}/forks", timeout=30)
  1205. if resp.status_code in {200, 202}:
  1206. fork_repo = resp.json()["full_name"]
  1207. elif resp.status_code == 403:
  1208. return False, "GitHub token lacks permission to fork repos"
  1209. else:
  1210. return False, f"Failed to fork {target_repo}: {resp.status_code}"
  1211. except httpx.HTTPError as e:
  1212. return False, f"Network error forking repo: {e}"
  1213. try:
  1214. default_branch = call("get", target_repo).json().get("default_branch", "main")
  1215. except Exception:
  1216. default_branch = "main"
  1217. try:
  1218. ref = call("get", f"{fork_repo}/git/refs/heads/{default_branch}").json()
  1219. base_sha = ref["object"]["sha"]
  1220. except Exception as e:
  1221. return False, f"Failed to get base branch: {e}"
  1222. branch_name = f"add-skill-{skill_name}"
  1223. try:
  1224. call("post", f"{fork_repo}/git/refs",
  1225. json={"ref": f"refs/heads/{branch_name}", "sha": base_sha})
  1226. except Exception as e:
  1227. return False, f"Failed to create branch: {e}"
  1228. for f in skill_path.rglob("*"):
  1229. if not f.is_file():
  1230. continue
  1231. rel = str(f.relative_to(skill_path))
  1232. try:
  1233. call("put", f"{fork_repo}/contents/skills/{skill_name}/{rel}",
  1234. json={"message": f"Add {skill_name} skill: {rel}",
  1235. "content": base64.b64encode(f.read_bytes()).decode(), "branch": branch_name})
  1236. except Exception as e:
  1237. return False, f"Failed to upload {rel}: {e}"
  1238. try:
  1239. resp = call("post", f"{target_repo}/pulls", json={
  1240. "title": f"Add skill: {skill_name}",
  1241. "body": f"Submitting the `{skill_name}` skill via Hermes Skills Hub.\n\n"
  1242. f"This skill was scanned by the Hermes Skills Guard before submission.",
  1243. "head": f"{fork_repo.split('/')[0]}:{branch_name}", "base": default_branch})
  1244. if resp.status_code == 201:
  1245. return True, f"PR created: {resp.json().get('html_url', '')}"
  1246. return False, f"Failed to create PR: {resp.status_code} {resp.text[:200]}"
  1247. except httpx.HTTPError as e:
  1248. return False, f"Network error creating PR: {e}"
  1249. def do_snapshot_export(output_path: str, console: Optional[Console] = None) -> None:
  1250. """Export current hub skill configuration to a portable JSON file."""
  1251. from tools.skills_hub import HubLockFile, TapsManager
  1252. c = console or _console
  1253. installed = HubLockFile().list_installed()
  1254. tap_list = TapsManager().list_taps()
  1255. snapshot = {
  1256. "hermes_version": "0.1.0",
  1257. "exported_at": datetime.now(UTC).isoformat(),
  1258. "skills": [
  1259. {"name": entry["name"], "source": entry.get("source", ""),
  1260. "identifier": entry.get("identifier", ""),
  1261. "category": (str(Path(entry["install_path"]).parent)
  1262. if "/" in entry.get("install_path", "") else "")}
  1263. for entry in installed],
  1264. "taps": tap_list}
  1265. payload = json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n"
  1266. if output_path == "-":
  1267. sys.stdout.write(payload)
  1268. return
  1269. Path(output_path).write_text(payload, encoding="utf-8")
  1270. c.print(f"[bold green]Snapshot exported:[/] {Path(output_path)}")
  1271. c.print(f"[dim]{len(installed)} skill(s), {len(tap_list)} tap(s)[/]\n")
  1272. def do_snapshot_import(input_path: str, force: bool = False,
  1273. console: Optional[Console] = None) -> Optional[bool]:
  1274. """Re-install skills from a snapshot file. Returns False when the file is unreadable or any
  1275. entry failed to install (e.g. refused by the scan gate), else None — as ``do_update`` does."""
  1276. from tools.skills_hub import TapsManager
  1277. c = console or _console
  1278. inp = Path(input_path)
  1279. if not inp.exists():
  1280. _print_error(c, f"File not found: {inp}")
  1281. return False
  1282. try:
  1283. snapshot = json.loads(inp.read_text(encoding="utf-8-sig"))
  1284. except json.JSONDecodeError:
  1285. _print_error(c, f"Invalid JSON in {inp}")
  1286. return False
  1287. taps = snapshot.get("taps", [])
  1288. if taps:
  1289. mgr = TapsManager()
  1290. for tap in taps:
  1291. if tap.get("repo", ""):
  1292. mgr.add(tap["repo"], tap.get("path", "skills/"))
  1293. c.print(f"[dim]Restored {len(taps)} tap(s)[/]")
  1294. skills = snapshot.get("skills", [])
  1295. if not skills:
  1296. c.print("[dim]No skills in snapshot to install.[/]\n")
  1297. return
  1298. c.print(f"[bold]Importing {len(skills)} skill(s) from snapshot...[/]\n")
  1299. failed: list[str] = []
  1300. for entry in skills:
  1301. identifier = entry.get("identifier", "")
  1302. if not identifier:
  1303. c.print(f"[yellow]Skipping entry with no identifier: {entry.get('name', '?')}[/]")
  1304. continue
  1305. c.print(f"[bold]--- {entry.get('name', identifier)} ---[/]")
  1306. if do_install(identifier, category=entry.get("category", ""), force=force, console=c) is False:
  1307. failed.append(entry.get("name", identifier))
  1308. if failed:
  1309. c.print(f"[bold red]Snapshot import incomplete.[/] Not installed: {', '.join(failed)} "
  1310. "(see the messages above).\n")
  1311. return False
  1312. c.print("[bold green]Snapshot import complete.[/]\n")
  1313. return None
  1314. # --- CLI argparse entry point ---
  1315. def _snapshot_cli(args) -> Optional[bool]:
  1316. snap_action = getattr(args, "snapshot_action", None)
  1317. if snap_action == "export":
  1318. do_snapshot_export(args.output)
  1319. elif snap_action == "import":
  1320. return do_snapshot_import(args.input, force=getattr(args, "force", False))
  1321. else:
  1322. _console.print("Usage: hermes skills snapshot [export|import]\n")
  1323. return None
  1324. def _tap_cli(args) -> None:
  1325. tap_action = getattr(args, "tap_action", None)
  1326. if not tap_action:
  1327. _console.print("Usage: hermes skills tap [list|add|remove]\n")
  1328. return
  1329. do_tap(tap_action, repo=getattr(args, "repo", "") or getattr(args, "name", ""))
  1330. # `hermes skills <action>` -> handler(args). Lambdas late-bind the do_* names so
  1331. # tests that patch("hermes_cli.skills_hub.do_install") still intercept.
  1332. _CLI_ACTIONS = {
  1333. "browse": lambda a: do_browse(page=a.page, page_size=a.size, source=a.source),
  1334. "search": lambda a: do_search(a.query, source=a.source, limit=a.limit,
  1335. as_json=getattr(a, "json", False)),
  1336. "install": lambda a: do_install(a.identifier, category=a.category, force=a.force,
  1337. skip_confirm=getattr(a, "yes", False),
  1338. name_override=getattr(a, "name", "") or ""),
  1339. "inspect": lambda a: do_inspect(a.identifier),
  1340. "list": lambda a: do_list(source_filter=a.source,
  1341. enabled_only=getattr(a, "enabled_only", False)),
  1342. "check": lambda a: do_check(name=getattr(a, "name", None)),
  1343. "update": lambda a: do_update(name=getattr(a, "name", None), force=getattr(a, "force", False)),
  1344. "audit": lambda a: do_audit(name=getattr(a, "name", None), deep=getattr(a, "deep", False)),
  1345. "uninstall": lambda a: do_uninstall(a.name, skip_confirm=getattr(a, "yes", False)),
  1346. "reset": lambda a: do_reset(a.name, restore=getattr(a, "restore", False),
  1347. skip_confirm=getattr(a, "yes", False)),
  1348. "list-modified": lambda a: do_list_modified(as_json=getattr(a, "json", False)),
  1349. "diff": lambda a: do_diff(a.name),
  1350. "opt-out": lambda a: do_opt_out(remove=getattr(a, "remove", False),
  1351. skip_confirm=getattr(a, "yes", False)),
  1352. "opt-in": lambda a: do_opt_in(sync=getattr(a, "sync", False)),
  1353. "repair-official": lambda a: do_repair_official(a.name, restore=getattr(a, "restore", False),
  1354. skip_confirm=getattr(a, "yes", False)),
  1355. "publish": lambda a: do_publish(a.skill_path, target=getattr(a, "to", "github"),
  1356. repo=getattr(a, "repo", "")),
  1357. "snapshot": _snapshot_cli, "tap": _tap_cli}
  1358. def skills_command(args) -> Optional[int]:
  1359. """Router for `hermes skills <subcommand>` — called from hermes_cli/main.py."""
  1360. handler = _CLI_ACTIONS.get(getattr(args, "skills_action", None))
  1361. if handler is None:
  1362. _console.print("Usage: hermes skills [browse|search|install|inspect|list|list-modified|diff|check|update|audit|uninstall|reset|opt-out|opt-in|publish|snapshot|tap]\n")
  1363. _console.print("Run 'hermes skills <command> --help' for details.\n")
  1364. return None
  1365. # A handler reporting a real failure (install/update/uninstall's False) must exit non-zero: the
  1366. # Desktop Hub reads the spawned action's exit code to decide whether to toast, so an exit-0
  1367. # failure renders as "the button did nothing" while the reason sits unread in the action log.
  1368. # Returned, not sys.exit()-ed: `hermes` turns a handler's int into the exit code.
  1369. return 1 if handler(args) is False else None
  1370. # --- Slash command entry point (/skills in chat) ---
  1371. def _opt_value(args: list[str], flag: str, default: str, last: bool = False) -> str:
  1372. """Value following `flag` (default if absent/trailing); `last` makes a repeated flag's final
  1373. occurrence win (historical install/publish/browse behaviour), else the first."""
  1374. hits = [args[i + 1] for i, a in enumerate(args) if a == flag and i + 1 < len(args)]
  1375. return (hits[-1] if last else hits[0]) if hits else default
  1376. def _int_or(text: str, default: int) -> int:
  1377. try:
  1378. return int(text)
  1379. except ValueError:
  1380. return default
  1381. def _opt_int(args: list[str], flag: str, default: int) -> int:
  1382. """Like _opt_value(last=True) but int-parsed; a non-integer keeps the default."""
  1383. return _int_or(_opt_value(args, flag, str(default), last=True), default)
  1384. def _slash_search(args, c):
  1385. source, limit, as_json, query_parts, i = "all", 25, False, [], 0
  1386. while i < len(args):
  1387. flag, value = args[i], args[i + 1] if i + 1 < len(args) else None
  1388. takes_value = flag in ("--source", "--limit") and value is not None
  1389. if flag == "--source" and takes_value:
  1390. source = value
  1391. elif flag == "--limit" and takes_value:
  1392. limit = _int_or(value, limit)
  1393. elif flag == "--json":
  1394. as_json = True
  1395. else:
  1396. query_parts.append(flag)
  1397. i += 2 if takes_value else 1
  1398. do_search(" ".join(query_parts), source=source, limit=limit, console=c, as_json=as_json)
  1399. def _slash_snapshot(args, c):
  1400. if len(args) > 1 and args[0] == "export":
  1401. do_snapshot_export(args[1], console=c)
  1402. elif len(args) > 1 and args[0] == "import":
  1403. do_snapshot_import(args[1], force="--force" in args, console=c)
  1404. else:
  1405. c.print("[bold red]Usage:[/] /skills snapshot export <file> | /skills snapshot import <file>\n")
  1406. def _first_positional(args):
  1407. """First argument unless it is a flag (audit's historical parse)."""
  1408. return args[0] if args and not args[0].startswith("--") else None
  1409. # Slash commands run inside prompt_toolkit where input() hangs, so install/uninstall/reset
  1410. # always skip confirmation — typing the command is implicit consent. `--now` invalidates the
  1411. # prompt cache immediately (costs more money); the default defers to the next session.
  1412. _SLASH_ACTIONS = {
  1413. "browse": lambda args, c: do_browse(
  1414. page=_opt_int(args, "--page", 1), page_size=_opt_int(args, "--size", 20),
  1415. source=_opt_value(args, "--source", "all", last=True), console=c),
  1416. "search": _slash_search,
  1417. "install": lambda args, c: do_install(
  1418. args[0], category=_opt_value(args, "--category", "", last=True),
  1419. force="--force" in args, skip_confirm=True, invalidate_cache="--now" in args,
  1420. name_override=_opt_value(args, "--name", "", last=True), console=c),
  1421. "inspect": lambda args, c: do_inspect(args[0], console=c),
  1422. "list": lambda args, c: do_list(
  1423. source_filter=_opt_value(args, "--source", "all"),
  1424. enabled_only="--enabled-only" in args or "--enabled" in args, console=c),
  1425. "check": lambda args, c: do_check(name=args[0] if args else None, console=c),
  1426. "update": lambda args, c: do_update(
  1427. name=next((a for a in args if not a.startswith("--")), None), console=c,
  1428. force="--force" in args),
  1429. "audit": lambda args, c: do_audit(name=_first_positional(args), console=c,
  1430. deep="--deep" in args),
  1431. "uninstall": lambda args, c: do_uninstall(
  1432. args[0], console=c, skip_confirm=True, invalidate_cache="--now" in args),
  1433. "reset": lambda args, c: do_reset(
  1434. args[0], restore="--restore" in args, console=c, skip_confirm=True,
  1435. invalidate_cache="--now" in args),
  1436. **dict.fromkeys(("list-modified", "modified"),
  1437. lambda args, c: do_list_modified(console=c, as_json="--json" in args)),
  1438. "diff": lambda args, c: do_diff(args[0], console=c),
  1439. "publish": lambda args, c: do_publish(
  1440. args[0], target=_opt_value(args, "--to", "github", last=True),
  1441. repo=_opt_value(args, "--repo", "", last=True), console=c),
  1442. "snapshot": _slash_snapshot,
  1443. "tap": lambda args, c: (do_tap(args[0], repo=args[1] if len(args) > 1 else "", console=c)
  1444. if args else do_tap("list", console=c)),
  1445. **dict.fromkeys(("help", "--help", "-h"), lambda args, c: _print_skills_help(c))}
  1446. # Actions that need at least one argument -> usage lines printed when called bare.
  1447. _SLASH_USAGE = {
  1448. "search": ("[bold red]Usage:[/] /skills search <query> [--source skills-sh|github|official|nvidia|openai|anthropic|huggingface] [--limit N] [--json]\n",),
  1449. "install": ("[bold red]Usage:[/] /skills install <identifier-or-url> [--name <name>] [--category <cat>] [--force] [--now]\n",),
  1450. "inspect": ("[bold red]Usage:[/] /skills inspect <identifier>\n",),
  1451. "uninstall": ("[bold red]Usage:[/] /skills uninstall <name> [--now]\n",),
  1452. "reset": (
  1453. "[bold red]Usage:[/] /skills reset <name> [--restore] [--now]\n",
  1454. "[dim]Clears the bundled-skills manifest entry so future updates stop marking it as user-modified.[/]",
  1455. "[dim]Pass --restore to also replace the current copy with the bundled version.[/]\n"),
  1456. "diff": ("[bold red]Usage:[/] /skills diff <name>\n",),
  1457. "publish": ("[bold red]Usage:[/] /skills publish <skill-path> [--to github] [--repo owner/repo]\n",),
  1458. }
  1459. def handle_skills_slash(cmd: str, console: Optional[Console] = None) -> None:
  1460. """Parse and dispatch `/skills <subcommand> [args]` from the chat interface."""
  1461. c = console or _console
  1462. parts = cmd.strip().split()
  1463. if parts and parts[0].lower() == "/skills":
  1464. parts = parts[1:]
  1465. if not parts:
  1466. _print_skills_help(c)
  1467. return
  1468. action, args = parts[0].lower(), parts[1:]
  1469. handler = _SLASH_ACTIONS.get(action)
  1470. if handler is None:
  1471. c.print(f"[bold red]Unknown action:[/] {action}")
  1472. _print_skills_help(c)
  1473. return
  1474. if not args and action in _SLASH_USAGE:
  1475. for line in _SLASH_USAGE[action]:
  1476. c.print(line)
  1477. return
  1478. handler(args, c)
  1479. def _print_skills_help(console: Console) -> None:
  1480. """Print help for the /skills slash command."""
  1481. console.print(Panel(
  1482. "[bold]Skills Hub Commands:[/]\n\n"
  1483. " [cyan]browse[/] [--source official] Browse all available skills (paginated)\n"
  1484. " [cyan]search[/] <query> Search registries for skills\n"
  1485. " [cyan]install[/] <identifier> Install a skill (with security scan)\n"
  1486. " [cyan]inspect[/] <identifier> Preview a skill without installing\n"
  1487. " [cyan]list[/] [--source hub|builtin|local] [--enabled-only]\n"
  1488. " List installed skills; --enabled-only filters to the active profile's live set\n"
  1489. " [cyan]check[/] [name] Check hub skills for upstream updates\n"
  1490. " [cyan]update[/] [name] Update hub skills with upstream changes\n"
  1491. " [cyan]audit[/] [name] Re-scan hub skills for security\n"
  1492. " [cyan]uninstall[/] <name> Remove a hub-installed skill\n"
  1493. " [cyan]list-modified[/] List bundled skills you've edited (kept by update)\n"
  1494. " [cyan]diff[/] <name> Diff your copy of a bundled skill vs the stock version\n"
  1495. " [cyan]reset[/] <name> [--restore] Reset bundled-skill tracking (fix 'user-modified' flag)\n"
  1496. " [cyan]publish[/] <path> --repo <r> Publish a skill to GitHub via PR\n"
  1497. " [cyan]snapshot[/] export|import Export/import skill configurations\n"
  1498. " [cyan]tap[/] list|add|remove Manage skill sources\n",
  1499. title="/skills"))