Skip to content

The agent that grows with you

refactor(hermes_cli): skills_hub table/result/probe helpers; publish request helper; list/diff data-driven

Teknium95ab6f053642
diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.py
index 4d78d768b77..868729b5e13 100644
--- a/hermes_cli/skills_hub.py
+++ b/hermes_cli/skills_hub.py
@@ -60,11 +60,28 @@ def _truncate(text: str, width: int) -> str:
return text[:width] + ("..." if len(text) > width else "")
-def _identifier_column(table: Table, style: str) -> None:
+def _ident_col(style: str) -> tuple:
# 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)
+ return "Identifier", {"style": style, "overflow": "fold", "no_wrap": False}
+
+
+def _table(*columns, **table_kw) -> Table:
+ """Rich table from (header, add_column-kwargs) pairs; a bare header is a dim column."""
+ table = Table(**table_kw)
+ for col in columns:
+ header, kw = col if isinstance(col, tuple) else (col, {"style": "dim"})
+ table.add_column(header, **kw)
+ return table
+
+
+def _try(fn, *args):
+ """`fn(*args)`, or None when it raises (adapter probes are best-effort)."""
+ try:
+ return fn(*args)
+ except Exception:
+ return None
def _sources():
@@ -102,11 +119,13 @@ def _clear_skills_cache() -> None:
def _finish_change(c: Console, invalidate_cache: bool, what: str = "Change will take effect",
- verb: str = "apply") -> None:
- """Apply-now (cache clear) or tell the user the change lands next session."""
+ verb: str = "apply", notice: bool = True) -> None:
+ """Apply-now (cache clear) or, when `notice`, tell the user the change lands next session."""
if invalidate_cache:
_clear_skills_cache()
return
+ if not notice:
+ return
c.print(f"[dim]{what} in your next session.[/]")
c.print(f"[dim]Use /reset to start a new session now, or --now to {verb} immediately (invalidates prompt cache).[/]\n")
@@ -121,6 +140,24 @@ def _print_listed(c: Console, label: str, items) -> None:
c.print(f"[dim]{label}: {', '.join(items)}[/]")
+def _report_pair(c: Console, success: bool, msg: str) -> bool:
+ """`(success, message)` result: green message + blank line, or red error."""
+ if success:
+ c.print(f"[bold green]{msg}[/]\n")
+ else:
+ _print_error(c, msg)
+ return success
+
+
+def _report_ok(c: Console, result: dict, fallback: str = "") -> bool:
+ """skills_sync-style `{ok, message}` result: green message on success, red error otherwise."""
+ if result.get("ok"):
+ c.print(f"[bold green]{result['message']}[/]")
+ return True
+ _print_error(c, result.get("message", fallback))
+ return False
+
+
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:
@@ -172,10 +209,7 @@ def _resolve_short_name(name: str, sources, console: Console) -> str:
c.print(f"[dim]Resolved to: {official[0].identifier} (official catalog)[/]")
return official[0].identifier
c.print(f"\n[yellow]Multiple skills named '{name}' found:[/]")
- table = Table()
- for col in ("Source", "Trust"):
- table.add_column(col, style="dim")
- _identifier_column(table, "bold cyan")
+ table = _table("Source", "Trust", _ident_col("bold cyan"))
for r in exact:
table.add_row(r.source, _trust_cell(r.trust_level, r.source), r.identifier)
c.print(table)
@@ -198,32 +232,27 @@ def _resolve_source_meta_and_bundle(identifier: str, sources):
first_meta = None
first_meta_source = None
for src in sources:
- try:
- meta = src.inspect(identifier)
- except Exception:
- meta = None
- try:
- bundle = src.fetch(identifier)
- except Exception:
- bundle = None
+ meta = _try(src.inspect, identifier)
+ bundle = _try(src.fetch, identifier)
if bundle:
if meta is None:
- try:
- meta = src.inspect(identifier)
- except Exception:
- meta = None
+ meta = _try(src.inspect, identifier)
return meta, bundle, src
if first_meta is None and meta:
first_meta, first_meta_source = meta, src
return first_meta, None, first_meta_source
+def _full_identifier(identifier: str, sources, c) -> str:
+ """Identifiers without a slash are short names; "" when they cannot be resolved."""
+ return identifier if "/" in identifier else _resolve_short_name(identifier, sources, c)
+
+
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
+ identifier = _full_identifier(identifier, sources, c)
+ if not identifier:
+ return "", None, None, None
return (identifier, *_resolve_source_meta_and_bundle(identifier, sources))
@@ -271,8 +300,7 @@ def _prompt_for_skill_name(c: Console, url: str, default: str = "") -> Optional[
answer = _line_input("Name: ")
if answer is None:
return None
- if not answer and default:
- answer = default
+ answer = answer or default
if not _is_valid_installed_skill_name(answer):
c.print(f"[bold red]Invalid name:[/] {answer!r}. Aborting install.\n")
return None
@@ -324,12 +352,8 @@ def do_search(query: str, source: str = "all", limit: int = 10, console: Optiona
c.print("[dim]No skills found matching your query.[/]\n")
return
- table = Table(title=f"Skills Hub — {len(results)} result(s)")
- table.add_column("Name", style="bold cyan")
- table.add_column("Description", max_width=60)
- for col in ("Source", "Trust"):
- table.add_column(col, style="dim")
- _identifier_column(table, "dim")
+ table = _table(("Name", {"style": "bold cyan"}), ("Description", {"max_width": 60}), "Source",
+ "Trust", _ident_col("dim"), title=f"Skills Hub — {len(results)} result(s)")
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)
@@ -385,13 +409,10 @@ def _render_browse_page(c: Console, deduped, page_items, page: int, total_pages:
c.print(f"[bright_cyan]★ {official_count} official optional skill(s) from Nous Research[/]")
c.print()
- 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)
- _identifier_column(table, "dim")
+ table = _table(("#", {"style": "dim", "width": 4, "justify": "right"}),
+ ("Name", {"style": "bold cyan", "max_width": 22}), ("Description", {"max_width": 44}),
+ ("Source", {"style": "dim", "width": 12}), ("Trust", {"width": 10}),
+ _ident_col("dim"), show_header=True, header_style="bold")
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"),
@@ -481,10 +502,7 @@ def do_inspect(identifier: str, console: Optional[Console] = None) -> None:
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())
+ ident, meta, bundle, _ = _resolve_identifier(identifier, _sources(), Console(quiet=True))
if not ident or not meta:
return None
out: dict = {
@@ -562,23 +580,17 @@ def _announce_blueprint(c: Console, skill_name: str) -> None:
return
if spec is None:
return
+ lead = f"[bold cyan]Blueprint:[/] '{skill_name}' is an automation (schedule [bold]{spec.schedule}[/])"
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")
+ c.print(f"{lead}.")
+ 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")
+ c.print(f"{lead}, 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
@@ -636,25 +648,26 @@ def _scan_quarantined(c: Console, q_path: Path, bundle, meta, identifier: str):
return result
+_INSTALL_PANELS = {
+ "official": (
+ "[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",
+ "Official Skill", "bright_cyan"),
+ "external": (
+ "[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",
+ "Disclaimer", "yellow")}
+
+
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}/[/]"
+ body, title, style = _INSTALL_PANELS["official" if bundle.source == "official" else "external"]
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"))
+ c.print(Panel(body + files_at, title=title, border_style=style))
return _confirm_or_cancel(c, f"[bold]Install '{bundle.name}'?[/]",
cancel="[dim]Installation cancelled.[/]\n")
@@ -676,10 +689,9 @@ def do_install(identifier: str, category: str = "", force: bool = False,
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
+ identifier = _full_identifier(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:
@@ -695,9 +707,7 @@ def do_install(identifier: str, category: str = "", force: bool = False,
# 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])
+ category = "/".join(bundle.identifier.split("/")[1:-1])
existing = HubLockFile().get_installed(bundle.name)
if existing:
@@ -788,9 +798,8 @@ def do_list(source_filter: str = "all", enabled_only: bool = False,
all_skills = _find_all_skills(skip_disabled=True) # include disabled ones to annotate status
disabled_names = get_disabled_skill_names()
- 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")
+ table = _table(("Name", {"style": "bold cyan"}), "Category", "Source", "Trust", "Status",
+ title="Installed Skills" + (" (enabled only)" if enabled_only else ""))
counts = {"hub": 0, "builtin": 0, "local": 0}
enabled_count = disabled_count = 0
@@ -800,32 +809,20 @@ def do_list(source_filter: str = "all", enabled_only: bool = False,
if hub_entry:
source_type, source_display = "hub", hub_entry.get("source", "hub")
trust = hub_entry.get("trust_level", "community")
- elif name in builtin_names:
- source_type = source_display = trust = "builtin"
else:
- source_type = source_display = trust = "local"
- if source_filter != "all" and source_filter != source_type:
- continue
+ source_type = source_display = trust = "builtin" if name in builtin_names else "local"
is_enabled = name not in disabled_names
- if enabled_only and not is_enabled:
+ if source_filter not in ("all", source_type) or (enabled_only and not is_enabled):
continue
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, skill.get("category", ""), source_display,
- _trust_cell(trust, source_display), status_cell)
+ enabled_count += is_enabled
+ disabled_count += not is_enabled
+ table.add_row(name, skill.get("category", ""), source_display, _trust_cell(trust, source_display),
+ "[bold green]enabled[/]" if is_enabled else "[dim red]disabled[/]")
c.print(table)
- 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"
- c.print(summary + "[/]\n")
+ tail = f"{enabled_count} enabled shown" if enabled_only else f"{enabled_count} enabled, {disabled_count} disabled"
+ c.print(f"[dim]{counts['hub']} hub-installed, {counts['builtin']} builtin, {counts['local']} local — {tail}[/]\n")
def do_check(name: Optional[str] = None, console: Optional[Console] = None) -> None:
@@ -836,9 +833,7 @@ 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")
- for col in ("Name", "Source", "Status"):
- table.add_column(col, style="bold cyan" if col == "Name" else "dim")
+ table = _table(("Name", {"style": "bold cyan"}), "Source", "Status", title="Skill Updates")
for entry in results:
table.add_row(entry.get("name", ""), entry.get("source", ""), entry.get("status", ""))
c.print(table)
@@ -852,10 +847,8 @@ def _has_local_edits(installed: dict) -> bool:
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
+ return bool(recorded_hash) and skill_path.is_dir() and content_hash(skill_path) != recorded_hash
except OSError:
return False
@@ -940,12 +933,8 @@ def do_uninstall(name: str, console: Optional[Console] = None, skip_confirm: boo
# 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 _report_pair(c, *uninstall_skill(name)):
_finish_change(c, invalidate_cache)
- else:
- _print_error(c, msg)
def do_reset(name: str, restore: bool = False, console: Optional[Console] = None,
@@ -958,10 +947,8 @@ def do_reset(name: str, restore: bool = False, console: Optional[Console] = None
"[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"]:
- _print_error(c, result["message"])
+ if not _report_ok(c, result):
return
- c.print(f"[bold green]{result['message']}[/]")
synced = result.get("synced") or {}
_print_listed(c, "Copied", synced.get("copied"))
_print_listed(c, "Updated", synced.get("updated"))
@@ -999,6 +986,11 @@ def _print_diff_line(c: Console, line: str) -> None:
c.print(line, highlight=False)
+_DIFF_STATUS_LINE = {
+ "added": "[green]+ only in your copy:[/] {path}", "removed": "[red]- only in stock:[/] {path}",
+ "binary": "[yellow]~ {path}:[/] binary file differs"}
+
+
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
@@ -1012,16 +1004,11 @@ def do_diff(name: str, console: Optional[Console] = None) -> None:
return
c.print(f"\n[bold]{result['message']}[/]\n")
for entry in result["diffs"]:
- status = entry["status"]
- if status == "modified":
+ if entry["status"] == "modified":
for line in entry["diff"].splitlines():
_print_diff_line(c, line)
- elif status == "added":
- c.print(f"[green]+ only in your copy:[/] {entry['path']}")
- elif status == "removed":
- c.print(f"[red]- only in stock:[/] {entry['path']}")
- else: # binary
- c.print(f"[yellow]~ {entry['path']}:[/] binary file differs")
+ else:
+ c.print(_DIFF_STATUS_LINE.get(entry["status"], _DIFF_STATUS_LINE["binary"]).format(**entry))
c.print()
c.print(f"[dim]Revert with: hermes skills reset {name} --restore[/]\n")
@@ -1033,10 +1020,8 @@ def do_opt_out(remove: bool = False, console: Optional[Console] = None, skip_con
from tools.skills_sync import set_bundled_skills_opt_out, remove_pristine_bundled_skills
c = console or _console
res = set_bundled_skills_opt_out(True) # the marker first: always-safe
- if not res["ok"]:
- _print_error(c, res["message"])
+ if not _report_ok(c, res):
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. "
@@ -1063,8 +1048,7 @@ def do_opt_out(remove: bool = False, console: Optional[Console] = None, skip_con
c.print(f"[bold green]{result['message']}[/]")
_print_listed(c, "Removed", result["removed"])
c.print()
- if invalidate_cache:
- _clear_skills_cache()
+ _finish_change(c, invalidate_cache, notice=False)
def do_opt_in(sync: bool = False, console: Optional[Console] = None,
@@ -1072,16 +1056,12 @@ def do_opt_in(sync: bool = False, console: Optional[Console] = None,
"""Remove the opt-out marker so bundled-skill seeding resumes."""
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"]:
- _print_error(c, res["message"])
+ if not _report_ok(c, set_bundled_skills_opt_out(False)):
return
- c.print(f"[bold green]{res['message']}[/]")
if sync:
copied = len(sync_skills(quiet=True).get("copied", []))
c.print(f"[dim]Re-seeded {copied} bundled skill(s).[/]")
- if invalidate_cache:
- _clear_skills_cache()
+ _finish_change(c, invalidate_cache, notice=False)
c.print()
@@ -1096,18 +1076,15 @@ def do_repair_official(name: str, restore: bool = False, console: Optional[Conso
):
return
result = restore_official_optional_skill(name, restore=restore)
- if not result.get("ok"):
- _print_error(c, result.get("message", "Repair failed"))
+ if not _report_ok(c, result, "Repair failed"):
return
- c.print(f"[bold green]{result['message']}[/]")
_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()
+ _finish_change(c, invalidate_cache, notice=False)
# --- taps / publish / snapshot ---
@@ -1129,9 +1106,7 @@ def do_tap(action: str, repo: str = "", console: Optional[Console] = None) -> No
if not taps:
c.print("[dim]No custom taps configured. Using default sources only.[/]\n")
return
- table = Table(title="Configured Taps")
- table.add_column("Repo", style="bold cyan")
- table.add_column("Path", style="dim")
+ table = _table(("Repo", {"style": "bold cyan"}), "Path", title="Configured Taps")
for t in taps:
label = t.get("repo") or t.get("name") or t.get("path", "unknown")
table.add_row(label, t.get("path", "skills/"))
@@ -1140,7 +1115,7 @@ def do_tap(action: str, repo: str = "", console: Optional[Console] = None) -> No
elif action in _TAP_OPS:
method, ok_line, fail_line = _TAP_OPS[action]
if not repo:
- c.print(f"[bold red]Error:[/] Repo required. Usage: hermes skills tap {action} owner/repo\n")
+ _print_error(c, f"Repo required. Usage: hermes skills tap {action} owner/repo")
return
c.print((ok_line if getattr(mgr, method)(repo) else fail_line).format(repo=repo))
else:
@@ -1188,20 +1163,16 @@ def do_publish(skill_path: str, target: str = "github", repo: str = "",
if target == "github":
if not repo:
- c.print("[bold red]Error:[/] --repo required for GitHub publish.\n"
- "Usage: hermes skills publish <path> --to github --repo owner/repo\n")
+ _print_error(c, "--repo required for GitHub publish.\n"
+ "Usage: hermes skills publish <path> --to github --repo owner/repo")
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")
+ _print_error(c, "GitHub authentication required.\n"
+ f"Set GITHUB_TOKEN in {display_hermes_home()}/.env or run 'gh auth login'.")
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:
- _print_error(c, msg)
+ _report_pair(c, *_github_publish(path, name, repo, auth))
elif target == "clawhub":
c.print("[yellow]ClawHub publishing is not yet supported. "
"Submit manually at https://clawhub.ai/submit[/]\n")
@@ -1216,8 +1187,11 @@ def _github_publish(skill_path: Path, skill_name: str, target_repo: str, auth) -
headers = auth.get_headers()
api = "https://api.github.com/repos"
+ def call(method: str, path: str, timeout: int = 15, **kw):
+ return getattr(httpx, method)(f"{api}/{path}", headers=headers, timeout=timeout, **kw)
+
try:
- resp = httpx.post(f"{api}/{target_repo}/forks", headers=headers, timeout=30)
+ resp = call("post", f"{target_repo}/forks", timeout=30)
if resp.status_code in {200, 202}:
fork_repo = resp.json()["full_name"]
elif resp.status_code == 403:
@@ -1228,22 +1202,17 @@ def _github_publish(skill_path: Path, skill_name: str, target_repo: str, auth) -
return False, f"Network error forking repo: {e}"
try:
- resp = httpx.get(f"{api}/{target_repo}", headers=headers, timeout=15)
- default_branch = resp.json().get("default_branch", "main")
+ default_branch = call("get", target_repo).json().get("default_branch", "main")
except Exception:
default_branch = "main"
-
try:
- resp = httpx.get(f"{api}/{fork_repo}/git/refs/heads/{default_branch}",
- headers=headers, timeout=15)
- base_sha = resp.json()["object"]["sha"]
+ base_sha = call("get", f"{fork_repo}/git/refs/heads/{default_branch}").json()["object"]["sha"]
except Exception as e:
return False, f"Failed to get base branch: {e}"
branch_name = f"add-skill-{skill_name}"
try:
- httpx.post(f"{api}/{fork_repo}/git/refs", headers=headers, timeout=15,
- json={"ref": f"refs/heads/{branch_name}", "sha": base_sha})
+ call("post", f"{fork_repo}/git/refs", json={"ref": f"refs/heads/{branch_name}", "sha": base_sha})
except Exception as e:
return False, f"Failed to create branch: {e}"
@@ -1252,24 +1221,18 @@ def _github_publish(skill_path: Path, skill_name: str, target_repo: str, auth) -
continue
rel = str(f.relative_to(skill_path))
try:
- httpx.put(
- f"{api}/{fork_repo}/contents/skills/{skill_name}/{rel}",
- headers=headers, timeout=15,
- json={"message": f"Add {skill_name} skill: {rel}",
- "content": base64.b64encode(f.read_bytes()).decode(),
- "branch": branch_name})
+ call("put", f"{fork_repo}/contents/skills/{skill_name}/{rel}",
+ 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}"
try:
- resp = httpx.post(
- 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"
- f"This skill was scanned by the Hermes Skills Guard before submission.",
- "head": f"{fork_repo.split('/')[0]}:{branch_name}",
- "base": default_branch})
+ resp = call("post", f"{target_repo}/pulls", json={
+ "title": f"Add skill: {skill_name}",
+ "body": f"Submitting the `{skill_name}` skill via Hermes Skills Hub.\n\n"
+ f"This skill was scanned by the Hermes Skills Guard before submission.",
+ "head": f"{fork_repo.split('/')[0]}:{branch_name}", "base": default_branch})
if resp.status_code == 201:
return True, f"PR created: {resp.json().get('html_url', '')}"
return False, f"Failed to create PR: {resp.status_code} {resp.text[:200]}"
@@ -1416,33 +1379,32 @@ def _opt_value(args: List[str], flag: str, default: str, last: bool = False) ->
return found
-def _opt_int(args: List[str], flag: str, default: int) -> int:
- """Like _opt_value(last=True) but int-parsed; a non-integer keeps the default."""
+def _int_or(text: str, default: int) -> int:
try:
- return int(_opt_value(args, flag, str(default), last=True))
+ return int(text)
except ValueError:
return default
+def _opt_int(args: List[str], flag: str, default: int) -> int:
+ """Like _opt_value(last=True) but int-parsed; a non-integer keeps the default."""
+ return _int_or(_opt_value(args, flag, str(default), last=True), default)
+
+
def _slash_search(args, c):
- source, limit, as_json, query_parts = "all", 25, False, []
- i = 0
+ source, limit, as_json, query_parts, i = "all", 25, False, [], 0
while i < len(args):
- if args[i] == "--source" and i + 1 < len(args):
- source = args[i + 1]
- i += 2
- elif args[i] == "--limit" and i + 1 < len(args):
- try:
- limit = int(args[i + 1])
- except ValueError:
- pass
- i += 2
- elif args[i] == "--json":
+ flag, value = args[i], args[i + 1] if i + 1 < len(args) else None
+ takes_value = flag in ("--source", "--limit") and value is not None
+ if flag == "--source" and takes_value:
+ source = value
+ elif flag == "--limit" and takes_value:
+ limit = _int_or(value, limit)
+ elif flag == "--json":
as_json = True
- i += 1
else:
- query_parts.append(args[i])
- i += 1
+ query_parts.append(flag)
+ i += 2 if takes_value else 1
do_search(" ".join(query_parts), source=source, limit=limit, console=c, as_json=as_json)
@@ -1487,8 +1449,8 @@ _SLASH_ACTIONS = {
"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),
+ **dict.fromkeys(("list-modified", "modified"),
+ lambda args, c: do_list_modified(console=c, as_json="--json" in args)),
"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),
@@ -1496,9 +1458,7 @@ _SLASH_ACTIONS = {
"snapshot": _slash_snapshot,
"tap": lambda args, c: (do_tap(args[0], repo=args[1] if len(args) > 1 else "", console=c)
if args else do_tap("list", console=c)),
- "help": lambda args, c: _print_skills_help(c),
- "--help": lambda args, c: _print_skills_help(c),
- "-h": lambda args, c: _print_skills_help(c)}
+ **dict.fromkeys(("help", "--help", "-h"), lambda args, c: _print_skills_help(c))}
# Actions that need at least one argument -> usage lines printed when called bare.
_SLASH_USAGE = {