The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools/skills): split skills_hub into per-source modules; extract skill_manager guards/batch, skills_tool dedup/plugin/setup; compact skill_usage, skills_guard
Teknium7c1ec19d4ab2
diff --git a/tools/skill_ledger.py b/tools/skill_ledger.pyindex 348e2ed1a9a..6a5e6c580c6 100644--- a/tools/skill_ledger.py+++ b/tools/skill_ledger.py@@ -1,27 +1,23 @@-"""Per-mutation skill audit ledger + single-edit rollback (tracker #79686 P3).+"""Per-mutation skill audit ledger + single-edit rollback.-Every skill mutation — regardless of actor — appends one JSONL entry to-``~/.hermes/skills/.curator_ledger.jsonl`` describing who changed what, with-before/after file manifests whose contents are stored content-addressed-(sha256-deduped) under ``~/.hermes/.curator_backups/blobs/``.+Every skill mutation — any actor — appends one JSONL entry to+``~/.hermes/skills/.curator_ledger.jsonl`` with before/after file manifests+whose contents are stored content-addressed (sha256-deduped) under+``~/.hermes/.curator_backups/blobs/``.Design decisions (Teknium-approved):- - JSONL, not the state DB: the ledger is a durable, human-greppable audit- trail that survives DB resets and is trivially rsync/backup friendly.- - The ledger covers ALL actors, tagged ``curator`` / ``agent`` / ``user``.- The curator *invariant* (never hard-delete autonomously) is unchanged and- applies only to autonomous actors; foreground user deletes stay- hard-delete — but they are still ledgered so they're recoverable via+ - JSONL, not the state DB: durable, human-greppable, survives DB resets.+ - Covers ALL actors (``curator`` / ``agent`` / ``user``). The curator+ invariant (never hard-delete autonomously) applies only to autonomous+ actors; user deletes stay hard-delete but are ledgered and recoverable via``hermes curator rollback <entry-id>``.- - Per-file content-addressed blobs (not tarballs): a mutation typically- touches one file, so a whole-tree tarball per mutation would be wasteful,- and identical content across entries dedupes to a single blob.+ - Per-file content-addressed blobs, not tarballs: a mutation usually touches+ one file, and identical content dedupes to one blob.The ledger is TELEMETRY, NOT A GATE: a ledger failure must never block the-mutation it describes. Every public write path here is wrapped so exceptions-are logged and swallowed. The one deliberate exception is ``rollback_entry``,-which FAILS CLOSED when its own pre-rollback safety capture fails (consistent-with the whole-run tarball rollback in agent/curator_backup.py).+mutation it describes — every public write path swallows and logs. The one+exception is ``rollback_entry``, which FAILS CLOSED when its own pre-rollback+safety capture fails (consistent with agent/curator_backup.py)."""from __future__ import annotations@@ -46,31 +42,26 @@ ACTOR_CURATOR = "curator"ACTOR_AGENT = "agent"ACTOR_USER = "user"-# Snapshot-id shape used by agent.curator_backup (kept in sync by the-# test suite; duplicated here so the ledger can read the newest-# skills.tar.gz without importing the backup stack).+# Snapshot-id shape used by agent.curator_backup (duplicated so the ledger can+# read the newest skills.tar.gz without importing the backup stack)._BACKUP_ID_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}Z(-\d{2})?$")# ".archive/<name>-YYYYMMDDHHMMSS" collision suffix added by archive_skill._ARCHIVE_TS_SUFFIX_RE = re.compile(r"^(.+)-\d{14}$")-# Actions whose rollback must restore a COMPLETE skill package. These are-# the actions where a hollow before-capture (support files re-homed out of-# the tree first) makes `hermes curator rollback` restore a shell of a-# skill instead of the package (issue #96962).+# Actions whose rollback must restore a COMPLETE package: consolidation may+# have re-homed support files out of the tree first, so a disk-only capture+# would make rollback restore a hollow skill._PACKAGE_RESTORE_ACTIONS = frozenset({"delete", "archive", "purge"})_VALID_ACTORS = {ACTOR_CURATOR, ACTOR_AGENT, ACTOR_USER}+_NON_PACKAGE_TOPS = {".curator_backups", ".hub", ".archive"}-# Explicit actor override for call sites that know who they are acting for:-# the CLI sets "user", the curator's automatic-transition walk sets "curator".+# Explicit actor override: the CLI sets "user", the curator walk sets "curator"._actor_override: contextvars.ContextVar[Optional[str]] = contextvars.ContextVar("skill_ledger_actor", default=None)def set_ledger_actor(actor: Optional[str]) -> contextvars.Token:- """Bind an explicit actor for subsequent ledger records in this context.-- Returns a Token; callers must reset_ledger_actor(token) in a finally.- """+ """Bind an explicit actor for this context; reset_ledger_actor(token) in a finally."""return _actor_override.set(actor)@@ -79,11 +70,7 @@ def reset_ledger_actor(token: contextvars.Token) -> None:def derive_actor() -> str:- """Best-effort actor derivation.-- Priority: explicit override (CLI → user, curator walk → curator), then- the background-review provenance signal (→ curator), else agent.- """+ """Explicit override, else background-review provenance -> curator, else agent."""override = _actor_override.get()if override in _VALID_ACTORS:return override@@ -109,6 +96,10 @@ def blobs_dir() -> Path:return get_hermes_home() / ".curator_backups" / "blobs"+def _skills_dir() -> Path:+ return get_hermes_home() / "skills"++def ledger_enabled() -> bool:"""Config gate ``skills.ledger`` (default True). Lazy import so thismodule stays importable without the CLI config layer."""@@ -121,13 +112,33 @@ def ledger_enabled() -> bool:return True+def _norm(path: Path | str) -> Path:+ return Path(os.path.normpath(str(path)))+++def _rel_posix(path: Path | str, root: Path) -> Optional[str]:+ """POSIX path of ``path`` relative to ``root`` (both normalized), or None when outside."""+ try:+ return _norm(path).relative_to(_norm(root)).as_posix()+ except ValueError:+ return None+++def _is_within(root: Path, path: Path) -> bool:+ """True when *path* (normalized, no symlink resolution) sits under *root*."""+ try:+ root_r, path_r = _norm(root), _norm(path)+ return path_r == root_r or root_r in path_r.parents+ except Exception:+ return False++# ---------------------------------------------------------------------------# Blob store (content-addressed, deduped)# ---------------------------------------------------------------------------def _store_blob(data: bytes) -> str:- """Write *data* to the blob store keyed by its sha256. Dedupes: an- existing blob with the same hash is left alone. Returns the hash."""+ """Write *data* keyed by sha256 (existing blob left alone). Returns the hash."""digest = hashlib.sha256(data).hexdigest()dest = blobs_dir() / digestif not dest.exists():@@ -154,17 +165,12 @@ def snapshot_paths(*,complete_package: bool = False,) -> List[Dict[str, str]]:- """Capture {path, sha256} for every file under *root* (recursively),- storing each file's content as a blob. Empty list when root is None or- doesn't exist. Raises on I/O failure — callers decide whether that is- fatal (rollback safety capture) or swallowed (telemetry hooks).+ """Capture {path, sha256} for every file under *root*, storing each as a blob.+ Empty when root is None/missing. Raises on I/O failure — callers decide+ whether that is fatal (rollback safety capture) or swallowed (telemetry).``complete_package=True`` unions in files from the newest curator- ``skills.tar.gz`` for this skill (issue #96962). Consolidation re-homes- ``references/`` / ``scripts/`` out of the tree before the- delete/archive, so a disk-only capture ledgers ``files: 1`` and- rollback would restore a hollow skill. Disk hashes win over the- backup copy."""+ ``skills.tar.gz`` for this skill (disk hashes win)."""if root is None:return []root = Path(root)@@ -172,42 +178,25 @@ def snapshot_paths(files = [root]elif root.is_dir():files = sorted(p for p in root.rglob("*") if p.is_file())- else:+ elif complete_package:files = []- if not complete_package:- return []- out: List[Dict[str, str]] = []- for f in files:- data = f.read_bytes()- out.append({"path": str(f), "sha256": _store_blob(data)})+ else:+ return []+ out = [{"path": str(f), "sha256": _store_blob(f.read_bytes())} for f in files]if complete_package:out = fill_snapshot_from_curator_backup(root, out)return out# ----------------------------------------------------------------------------# Package-completeness fill from the newest curator backup (issue #96962)+# Package-completeness fill from the newest curator backup# ----------------------------------------------------------------------------def _skills_dir() -> Path:- return get_hermes_home() / "skills"--def _package_rel(root: Path) -> Optional[str]:- """Relative POSIX path of a skill directory under ``skills/``, or None- when *root* is not inside the local skills dir. Backup / hub metadata- roots are excluded — they are never a skill package."""- try:- rel = Path(os.path.normpath(str(root))).relative_to(- Path(os.path.normpath(str(_skills_dir())))- )- except ValueError:- return None- posix = rel.as_posix().strip("/")- if not posix:- return None- top = posix.split("/", 1)[0]- if top in {".curator_backups", ".hub", ".archive"}:+ """Relative POSIX path of a skill dir under ``skills/``; None when outside+ it or under backup/hub/archive metadata roots (never a package)."""+ posix = (_rel_posix(root, _skills_dir()) or "").strip("/")+ if not posix or posix.split("/", 1)[0] in _NON_PACKAGE_TOPS:return Nonereturn posix@@ -217,35 +206,34 @@ def _strip_archive_timestamp(name: str) -> str:return match.group(1) if match else name+def _skill_md_parent(items: Optional[List[Dict[str, str]]]) -> Optional[Path]:+ for item in items or []:+ path = Path(str(item.get("path", "")))+ if path.name == "SKILL.md":+ return path.parent+ return None++def package_prefixes(root: Optional[Path] = None,skill: Optional[str] = None,before: Optional[List[Dict[str, str]]] = None,) -> List[str]:- """Tar member prefixes that belong to this skill's package.-- Every spelling the package may carry: its live location under- ``skills/``, the bare skill name, the name minus an archive collision- suffix, and — for rollback-time fills where *root* is gone — the- package parent recorded in the before-state SKILL.md paths."""- found: List[str] = []-- def add(prefix: Optional[str]) -> None:- if not prefix:- return- prefix = prefix.strip("/")- if prefix and prefix not in found:- found.append(prefix)-- if root is not None:- add(_package_rel(Path(root)))+ """Tar member prefixes that belong to this skill's package: its live+ location under ``skills/``, the package parent recorded in the before-state+ SKILL.md path (for rollback fills where *root* is gone), the bare skill+ name, and the name minus an archive collision suffix."""+ candidates = [_package_rel(Path(root)) if root is not None else None]for item in before or []:path = Path(str(item.get("path", "")))if path.name == "SKILL.md":- add(_package_rel(path.parent))- if skill:- add(skill)- add(_strip_archive_timestamp(skill))+ candidates.append(_package_rel(path.parent))+ candidates += [skill, _strip_archive_timestamp(skill) if skill else None]+ found: List[str] = []+ for prefix in candidates:+ prefix = (prefix or "").strip("/")+ if prefix and prefix not in found:+ found.append(prefix)return found@@ -254,28 +242,24 @@ def _latest_skills_tarball() -> Optional[Path]:backups = _skills_dir() / ".curator_backups"if not backups.is_dir():return None- candidates: List[Path] = []try:children = list(backups.iterdir())except OSError:return None- for child in children:- if not child.is_dir() or not _BACKUP_ID_RE.match(child.name):- continue- archive = child / "skills.tar.gz"- if archive.is_file():- candidates.append(archive)+ candidates = [+ child / "skills.tar.gz"+ for child in children+ if child.is_dir() and _BACKUP_ID_RE.match(child.name) and (child / "skills.tar.gz").is_file()+ ]if not candidates:return None# Parent dirs sort lexicographically == chronologically for the id shape.- candidates.sort(key=lambda p: p.parent.name, reverse=True)- return candidates[0]+ return max(candidates, key=lambda p: p.parent.name)def _read_package_files_from_latest_backup(prefixes: List[str]) -> Dict[str, bytes]:"""``{posix-relpath: bytes}`` for files under *prefixes* in the newest- snapshot. Malicious member names (absolute, ``..`` traversal) are- rejected."""+ snapshot. Malicious member names (absolute, ``..`` traversal) are rejected."""if not prefixes:return {}archive = _latest_skills_tarball()@@ -295,9 +279,8 @@ def _read_package_files_from_latest_backup(prefixes: List[str]) -> Dict[str, bytif name not in exact and not name.startswith(prefixed):continueextracted = tf.extractfile(member)- if extracted is None:- continue- out[name] = extracted.read()+ if extracted is not None:+ out[name] = extracted.read()except (OSError, tarfile.TarError) as exc:logger.debug("skill_ledger: could not read curator backup package: %s", exc)return {}@@ -312,17 +295,14 @@ def fill_snapshot_from_curator_backup() -> List[Dict[str, str]]:"""Union missing skill-package files from the newest curator snapshot.- Completeness fill, not a gate: failures are swallowed and the existing- capture is returned unchanged. Disk/already-ledgered hashes win — the- backup only fills paths ABSENT from *existing*.+ Completeness fill, not a gate: failures are swallowed and *existing* is+ returned unchanged; the backup only fills paths ABSENT from it.Filled files are addressed where the rollback must restore them: under- *root* itself when it is known (delete/archive/purge all restore to the- captured location — for purge that is ``.archive/<name>/``, NOT the- live tree), else under the live skills dir. Backup members carry a- leading package-dir segment (arcname = top-level dir name); it is- stripped when *root* already names the package. Every fill target must- stay under ``skills/`` and HERMES_HOME.+ *root* when known (for purge that is ``.archive/<name>/``, NOT the live+ tree), else under the live skills dir. Backup members carry a leading+ package-dir segment, stripped when *root* already names the package.+ Every fill target must stay under ``skills/`` and HERMES_HOME."""out = list(existing or [])prefixes = package_prefixes(root, skill, out)@@ -337,39 +317,21 @@ def fill_snapshot_from_curator_backup(return outskills = _skills_dir()dest_root = Path(root) if root is not None else None- pkg_name = (- _strip_archive_timestamp(dest_root.name) if dest_root is not None else None- )- have = set()- for item in out:- path = Path(str(item.get("path", "")))- try:- have.add(- Path(os.path.normpath(str(path)))- .relative_to(Path(os.path.normpath(str(skills))))- .as_posix()- )- except ValueError:- continue+ pkg_names = {dest_root.name, _strip_archive_timestamp(dest_root.name)} if dest_root else set()+ have = {+ rel for rel in (_rel_posix(str(item.get("path", "")), skills) for item in out) if rel is not None+ }for rel, data in extra.items():parts = rel.split("/")- if dest_root is not None and parts and parts[0] in (pkg_name, dest_root.name):+ if dest_root is not None and parts and parts[0] in pkg_names:parts = parts[1:]if not parts:continue- base = dest_root if dest_root is not None else skills- dest = base.joinpath(*parts)+ dest = (dest_root if dest_root is not None else skills).joinpath(*parts)if not _is_within(skills, dest) or not _is_within(get_hermes_home(), dest):continue- try:- rel_key = (- Path(os.path.normpath(str(dest)))- .relative_to(Path(os.path.normpath(str(skills))))- .as_posix()- )- except ValueError:- continue- if rel_key in have:+ rel_key = _rel_posix(dest, skills)+ if rel_key is None or rel_key in have:continuetry:out.append({"path": str(dest), "sha256": _store_blob(data)})@@ -430,9 +392,8 @@ def record_mutation(*after_root* (pre-captured *before* list, or capture from *before_root*)and append. NEVER raises and never blocks the mutation.- Package-destroying actions (delete/archive/purge) always capture a- COMPLETE package: re-homed support files are filled in from the newest- curator backup so a rollback never restores a hollow skill (#96962)."""+ delete/archive/purge always capture a COMPLETE package (support files+ filled from the newest curator backup) so rollback never restores a shell."""if not ledger_enabled():return Nonetry:@@ -440,9 +401,7 @@ def record_mutation(if before is None:before = snapshot_paths(before_root, complete_package=_complete)elif _complete:- before = fill_snapshot_from_curator_backup(- before_root, before, skill=skill- )+ before = fill_snapshot_from_curator_backup(before_root, before, skill=skill)after = snapshot_paths(after_root)return append_entry(action, skill, before=before, after=after, actor=actor, evidence=evidence@@ -458,12 +417,9 @@ def capture_before(complete_package: bool = False,skill: Optional[str] = None,) -> Optional[List[Dict[str, str]]]:- """Best-effort pre-mutation capture. Returns None on failure or when the- ledger is disabled (callers pass the result straight to record_mutation).-- ``complete_package=True`` fills support files from the newest curator- backup — required for delete/archive/purge captures, where consolidation- may have re-homed the support files out of the tree first (#96962)."""+ """Best-effort pre-mutation capture; None on failure or when disabled+ (callers pass the result straight to record_mutation). Use+ ``complete_package=True`` for delete/archive/purge captures."""if not ledger_enabled():return Nonetry:@@ -509,30 +465,16 @@ def list_entries(def get_entry(entry_id: str) -> Optional[Dict[str, Any]]:if not entry_id:return None- for row in list_entries():- if row.get("id") == entry_id:- return row- return None+ return next((row for row in list_entries() if row.get("id") == entry_id), None)# ---------------------------------------------------------------------------# Single-edit rollback# ----------------------------------------------------------------------------def _is_within(root: Path, path: Path) -> bool:- """True when *path* (normalized, no symlink resolution needed for the- containment check itself) sits under *root*. Handles ``..`` traversal."""- try:- root_r = Path(os.path.normpath(str(root)))- path_r = Path(os.path.normpath(str(path)))- return path_r == root_r or root_r in path_r.parents- except Exception:- return False--def _validate_entry_paths(entry: Dict[str, Any]) -> Optional[str]:- """All paths in an entry must live under HERMES_HOME. Defense in depth —- a hand-edited ledger must not become a write-anywhere primitive."""+ """All paths in an entry must live under HERMES_HOME — a hand-edited+ ledger must not become a write-anywhere primitive."""home = get_hermes_home()for section in ("before", "after"):for item in entry.get(section) or []:@@ -545,11 +487,10 @@ def _validate_entry_paths(entry: Dict[str, Any]) -> Optional[str]:def rollback_entry(entry_id: str) -> Tuple[bool, str]:"""Restore the before-state of the single mutation *entry_id*.- Fail-closed semantics (mirrors agent/curator_backup.rollback + #63366):+ Fail-closed (mirrors agent/curator_backup.rollback):1. Every needed before-blob must exist — verified BEFORE any change.- 2. A pre-rollback safety ledger entry capturing the CURRENT state of- every touched path is appended first; if that capture fails, the- rollback aborts and nothing is changed.+ 2. A pre-rollback safety entry capturing the CURRENT state of every+ touched path is appended first; if that fails, nothing is changed."""entry = get_entry(entry_id)if entry is None:@@ -562,21 +503,13 @@ def rollback_entry(entry_id: str) -> Tuple[bool, str]:before = list(entry.get("before") or [])after = list(entry.get("after") or [])- # Historical hollow entries (#96962): a delete/archive/purge captured- # only what was left after consolidation re-homed the support files- # (``files: 1`` = SKILL.md). Fill the before-state from the newest- # curator backup so the rollback restores the complete package, not a- # shell. Disk hashes already in the entry win; this only adds missing- # paths. The filled set is re-validated against HERMES_HOME below.+ # Historical hollow delete/archive/purge entries (``files: 1`` = SKILL.md):+ # fill the before-state from the newest curator backup so the rollback+ # restores the complete package. Entry hashes win; only missing paths are+ # added, and the filled set is re-validated against HERMES_HOME.if entry.get("action") in _PACKAGE_RESTORE_ACTIONS:- skill_root: Optional[Path] = None- for item in before:- p = Path(str(item.get("path", "")))- if p.name == "SKILL.md":- skill_root = p.parent- breakbefore = fill_snapshot_from_curator_backup(- skill_root, before, skill=str(entry.get("skill") or "") or None+ _skill_md_parent(before), before, skill=str(entry.get("skill") or "") or None)path_err = _validate_entry_paths({**entry, "before": before, "after": after})if path_err:diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.pynew file mode 100644index 00000000000..7d436997b61--- /dev/null+++ b/tools/skill_manager_batch.py@@ -0,0 +1,264 @@+"""Atomic multi-op batch path for ``skill_manage`` (extracted from skill_manager_tool).++``skill_manage``/``_find_skill``/``_skill_gate_bypass`` are reached lazily+through ``tools.skill_manager_tool`` so the origin module owns all state.+"""++import json+import logging+import posixpath+import shutil+import tempfile+from pathlib import Path++logger = logging.getLogger("tools.skill_manager_tool")++_BATCH_OP_ACTIONS = {"create", "patch", "write_file", "remove_file"}+_BATCH_MAX_OPS = 20+++def _norm_target(op) -> str:+ fp = (op.get("file_path") or "").strip()+ if not fp:+ return "SKILL.md"+ return posixpath.normpath(fp.lstrip("/"))+++def _validate_batch_ops(operations, default_name, tool_error):+ """Shape checks with no side effects. Returns (names, None) or (None, error_json)."""+ from tools.skill_manager_guards import _background_review_preflight++ names = []+ for i, op in enumerate(operations):+ if not isinstance(op, dict) or not op.get("action"):+ return None, tool_error(f"operations[{i}] needs an 'action'.", success=False)+ act = op["action"]+ if act not in _BATCH_OP_ACTIONS:+ return None, tool_error(+ f"operations[{i}]: unknown action '{act}'. "+ f"Batchable: {', '.join(sorted(_BATCH_OP_ACTIONS))}; "+ "delete must be sole.",+ success=False,+ )+ nm = op.get("name") or default_name+ if not nm:+ return None, tool_error(f"operations[{i}] needs a 'name' (the skill it targets).", success=False)+ names.append(nm)+ if act == "create" and nm in names[:-1]:+ return None, tool_error(+ f"operations[{i}]: create for '{nm}' must precede that "+ "skill's other ops.",+ success=False,+ )+ preflight = _background_review_preflight(act, nm)+ if preflight is not None:+ return None, json.dumps(preflight, ensure_ascii=False)++ # Intra-batch clobber guard: sequential last-wins would SILENTLY discard an+ # earlier op's work. A DESTRUCTIVE op (create/write_file/remove_file/full+ # SKILL.md rewrite) on a file an earlier op touched is rejected; additive+ # patches are always legal, so patch chains and write-then-patch stay+ # allowed. Paths are normalized so spelling variants can't slip past.+ touched_files = set()+ for i, op in enumerate(operations):+ act = op["action"]+ nm = names[i]+ # create and full-rewrite patch (content) always hit SKILL.md.+ full_rewrite = act == "patch" and bool(op.get("content"))+ target = "SKILL.md" if (act == "create" or full_rewrite) else _norm_target(op)+ key = (nm, target)+ destructive = act in ("create", "write_file", "remove_file") or full_rewrite+ if destructive and key in touched_files:+ return None, tool_error(+ f"operations[{i}]: {act} on '{target}' of skill '{nm}' — an "+ "earlier op in this batch already touched that file, and this "+ "op would silently discard its work. One destructive op "+ "(write_file/remove_file/full rewrite) per file per batch; "+ "put it first, or fold the change in. Patch chains are fine.",+ success=False,+ )+ touched_files.add(key)+ return names, None+++def _stage_batch_if_gated(operations, names):+ """Approval gate for the WHOLE batch as one pending write."""+ from tools.skill_manager_tool import _run_write_gate++ def _staging(wa):+ acts = ", ".join(op["action"] for op in operations)+ skills = ", ".join(sorted(set(names)))+ gist = f"batch({len(operations)} ops: {acts}) on {skills}"+ return {"action": "batch", "operations": operations}, gist++ return _run_write_gate(_staging)+++def _snapshot_skills(names, snap_root, find_skill):+ """Copy every touched skill aside. Returns (snapshots, None) or (None, error_text)."""+ snapshots = {} # skill name -> (pre_dir or None, snapshot_dir or None)+ for nm in dict.fromkeys(names): # ordered unique+ pre = find_skill(nm)+ pre_dir = Path(pre["path"]) if pre else None+ snap = None+ if pre_dir is not None and pre_dir.is_dir():+ snap = snap_root / nm+ try:+ shutil.copytree(pre_dir, snap)+ except Exception as exc: # noqa: BLE001 — no snapshot, no atomicity+ return None, f"Could not snapshot '{nm}' for atomic batch: {exc}"+ snapshots[nm] = (pre_dir, snap)+ return snapshots, None+++def _restore_snapshot(pre_dir, snap, post_dir) -> None:+ if snap is not None:+ if post_dir is not None and post_dir.is_dir():+ # Never destroy the only other copy before the restore lands: move+ # the broken state aside and delete it only after the snapshot is+ # back, so a failed copytree (disk full, locked file) can't turn+ # into total skill loss.+ aside = post_dir.with_name(post_dir.name + ".rollback-broken")+ shutil.rmtree(aside, ignore_errors=True)+ post_dir.rename(aside)+ try:+ shutil.copytree(snap, pre_dir)+ except Exception:+ # Restore failed: put the broken (half-applied) state back+ # rather than leaving nothing.+ shutil.rmtree(pre_dir, ignore_errors=True)+ aside.rename(pre_dir)+ raise+ shutil.rmtree(aside, ignore_errors=True)+ else:+ shutil.copytree(snap, pre_dir)+ elif post_dir is not None and post_dir.is_dir():+ # Batch created this skill: remove the partial result.+ shutil.rmtree(post_dir)+++def _rollback(snapshots, find_skill):+ """Restore every snapshot. Returns (note, failed)."""+ notes = []+ for nm, (pre_dir, snap) in snapshots.items():+ try:+ post = find_skill(nm)+ _restore_snapshot(pre_dir, snap, Path(post["path"]) if post else None)+ except Exception as exc: # noqa: BLE001+ notes.append(+ f"ROLLBACK FAILED for '{nm}' ({exc}); snapshot preserved at '{snap}'"+ if snap is not None+ else f"ROLLBACK FAILED for '{nm}' ({exc})"+ )+ return ("; ".join(notes) if notes else "all touched skills rolled back"), bool(notes)+++def _skill_manage_batch(+ operations,+ default_name: str = None,+ task_id: str = None,+ session_id: str = None,+) -> str:+ """Apply a sequence of operations atomically (memory-tool pattern).++ Each op carries its own ``name`` and ``action``. Every touched skill is+ snapshotted before any op runs; any failure rolls ALL touched skills back+ (skills the batch created are removed).++ Rules: ``delete`` only as the SOLE op (its recoverable-archive path doesn't+ compose with rollback) and is routed to the single-op handler, preserving+ absorbed_into/archive semantics; ``create`` must precede that skill's other+ ops; the same-file clobber guard rejects silently-lost work.+ ``default_name`` is the legacy top-level ``name`` fallback (staged replay).+ """+ from tools import skill_manager_tool as _smt+ from tools.registry import tool_error++ if not isinstance(operations, list) or not operations:+ return tool_error("operations must be a non-empty array.", success=False)+ if len(operations) > _BATCH_MAX_OPS:+ return tool_error(f"operations is capped at {_BATCH_MAX_OPS} ops per call.", success=False)+ if any(isinstance(op, dict) and op.get("action") == "delete" for op in operations):+ if len(operations) != 1:+ return tool_error(+ "delete must be the SOLE op in its call — it doesn't "+ "compose with other ops' rollback.",+ success=False,+ )+ op = operations[0]+ nm = op.get("name") or default_name+ if not nm:+ return tool_error("operations[0] (delete) needs a 'name'.", success=False)+ return _smt.skill_manage(+ action="delete",+ name=nm,+ absorbed_into=op.get("absorbed_into"),+ task_id=task_id,+ session_id=session_id,+ )++ names, err = _validate_batch_ops(operations, default_name, tool_error)+ if err is not None:+ return err++ if not _smt._skill_gate_bypass.get():+ staged = _stage_batch_if_gated(operations, names)+ if staged is not None:+ return staged++ snap_root = Path(tempfile.mkdtemp(prefix="skill_batch_"))+ snapshots, snap_err = _snapshot_skills(names, snap_root, _smt._find_skill)+ if snap_err is not None:+ shutil.rmtree(snap_root, ignore_errors=True)+ return tool_error(snap_err, success=False)++ # Execute through the single-op path with the gate bypassed (the batch+ # already cleared/staged it); ledger + telemetry fire per-op.+ results = []+ rollback_failed = False+ token = _smt._skill_gate_bypass.set(True)+ try:+ for i, op in enumerate(operations):+ raw = _smt._skill_manage_from(+ {**op, "name": names[i]}, task_id=task_id, session_id=session_id,+ )+ try:+ parsed = json.loads(raw)+ except Exception: # noqa: BLE001+ parsed = {"success": False, "error": "unparseable op result"}+ if not parsed.get("success"):+ note, rollback_failed = _rollback(snapshots, _smt._find_skill)+ fail = {+ "success": False,+ "error": (+ f"operations[{i}] ({op['action']} on '{names[i]}') failed: "+ f"{parsed.get('error', 'unknown error')} — batch aborted, {note}."+ ),+ "failed_index": i,+ "completed_before_failure": i,+ }+ # Carry the failing op's teaching payload (patch's file_preview /+ # fuzzy-match hints) through — without it the model recovers blind.+ for k, v in parsed.items():+ if k not in ("success", "error") and v is not None:+ fail.setdefault(k, v)+ return json.dumps(fail, ensure_ascii=False)+ results.append({"name": names[i], "action": op["action"],+ "file_path": op.get("file_path"),+ "success": True})+ finally:+ _smt._skill_gate_bypass.reset(token)+ if rollback_failed:+ # Keep the snapshots so the operator can still recover by hand.+ logger.warning(+ "skill_manage batch rollback failed, snapshots kept at %s",+ snap_root,+ )+ else:+ shutil.rmtree(snap_root, ignore_errors=True)++ return json.dumps(+ {"success": True, "operations_applied": len(results),+ "results": results},+ ensure_ascii=False,+ )diff --git a/tools/skill_manager_guards.py b/tools/skill_manager_guards.pynew file mode 100644index 00000000000..f303249ce15--- /dev/null+++ b/tools/skill_manager_guards.py@@ -0,0 +1,407 @@+"""Write/delete guards for ``skill_manage`` (extracted from skill_manager_tool).++Every guard returns ``None`` when the operation may proceed, otherwise a+refusal (error dict or message). Origin-owned state (``_find_skill``,+``_skills_dir``) is reached lazily through ``tools.skill_manager_tool`` so+test patches on that module keep working.+"""++import contextvars as _ctxvars+import logging+import threading+from pathlib import Path+from typing import Any, Dict, Optional++logger = logging.getLogger("tools.skill_manager_tool")++_ERR_KEY = "error"+++def _refusal(message: str, **extra: Any) -> Dict[str, Any]:+ out: Dict[str, Any] = {"success": False, _ERR_KEY: message}+ out.update(extra)+ return out+++def _is_background_review() -> bool:+ """True inside the autonomous curator review fork; False on any lookup failure."""+ try:+ from tools.skill_provenance import is_background_review+ return bool(is_background_review())+ except Exception:+ return False+++def _resolved_str(path: Path) -> str:+ try:+ return str(path.resolve())+ except Exception:+ return str(path)+++# ---------------------------------------------------------------------------+# Background-review read marks+# ---------------------------------------------------------------------------++class _BackgroundReviewReadMarks:+ """Read marks shared by copied tool contexts within one review run."""++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._paths: set[str] = set()++ def add(self, path: str) -> None:+ with self._lock:+ self._paths.add(path)++ def contains(self, path: str) -> bool:+ with self._lock:+ return path in self._paths+++_background_review_read_paths: (+ "_ctxvars.ContextVar[Optional[_BackgroundReviewReadMarks]]"+) = _ctxvars.ContextVar("background_review_read_paths", default=None)+++def mark_background_review_skill_read(path: Path) -> None:+ """Record that the active background-review fork has read a skill file.++ The review fork may evolve skills but must not patch content it only+ inferred from the transcript: skill_view calls this after returning file+ content, and the write guards below require the target to be marked.+ """+ if not _is_background_review():+ return+ marks = _background_review_read_paths.get()+ if marks is None:+ marks = _BackgroundReviewReadMarks()+ _background_review_read_paths.set(marks)+ marks.add(_resolved_str(path))+++def _background_review_has_read(path: Path) -> bool:+ marks = _background_review_read_paths.get()+ return marks is not None and marks.contains(_resolved_str(path))+++def _reset_background_review_read_marks() -> None:+ """Start a fresh, isolated read set for the current review context."""+ _background_review_read_paths.set(_BackgroundReviewReadMarks())+++# ---------------------------------------------------------------------------+# Delete-target safety+# ---------------------------------------------------------------------------++def _containing_skills_root(skill_path: Path) -> Path:+ """Skills root (local or external_dirs entry) containing ``skill_path``;+ falls back to the local skills dir when no root matches."""+ from agent.skill_utils import get_all_skills_dirs+ from tools import skill_manager_tool as _smt++ try:+ resolved = skill_path.resolve()+ except OSError:+ resolved = skill_path+ for root in get_all_skills_dirs():+ try:+ resolved.relative_to(root.resolve())+ return root+ except (ValueError, OSError):+ continue+ return _smt._skills_dir()+++def _is_path_redirect(path: Path) -> bool:+ """True when ``path`` is a symlink or (Windows 3.12+) a junction — either+ lets a poisoned tree redirect ``shutil.rmtree`` outside the skills root."""+ try:+ return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())+ except OSError:+ return False+++def _validate_delete_target(skill_dir: Path) -> Optional[str]:+ """Last-line guard before ``shutil.rmtree(skill_dir)``.++ ``_find_skill`` already restricts the dir to a real SKILL.md parent, but+ even a poisoned tree must never recursively delete (1) a path outside every+ known skills root, (2) a skills root itself, or (3) a symlink/junction+ (rmtree would follow it). Returns a refusal string or ``None``.+ """+ from agent.skill_utils import get_all_skills_dirs++ if _is_path_redirect(skill_dir):+ return (+ f"Refusing to delete '{skill_dir}': the skill directory is a "+ f"symlink/junction. Remove the link target manually if intended."+ )+ try:+ resolved = skill_dir.resolve()+ except OSError as exc:+ return f"Refusing to delete '{skill_dir}': could not resolve path ({exc})."++ for root in get_all_skills_dirs():+ try:+ root = root.resolve()+ except OSError:+ continue+ if resolved == root:+ return (+ f"Refusing to delete '{skill_dir}': resolves to the skills root "+ f"itself, which would remove every installed skill."+ )+ try:+ rel = resolved.relative_to(root)+ except ValueError:+ continue+ if rel.parts:+ return None+ return (+ f"Refusing to delete '{skill_dir}': path does not resolve inside any "+ f"known skills root."+ )+++# ---------------------------------------------------------------------------+# Ownership / provenance guards+# ---------------------------------------------------------------------------++def _pinned_guard(name: str) -> Optional[str]:+ """Refusal message if *name* is pinned or essential, else None.++ Pin only guards against **deletion** (curator auto-archive and+ ``skill_manage(delete)``); patches/edits stay allowed. Essential skills+ (``ESSENTIAL_SKILLS``) are permanently pinned because the system prompt+ references them. Best-effort: an unreadable sidecar lets the delete through.+ """+ try:+ from agent.skill_utils import ESSENTIAL_SKILLS+ if name in ESSENTIAL_SKILLS:+ return (+ f"Skill '{name}' is essential to Hermes (the agent's own "+ f"operating manual referenced by the system prompt) and "+ f"cannot be deleted. Patches and edits are still allowed."+ )+ except Exception:+ logger.debug("essential-guard lookup failed for %s", name, exc_info=True)+ try:+ from tools import skill_usage+ if skill_usage.get_record(name).get("pinned"):+ return (+ f"Skill '{name}' is pinned and cannot be deleted by "+ f"skill_manage. Ask the user to run "+ f"`hermes curator unpin {name}` if they want to delete it. "+ f"Patches and edits are allowed on pinned skills; only "+ f"deletion is blocked."+ )+ except Exception:+ logger.debug("pinned-guard lookup failed for %s", name, exc_info=True)+ return None+++def _background_review_write_guard(+ name: str,+ skill_dir: Path,+ action: str,+) -> Optional[Dict[str, Any]]:+ """Refuse autonomous curator writes to anything but curator-owned sediment.++ Foreground agents may edit external/bundled/hub skills at the user's+ direction; the background review fork has no user in the loop, so it is+ also blocked on pinned skills (stricter than ``_pinned_guard``).+ """+ if not _is_background_review():+ return None++ try:+ from tools import skill_usage+ if skill_usage.get_record(name).get("pinned"):+ return _refusal(+ f"Refusing background curator {action} for pinned skill "+ f"'{name}': pinned skills are off-limits to autonomous "+ "maintenance. Ask the user to run "+ f"`hermes curator unpin {name}` if they want it changed."+ )+ except Exception:+ logger.debug("pinned skill guard lookup failed for %s", name, exc_info=True)++ try:+ from agent.skill_utils import is_external_skill_path+ if is_external_skill_path(skill_dir):+ return _refusal(+ f"Refusing background curator {action} for skill '{name}': "+ "the skill lives in skills.external_dirs, which are "+ "externally owned and read-only to autonomous curation."+ )+ except Exception:+ logger.debug("external skill guard lookup failed for %s", name, exc_info=True)++ try:+ from tools import skill_usage+ for predicate, label in (+ (skill_usage.is_protected_builtin, "protected built-in"),+ (skill_usage.is_hub_installed, "hub-installed"),+ (skill_usage.is_bundled, "bundled"),+ ):+ if predicate(name):+ return _refusal(+ f"Refusing background curator {action} for {label} "+ f"skill '{name}'."+ )+ # Not curator-managed (no `created_by: "agent"` marker) => user-owned.+ # A MISSING record and an explicit `created_by: null` must resolve+ # IDENTICALLY: keying on record presence made the policy depend on the+ # guard's own side effect (the first successful write created a null+ # record and the next identical write was refused). Fail closed for+ # both; `hermes curator adopt <name>` is the supported way in.+ usage_rec = skill_usage.load_usage().get(name)+ if not skill_usage._is_curator_managed_record(usage_rec):+ if isinstance(usage_rec, dict):+ _detail = f"created_by={usage_rec.get('created_by')!r}"+ else:+ _detail = "no usage record"+ return _refusal(+ f"Refusing background curator {action} for skill "+ f"'{name}': the skill is not curator-managed ({_detail}). "+ "User-owned skills are off-limits to autonomous curation. "+ f"Run `hermes curator adopt {name}` to opt it in."+ )+ except Exception:+ logger.warning("owned skill guard lookup failed for %s", name, exc_info=True)+ return _refusal(+ f"Refusing background curator {action} for skill '{name}': "+ "agent ownership could not be verified because the provenance "+ "record is unavailable or unreadable."+ )+ return None+++def _background_review_read_before_write_guard(+ name: str,+ target: Path,+ action: str,+ file_label: str,+) -> Optional[Dict[str, Any]]:+ """Require review forks to load the exact target before mutating it."""+ if not _is_background_review() or _background_review_has_read(target):+ return None+ return _refusal(+ f"Refusing background curator {action} for skill '{name}': "+ f"the current {file_label} content has not been loaded in this "+ "review turn. Call skill_view(name) for SKILL.md, or "+ "skill_view(name, file_path=...) for a supporting file, then "+ "retry the write using the content just returned.",+ _read_before_write_required=True,+ )+++def _background_review_preflight(action: str, name: str) -> Optional[Dict[str, Any]]:+ if action not in {"edit", "patch", "delete", "write_file", "remove_file"}:+ return None+ from tools import skill_manager_tool as _smt++ existing = _smt._find_skill(name)+ if not existing:+ return None+ return _background_review_write_guard(name, existing["path"], action)+++def _curator_consolidation_delete_guard(+ name: str, absorbed_into: Optional[str]+) -> Optional[Dict[str, Any]]:+ """Fail closed on unverified deletes during the curator consolidation pass.++ The review fork's only legitimate ``skill_manage(delete)`` is a verified+ consolidation declared via ``absorbed_into=<umbrella>`` (existence is+ validated in ``_delete_skill``). A bare delete (``None`` or ``""``) is the+ fail-open behavior that once archived whole clusters of active skills; the+ deterministic inactivity prune archives via ``skill_usage.archive_skill``+ without ever calling ``skill_manage``, so a bare prune here can only be the+ LLM pass pruning without evidence. Refuse it; keep the skill active.+ """+ if not _is_background_review():+ return None+ if isinstance(absorbed_into, str) and absorbed_into.strip():+ return None+ return _refusal(+ f"Refusing background curator delete of skill '{name}': the "+ "consolidation pass may only archive a skill it has absorbed into "+ "an umbrella. Pass absorbed_into=<umbrella> (the umbrella must "+ "already exist) to record a verified consolidation. Pruning a "+ "skill with no forwarding target is not permitted here — the "+ "deterministic inactivity prune handles staleness archival "+ "separately. Keeping '{name}' active.".format(name=name),+ _fail_closed=True,+ )+++# ---------------------------------------------------------------------------+# Org-mirror handling+# ---------------------------------------------------------------------------++def _maybe_auto_propose_org_edit(name: str, skill_path: Path) -> Optional[str]:+ """Submit an org-skill edit upstream when `sync.org_auto_propose` is on.++ Returns a short note for the tool result, or None when nothing happened.+ Never raises: the edit is already saved locally and can be proposed later.+ """+ from tools import skill_manager_tool as _smt++ try:+ from agent.skill_utils import is_org_mirror_path+ from tools import skills_sync_client as ssc++ if not is_org_mirror_path(skill_path, _smt._skills_dir()):+ return None+ if not ssc.sync_org_auto_propose():+ return (+ f"This skill is shared by your organisation. Your edit is "+ f"saved locally and will not be overwritten by org updates. "+ f"Run `hermes sync propose {name}` to share it back."+ )+ result = ssc.propose_skill(name)+ if result.get("proposal_pending"):+ return (+ f"Auto-proposed to your organisation as proposal "+ f"#{result.get('proposal_id')} (pending admin review)."+ )+ return "Auto-proposed to your organisation (merged into the shared set)."+ except Exception as e:+ logger.debug("auto-propose skipped for %s: %s", name, e)+ return (+ f"Edit saved locally. Could not submit it to your organisation "+ f"right now — run `hermes sync propose {name}` to retry."+ )+++def _org_mirror_write_guard(name: str, skill_path: Path, action: str) -> Optional[Dict[str, Any]]:+ """Org-shared skills are EDITABLE IN PLACE — this only blocks deletion.++ Refusing every write to `_org/` froze shared skills while personal ones+ kept improving (agents don't fork mid-task). Edits now land in the mirror,+ survive the next org pull (baseline sidecar in skills_sync_client), and+ reach the org via `hermes sync propose` or `sync.org_auto_propose`.+ Deletion stays refused: the mirror is a view of org HEAD, so a local+ delete just comes back, and removing for everyone is an admin action.+ """+ if action not in {"delete", "remove_file"}:+ return None+ from tools import skill_manager_tool as _smt++ try:+ from agent.skill_utils import is_org_mirror_path++ if is_org_mirror_path(skill_path, _smt._skills_dir()):+ return _refusal(+ f"Cannot {action} '{name}' locally: it is shared by your "+ "organisation, so a local delete would just come back on "+ "the next sync. Ask an org admin to remove it for "+ "everyone. (Editing it IS allowed — your changes are kept "+ "and can be proposed back with `hermes sync propose "+ f"{name}`.)"+ )+ except Exception:+ logger.debug("org mirror guard lookup failed for %s", name, exc_info=True)+ return Nonediff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.pyindex 28f4058f8dc..ae6d55a2cbe 100644--- a/tools/skill_manager_tool.py+++ b/tools/skill_manager_tool.py@@ -2,45 +2,27 @@"""Skill Manager Tool -- Agent-Managed Skill Creation & Editing-Allows the agent to create, update, and delete skills, turning successful-approaches into reusable procedural knowledge. New skills are created in-~/.hermes/skills/. Existing skills (bundled, hub-installed, or user-created)-can be modified or deleted wherever they live.--Skills are the agent's procedural memory: they capture *how to do a specific-type of task* based on proven experience. General memory (MEMORY.md, USER.md) is-broad and declarative. Skills are narrow and actionable.--Actions:- create -- Create a new skill (SKILL.md + directory structure)- edit -- Replace the SKILL.md content of a user skill (full rewrite)- patch -- Targeted find-and-replace within SKILL.md or any supporting file- delete -- Remove a user skill entirely- write_file -- Add/overwrite a supporting file (reference, template, script, asset)- remove_file-- Remove a supporting file from a user skill--Directory layout for user skills:- ~/.hermes/skills/- ├── my-skill/- │ ├── SKILL.md- │ ├── references/- │ ├── templates/- │ ├── scripts/- │ └── assets/- └── category-name/- └── another-skill/- └── SKILL.md+Lets the agent create, patch, and delete skills — its procedural memory+(narrow, actionable "how to do X"), as opposed to MEMORY.md/USER.md (broad,+declarative). New skills land in ~/.hermes/skills/ (or ``skills.create_dir``);+existing skills (bundled, hub-installed, user-created) are modified in place.++Actions: create, edit (legacy full rewrite), patch, delete, write_file,+remove_file. Layout: ``<skills>/[category/]<skill>/SKILL.md`` plus optional+``references/ templates/ scripts/ assets/`` subdirs."""+import contextvars as _ctxvarsimport jsonimport loggingimport reimport shutilimport threading-import contextvars as _ctxvarsfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple+import yaml+from hermes_constants import get_hermes_home, display_hermes_homefrom utils import atomic_write_text, is_truthy_valuefrom hermes_cli.config import cfg_get@@ -50,72 +32,34 @@ from agent.skill_utils import (parse_frontmatter as _parse_frontmatter,SKILL_PROMPT_DESC_LIMIT,)+from tools.skill_manager_guards import ( # noqa: F401 — re-exported for callers/tests+ _BackgroundReviewReadMarks,+ _background_review_has_read,+ _background_review_preflight,+ _background_review_read_before_write_guard,+ _background_review_read_paths,+ _background_review_write_guard,+ _containing_skills_root,+ _curator_consolidation_delete_guard,+ _is_path_redirect,+ _maybe_auto_propose_org_edit,+ _org_mirror_write_guard,+ _pinned_guard,+ _reset_background_review_read_marks,+ _validate_delete_target,+ _is_background_review,+ mark_background_review_skill_read,+)+from tools.skill_manager_batch import ( # noqa: F401+ _BATCH_MAX_OPS,+ _BATCH_OP_ACTIONS,+ _skill_manage_batch,+)logger = logging.getLogger(__name__)-class _BackgroundReviewReadMarks:- """Read marks shared by copied tool contexts within one review run."""-- def __init__(self) -> None:- self._lock = threading.Lock()- self._paths: set[str] = set()-- def add(self, path: str) -> None:- with self._lock:- self._paths.add(path)-- def contains(self, path: str) -> bool:- with self._lock:- return path in self._paths---_background_review_read_paths: (- "_ctxvars.ContextVar[Optional[_BackgroundReviewReadMarks]]"-) = _ctxvars.ContextVar("background_review_read_paths", default=None)---def mark_background_review_skill_read(path: Path) -> None:- """Record that the active background-review fork has read a skill file.-- The autonomous review fork is allowed to evolve skills, but it must not- patch or rewrite content it has only inferred from the transcript. The- skill_view tool calls this after returning file content to the model; write- paths below require the corresponding target path to be present when the- current origin is ``background_review``.- """- try:- from tools.skill_provenance import is_background_review- if not is_background_review():- return- except Exception:- return-- try:- resolved = str(path.resolve())- except Exception:- resolved = str(path)- marks = _background_review_read_paths.get()- if marks is None:- marks = _BackgroundReviewReadMarks()- _background_review_read_paths.set(marks)- marks.add(resolved)---def _background_review_has_read(path: Path) -> bool:- try:- resolved = str(path.resolve())- except Exception:- resolved = str(path)- marks = _background_review_read_paths.get()- return marks is not None and marks.contains(resolved)---def _reset_background_review_read_marks() -> None:- """Start a fresh, isolated read set for the current review context."""- _background_review_read_paths.set(_BackgroundReviewReadMarks())--# Import security scanner — external hub installs always get scanned;-# agent-created skills only get scanned when skills.guard_agent_created is on.+# External hub installs are always scanned; agent-created skills only when+# skills.guard_agent_created is on.try:from tools.skills_guard import scan_skill, should_allow_install, format_scan_report_GUARD_AVAILABLE = True@@ -124,18 +68,12 @@ except ImportError:def _guard_agent_created_enabled() -> bool:- """Read skills.guard_agent_created from config (default False).-- Off by default because the agent can already execute the same code- paths via terminal() with no gate, so the scan adds friction without- meaningful security. Users who want belt-and-suspenders can turn it- on via `hermes config set skills.guard_agent_created true`.- """+ """skills.guard_agent_created (default False): the agent can already run+ the same code via terminal() ungated, so the scan is opt-in belt-and-suspenders."""try:from hermes_cli.config import load_config- cfg = load_config()return is_truthy_value(- cfg_get(cfg, "skills", "guard_agent_created"),+ cfg_get(load_config(), "skills", "guard_agent_created"),default=False,)except Exception:@@ -145,31 +83,23 @@ def _guard_agent_created_enabled() -> bool:def _security_scan_skill(skill_dir: Path) -> Optional[str]:"""Scan a skill directory after write. Returns error string if blocked, else None.- No-op when skills.guard_agent_created is disabled (the default).+ No-op when skills.guard_agent_created is disabled (the default). An "ask"+ verdict means dangerous findings for an agent-created skill — surfaced as+ an error so the agent can retry with the flagged content removed."""- if not _GUARD_AVAILABLE:- return None- if not _guard_agent_created_enabled():+ if not _GUARD_AVAILABLE or not _guard_agent_created_enabled():return Nonetry:result = scan_skill(skill_dir, source="agent-created")allowed, reason = should_allow_install(result)- if allowed is False:- report = format_scan_report(result)- return f"Security scan blocked this skill ({reason}):\n{report}"if allowed is None:- # "ask" verdict — for agent-created skills this means dangerous- # findings were detected. Surface as an error so the agent can- # retry with the flagged content removed.- report = format_scan_report(result)logger.warning("Agent-created skill blocked (dangerous findings): %s", reason)- return f"Security scan blocked this skill ({reason}):\n{report}"+ if allowed is not True:+ return f"Security scan blocked this skill ({reason}):\n{format_scan_report(result)}"except Exception as e:logger.warning("Security scan failed for %s: %s", skill_dir, e, exc_info=True)return None-import yaml-# All skills live in ~/.hermes/skills/ (single source of truth)HERMES_HOME = get_hermes_home()@@ -178,30 +108,30 @@ _SKILLS_DIR_AT_IMPORT = SKILLS_DIRdef _skills_dir() -> Path:- """Return the active profile's skills directory at call time.+ """Active profile's skills directory at call time.- Long-lived multi-profile runtimes (Dashboard/TUI/Desktop backend, cron,- kanban workers) import this module once under the launch HERMES_HOME and- later bind a different profile per session (#40677). Honor an explicitly- patched module-level ``SKILLS_DIR`` (tests), otherwise resolve from the- live profile-scoped HERMES_HOME on every call.+ Long-lived multi-profile runtimes import this module once and later bind a+ different profile per session. Honor an explicitly patched module-level+ ``SKILLS_DIR`` (tests), otherwise resolve from the live HERMES_HOME."""configured = Path(SKILLS_DIR)if configured != _SKILLS_DIR_AT_IMPORT:return configuredreturn get_hermes_home() / "skills"+MAX_NAME_LENGTH = 64MAX_DESCRIPTION_LENGTH = 1024+MAX_SKILL_CONTENT_CHARS = 100_000 # ~36k tokens at 2.75 chars/token+MAX_SKILL_FILE_BYTES = 1_048_576 # 1 MiB per supporting file+VALID_NAME_RE = re.compile(r'^[a-z0-9][a-z0-9._-]*$') # filesystem-safe, URL-friendly+ALLOWED_SUBDIRS = {"references", "templates", "scripts", "assets"} # for write_file/remove_file+_FRONTMATTER_END_RE = re.compile(r'\n---\s*\n')def _display_create_dir() -> str:- """Display string for the skill-creation directory (schema/instruction text).-- Renders ``skills.create_dir`` when configured so every instruction that- names the creation path follows the config, falling back to the- profile-local skills dir.- """+ """Display string for the skill-creation directory (schema/instruction text);+ follows ``skills.create_dir`` when configured."""try:from agent.skill_utils import display_skill_create_dirreturn display_skill_create_dir()@@ -209,363 +139,8 @@ def _display_create_dir() -> str:return f"{display_hermes_home()}/skills/"-def _containing_skills_root(skill_path: Path) -> Path:- """Return the skills root directory (local or external_dirs entry) that- contains ``skill_path``. Falls back to the local ``SKILLS_DIR`` if no- match is found (defensive — callers should have located the skill via- ``_find_skill`` first).- """- from agent.skill_utils import get_all_skills_dirs-- try:- resolved = skill_path.resolve()- except OSError:- resolved = skill_path-- for root in get_all_skills_dirs():- try:- resolved.relative_to(root.resolve())- return root- except (ValueError, OSError):- continue- return _skills_dir()---def _is_path_redirect(path: Path) -> bool:- """True when ``path`` is a symlink or (on Windows) a directory junction.-- Either form lets a poisoned skills tree redirect a subsequent- ``shutil.rmtree`` to content outside the skills root. ``is_junction``- only exists on Python 3.12+ Windows; gate with ``hasattr``.- """- try:- return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())- except OSError:- return False---def _validate_delete_target(skill_dir: Path) -> Optional[str]:- """Last-line guard before ``shutil.rmtree(skill_dir)`` in ``_delete_skill``.-- ``_find_skill`` already restricts ``skill_dir`` to a real ``SKILL.md``- parent discovered by walking the skills roots, so the agent cannot inject- an arbitrary path the way Kilo Code's HTTP endpoint could (their issue- #11227: a built-in-skill sentinel resolved to the server cwd and a- recursive delete wiped the user's entire working directory). This is the- matching defense-in-depth for our agent-facing ``skill_manage`` delete- path: even if discovery or a poisoned tree hands us a bad directory, never- recursively delete-- 1. a path that is not strictly *inside* one of the known skills roots,- 2. a skills root itself (would wipe every installed skill), or- 3. a directory reached via a symlink / junction (``rmtree`` would follow- it into content outside the skills tree).-- Returns an error string to refuse on, or ``None`` when the delete is safe.- """- from agent.skill_utils import get_all_skills_dirs-- # (3) Reject symlink/junction redirects on the skill directory itself.- if _is_path_redirect(skill_dir):- return (- f"Refusing to delete '{skill_dir}': the skill directory is a "- f"symlink/junction. Remove the link target manually if intended."- )-- try:- resolved = skill_dir.resolve()- except OSError as exc:- return f"Refusing to delete '{skill_dir}': could not resolve path ({exc})."-- roots = []- for root in get_all_skills_dirs():- try:- roots.append(root.resolve())- except OSError:- continue-- for root in roots:- # (2) Never rmtree a skills root itself.- if resolved == root:- return (- f"Refusing to delete '{skill_dir}': resolves to the skills root "- f"itself, which would remove every installed skill."- )- # (1) Must be strictly inside a known root.- try:- rel = resolved.relative_to(root)- except ValueError:- continue- if rel.parts: # at least one component below the root- return None-- return (- f"Refusing to delete '{skill_dir}': path does not resolve inside any "- f"known skills root."- )---def _pinned_guard(name: str) -> Optional[str]:- """Return a refusal message if *name* is pinned or essential, else None.-- Pin protects a skill from **deletion** — both the curator's auto-archive- passes and the agent's ``skill_manage(action="delete")`` tool call. The- agent can still patch/edit pinned skills; pin only guards against- irrecoverable loss, not against content evolution.-- Essential skills (``agent/skill_utils.ESSENTIAL_SKILLS``, e.g.- ``hermes-agent``) are treated as permanently pinned: the system prompt- always references them, so deleting one leaves a dangling instruction.-- Best-effort: if the sidecar is unreadable we let the delete through- rather than block on a broken telemetry file.- """- try:- from agent.skill_utils import ESSENTIAL_SKILLS- if name in ESSENTIAL_SKILLS:- return (- f"Skill '{name}' is essential to Hermes (the agent's own "- f"operating manual referenced by the system prompt) and "- f"cannot be deleted. Patches and edits are still allowed."- )- except Exception:- logger.debug("essential-guard lookup failed for %s", name, exc_info=True)- try:- from tools import skill_usage- rec = skill_usage.get_record(name)- if rec.get("pinned"):- return (- f"Skill '{name}' is pinned and cannot be deleted by "- f"skill_manage. Ask the user to run "- f"`hermes curator unpin {name}` if they want to delete it. "- f"Patches and edits are allowed on pinned skills; only "- f"deletion is blocked."- )- except Exception:- logger.debug("pinned-guard lookup failed for %s", name, exc_info=True)- return None---def _background_review_write_guard(- name: str,- skill_dir: Path,- action: str,-) -> Optional[Dict[str, Any]]:- """Refuse autonomous curator writes to externally owned skills.-- Foreground agents may still perform user-directed edits to external,- bundled, or hub-installed skills. The background review fork is different:- it is autonomous lifecycle maintenance, so its write surface is restricted- to local curator-owned sediment.- """- try:- from tools.skill_provenance import is_background_review- if not is_background_review():- return None- except Exception:- return None-- # Pin must be respected by autonomous maintenance. The curator already- # skips pinned skills from every auto-transition; the background review- # fork is the same kind of autonomous, no-user-present actor, so it must- # not write to a pinned skill either (issue #25839). This is stricter than- # the foreground ``_pinned_guard`` (which only blocks deletion) precisely- # because there is no user in the loop to consent to an edit here.- try:- from tools import skill_usage- if skill_usage.get_record(name).get("pinned"):- return {- "success": False,- "error": (- f"Refusing background curator {action} for pinned skill "- f"'{name}': pinned skills are off-limits to autonomous "- "maintenance. Ask the user to run "- f"`hermes curator unpin {name}` if they want it changed."- ),- }- except Exception:- logger.debug("pinned skill guard lookup failed for %s", name, exc_info=True)-- try:- from agent.skill_utils import is_external_skill_path- if is_external_skill_path(skill_dir):- return {- "success": False,- "error": (- f"Refusing background curator {action} for skill '{name}': "- "the skill lives in skills.external_dirs, which are "- "externally owned and read-only to autonomous curation."- ),- }- except Exception:- logger.debug("external skill guard lookup failed for %s", name, exc_info=True)-- try:- from tools import skill_usage- if skill_usage.is_protected_builtin(name):- return {- "success": False,- "error": (- f"Refusing background curator {action} for protected "- f"built-in skill '{name}'."- ),- }- if skill_usage.is_hub_installed(name):- return {- "success": False,- "error": (- f"Refusing background curator {action} for hub-installed "- f"skill '{name}'."- ),- }- if skill_usage.is_bundled(name):- return {- "success": False,- "error": (- f"Refusing background curator {action} for bundled "- f"skill '{name}'."- ),- }- # Skills that are not curator-managed are off-limits to autonomous- # curation. This prevents the LLM consolidation pass from mutating- # skills the user owns (manually authored, URL-installed, or created by- # a foreground `skill_manage(create)` at the user's request), which lack- # the `created_by: "agent"` marker.- #- # A MISSING record and an explicit `created_by: null` must resolve- # IDENTICALLY (issue #67140). Keying on `isinstance(usage_rec, dict)`- # made the policy depend on the guard's own side effect: a local skill- # with no telemetry record passed, the successful write called- # bump_patch() which created a `created_by: null` record, and the very- # same write was refused from then on. "Allowed exactly once" is not a- # policy — it is a race with our own bookkeeping. Fail closed for both- # shapes; `hermes curator adopt <name>` is the supported way in.- usage_data = skill_usage.load_usage()- usage_rec = usage_data.get(name)- if not skill_usage._is_curator_managed_record(usage_rec):- if isinstance(usage_rec, dict):- _detail = f"created_by={usage_rec.get('created_by')!r}"- else:- _detail = "no usage record"- return {- "success": False,- "error": (- f"Refusing background curator {action} for skill "- f"'{name}': the skill is not curator-managed ({_detail}). "- "User-owned skills are off-limits to autonomous curation. "- f"Run `hermes curator adopt {name}` to opt it in."- ),- }- except Exception:- logger.warning("owned skill guard lookup failed for %s", name, exc_info=True)- return {- "success": False,- "error": (- f"Refusing background curator {action} for skill '{name}': "- "agent ownership could not be verified because the provenance "- "record is unavailable or unreadable."- ),- }- return None---def _background_review_read_before_write_guard(- name: str,- target: Path,- action: str,- file_label: str,-) -> Optional[Dict[str, Any]]:- """Require review forks to load the exact target before mutating it."""- try:- from tools.skill_provenance import is_background_review- if not is_background_review():- return None- except Exception:- return None-- if _background_review_has_read(target):- return None-- return {- "success": False,- "error": (- f"Refusing background curator {action} for skill '{name}': "- f"the current {file_label} content has not been loaded in this "- "review turn. Call skill_view(name) for SKILL.md, or "- "skill_view(name, file_path=...) for a supporting file, then "- "retry the write using the content just returned."- ),- "_read_before_write_required": True,- }---def _background_review_preflight(action: str, name: str) -> Optional[Dict[str, Any]]:- if action not in {"edit", "patch", "delete", "write_file", "remove_file"}:- return None- existing = _find_skill(name)- if not existing:- return None- return _background_review_write_guard(name, existing["path"], action)---def _curator_consolidation_delete_guard(- name: str, absorbed_into: Optional[str]-) -> Optional[Dict[str, Any]]:- """Fail closed on unverified deletes during the curator consolidation pass.-- The curator's forked review agent (``is_background_review()``) runs the- LLM umbrella-building pass. Its only legitimate ``skill_manage(delete)`` is- a *verified consolidation*: the skill's content was absorbed into an- umbrella, declared via ``absorbed_into=<umbrella>`` where the umbrella- exists on disk (validated separately in ``_delete_skill``).-- A delete with no forwarding target — ``absorbed_into`` omitted (``None``)- or empty (``""``) — is the fail-open behavior reported in #29912: the- consolidation pass archived whole clusters of active skills with zero- verified consolidations (``consolidated_this_run == 0``), leaving active- automations pointing at names that no longer resolve. The deterministic- inactivity prune is the only legitimate prune path, and it archives via- ``skill_usage.archive_skill()`` directly without ever calling- ``skill_manage`` — so a bare prune reaching here can only be the LLM pass- pruning without consolidation evidence. Refuse it; keep the skill active.-- Returns an error dict to abort the delete, or ``None`` when the delete is- allowed to proceed (not the curator pass, or a declared consolidation).- """- try:- from tools.skill_provenance import is_background_review- if not is_background_review():- return None- except Exception:- return None-- declared = isinstance(absorbed_into, str) and absorbed_into.strip()- if declared:- return None-- return {- "success": False,- "error": (- f"Refusing background curator delete of skill '{name}': the "- "consolidation pass may only archive a skill it has absorbed into "- "an umbrella. Pass absorbed_into=<umbrella> (the umbrella must "- "already exist) to record a verified consolidation. Pruning a "- "skill with no forwarding target is not permitted here — the "- "deterministic inactivity prune handles staleness archival "- "separately. Keeping '{name}' active.".format(name=name)- ),- "_fail_closed": True,- }---MAX_SKILL_CONTENT_CHARS = 100_000 # ~36k tokens at 2.75 chars/token-MAX_SKILL_FILE_BYTES = 1_048_576 # 1 MiB per supporting file--# Characters allowed in skill names (filesystem-safe, URL-friendly)-VALID_NAME_RE = re.compile(r'^[a-z0-9][a-z0-9._-]*$')--# Subdirectories allowed for write_file/remove_file-ALLOWED_SUBDIRS = {"references", "templates", "scripts", "assets"}+def _err(message: str) -> Dict[str, Any]:+ return {"success": False, "error": message}# =============================================================================@@ -592,59 +167,41 @@ def _validate_category(category: Optional[str]) -> Optional[str]:return Noneif not isinstance(category, str):return "Category must be a string."-category = category.strip()if not category:return None+ invalid = (+ f"Invalid category '{category}'. Use lowercase letters, numbers, "+ "hyphens, dots, and underscores. Categories must be a single directory name."+ )if "/" in category or "\\" in category:- return (- f"Invalid category '{category}'. Use lowercase letters, numbers, "- "hyphens, dots, and underscores. Categories must be a single directory name."- )+ return invalidif len(category) > MAX_NAME_LENGTH:return f"Category exceeds {MAX_NAME_LENGTH} characters."- if not VALID_NAME_RE.match(category):- return (- f"Invalid category '{category}'. Use lowercase letters, numbers, "- "hyphens, dots, and underscores. Categories must be a single directory name."- )- return None+ return None if VALID_NAME_RE.match(category) else invaliddef _validate_frontmatter(content: str, *, new_skill: bool = False) -> Optional[str]:- """- Validate that SKILL.md content has proper frontmatter with required fields.- Returns error message or None if valid.-- When ``new_skill`` is True (create path only), the description must also- fit the 60-char system-prompt budget (SKILL_PROMPT_DESC_LIMIT) so newly- authored skills never lose routing signal to index truncation. Edit and- patch paths deliberately skip this so existing over-limit skills remain- maintainable while their descriptions are cleaned up.+ """Validate SKILL.md frontmatter (name + description) and a non-empty body.++ ``new_skill`` (create path only) also enforces the SKILL_PROMPT_DESC_LIMIT+ budget so new skills never lose routing signal to index truncation; edit+ and patch skip it so existing over-limit skills remain maintainable."""if not content.strip():return "Content cannot be empty."-- # Tolerate a leading UTF-8 BOM (Windows editors) before the fence.- content = content.lstrip("\ufeff")-+ content = content.lstrip("\ufeff") # tolerate a Windows UTF-8 BOMif not content.startswith("---"):return "SKILL.md must start with YAML frontmatter (---). See existing skills for format."-- end_match = re.search(r'\n---\s*\n', content[3:])+ end_match = _FRONTMATTER_END_RE.search(content[3:])if not end_match:return "SKILL.md frontmatter is not closed. Ensure you have a closing '---' line."-- yaml_content = content[3:end_match.start() + 3]-try:- parsed = yaml.safe_load(yaml_content)+ parsed = yaml.safe_load(content[3:end_match.start() + 3])except yaml.YAMLError as e:return f"YAML frontmatter parse error: {e}"-if not isinstance(parsed, dict):return "Frontmatter must be a YAML mapping (key: value pairs)."-if "name" not in parsed:return "Frontmatter must include 'name' field."if "description" not in parsed:@@ -660,19 +217,13 @@ def _validate_frontmatter(content: str, *, new_skill: bool = False) -> Optional[f"longer descriptions to {SKILL_PROMPT_DESC_LIMIT - 3} chars + '...', "f"destroying the routing signal. Move detail into the skill body.")-- body = content[end_match.end() + 3:].strip()- if not body:+ if not content[end_match.end() + 3:].strip():return "SKILL.md must have content after the frontmatter (instructions, procedures, etc.)."-return Nonedef _validate_content_size(content: str, label: str = "SKILL.md") -> Optional[str]:- """Check that content doesn't exceed the character limit for agent writes.-- Returns an error message or None if within bounds.- """+ """Error message when content exceeds the agent-write character limit, else None."""if len(content) > MAX_SKILL_CONTENT_CHARS:return (f"{label} content is {len(content):,} characters "@@ -683,13 +234,21 @@ def _validate_content_size(content: str, label: str = "SKILL.md") -> Optional[streturn None-def _resolve_skill_dir(name: str, category: str = None) -> Path:- """Build the directory path for a new skill, optionally under a category.+def _description_preview(content: str) -> str:+ """First 120 chars of the frontmatter description (verbose notifications); '' on any failure."""+ try:+ fm_end = _FRONTMATTER_END_RE.search(content[3:])+ if fm_end:+ parsed = yaml.safe_load(content[3:fm_end.start() + 3])+ return str(parsed.get("description", ""))[:120]+ except Exception:+ pass+ return ""- Honors ``skills.create_dir`` from config.yaml: when configured, new- skills are created there (e.g. a shared brain/fleet directory) instead- of the profile-local skills dir. Falls back to the local dir when unset.- """++def _resolve_skill_dir(name: str, category: str = None) -> Path:+ """Directory for a new skill; honors ``skills.create_dir`` (e.g. a shared+ fleet directory) and falls back to the profile-local skills dir."""base = _skills_dir()try:from agent.skill_utils import get_skill_create_dir@@ -698,280 +257,142 @@ def _resolve_skill_dir(name: str, category: str = None) -> Path:base = create_direxcept Exception:logger.debug("skills.create_dir lookup failed", exc_info=True)- if category:- return base / category / name- return base / name+ return base / category / name if category else base / name+++def _iter_skill_dirs(root: Path):+ """Yield every non-excluded skill directory (parent of a SKILL.md) under ``root``."""+ from agent.skill_utils import is_excluded_skill_path++ for skill_md in root.rglob("SKILL.md"):+ if not is_excluded_skill_path(skill_md):+ yield skill_md.parentdef _find_skill(name: str) -> Optional[Dict[str, Any]]:+ """Find a skill by name across the local skills dir then skills.external_dirs.++ Accepts the bare directory name (``axolotl``) and the categorized relative+ path (``mlops/axolotl``) — the two forms skill_view resolves. Bare lookups+ compare the skill's own dir name so category-nested skills still match.+ Returns ``{"path": Path}`` or None."""- Find a skill by name across all skill directories.-- Searches the local skills dir (~/.hermes/skills/) first, then any- external dirs configured via skills.external_dirs. Returns- {"path": Path} or None.-- Accepts both the bare directory name (``axolotl``) and the categorized- relative path (``mlops/axolotl``) — the same two forms skill_view- resolves, and the form skill_view's ambiguity hint explicitly tells- the caller to use. The bare-name match compares the skill's own- directory name (``parent.name``), so bare lookups keep working for- category-nested skills.- """- from agent.skill_utils import get_all_skills_dirs, is_excluded_skill_path-- # Resolve the local skills root once — the categorized form matches the- # skill dir's path RELATIVE to that root. Only computed lazily (bare-name- # lookups never need it) and never for external dirs (relative_to raises).- _resolved_root: Optional[Path] = None-- def _local_root() -> Path:- nonlocal _resolved_root- if _resolved_root is None:- try:- _resolved_root = _skills_dir().resolve()- except OSError:- logger.debug(- "skills dir resolve failed; categorized lookups fall back to the unresolved path",- exc_info=True,- )- _resolved_root = _skills_dir()- return _resolved_root+ from agent.skill_utils import get_all_skills_dirs++ # The categorized form matches the skill dir RELATIVE to the local root+ # (never external dirs — relative_to raises there).+ local_root = None+ if "/" in name or "\\" in name:+ try:+ local_root = _skills_dir().resolve()+ except OSError:+ logger.debug(+ "skills dir resolve failed; categorized lookups fall back to the unresolved path",+ exc_info=True,+ )+ local_root = _skills_dir()for skills_dir in get_all_skills_dirs():if not skills_dir.exists():continue- for skill_md in skills_dir.rglob("SKILL.md"):- if is_excluded_skill_path(skill_md):- continue- # Fast path first: the bare directory name. Avoids the resolve()- # machinery entirely on the common match.- if skill_md.parent.name == name:- return {"path": skill_md.parent}- # Categorized form (``category/skill-name``): compare the skill- # dir's POSIX relative path so the lookup works on Windows too.- if "/" in name or "\\" in name:+ for skill_dir in _iter_skill_dirs(skills_dir):+ if skill_dir.name == name:+ return {"path": skill_dir}+ if local_root is not None:try:- rel = skill_md.parent.resolve().relative_to(_local_root())+ rel = skill_dir.resolve().relative_to(local_root)except ValueError:continue- if rel.as_posix() == name:- return {"path": skill_md.parent}- return None---def _maybe_auto_propose_org_edit(name: str, skill_path: Path) -> Optional[str]:- """Submit an org-skill edit upstream when `sync.org_auto_propose` is on.-- Returns a short note for the tool result, or None when nothing happened.- Never raises: an offline/failed submission must not fail the edit itself —- the change is already saved locally and can be proposed later.- """- try:- from agent.skill_utils import is_org_mirror_path- from tools import skills_sync_client as ssc-- if not is_org_mirror_path(skill_path, _skills_dir()):- return None- if not ssc.sync_org_auto_propose():- return (- f"This skill is shared by your organisation. Your edit is "- f"saved locally and will not be overwritten by org updates. "- f"Run `hermes sync propose {name}` to share it back."- )- result = ssc.propose_skill(name)- if result.get("proposal_pending"):- return (- f"Auto-proposed to your organisation as proposal "- f"#{result.get('proposal_id')} (pending admin review)."- )- return "Auto-proposed to your organisation (merged into the shared set)."- except Exception as e:- logger.debug("auto-propose skipped for %s: %s", name, e)- return (- f"Edit saved locally. Could not submit it to your organisation "- f"right now — run `hermes sync propose {name}` to retry."- )---def _org_mirror_write_guard(name: str, skill_path: Path, action: str) -> Optional[Dict[str, Any]]:- """Org-shared skills are EDITABLE IN PLACE — this only blocks deletion.-- Earlier versions refused every write to `_org/`, which broke the learning- loop exactly where it matters most: the agent is told to patch a skill the- moment it finds a gap, and shared skills are the ones the most people use.- Blocking that froze org skills while personal ones kept improving, and the- "fork it into a personal skill" alternative is not something an agent does- mid-task — so improvements were simply lost.-- Now an edit lands in the mirror and is protected from being overwritten by- the next org pull (see the baseline sidecar in skills_sync_client). It- reaches the organisation when the user runs `hermes sync propose`, or- immediately if `sync.org_auto_propose` is on.-- Deletion is still refused: the mirror is a materialized view of the org- HEAD, so a local delete is meaningless (the next pull restores it) and- removing a skill for the organisation is an admin action, not a local one.- """- if action not in {"delete", "remove_file"}:- return None- try:- from agent.skill_utils import is_org_mirror_path-- if is_org_mirror_path(skill_path, _skills_dir()):- return {- "success": False,- "error": (- f"Cannot {action} '{name}' locally: it is shared by your "- "organisation, so a local delete would just come back on "- "the next sync. Ask an org admin to remove it for "- "everyone. (Editing it IS allowed — your changes are kept "- "and can be proposed back with `hermes sync propose "- f"{name}`.)"- ),- }- except Exception:- logger.debug("org mirror guard lookup failed for %s", name, exc_info=True)+ if rel.as_posix() == name: # POSIX form so it works on Windows too+ return {"path": skill_dir}return Nonedef _find_skill_in_other_profiles(name: str) -> List[Tuple[str, Path]]:- """Look for ``name`` under SKILL.md across OTHER Hermes profiles.+ """``(profile_name, skill_dir)`` pairs for OTHER profiles holding ``name``.- Returns a list of ``(profile_name, skill_dir)`` pairs. Used to make- the "Skill X not found" error explain when the user is editing the- wrong profile. Empty list when no other profile has the skill (or- when profile discovery fails — fail-quiet, the caller falls back to- the plain "not found" error).+ Lets the "not found" error explain a wrong-profile mistake. Fail-quiet:+ empty list when discovery fails."""matches: List[Tuple[str, Path]] = []try:from hermes_constants import get_default_hermes_root- from agent.skill_utils import is_excluded_skill_path- except Exception:- return matches-- try:root = get_default_hermes_root()except Exception:return matches- # Collect (profile_name, skills_dir) for every profile EXCEPT the- # one whose skills dir we already searched in _find_skill()._active = _skills_dir()active_dir = _active.resolve() if _active.exists() else _active- candidates: List[Tuple[str, Path]] = []- # Default profile (~/.hermes/skills) — only consider when active is non-default.- default_skills = root / "skills"+ # Every profile's skills dir EXCEPT the active one (already searched).+ candidates: List[Tuple[str, Path]] = [("default", root / "skills")]+ profiles_root = root / "profiles"try:- if default_skills.resolve() != active_dir:- candidates.append(("default", default_skills))- except (OSError, RuntimeError):+ if profiles_root.is_dir():+ candidates += [(e.name, e / "skills") for e in profiles_root.iterdir() if e.is_dir()]+ except OSError:pass- # All named profiles (~/.hermes/profiles/*/skills)- profiles_root = root / "profiles"- if profiles_root.is_dir():- try:- for entry in profiles_root.iterdir():- if not entry.is_dir():- continue- pskills = entry / "skills"- try:- if pskills.resolve() == active_dir:- continue- except (OSError, RuntimeError):- continue- candidates.append((entry.name, pskills))- except OSError:- pass-for profile_name, skills_dir in candidates:- if not skills_dir.is_dir():- continuetry:- for skill_md in skills_dir.rglob("SKILL.md"):- if is_excluded_skill_path(skill_md):- continue- if skill_md.parent.name == name:- matches.append((profile_name, skill_md.parent))+ if skills_dir.resolve() == active_dir or not skills_dir.is_dir():+ continue+ for skill_dir in _iter_skill_dirs(skills_dir):+ if skill_dir.name == name:+ matches.append((profile_name, skill_dir))break # one match per profile is enough- except OSError:+ except (OSError, RuntimeError):continuereturn matchesdef _skill_not_found_error(name: str, suffix: str = "") -> str:- """Build a "skill not found" error that names other profiles holding- the same skill, so the agent can recognize a profile-scoping mistake.-- ``suffix`` is appended after the cross-profile hint if present- (e.g. ``" Create it first with action='create'."``).- """+ """"Skill not found" error naming other profiles that hold the skill;+ ``suffix`` is appended after the hint."""from agent.file_safety import _resolve_active_profile_nameactive = _resolve_active_profile_name()base = f"Skill '{name}' not found in active profile '{active}'."others = _find_skill_in_other_profiles(name)- if others:- if len(others) == 1:- other_profile, other_path = others[0]- base += (- f" A skill by that name exists in profile "- f"'{other_profile}' ({other_path}). To edit it, switch "- f"profiles (`hermes -p {other_profile}`) or edit the file "- f"directly (file tools / terminal)."- )- else:- names = ", ".join(f"'{p}'" for p, _ in others)- base += (- f" Skills by that name exist in other profiles: {names}. "- f"Switch profiles (`hermes -p <name>`) to edit there, or "- f"edit the files directly (file tools / terminal)."- )+ if len(others) == 1:+ other_profile, other_path = others[0]+ base += (+ f" A skill by that name exists in profile "+ f"'{other_profile}' ({other_path}). To edit it, switch "+ f"profiles (`hermes -p {other_profile}`) or edit the file "+ f"directly (file tools / terminal)."+ )+ elif others:+ names = ", ".join(f"'{p}'" for p, _ in others)+ base += (+ f" Skills by that name exist in other profiles: {names}. "+ f"Switch profiles (`hermes -p <name>`) to edit there, or "+ f"edit the files directly (file tools / terminal)."+ )else:base += " Use skills_list() to see available skills."-- if suffix:- base += suffix- return base+ return base + suffixdef _validate_file_path(file_path: str) -> Optional[str]:- """- Validate a file path for write_file/remove_file.- Must be under an allowed subdirectory and not escape the skill dir.- """+ """Validate a write_file/remove_file path: under an allowed subdir, no escape."""from tools.path_security import has_traversal_componentif not file_path:return "file_path is required."-normalized = Path(file_path)-- # Prevent path traversal (checked before any allow-listing so the SKILL.md- # exception below can never be reached by a traversal-laden path).+ # Traversal is checked before any allow-listing so the SKILL.md exception+ # can never be reached by a traversal-laden path.if has_traversal_component(file_path):return "Path traversal ('..') is not allowed."-- # SKILL.md is the canonical skill file and lives at the skill root, not- # under an allowed subdirectory. Accept its two natural spellings —- # 'SKILL.md' and '<skill-name>/SKILL.md' — so callers can target the main- # file. The traversal guard above still applies, so this can't escape.- if normalized.parts and normalized.name == "SKILL.md":- if len(normalized.parts) == 1 or len(normalized.parts) == 2:- return None-- # Must be under an allowed subdirectory+ # SKILL.md lives at the skill root; accept 'SKILL.md' and '<skill>/SKILL.md'.+ if normalized.name == "SKILL.md" and len(normalized.parts) in (1, 2):+ return Noneif not normalized.parts or normalized.parts[0] not in ALLOWED_SUBDIRS:allowed = ", ".join(sorted(ALLOWED_SUBDIRS))return f"File must be under one of: {allowed}. Got: '{file_path}'"-- # Must have a filename (not just a directory)if len(normalized.parts) < 2:return f"Provide a file path, not just a directory. Example: '{normalized.parts[0]}/myfile.md'"-return None@@ -981,11 +402,59 @@ def _resolve_skill_target(skill_dir: Path, file_path: str) -> Tuple[Optional[Pattarget = skill_dir / file_patherror = validate_within_dir(target, skill_dir)- if error:- return None, error+ return (None, error) if error else (target, None)+++def _resolve_supporting_file(skill_dir: Path, file_path: str):+ """``_validate_file_path`` + ``_resolve_skill_target``. Returns (target, None) or (None, error_dict)."""+ err = _validate_file_path(file_path)+ if err:+ return None, _err(err)+ target, err = _resolve_skill_target(skill_dir, file_path)+ if err:+ return None, _err(err)return target, None+def _locate_for_write(name: str, action: str, not_found_suffix: str = ""):+ """Find the skill and run the org-mirror + background-review write guards.++ Returns ``(skill_dir, None)`` or ``(None, error_dict)``.+ """+ existing = _find_skill(name)+ if not existing:+ return None, _err(_skill_not_found_error(name, not_found_suffix))+ skill_dir = existing["path"]+ guard = (+ _org_mirror_write_guard(name, skill_dir, action)+ or _background_review_write_guard(name, skill_dir, action)+ )+ if guard:+ return None, guard+ return skill_dir, None+++def _write_scanned(target: Path, content: str, skill_dir: Path,+ original: Optional[str]) -> Optional[str]:+ """Atomically write ``content``, then security-scan the skill; on block,+ restore ``original`` (or unlink a newly created file) and return the error."""+ atomic_write_text(target, content, preserve_mode=True, create_mode=0o644)+ scan_error = _security_scan_skill(skill_dir)+ if scan_error:+ if original is not None:+ atomic_write_text(target, original, preserve_mode=True)+ else:+ target.unlink(missing_ok=True)+ return scan_error+++def _attach_org_note(result: Dict[str, Any], name: str, skill_dir: Path) -> None:+ org_note = _maybe_auto_propose_org_edit(name, skill_dir)+ if org_note:+ result["org_sharing"] = org_note+ result["message"] = f"{result['message']} {org_note}"++# =============================================================================# Core actions# =============================================================================@@ -1002,71 +471,61 @@ def _add_description_prompt_preview(result: Dict[str, Any], content: str) -> Non)-def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Any]:- """Create a new user skill with SKILL.md content."""- # Validate name- err = _validate_name(name)- if err:- return {"success": False, "error": err}+def _attach_lint_findings(result: Dict[str, Any], skill_md: Path) -> None:+ """Attach ADVISORY skill-authoring-convention findings (never a hard block;+ hard rejects already ran in _validate_frontmatter)."""+ try:+ from tools.skill_linter import lint_skill # local import: optional path- err = _validate_category(category)- if err:- return {"success": False, "error": err}+ findings = lint_skill(skill_md)+ except Exception:+ return+ if not findings:+ return+ result["lint_warnings"] = [+ {"severity": f.severity, "rule": f.rule, "message": f.message}+ for f in findings+ ]+ result["lint_hint"] = (+ "The skill was created. These are advisory authoring-convention "+ "findings (not blockers) — fix them with skill_manage(action='patch') "+ "to match Hermes skill standards."+ )- # Validate content- err = _validate_frontmatter(content, new_skill=True)- if err:- return {"success": False, "error": err}- err = _validate_content_size(content)+def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Any]:+ """Create a new user skill with SKILL.md content."""+ err = (+ _validate_name(name)+ or _validate_category(category)+ or _validate_frontmatter(content, new_skill=True)+ or _validate_content_size(content)+ )if err:- return {"success": False, "error": err}-- # Check for name collisions across all directories+ return _err(err)existing = _find_skill(name)if existing:- return {- "success": False,- "error": f"A skill named '{name}' already exists at {existing['path']}."- }+ return _err(f"A skill named '{name}' already exists at {existing['path']}.")- # Create the skill directoryskill_dir = _resolve_skill_dir(name, category)skill_dir.mkdir(parents=True, exist_ok=True)-- # Write instructional documents with a readable mode while preserving- # the mode of an existing file across the atomic replacement.skill_md = skill_dir / "SKILL.md"atomic_write_text(skill_md, content, preserve_mode=True, create_mode=0o644)-- # Security scan — roll back on blockscan_error = _security_scan_skill(skill_dir)if scan_error:shutil.rmtree(skill_dir, ignore_errors=True)- return {"success": False, "error": scan_error}-- # Extract description from frontmatter for verbose notifications- _desc = ""- try:- _fm_end = re.search(r'\n---\s*\n', content[3:])- if _fm_end:- _parsed = yaml.safe_load(content[3:_fm_end.start() + 3])- _desc = str(_parsed.get("description", ""))[:120]- except Exception:- pass+ return _err(scan_error)try:_display_path = str(skill_dir.relative_to(_skills_dir()))except ValueError:- # Skill created under skills.create_dir — not relative to the- # profile-local root, so show the absolute path.- _display_path = str(skill_dir)+ _display_path = str(skill_dir) # created under skills.create_dirresult = {"success": True,"message": f"Skill '{name}' created.","path": _display_path,"skill_md": str(skill_md),- "_change": {"description": _desc},+ "_change": {"description": _description_preview(content)},}if category:result["category"] = category@@ -1079,92 +538,32 @@ def _create_skill(name: str, content: str, category: str = None) -> Dict[str, Anreturn result-def _attach_lint_findings(result: Dict[str, Any], skill_md: Path) -> None:- """Run the advisory SKILL.md linter and attach any findings to *result*.-- The linter enforces the CONTRIBUTING "Skill authoring standards (HARDLINE)"- conventions that the hard validator does not (shell-utility references,- missing metadata, dangling reference links, POSIX gating, forbidden files).- Findings are ADVISORY — surfaced as guidance so the author can fix them,- never a hard block. The hard rejects already ran in _validate_frontmatter.- """- try:- from tools.skill_linter import lint_skill # local import: optional path-- findings = lint_skill(skill_md)- except Exception:- return- if not findings:- return- result["lint_warnings"] = [- {"severity": f.severity, "rule": f.rule, "message": f.message}- for f in findings- ]- result["lint_hint"] = (- "The skill was created. These are advisory authoring-convention "- "findings (not blockers) — fix them with skill_manage(action='patch') "- "to match Hermes skill standards."- )--def _edit_skill(name: str, content: str) -> Dict[str, Any]:"""Replace the SKILL.md of any existing skill (full rewrite)."""- err = _validate_frontmatter(content)- if err:- return {"success": False, "error": err}-- err = _validate_content_size(content)+ err = _validate_frontmatter(content) or _validate_content_size(content)if err:- return {"success": False, "error": err}-- existing = _find_skill(name)- if not existing:- return {"success": False, "error": _skill_not_found_error(name)}- org_guard = _org_mirror_write_guard(name, existing["path"], "edit")- if org_guard:- return org_guard- guard = _background_review_write_guard(name, existing["path"], "edit")+ return _err(err)+ skill_dir, guard = _locate_for_write(name, "edit")if guard:return guard-- skill_md = existing["path"] / "SKILL.md"- read_guard = _background_review_read_before_write_guard(- name, skill_md, "edit", "SKILL.md"- )+ skill_md = skill_dir / "SKILL.md"+ read_guard = _background_review_read_before_write_guard(name, skill_md, "edit", "SKILL.md")if read_guard:return read_guard- # Back up original content for rollback+ # SKILL.md always exists here (_find_skill requires it), so a blocked scan restores it.original_content = skill_md.read_text(encoding="utf-8") if skill_md.exists() else None- atomic_write_text(skill_md, content, preserve_mode=True, create_mode=0o644)-- # Security scan — roll back on block- scan_error = _security_scan_skill(existing["path"])+ scan_error = _write_scanned(skill_md, content, skill_dir, original_content)if scan_error:- if original_content is not None:- atomic_write_text(skill_md, original_content, preserve_mode=True)- return {"success": False, "error": scan_error}-- # Extract description from new content for verbose notifications- _desc = ""- try:- _fm_end = re.search(r'\n---\s*\n', content[3:])- if _fm_end:- _parsed = yaml.safe_load(content[3:_fm_end.start() + 3])- _desc = str(_parsed.get("description", ""))[:120]- except Exception:- pass+ return _err(scan_error)result = {"success": True,"message": f"Skill '{name}' updated (full rewrite).",- "path": str(existing["path"]),- "_change": {"description": _desc},+ "path": str(skill_dir),+ "_change": {"description": _description_preview(content)},}- org_note = _maybe_auto_propose_org_edit(name, existing["path"])- if org_note:- result["org_sharing"] = org_note- result["message"] = f"{result['message']} {org_note}"+ _attach_org_note(result, name, skill_dir)_add_description_prompt_preview(result, content)return result@@ -1176,311 +575,183 @@ def _patch_skill(file_path: str = None,replace_all: bool = False,) -> Dict[str, Any]:- """Targeted find-and-replace within a skill file.-- Defaults to SKILL.md. Use file_path to patch a supporting file instead.- Requires a unique match unless replace_all is True.- """+ """Targeted find-and-replace within SKILL.md (default) or a supporting file.+ Requires a unique match unless replace_all is True."""if not old_string:- # A bare "required" error is a dead end: the model cannot tell whether it- # omitted the arg or supplied it wrongly, so it retries blindly and often- # escapes to action='write_file', clobbering the whole skill file. Tell it- # how to recover. Upstream: NousResearch/hermes-agent#33064.- return {- "success": False,- "error": (- "old_string is required for 'patch' and must be the EXACT text currently in the "- "file. Read the target file first (read_file on the skill's SKILL.md, or the file "- "named by file_path) and copy the snippet verbatim, then retry 'patch'. "- "Do NOT fall back to action='write_file' — that rewrites the entire file and "- "destroys unrelated content."- ),- }+ # A bare "required" error is a dead end: the model retries blindly and+ # often escapes to action='write_file', clobbering the whole file.+ return _err(+ "old_string is required for 'patch' and must be the EXACT text currently in the "+ "file. Read the target file first (read_file on the skill's SKILL.md, or the file "+ "named by file_path) and copy the snippet verbatim, then retry 'patch'. "+ "Do NOT fall back to action='write_file' — that rewrites the entire file and "+ "destroys unrelated content."+ )if new_string is None:- return {"success": False, "error": "new_string is required for 'patch'. Use an empty string to delete matched text."}- # No old_string == new_string guard here: fuzzy_find_and_replace already- # rejects that with "old_string and new_string are identical"- # (tools/fuzzy_match.py), and its error carries a file_preview this layer- # cannot produce. Duplicating it here would only shadow the richer message.+ return _err("new_string is required for 'patch'. Use an empty string to delete matched text.")+ # No old_string == new_string guard here: fuzzy_find_and_replace rejects+ # that with a richer error (file_preview) this layer cannot produce.- existing = _find_skill(name)- if not existing:- return {"success": False, "error": _skill_not_found_error(name)}-- skill_dir = existing["path"]- org_guard = _org_mirror_write_guard(name, skill_dir, "patch")- if org_guard:- return org_guard- guard = _background_review_write_guard(name, skill_dir, "patch")+ skill_dir, guard = _locate_for_write(name, "patch")if guard:return guardif file_path:- # Patching a supporting file- err = _validate_file_path(file_path)+ target, err = _resolve_supporting_file(skill_dir, file_path)if err:- return {"success": False, "error": err}- target, err = _resolve_skill_target(skill_dir, file_path)- if err:- return {"success": False, "error": err}- assert target is not None+ return errelse:- # Patching SKILL.mdtarget = skill_dir / "SKILL.md"-if not target.exists():- return {"success": False, "error": f"File not found: {target.relative_to(skill_dir)}"}+ return _err(f"File not found: {target.relative_to(skill_dir)}")- read_guard = _background_review_read_before_write_guard(- name,- target,- "patch",- "SKILL.md" if not file_path else file_path,- )+ target_label = file_path or "SKILL.md"+ read_guard = _background_review_read_before_write_guard(name, target, "patch", target_label)if read_guard:return read_guardcontent = target.read_text(encoding="utf-8")-- # Use the same fuzzy matching engine as the file patch tool.- # This handles whitespace normalization, indentation differences,- # escape sequences, and block-anchor matching — saving the agent- # from exact-match failures on minor formatting mismatches.+ # Same fuzzy engine as the file patch tool (whitespace/indent/escape+ # normalization, block anchors) so minor formatting mismatches don't fail.from tools.fuzzy_match import fuzzy_find_and_replacenew_content, match_count, _strategy, match_error = fuzzy_find_and_replace(content, old_string, new_string, replace_all)if match_error:- # Show a short preview of the file so the model can self-correct- preview = content[:500] + ("..." if len(content) > 500 else "")- err_msg = match_errortry:from tools.fuzzy_match import format_no_match_hint- err_msg += format_no_match_hint(match_error, match_count, old_string, content)+ match_error += format_no_match_hint(match_error, match_count, old_string, content)except Exception:pass- return {- "success": False,- "error": err_msg,- "file_preview": preview,- }+ return _err(match_error) | {"file_preview": content[:500] + ("..." if len(content) > 500 else "")}- # Check size limit on the result- target_label = "SKILL.md" if not file_path else file_patherr = _validate_content_size(new_content, label=target_label)if err:- return {"success": False, "error": err}-- # If patching SKILL.md, validate frontmatter is still intact+ return _err(err)if not file_path:err = _validate_frontmatter(new_content)if err:- return {- "success": False,- "error": f"Patch would break SKILL.md structure: {err}",- }+ return _err(f"Patch would break SKILL.md structure: {err}")- original_content = content # for rollback- atomic_write_text(target, new_content, preserve_mode=True, create_mode=0o644)-- # Security scan — roll back on block- scan_error = _security_scan_skill(skill_dir)+ scan_error = _write_scanned(target, new_content, skill_dir, content)if scan_error:- atomic_write_text(target, original_content, preserve_mode=True)- return {"success": False, "error": scan_error}+ return _err(scan_error)result = {"success": True,- "message": f"Patched {'SKILL.md' if not file_path else file_path} in skill '{name}' ({match_count} replacement{'s' if match_count > 1 else ''}).",- }- # Include change previews for verbose notifications- result["_change"] = {- "old": old_string[:200] + ("…" if len(old_string) > 200 else ""),- "new": new_string[:200] + ("…" if len(new_string) > 200 else ""),+ "message": f"Patched {target_label} in skill '{name}' ({match_count} replacement{'s' if match_count > 1 else ''}).",+ "_change": {+ "old": old_string[:200] + ("…" if len(old_string) > 200 else ""),+ "new": new_string[:200] + ("…" if len(new_string) > 200 else ""),+ },}- org_note = _maybe_auto_propose_org_edit(name, skill_dir)- if org_note:- result["org_sharing"] = org_note- result["message"] = f"{result['message']} {org_note}"+ _attach_org_note(result, name, skill_dir)return resultdef _delete_skill(name: str, absorbed_into: Optional[str] = None) -> Dict[str, Any]:"""Delete a skill.- ``absorbed_into`` declares intent:- - ``None`` / missing → caller didn't declare (legacy / non-curator path);- accepted for backward compat but logs a warning because the curator- classification pipeline can't tell consolidation from pruning without it.- - ``""`` (empty) → explicit "truly pruned, no forwarding target".- - ``"<skill-name>"`` → content was absorbed into that umbrella; the- target must exist on disk. Validated here so the model can't claim an- umbrella that doesn't exist.+ ``absorbed_into``: ``None`` = undeclared (legacy path, accepted);+ ``""`` = explicit prune with no forwarding target; ``"<skill>"`` = content+ absorbed into that umbrella, which must exist on disk (validated here so+ the model can't claim a nonexistent umbrella)."""- existing = _find_skill(name)- if not existing:- return {"success": False, "error": _skill_not_found_error(name)}- org_guard = _org_mirror_write_guard(name, existing["path"], "delete")- if org_guard:- return org_guard- guard = _background_review_write_guard(name, existing["path"], "delete")+ skill_dir, guard = _locate_for_write(name, "delete")if guard:return guard-- # Fail closed on unverified deletes during the curator consolidation pass.- # A bare prune (no absorbed_into) from the LLM umbrella pass is the- # fail-open behavior reported in #29912 — refuse it; keep the skill active.fail_closed = _curator_consolidation_delete_guard(name, absorbed_into)if fail_closed:return fail_closed-pinned_err = _pinned_guard(name)if pinned_err:- return {"success": False, "error": pinned_err}+ return _err(pinned_err)- # Validate absorbed_into target when declared non-empty- absorbed_target = (- absorbed_into.strip()- if absorbed_into is not None and isinstance(absorbed_into, str)- else ""- )+ absorbed_target = absorbed_into.strip() if isinstance(absorbed_into, str) else ""is_consolidation = bool(absorbed_target)if is_consolidation:- target_name = absorbed_target- if target_name == name:- return {- "success": False,- "error": f"absorbed_into='{target_name}' cannot equal the skill being deleted.",- }- target = _find_skill(target_name)- if not target:- return {- "success": False,- "error": (- f"absorbed_into='{target_name}' does not exist. "- f"Create or patch the umbrella skill first, then retry the delete."- ),- }+ if absorbed_target == name:+ return _err(f"absorbed_into='{absorbed_target}' cannot equal the skill being deleted.")+ if not _find_skill(absorbed_target):+ return _err(+ f"absorbed_into='{absorbed_target}' does not exist. "+ f"Create or patch the umbrella skill first, then retry the delete."+ )- skill_dir = existing["path"]skills_root = _containing_skills_root(skill_dir)-- # Defense-in-depth before the recursive delete (port of Kilo Code #11240).- unsafe = _validate_delete_target(skill_dir)+ unsafe = _validate_delete_target(skill_dir) # defense-in-depth before rmtreeif unsafe:- return {"success": False, "error": unsafe}-- # During the curator consolidation pass, a verified consolidation must be- # RECOVERABLE: archival into ~/.hermes/skills/.archive/ is documented as- # the maximum destructive action the curator may take, and- # `hermes curator restore` promises the skill can be brought back. Route- # through the recoverable archive primitive instead of permanent rmtree so- # a misjudged consolidation can be undone (#29912). Foreground,- # user-directed deletes keep their existing hard-delete semantics.- try:- from tools.skill_provenance import is_background_review- curator_pass = is_background_review()- except Exception:- curator_pass = False+ return _err(unsafe)- if curator_pass:+ # During the curator consolidation pass a verified consolidation must be+ # RECOVERABLE (`hermes curator restore`), so route through the archive+ # primitive instead of rmtree. Foreground deletes keep hard-delete semantics.+ absorbed_note = f" Content absorbed into '{absorbed_target}'." if is_consolidation else ""+ if _is_background_review():try:from tools.skill_usage import archive_skillok, archive_msg = archive_skill(name)except Exception as e:- return {"success": False, "error": f"failed to archive '{name}': {e}"}+ return _err(f"failed to archive '{name}': {e}")if not ok:- return {"success": False, "error": archive_msg}- message = f"Skill '{name}' archived ({archive_msg})."- if is_consolidation:- message += f" Content absorbed into '{absorbed_target}'."- return {"success": True, "message": message, "_archived": True}+ return _err(archive_msg)+ return {+ "success": True,+ "message": f"Skill '{name}' archived ({archive_msg}).{absorbed_note}",+ "_archived": True,+ }shutil.rmtree(skill_dir)+ _rmdir_if_empty(skill_dir.parent, skills_root) # empty category dir, never the root+ return {"success": True, "message": f"Skill '{name}' deleted.{absorbed_note}"}- # Clean up empty category directories (don't remove the skills root itself)- parent = skill_dir.parent- if parent != skills_root and parent.exists() and not any(parent.iterdir()):- parent.rmdir()-- message = f"Skill '{name}' deleted."- if is_consolidation:- message += f" Content absorbed into '{absorbed_target}'."- return {- "success": True,- "message": message,- }+def _rmdir_if_empty(parent: Path, stop: Path) -> None:+ if parent != stop and parent.exists() and not any(parent.iterdir()):+ parent.rmdir()def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:"""Add or overwrite a supporting file within any skill directory."""err = _validate_file_path(file_path)if err:- return {"success": False, "error": err}-+ return _err(err)if not file_content and file_content != "":- return {"success": False, "error": "file_content is required."}-- # Check size limits+ return _err("file_content is required.")content_bytes = len(file_content.encode("utf-8"))if content_bytes > MAX_SKILL_FILE_BYTES:- return {- "success": False,- "error": (- f"File content is {content_bytes:,} bytes "- f"(limit: {MAX_SKILL_FILE_BYTES:,} bytes / 1 MiB). "- f"Consider splitting into smaller files."- ),- }+ return _err(+ f"File content is {content_bytes:,} bytes "+ f"(limit: {MAX_SKILL_FILE_BYTES:,} bytes / 1 MiB). "+ f"Consider splitting into smaller files."+ )err = _validate_content_size(file_content, label=file_path)if err:- return {"success": False, "error": err}+ return _err(err)- existing = _find_skill(name)- if not existing:- return {"success": False, "error": _skill_not_found_error(name, " Create it first with action='create'.")}- org_guard = _org_mirror_write_guard(name, existing["path"], "write_file")- if org_guard:- return org_guard- guard = _background_review_write_guard(name, existing["path"], "write_file")+ skill_dir, guard = _locate_for_write(name, "write_file", " Create it first with action='create'.")if guard:return guard-- target, err = _resolve_skill_target(existing["path"], file_path)+ target, err = _resolve_supporting_file(skill_dir, file_path)if err:- return {"success": False, "error": err}- assert target is not None+ return errif target.exists():- read_guard = _background_review_read_before_write_guard(- name, target, "write_file", file_path- )+ read_guard = _background_review_read_before_write_guard(name, target, "write_file", file_path)if read_guard:return read_guardtarget.parent.mkdir(parents=True, exist_ok=True)- # Back up for rollbackoriginal_content = target.read_text(encoding="utf-8") if target.exists() else None- atomic_write_text(target, file_content, preserve_mode=True, create_mode=0o644)-- # Security scan — roll back on block- scan_error = _security_scan_skill(existing["path"])+ scan_error = _write_scanned(target, file_content, skill_dir, original_content)if scan_error:- if original_content is not None:- atomic_write_text(target, original_content, preserve_mode=True)- else:- target.unlink(missing_ok=True)- return {"success": False, "error": scan_error}+ return _err(scan_error)result = {"success": True,"message": f"File '{file_path}' written to skill '{name}'.","path": str(target),}- org_note = _maybe_auto_propose_org_edit(name, existing["path"])- if org_note:- result["org_sharing"] = org_note- result["message"] = f"{result['message']} {org_note}"+ _attach_org_note(result, name, skill_dir)return result@@ -1488,98 +759,68 @@ def _remove_file(name: str, file_path: str) -> Dict[str, Any]:"""Remove a supporting file from any skill directory."""err = _validate_file_path(file_path)if err:- return {"success": False, "error": err}-+ return _err(err)existing = _find_skill(name)if not existing:- return {"success": False, "error": _skill_not_found_error(name)}-+ return _err(_skill_not_found_error(name))skill_dir = existing["path"]guard = _background_review_write_guard(name, skill_dir, "remove_file")if guard:return guard- target, err = _resolve_skill_target(skill_dir, file_path)+ target, err = _resolve_supporting_file(skill_dir, file_path)if err:- return {"success": False, "error": err}- assert target is not None+ return errif not target.exists():- # List what's actually there for the model to see- available = []- for subdir in ALLOWED_SUBDIRS:- d = skill_dir / subdir- if d.exists():- for f in d.rglob("*"):- if f.is_file():- available.append(str(f.relative_to(skill_dir)))+ available = [+ str(f.relative_to(skill_dir))+ for subdir in ALLOWED_SUBDIRS+ if (skill_dir / subdir).exists()+ for f in (skill_dir / subdir).rglob("*")+ if f.is_file()+ ]return {"success": False,"error": f"File '{file_path}' not found in skill '{name}'.","available_files": available if available else None,}-- read_guard = _background_review_read_before_write_guard(- name, target, "remove_file", file_path- )+ read_guard = _background_review_read_before_write_guard(name, target, "remove_file", file_path)if read_guard:return read_guardtarget.unlink()-- # Clean up empty subdirectories- parent = target.parent- if parent != skill_dir and parent.exists() and not any(parent.iterdir()):- parent.rmdir()-- return {- "success": True,- "message": f"File '{file_path}' removed from skill '{name}'.",- }+ _rmdir_if_empty(target.parent, skill_dir)+ return {"success": True, "message": f"File '{file_path}' removed from skill '{name}'."}# =============================================================================# Main entry point# =============================================================================-# ContextVar bypass: set while replaying an already-approved staged skill write-# so skill_manage() does not re-gate (and re-stage) it.-import contextvars as _ctxvars+# Set while replaying an already-approved staged skill write so skill_manage()+# does not re-gate (and re-stage) it._skill_gate_bypass: "_ctxvars.ContextVar[bool]" = _ctxvars.ContextVar("skill_gate_bypass", default=False)+_GATED_ACTIONS = {"create", "edit", "patch", "delete", "write_file", "remove_file"}-def _apply_skill_write_gate(action, name, **payload_kwargs):- """Evaluate the skill write gate. Returns a JSON tool-result string when the- write should NOT proceed (blocked or staged), or None to perform the real- write. Bypassed during approved-pending replay.- """- if action not in {"create", "edit", "patch", "delete", "write_file", "remove_file"}:- return None- if _skill_gate_bypass.get():- return None+def _run_write_gate(build_staging):+ """Shared write-gate evaluation. Returns None to proceed, or a JSON tool+ result when blocked/staged. ``build_staging(wa)`` -> (payload, gist) is+ only called when the decision is to stage. Fails open if write_approval+ cannot be imported."""try:from tools import write_approval as waexcept Exception:return None # fail open-decision = wa.evaluate_gate(wa.SKILLS)if decision.allow:return Noneif decision.blocked:return tool_error(decision.message, success=False)-- # stage — record the full skill_manage kwargs so approval can replay it.- payload = {"action": action, "name": name}- payload.update({k: v for k, v in payload_kwargs.items() if v is not None})- gist = wa.skill_gist(- action, name,- content=payload_kwargs.get("content") or "",- file_path=payload_kwargs.get("file_path") or "",- old_string=payload_kwargs.get("old_string") or "",- new_string=payload_kwargs.get("new_string") or "",- )+ payload, gist = build_staging(wa)record = wa.stage_write(wa.SKILLS, payload, summary=gist, origin=wa.current_origin())return json.dumps({"success": True, "staged": True, "pending_id": record["id"],@@ -1588,301 +829,58 @@ def _apply_skill_write_gate(action, name, **payload_kwargs):)-def apply_skill_pending(payload: Dict[str, Any]) -> str:- """Replay a staged skill write, bypassing the gate. Returns the tool result- JSON string. Called by the /skills approve handler.- """- token = _skill_gate_bypass.set(True)- try:- return skill_manage(- action=payload.get("action", ""),- name=payload.get("name", ""),- content=payload.get("content"),- category=payload.get("category"),- file_path=payload.get("file_path"),- file_content=payload.get("file_content"),- old_string=payload.get("old_string"),- new_string=payload.get("new_string"),- replace_all=payload.get("replace_all", False),- absorbed_into=payload.get("absorbed_into"),- operations=payload.get("operations"),+def _apply_skill_write_gate(action, name, **payload_kwargs):+ """Flat-shape write gate: stage the full skill_manage kwargs so approval can+ replay them. Bypassed during approved-pending replay."""+ if action not in _GATED_ACTIONS or _skill_gate_bypass.get():+ return None++ def _staging(wa):+ payload = {"action": action, "name": name}+ payload.update({k: v for k, v in payload_kwargs.items() if v is not None})+ gist = wa.skill_gist(+ action, name,+ content=payload_kwargs.get("content") or "",+ file_path=payload_kwargs.get("file_path") or "",+ old_string=payload_kwargs.get("old_string") or "",+ new_string=payload_kwargs.get("new_string") or "",)- finally:- _skill_gate_bypass.reset(token)+ return payload, gist+ return _run_write_gate(_staging)-_BATCH_OP_ACTIONS = {"create", "patch", "write_file", "remove_file"}-_BATCH_MAX_OPS = 20+_FLAT_OP_KEYS = ("content", "category", "file_path", "file_content",+ "old_string", "new_string")-def _skill_manage_batch(- operations,- default_name: str = None,- task_id: str = None,- session_id: str = None,-) -> str:- """Apply a sequence of operations atomically (memory-tool pattern).-- Each op carries its own ``name`` (skill) and ``action``; a single edit- is a list of one. Every skill the batch touches is snapshotted before- any op runs; any failure rolls ALL touched skills back to their- pre-batch state (skills the batch created are removed).-- Rules:- - ``delete`` only as the SOLE op of the call (its recoverable-archive- path doesn't compose with rollback) — routed to the single-op- handler, preserving absorbed_into/archive semantics;- - ``create`` for a skill must precede that skill's other ops;- - same-file clobber guard (below) rejects silently-lost work.-- ``default_name``: legacy top-level ``name`` fallback for ops that omit- their own (staged-replay / back-compat path).- """- import shutil- import tempfile-- # --- validate shape up front (no side effects before this passes) ---- if not isinstance(operations, list) or not operations:- return tool_error("operations must be a non-empty array.", success=False)- if len(operations) > _BATCH_MAX_OPS:- return tool_error(f"operations is capped at {_BATCH_MAX_OPS} ops per call.", success=False)- # delete: sole-op only; route through the normal single-op path so the- # gate, archive, ledger, and curator absorbed_into semantics all apply.- if any(isinstance(op, dict) and op.get("action") == "delete" for op in operations):- if len(operations) != 1:- return tool_error(- "delete must be the SOLE op in its call — it doesn't "- "compose with other ops' rollback.",- success=False,- )- op = operations[0]- nm = op.get("name") or default_name- if not nm:- return tool_error("operations[0] (delete) needs a 'name'.", success=False)- return skill_manage(- action="delete",- name=nm,- absorbed_into=op.get("absorbed_into"),- task_id=task_id,- session_id=session_id,- )- names = []- for i, op in enumerate(operations):- if not isinstance(op, dict) or not op.get("action"):- return tool_error(f"operations[{i}] needs an 'action'.", success=False)- act = op["action"]- if act not in _BATCH_OP_ACTIONS:- return tool_error(- f"operations[{i}]: unknown action '{act}'. "- f"Batchable: {', '.join(sorted(_BATCH_OP_ACTIONS))}; "- "delete must be sole.",- success=False,- )- nm = op.get("name") or default_name- if not nm:- return tool_error(f"operations[{i}] needs a 'name' (the skill it targets).", success=False)- names.append(nm)- if act == "create" and nm in names[:-1]:- return tool_error(- f"operations[{i}]: create for '{nm}' must precede that "- "skill's other ops.",- success=False,- )- preflight = _background_review_preflight(act, nm)- if preflight is not None:- return json.dumps(preflight, ensure_ascii=False)-- # --- intra-batch conflict guard: sequential last-wins semantics make- # these SILENTLY succeed while discarding earlier ops' work — always a- # confused plan, never intentional. Rule: a DESTRUCTIVE op (write_file,- # remove_file, full SKILL.md rewrite) on a file some earlier op in the- # batch already touched is rejected; ADDITIVE patches are always legal,- # so patch CHAINS (each op building on the previous text) and- # write-then-patch both stay allowed. Paths are normalized so spelling- # variants ('./references/x.md', 'references//x.md') can't slip past. ---- import posixpath-- def _norm_target(op) -> str:- fp = (op.get("file_path") or "").strip()- if not fp:- return "SKILL.md"- return posixpath.normpath(fp.lstrip("/"))-- touched_files = set() # (skill, normalized path) touched by ANY earlier op- for i, op in enumerate(operations):- act = op["action"]- nm = names[i]- # create and full-rewrite patch (content) always hit SKILL.md —- # _edit_skill ignores file_path on the rewrite shape.- full_rewrite = act == "patch" and bool(op.get("content"))- target = "SKILL.md" if (act == "create" or full_rewrite) else _norm_target(op)- key = (nm, target)- destructive = act in ("create", "write_file", "remove_file") or full_rewrite- if destructive and key in touched_files:- return tool_error(- f"operations[{i}]: {act} on '{target}' of skill '{nm}' — an "- "earlier op in this batch already touched that file, and this "- "op would silently discard its work. One destructive op "- "(write_file/remove_file/full rewrite) per file per batch; "- "put it first, or fold the change in. Patch chains are fine.",- success=False,- )- touched_files.add(key)- # --- approval gate: stage the WHOLE batch as one pending write ---- if not _skill_gate_bypass.get():- try:- from tools import write_approval as wa- except Exception:- wa = None # fail open, matching _apply_skill_write_gate- if wa is not None:- decision = wa.evaluate_gate(wa.SKILLS)- if decision.blocked:- return tool_error(decision.message, success=False)- if not decision.allow:- payload = {"action": "batch", "operations": operations}- acts = ", ".join(op["action"] for op in operations)- skills = ", ".join(sorted(set(names)))- gist = f"batch({len(operations)} ops: {acts}) on {skills}"- record = wa.stage_write(- wa.SKILLS, payload, summary=gist, origin=wa.current_origin()- )- return json.dumps(- {"success": True, "staged": True, "pending_id": record["id"],- "gist": gist, "message": decision.message},- ensure_ascii=False,- )-- # --- snapshot every touched skill for rollback ---- snap_root = Path(tempfile.mkdtemp(prefix="skill_batch_"))- snapshots = {} # skill name -> (pre_dir or None, snapshot_dir or None)- for nm in dict.fromkeys(names): # ordered unique- pre = _find_skill(nm)- pre_dir = Path(pre["path"]) if pre else None- snap = None- if pre_dir is not None and pre_dir.is_dir():- snap = snap_root / nm- try:- shutil.copytree(pre_dir, snap)- except Exception as exc: # noqa: BLE001 — no snapshot, no atomicity- shutil.rmtree(snap_root, ignore_errors=True)- return tool_error(f"Could not snapshot '{nm}' for atomic batch: {exc}", success=False)- snapshots[nm] = (pre_dir, snap)-- rollback_failed = False-- def _rollback() -> str:- notes = []- for nm, (pre_dir, snap) in snapshots.items():- try:- post = _find_skill(nm)- post_dir = Path(post["path"]) if post else None- if snap is not None:- if post_dir is not None and post_dir.is_dir():- # Never destroy the only other copy before the- # restore lands. Deleting first turned a failed- # copytree (disk full, locked file) into total- # skill loss once the finally below removed the- # snapshot too. Move the broken state aside, and- # delete it only after the snapshot is back.- aside = post_dir.with_name(post_dir.name + ".rollback-broken")- shutil.rmtree(aside, ignore_errors=True)- post_dir.rename(aside)- try:- shutil.copytree(snap, pre_dir)- except Exception:- # Restore failed: put the broken state back so- # the skill survives (half applied) rather than- # leaving nothing.- shutil.rmtree(pre_dir, ignore_errors=True)- aside.rename(pre_dir)- raise- shutil.rmtree(aside, ignore_errors=True)- else:- shutil.copytree(snap, pre_dir)- elif post_dir is not None and post_dir.is_dir():- # Batch created this skill: remove the partial result.- shutil.rmtree(post_dir)- except Exception as exc: # noqa: BLE001- notes.append(- f"ROLLBACK FAILED for '{nm}' ({exc}); snapshot preserved at '{snap}'"- if snap is not None- else f"ROLLBACK FAILED for '{nm}' ({exc})"- )- nonlocal rollback_failed- rollback_failed = bool(notes)- return "; ".join(notes) if notes else "all touched skills rolled back"-- # --- execute ops through the normal single-op path (gate bypassed:- # the batch already cleared/staged it above; ledger + telemetry- # fire per-op, which is the audit granularity we want) ---- results = []+def _skill_manage_from(payload: Dict[str, Any], **extra) -> str:+ """Call ``skill_manage`` with the flat-shape fields taken from ``payload``."""+ return skill_manage(+ action=payload.get("action", ""),+ name=payload.get("name", ""),+ replace_all=payload.get("replace_all", False),+ **{k: payload.get(k) for k in _FLAT_OP_KEYS},+ **extra,+ )+++def apply_skill_pending(payload: Dict[str, Any]) -> str:+ """Replay a staged skill write, bypassing the gate. Returns the tool result+ JSON string. Called by the /skills approve handler."""token = _skill_gate_bypass.set(True)try:- for i, op in enumerate(operations):- raw = skill_manage(- action=op["action"],- name=names[i],- content=op.get("content"),- category=op.get("category"),- file_path=op.get("file_path"),- file_content=op.get("file_content"),- old_string=op.get("old_string"),- new_string=op.get("new_string"),- replace_all=op.get("replace_all", False),- task_id=task_id,- session_id=session_id,- )- try:- parsed = json.loads(raw)- except Exception: # noqa: BLE001- parsed = {"success": False, "error": "unparseable op result"}- if not parsed.get("success"):- note = _rollback()- fail = {- "success": False,- "error": (- f"operations[{i}] ({op['action']} on '{names[i]}') failed: "- f"{parsed.get('error', 'unknown error')} — batch aborted, {note}."- ),- "failed_index": i,- "completed_before_failure": i,- }- # Carry the failing op's teaching payload through (e.g.- # patch's file_preview / fuzzy-match hints): without it the- # model recovers blind — live A/B showed sonnet probing a- # file with placeholder edits for 8 turns because the batch- # path dropped the preview the flat path always returned.- for k, v in parsed.items():- if k not in ("success", "error") and v is not None:- fail.setdefault(k, v)- return json.dumps(fail, ensure_ascii=False)- results.append({"name": names[i], "action": op["action"],- "file_path": op.get("file_path"),- "success": True})+ return _skill_manage_from(+ payload,+ absorbed_into=payload.get("absorbed_into"),+ operations=payload.get("operations"),+ )finally:_skill_gate_bypass.reset(token)- if rollback_failed:- # Keep the snapshots so the operator can still recover by- # hand. Deleting them here is what turned one failed restore- # into permanent skill loss.- logger.warning(- "skill_manage batch rollback failed, snapshots kept at %s",- snap_root,- )- else:- shutil.rmtree(snap_root, ignore_errors=True)-- return json.dumps(- {"success": True, "operations_applied": len(results),- "results": results},- ensure_ascii=False,- )-# Debounce state for the sync push hook. A burst of skill_manage writes-# (e.g. create + several write_file calls) collapses into a single push after-# a short quiet window, on a daemon timer so the agent write never blocks.+# Debounce state for the sync push hook: a burst of skill_manage writes+# collapses into one push after a quiet window, on a daemon timer._sync_push_timer = None_sync_push_lock = None_SYNC_PUSH_DEBOUNCE_S = 5.0@@ -1891,11 +889,9 @@ _SYNC_PUSH_DEBOUNCE_S = 5.0def _maybe_debounced_sync_push(skill_name: str) -> None:"""Schedule a debounced best-effort sync push after a skill write.- Cheap fast-path: if the skill isn't opted into sync, do nothing (no auth,- no network). Otherwise (re)arm a daemon timer; the actual push runs through- ``skills_sync_client.maybe_push_skills`` which enforces the access gate- and swallows all errors. Never blocks the caller (M1-C: agent never blocks- on sync).+ Fast-path: skills not opted into sync do nothing (no auth, no network).+ The push runs via ``skills_sync_client.maybe_push_skills`` which enforces+ the access gate and swallows errors. Never blocks the caller (M1-C)."""global _sync_push_timer, _sync_push_locktry:@@ -1906,8 +902,6 @@ def _maybe_debounced_sync_push(skill_name: str) -> None:except Exception:return- import threading-if _sync_push_lock is None:_sync_push_lock = threading.Lock()@@ -1921,15 +915,122 @@ def _maybe_debounced_sync_push(skill_name: str) -> None:with _sync_push_lock:if _sync_push_timer is not None:- try:- _sync_push_timer.cancel()- except Exception:- pass+ _sync_push_timer.cancel() # only sets an Event; never raises_sync_push_timer = threading.Timer(_SYNC_PUSH_DEBOUNCE_S, _fire)_sync_push_timer.daemon = True_sync_push_timer.start()+def _act_create(a):+ if not a["content"]:+ return tool_error("content is required for 'create'. Provide the full SKILL.md text (frontmatter + body).", success=False)+ return _create_skill(a["name"], a["content"], a["category"])+++def _act_edit(a):+ # Legacy alias for a full rewrite (old transcripts/callers; not in the schema).+ if not a["content"]:+ return tool_error("content is required for a full rewrite. Provide the full updated SKILL.md text.", success=False)+ return _edit_skill(a["name"], a["content"])+++def _act_patch(a):+ # Two shapes: old_string/new_string = targeted replacement;+ # content (alone) = full SKILL.md rewrite (absorbs the old 'edit').+ if a["content"] and (a["old_string"] or a["new_string"] is not None):+ return tool_error(+ "Pass EITHER content (full SKILL.md rewrite) OR "+ "old_string/new_string (targeted replacement), not both.",+ success=False,+ )+ if a["content"]:+ return _edit_skill(a["name"], a["content"])+ # Targeted-replacement validation lives in _patch_skill so the public+ # tool and the helper return the same actionable guidance.+ return _patch_skill(a["name"], a["old_string"], a["new_string"], a["file_path"], a["replace_all"])+++def _act_write_file(a):+ if not a["file_path"]:+ return tool_error("file_path is required for 'write_file'. Example: 'references/api-guide.md'", success=False)+ if a["file_content"] is None:+ return tool_error("file_content is required for 'write_file'.", success=False)+ return _write_file(a["name"], a["file_path"], a["file_content"])+++def _act_remove_file(a):+ if not a["file_path"]:+ return tool_error("file_path is required for 'remove_file'.", success=False)+ return _remove_file(a["name"], a["file_path"])+++# action -> handler(args dict). Handlers return a result dict, or a JSON string+# (tool_error) for argument-shape errors.+_ACTION_HANDLERS = {+ "create": _act_create,+ "edit": _act_edit,+ "patch": _act_patch,+ "delete": lambda a: _delete_skill(a["name"], absorbed_into=a["absorbed_into"]),+ "write_file": _act_write_file,+ "remove_file": _act_remove_file,+}+++def _record_success(action, name, result, *, file_path, absorbed_into, task_id,+ session_id, ledger_before) -> None:+ """Post-mutation side effects, all best-effort (never break the tool):+ audit ledger, prompt-cache clear, curator telemetry, debounced sync push."""+ try:+ from tools import skill_ledger as _ledger+ _post = _find_skill(name)+ _evidence = {}+ if action == "delete":+ # consolidation vs prune, and whether the recoverable archive handled it+ _evidence["absorbed_into"] = absorbed_into+ _evidence["archived"] = bool(result.get("_archived"))+ if session_id:+ _evidence["session_id"] = session_id+ if file_path:+ _evidence["file_path"] = file_path+ _ledger.record_mutation(+ action,+ name,+ before=ledger_before if ledger_before is not None else [],+ after_root=_post["path"] if _post else None,+ evidence=_evidence,+ )+ except Exception:+ pass+ try:+ from agent.prompt_builder import clear_skills_system_prompt_cache+ clear_skills_system_prompt_cache(clear_snapshot=True)+ except Exception:+ pass+ # Curator telemetry: only the background review fork marks a skill as+ # agent-created — foreground creates are user-directed and belong to the+ # user. A recoverable curator archive keeps its record as STATE_ARCHIVED+ # (so `hermes curator status`/`restore` see it); only a hard delete forgets.+ try:+ from tools.skill_usage import bump_patch, forget, record_created+ from tools.skill_provenance import is_background_review+ if action == "create":+ record_created(name, agent_created=is_background_review(),+ task_id=task_id, session_id=session_id)+ elif action in {"patch", "edit", "write_file", "remove_file"}:+ bump_patch(name, action=action, task_id=task_id, session_id=session_id)+ elif action == "delete" and not result.get("_archived"):+ forget(name)+ except Exception:+ pass+ # Sync push only runs AFTER the write gate passed (staged writes returned+ # early), so un-reviewed content is never pushed. Inert unless the access+ # gate is open, a sync URL is configured, and the skill is opted in.+ try:+ _maybe_debounced_sync_push(name)+ except Exception:+ pass++def skill_manage(action: str,name: str,@@ -1945,14 +1046,11 @@ def skill_manage(session_id: str = None,operations=None,) -> str:- """- Manage user-created skills. Dispatches to the appropriate action handler.-- ``operations``: batch shape — a list of {action, ...} dicts applied to- ONE skill atomically (see _skill_manage_batch). When set, the flat- single-op fields are ignored and ``action`` may be omitted/'batch'.+ """Manage user-created skills; dispatches to the action handler.- Returns JSON string with results.+ ``operations``: batch shape — a list of {action, ...} dicts applied+ atomically (see _skill_manage_batch). When set, the flat single-op fields+ are ignored and ``action`` may be omitted/'batch'. Returns a JSON string."""if operations is not None:return _skill_manage_batch(@@ -1964,163 +1062,46 @@ def skill_manage(return json.dumps(preflight, ensure_ascii=False)# Approval gate: when on, stages the write for review (skills are too large- # to review inline, so they always stage regardless of origin); when off- # (default) passes straight through. The gate is bypassed when this call is- # itself replaying an already-approved staged write (_skill_apply_pending).- gate_result = _apply_skill_write_gate(- action, name, content=content, category=category,- file_path=file_path, file_content=file_content,- old_string=old_string, new_string=new_string,+ # to review inline, so they always stage regardless of origin); bypassed+ # when replaying an already-approved staged write.+ args = dict(+ content=content, category=category, file_path=file_path,+ file_content=file_content, old_string=old_string, new_string=new_string,replace_all=replace_all, absorbed_into=absorbed_into,)+ gate_result = _apply_skill_write_gate(action, name, **args)if gate_result is not None:return gate_result- # Audit ledger (tracker #79686 P3): capture the pre-mutation state of the- # skill directory so every mutation — any actor — lands in the append-only- # JSONL ledger with before/after blobs. Telemetry, not a gate: failures- # here must NEVER block the mutation (capture_before returns None on- # error, and record_mutation below swallows everything).+ # Audit ledger: capture pre-mutation state. Telemetry, not a gate — failures+ # must NEVER block the mutation. delete destroys the whole package and+ # consolidation may have re-homed support files first, so complete the+ # capture from the newest curator backup or a restore is hollow._ledger_before = None- _ledger_before_dir = Nonetry:from tools import skill_ledger as _ledger_pre = _find_skill(name)- _ledger_before_dir = _pre["path"] if _pre else None- # delete destroys the whole package; consolidation may have re-homed- # support files out of the tree first, so complete the capture from- # the newest curator backup or rollback restores a hollow skill- # (#96962). Other actions capture disk state only._ledger_before = _ledger.capture_before(- _ledger_before_dir,+ _pre["path"] if _pre else None,complete_package=(action == "delete"),skill=name,)except Exception:pass- if action == "create":- if not content:- return tool_error("content is required for 'create'. Provide the full SKILL.md text (frontmatter + body).", success=False)- result = _create_skill(name, content, category)-- elif action == "edit":- # Legacy alias for a full rewrite (kept for old transcripts/callers;- # no longer advertised in the schema — use patch with `content`).- if not content:- return tool_error("content is required for a full rewrite. Provide the full updated SKILL.md text.", success=False)- result = _edit_skill(name, content)-- elif action == "patch":- # Two shapes: old_string/new_string = targeted replacement;- # content (alone) = full SKILL.md rewrite (absorbs the old 'edit').- if content and (old_string or new_string is not None):- return tool_error(- "Pass EITHER content (full SKILL.md rewrite) OR "- "old_string/new_string (targeted replacement), not both.",- success=False,- )- if content:- result = _edit_skill(name, content)- else:- # Targeted-replacement validation lives in _patch_skill so the- # public tool and the helper return the same actionable guidance.- # A bare "required" error here would shadow it and leave the- # model with nowhere to go but action='write_file'. #33064.- result = _patch_skill(name, old_string, new_string, file_path, replace_all)-- elif action == "delete":- result = _delete_skill(name, absorbed_into=absorbed_into)-- elif action == "write_file":- if not file_path:- return tool_error("file_path is required for 'write_file'. Example: 'references/api-guide.md'", success=False)- if file_content is None:- return tool_error("file_content is required for 'write_file'.", success=False)- result = _write_file(name, file_path, file_content)-- elif action == "remove_file":- if not file_path:- return tool_error("file_path is required for 'remove_file'.", success=False)- result = _remove_file(name, file_path)-+ handler = _ACTION_HANDLERS.get(action)+ if handler is None:+ result = _err(f"Unknown action '{action}'. Use: create, edit, patch, delete, write_file, remove_file")else:- result = {"success": False, "error": f"Unknown action '{action}'. Use: create, edit, patch, delete, write_file, remove_file"}+ result = handler({"name": name, **args})+ if isinstance(result, str):+ return result # tool_error JSON for argument-shape problemsif result.get("success"):- # Audit ledger append (best-effort; never blocks the mutation).- try:- from tools import skill_ledger as _ledger- _post = _find_skill(name)- _after_dir = _post["path"] if _post else None- _evidence = {}- if action == "delete":- # Record delete intent: consolidation vs prune, and whether- # the recoverable-archive path handled it (curator pass).- _evidence["absorbed_into"] = absorbed_into- _evidence["archived"] = bool(result.get("_archived"))- if session_id:- _evidence["session_id"] = session_id- if file_path:- _evidence["file_path"] = file_path- _ledger.record_mutation(- action,- name,- before=_ledger_before if _ledger_before is not None else [],- after_root=_after_dir,- evidence=_evidence,- )- except Exception:- pass- try:- from agent.prompt_builder import clear_skills_system_prompt_cache- clear_skills_system_prompt_cache(clear_snapshot=True)- except Exception:- pass- # Curator telemetry: bump patch_count on edit/patch/write_file (the actions- # that mutate an existing skill's guidance), drop the record on delete.- # Only mark a skill as agent-created when the background self-improvement- # review fork creates it — foreground `skill_manage(create)` calls are- # user-directed, and those skills belong to the user (the curator must- # not touch them). Best-effort; telemetry failures never break the tool.- try:- from tools.skill_usage import bump_patch, forget, record_created- from tools.skill_provenance import is_background_review- if action == "create":- record_created(- name,- agent_created=is_background_review(),- task_id=task_id,- session_id=session_id,- )- elif action in {"patch", "edit", "write_file", "remove_file"}:- bump_patch(- name,- action=action,- task_id=task_id,- session_id=session_id,- )- elif action == "delete":- # A recoverable curator archive (routed through archive_skill)- # keeps its usage record as STATE_ARCHIVED so `hermes curator- # status`/`restore` still see it. Only a hard delete forgets.- if not result.get("_archived"):- forget(name)- except Exception:- pass-- # Sync push hook (debounced, best-effort). Fires only AFTER the- # write gate passed (staged/unapproved writes never reach here -- the- # gate returns early above), so we never push un-reviewed content.- # Inert unless the access gate is open (the user is a Nous admin on the- # token), a sync base URL is configured, and the skill is opted into- # sync. Debounced so a burst of edits collapses to one push. Never- # raises -- an agent write must never block on sync (M1-C invariant).- try:- _maybe_debounced_sync_push(name)- except Exception:- pass-+ _record_success(+ action, name, result, file_path=file_path, absorbed_into=absorbed_into,+ task_id=task_id, session_id=session_id, ledger_before=_ledger_before,+ )return json.dumps(result, ensure_ascii=False)@@ -2235,16 +1216,8 @@ registry.register(name="skill_manage",toolset="skills",schema=SKILL_MANAGE_SCHEMA,- handler=lambda args, **kw: skill_manage(- action=args.get("action", ""),- name=args.get("name", ""),- content=args.get("content"),- category=args.get("category"),- file_path=args.get("file_path"),- file_content=args.get("file_content"),- old_string=args.get("old_string"),- new_string=args.get("new_string"),- replace_all=args.get("replace_all", False),+ handler=lambda args, **kw: _skill_manage_from(+ args,absorbed_into=args.get("absorbed_into"),operations=args.get("operations"),task_id=kw.get("task_id"),diff --git a/tools/skill_usage.py b/tools/skill_usage.pyindex aa7e616daa8..9e0bdcbaa40 100644--- a/tools/skill_usage.py+++ b/tools/skill_usage.py@@ -1,25 +1,19 @@"""Skill usage telemetry + provenance tracking for the Curator feature.-Tracks per-skill usage metadata in a sidecar JSON file (~/.hermes/skills/.usage.json)-keyed by skill name. Counters are bumped by the existing skill tools (skill_view,-skill_manage); the curator orchestrator reads the derived activity timestamp to-decide lifecycle transitions.--Design notes:- - Sidecar, not frontmatter. Keeps operational telemetry out of user-authored- SKILL.md content and avoids conflict pressure for bundled/hub skills.- - Atomic writes via tempfile + os.replace (same pattern as .bundled_manifest).- - All counter bumps are best-effort: failures log at DEBUG and return silently.- A broken sidecar never breaks the underlying tool call.- - Provenance filter: curator-managed skills are explicitly marked when- created through skill_manage. Bundled / hub-installed skills stay- off-limits, and manually authored skills are not inferred from location.--Lifecycle states:- active -> default- stale -> unused > stale_after_days (config)- archived -> unused > archive_after_days (config); moved to .archive/- pinned -> opt-out from auto transitions (boolean flag, orthogonal to state)+Per-skill usage metadata lives in a sidecar JSON file (~/.hermes/skills/.usage.json) keyed by skill name.+Counters are bumped by the skill tools (skill_view, skill_manage); the curator orchestrator reads the derived+activity timestamp to decide lifecycle transitions.++Design notes: sidecar, not frontmatter (keeps operational telemetry out of user-authored SKILL.md content and+avoids conflict pressure for bundled/hub skills); atomic writes via tempfile + os.replace (same pattern as+.bundled_manifest); all counter bumps are best-effort — failures log at DEBUG and return silently, so a broken+sidecar never breaks the underlying tool call; and curator-managed skills are explicitly marked when created+through skill_manage — bundled / hub-installed skills stay off-limits, and manually authored skills are not+inferred from location.++Lifecycle states: active (default) -> stale (unused > stale_after_days, config) -> archived (unused >+archive_after_days, config; moved to .archive/). ``pinned`` is a boolean opt-out from auto transitions,+orthogonal to state."""from __future__ import annotations@@ -28,10 +22,10 @@ import jsonimport loggingimport osimport tempfile-from contextlib import contextmanager+from contextlib import contextmanager, suppressfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Dict, List, Optional, Set, Tuple+from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Set, Tuplefrom hermes_constants import get_hermes_homefrom agent.skill_utils import is_excluded_skill_path, is_external_skill_path@@ -55,25 +49,20 @@ STATE_STALE = "stale"STATE_ARCHIVED = "archived"_VALID_STATES = {STATE_ACTIVE, STATE_STALE, STATE_ARCHIVED}-# Load-bearing bundled built-ins the curator must NEVER archive or consolidate,-# regardless of ``curator.prune_builtins``, pin state, or LLM judgment. These-# back advertised UX paths; silently archiving one turns its slash command-# into "Unknown command" with no signal to the user.-# Protection is by skill ``name`` (frontmatter ``name:``), matching the keys used-# throughout this module. Keep this list tiny and intentional — it is not a-# substitute for ``curator.prune_builtins: false``, which exempts ALL built-ins.-# (``plan`` used to live here; it is now a first-class built-in command with-# no skill on disk, so the set is currently empty.)+# Load-bearing bundled built-ins the curator must NEVER archive or consolidate, regardless of+# ``curator.prune_builtins``, pin state, or LLM judgment. These back advertised UX paths; silently archiving one+# turns its slash command into "Unknown command" with no signal to the user. Protection is by skill ``name``+# (frontmatter ``name:``), matching the keys used throughout this module. Keep this list tiny and intentional —+# it is not a substitute for ``curator.prune_builtins: false``, which exempts ALL built-ins. (``plan`` used to+# live here; it is now a first-class built-in command with no skill on disk, so the set is currently empty.)PROTECTED_BUILTIN_SKILLS: Set[str] = set()def is_protected_builtin(skill_name: str) -> bool:"""Whether *skill_name* is a load-bearing built-in the curator never touches.- Protected built-ins are exempt from archival and consolidation on every- path: the automatic state-transition walk, the LLM consolidation pass (they- are dropped from the candidate list), and direct ``archive_skill`` calls.- """+ Protected built-ins are exempt from archival and consolidation on every path: the automatic state-transition walk,+ the LLM consolidation pass (dropped from the candidate list), and direct ``archive_skill`` calls."""return skill_name in PROTECTED_BUILTIN_SKILLS@@ -85,44 +74,64 @@ def _usage_file() -> Path:return _skills_dir() / ".usage.json"+def _archive_dir() -> Path:+ return _skills_dir() / ".archive"+++def _flock(fd, lock: bool) -> None:+ if fcntl:+ fcntl.flock(fd, fcntl.LOCK_EX if lock else fcntl.LOCK_UN)+ else:+ fd.seek(0)+ msvcrt.locking(fd.fileno(), msvcrt.LK_LOCK if lock else msvcrt.LK_UNLCK, 1)++@contextmanagerdef _usage_file_lock():"""Serialize .usage.json read-modify-write cycles across processes."""lock_path = _usage_file().with_suffix(".json.lock")lock_path.parent.mkdir(parents=True, exist_ok=True)-if fcntl is None and msvcrt is None:yieldreturn-if msvcrt and (not lock_path.exists() or lock_path.stat().st_size == 0):lock_path.write_text(" ", encoding="utf-8")-fd = open(lock_path, "r+" if msvcrt else "a+", encoding="utf-8")try:- if fcntl:- fcntl.flock(fd, fcntl.LOCK_EX)- else:- fd.seek(0)- msvcrt.locking(fd.fileno(), msvcrt.LK_LOCK, 1)+ _flock(fd, True)yieldfinally:- if fcntl:- try:- fcntl.flock(fd, fcntl.LOCK_UN)- except (OSError, IOError):- pass- elif msvcrt:- try:- fd.seek(0)- msvcrt.locking(fd.fileno(), msvcrt.LK_UNLCK, 1)- except (OSError, IOError):- pass+ with suppress(OSError, IOError):+ _flock(fd, False)fd.close()-def _archive_dir() -> Path:- return _skills_dir() / ".archive"+def _atomic_write(path: Path, prefix: str, write: Callable[[Any], None]) -> None:+ """Write *path* via tempfile + fsync + os.replace; the temp file is removed on failure."""+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=prefix, suffix=".tmp")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ write(f)+ f.flush()+ os.fsync(f.fileno())+ os.replace(tmp, path)+ except BaseException:+ with suppress(OSError):+ os.unlink(tmp)+ raise+++def _read_lines(path: Path, fail_log: str) -> List[str]:+ """Stripped, non-empty lines of a small metadata file ([] if missing/unreadable)."""+ if not path.exists():+ return []+ try:+ lines = path.read_text(encoding="utf-8").splitlines()+ except OSError as e:+ logger.debug(fail_log, e)+ return []+ return [s for s in (line.strip() for line in lines) if s]def _now_iso() -> str:@@ -137,29 +146,19 @@ def _parse_iso_timestamp(value: Any) -> Optional[datetime]:parsed = datetime.fromisoformat(str(value))except (TypeError, ValueError):return None- if parsed.tzinfo is None:- parsed = parsed.replace(tzinfo=timezone.utc)- return parsed+ return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parseddef latest_activity_at(record: Dict[str, Any]) -> Optional[str]:"""Return the newest actual activity timestamp for a usage record.- "Activity" means a skill was used, viewed, or patched. Creation time is- intentionally excluded so callers can still distinguish never-active skills;- lifecycle code can fall back to ``created_at`` as its own anchor.- """- latest_dt: Optional[datetime] = None- latest_raw: Optional[str] = None- for key in ("last_used_at", "last_viewed_at", "last_patched_at"):- raw = record.get(key)- dt = _parse_iso_timestamp(raw)- if dt is None:- continue- if latest_dt is None or dt > latest_dt:- latest_dt = dt- latest_raw = str(raw)- return latest_raw+ "Activity" means a skill was used, viewed, or patched. Creation time is intentionally excluded so callers can+ still distinguish never-active skills; lifecycle code can fall back to ``created_at`` as its own anchor."""+ stamps = [+ (dt, str(raw)) for raw in (record.get(k) for k in ("last_used_at", "last_viewed_at", "last_patched_at"))+ if (dt := _parse_iso_timestamp(raw)) is not None+ ]+ return max(stamps, key=lambda t: t[0])[1] if stamps else Nonedef activity_count(record: Dict[str, Any]) -> int:@@ -173,74 +172,44 @@ def activity_count(record: Dict[str, Any]) -> int:return total-# ----------------------------------------------------------------------------# Provenance — which skills are agent-created (and thus eligible for curation)-# ----------------------------------------------------------------------------+# --- Provenance — which skills are agent-created (and thus eligible for curation) ---def _read_bundled_manifest_names() -> Set[str]:- """Return the set of skill names that were seeded from the bundled repo.-- Reads ~/.hermes/skills/.bundled_manifest (format: "name:hash" per line).- Returns empty set if the file is missing or unreadable.- """- manifest = _skills_dir() / ".bundled_manifest"- if not manifest.exists():- return set()- names: Set[str] = set()- try:- for line in manifest.read_text(encoding="utf-8").splitlines():- line = line.strip()- if not line:- continue- name = line.split(":", 1)[0].strip()- if name:- names.add(name)- except OSError as e:- logger.debug("Failed to read bundled manifest: %s", e)- return names+ """Skill names seeded from the bundled repo: ~/.hermes/skills/.bundled_manifest ("name:hash" per line). Empty set+ if the file is missing or unreadable."""+ lines = _read_lines(_skills_dir() / ".bundled_manifest", "Failed to read bundled manifest: %s")+ return {n for n in (line.split(":", 1)[0].strip() for line in lines) if n}def _read_hub_installed_names() -> Set[str]:- """Return the set of skill names installed via the Skills Hub.-- Reads ~/.hermes/skills/.hub/lock.json (see tools/skills_hub.py :: HubLockFile).- """+ """Skill names installed via the Skills Hub, read from ~/.hermes/skills/.hub/lock.json (see tools/skills_hub.py ::+ HubLockFile)."""lock_path = _skills_dir() / ".hub" / "lock.json"if not lock_path.exists():return set()try:- # Tolerate non-UTF-8 bytes in the lock file. Hub descriptions can carry- # Windows-1252 typographic chars (em-dash 0x97, smart quotes, bullets)- # written as single high bytes; a strict utf-8 read raises- # UnicodeDecodeError, which is a ValueError sibling (not OSError/- # JSONDecodeError) so it escapes the handler below and 500s the whole- # /api/skills endpoint. errors="replace" degrades the offending byte to- # U+FFFD, keeping the (structurally valid) JSON — and every other- # skill — readable. See #68053.+ # Tolerate non-UTF-8 bytes in the lock file. Hub descriptions can carry Windows-1252 typographic chars+ # (em-dash 0x97, smart quotes, bullets) written as single high bytes; a strict utf-8 read raises+ # UnicodeDecodeError, which is a ValueError sibling (not OSError/JSONDecodeError) so it escapes the+ # handler below and 500s the whole /api/skills endpoint. errors="replace" degrades the offending byte to+ # U+FFFD, keeping the (structurally valid) JSON — and every other skill — readable. See #68053.data = json.loads(lock_path.read_text(encoding="utf-8", errors="replace"))- if isinstance(data, dict):- installed = data.get("installed") or {}- if isinstance(installed, dict):- names = {str(k) for k in installed.keys()}- skills_dir = _skills_dir()- for entry in installed.values():- if not isinstance(entry, dict):- continue- install_path = entry.get("install_path")- if not isinstance(install_path, str) or not install_path.strip():- continue- skill_dir = Path(install_path)- if not skill_dir.is_absolute():- skill_dir = skills_dir / skill_dir- try:- resolved = skill_dir.resolve()- resolved.relative_to(skills_dir.resolve())- except (OSError, ValueError):- continue- skill_md = resolved / "SKILL.md"- if skill_md.exists():- names.add(_read_skill_name(skill_md, fallback=resolved.name))- return names+ installed = (data.get("installed") or {}) if isinstance(data, dict) else None+ if not isinstance(installed, dict):+ return set()+ names = {str(k) for k in installed}+ skills_dir = _skills_dir()+ for entry in installed.values():+ install_path = entry.get("install_path") if isinstance(entry, dict) else None+ if not isinstance(install_path, str) or not install_path.strip():+ continue+ try:+ resolved = (skills_dir / install_path).resolve()+ resolved.relative_to(skills_dir.resolve())+ except (OSError, ValueError):+ continue+ if (resolved / "SKILL.md").exists():+ names.add(_read_skill_name(resolved / "SKILL.md", fallback=resolved.name))+ return namesexcept (OSError, json.JSONDecodeError) as e:logger.debug("Failed to read hub lock file: %s", e)return set()@@ -249,15 +218,12 @@ def _read_hub_installed_names() -> Set[str]:def _prune_builtins_enabled() -> bool:"""Whether bundled built-in skills are eligible for curator pruning.- Reads ``curator.prune_builtins`` from config (default True). Lazy import- keeps this module importable without the CLI config layer (e.g. in the- update/sync context); on any failure we fall back to the default. The real- safety against a mass-prune is the curator's seed-on-first-sight, not this- flag — built-ins only archive after a fresh inactivity window.- """+ Reads ``curator.prune_builtins`` from config (default True). Lazy import keeps this module importable without the+ CLI config layer (e.g. in the update/sync context); on any failure we fall back to the default. The real safety+ against a mass-prune is the curator's seed-on-first-sight, not this flag — built-ins only archive after a fresh+ inactivity window."""try:from hermes_cli.config import load_config-cfg = load_config()cur = cfg.get("curator") if isinstance(cfg, dict) else Noneif isinstance(cur, dict):@@ -267,139 +233,88 @@ def _prune_builtins_enabled() -> bool:return True-def _suppressed_file() -> Path:- return _skills_dir() / ".curator_suppressed"--def read_suppressed_names() -> Set[str]:"""Built-in skills the curator pruned — the re-seeder must leave archived.- One skill name per line in ``~/.hermes/skills/.curator_suppressed``. This is- what makes pruning a built-in durable: without it, ``hermes update`` would- re-copy the bundled skill on the next sync.- """- path = _suppressed_file()- if not path.exists():- return set()- names: Set[str] = set()- try:- for line in path.read_text(encoding="utf-8").splitlines():- line = line.strip()- if line and not line.startswith("#"):- names.add(line)- except OSError as e:- logger.debug("Failed to read curator suppression list: %s", e)- return names+ One skill name per line in ``~/.hermes/skills/.curator_suppressed``. This is what makes pruning a built-in+ durable: without it, ``hermes update`` would re-copy the bundled skill on the next sync."""+ lines = _read_lines(_skills_dir() / ".curator_suppressed", "Failed to read curator suppression list: %s")+ return {line for line in lines if not line.startswith("#")}-def _write_suppressed_names(names: Set[str]) -> None:- path = _suppressed_file()+def _toggle_suppressed_name(skill_name: str, *, add: bool) -> None:+ if not skill_name or (skill_name in (names := read_suppressed_names())) == add:+ return+ (names.add if add else names.discard)(skill_name)+ data = "\n".join(sorted(names)) + ("\n" if names else "")try:- path.parent.mkdir(parents=True, exist_ok=True)- data = "\n".join(sorted(names)) + ("\n" if names else "")- fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".curator_suppressed_", suffix=".tmp")- try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write(data)- f.flush()- os.fsync(f.fileno())- os.replace(tmp, path)- except BaseException:- try:- os.unlink(tmp)- except OSError:- pass- raise+ _atomic_write(_skills_dir() / ".curator_suppressed", ".curator_suppressed_", lambda f: f.write(data))except Exception as e:logger.debug("Failed to write curator suppression list: %s", e, exc_info=True)def add_suppressed_name(skill_name: str) -> None:"""Record that a built-in skill was pruned, so sync won't restore it."""- if not skill_name:- return- names = read_suppressed_names()- if skill_name not in names:- names.add(skill_name)- _write_suppressed_names(names)+ _toggle_suppressed_name(skill_name, add=True)def remove_suppressed_name(skill_name: str) -> None:"""Clear a built-in's suppression entry (e.g. on restore)."""- if not skill_name:- return- names = read_suppressed_names()- if skill_name in names:- names.discard(skill_name)- _write_suppressed_names(names)+ _toggle_suppressed_name(skill_name, add=False)-def list_agent_created_skill_names() -> List[str]:- """Enumerate skills the curator may manage.+def _iter_skill_mds(base: Path, *, local_only: bool) -> Iterator[Tuple[str, Path]]:+ """Yield ``(frontmatter name, SKILL.md)`` for every skill under *base* — the flat layout AND nested+ category/skill/SKILL.md — skipping Hermes metadata, VCS, virtualenv/dependency, and cache dirs. With+ *local_only*, external skill dirs mounted below the local tree are skipped too: discovery may see them,+ but autonomous lifecycle curation must not."""+ for skill_md in base.rglob("SKILL.md"):+ if not (is_excluded_skill_path(skill_md) or (local_only and is_external_skill_path(skill_md))):+ yield _read_skill_name(skill_md, fallback=skill_md.parent.name), skill_md+++def _scan_local_skills(keep: Callable[[str, Path, Set[str], Dict[str, Any]], bool]) -> List[str]:+ """Sorted, de-duplicated names of local skills passing *keep(name, skill_md, bundled, usage)*.- Always includes agent-authored skills (those marked in ``.usage.json`` via- ``skill_manage(action="create")``). When ``curator.prune_builtins`` is- enabled, bundled built-in skills are ALSO included even though they have no- agent-created usage record — their inactivity clock is anchored on first- sight (see ``apply_automatic_transitions``). Hub-installed skills are never- included; manually authored skills are not inferred from filesystem- location.- """+ Hub-installed skills are always off-limits, and protected built-ins are never curation candidates+ (exempt from the automatic transition walk AND the LLM consolidation pass), so neither ever reaches+ *keep*."""base = _skills_dir()if not base.exists():return []- hub = _read_hub_installed_names()- bundled = _read_bundled_manifest_names()- prune_builtins = _prune_builtins_enabled()- usage = load_usage()+ hub, bundled, usage = _read_hub_installed_names(), _read_bundled_manifest_names(), load_usage()+ return sorted({+ name for name, skill_md in _iter_skill_mds(base, local_only=True)+ if name not in hub and not is_protected_builtin(name) and keep(name, skill_md, bundled, usage)+ })- names: List[str] = []- # Top-level SKILL.md files (flat layout) AND nested category/skill/SKILL.md- for skill_md in base.rglob("SKILL.md"):- # Skip Hermes metadata, VCS, virtualenv/dependency, and cache dirs- if is_excluded_skill_path(skill_md):- continue- # External skill dirs can be mounted below the local skills tree.- # Discovery may see them, but autonomous lifecycle curation must not.- if is_external_skill_path(skill_md):- continue- try:- skill_md.relative_to(base)- except ValueError:- continue- name = _read_skill_name(skill_md, fallback=skill_md.parent.name)- # Hub-installed skills are always off-limits.- if name in hub:- continue- # Protected built-ins are never curation candidates — exempt from the- # automatic transition walk AND the LLM consolidation pass.- if is_protected_builtin(name):- continue- if name in bundled:- # Built-ins are only candidates when pruning is enabled. They never- # carry a curator-managed record, so the record gate is skipped.- if not prune_builtins:- continue- names.append(name)- continue- # Agent-authored (or local-manual) skills must opt in via their record.- if not _is_curator_managed_record(usage.get(name)):- continue- names.append(name)- return sorted(set(names))++def list_agent_created_skill_names() -> List[str]:+ """Enumerate skills the curator may manage.++ Always includes agent-authored skills (those marked in ``.usage.json`` via ``skill_manage(action="create")``).+ When ``curator.prune_builtins`` is enabled, bundled built-in skills are ALSO included even though they have no+ agent-created usage record — their inactivity clock is anchored on first sight (see+ ``apply_automatic_transitions``). Hub-installed skills are never included; manually authored skills are not+ inferred from filesystem location."""+ if not _skills_dir().exists():+ return []+ prune_builtins = _prune_builtins_enabled() # read once, before the walk++ def _keep(name: str, _skill_md: Path, bundled: Set[str], usage: Dict[str, Any]) -> bool:+ # Built-ins are only candidates when pruning is enabled; they never carry a curator-managed record, so+ # the record gate is skipped. Agent-authored (or local-manual) skills must opt in via their record.+ return prune_builtins if name in bundled else _is_curator_managed_record(usage.get(name))+ return _scan_local_skills(_keep)def list_archived_skill_names() -> List[str]:"""Enumerate skills in ``~/.hermes/skills/.archive/``.- Archive layout is flat (``.archive/<skill>/``) as set by ``archive_skill``,- so the directory name is the skill name. Used by ``hermes curator- list-archived`` to help users pass a name to ``hermes curator restore``.- """+ Archive layout is flat (``.archive/<skill>/``) as set by ``archive_skill``, so the directory name is the skill+ name. Used by ``hermes curator list-archived`` to help users pass a name to ``hermes curator restore``."""archive_root = _archive_dir()- if not archive_root.exists():- return []- return sorted({p.name for p in archive_root.iterdir() if p.is_dir()})+ return sorted({p.name for p in archive_root.iterdir() if p.is_dir()}) if archive_root.exists() else []def _read_skill_name(skill_md: Path, fallback: str) -> str:@@ -409,14 +324,12 @@ def _read_skill_name(skill_md: Path, fallback: str) -> str:except OSError:return fallbackin_frontmatter = False- for line in text.split("\n"):- stripped = line.strip()+ for stripped in (line.strip() for line in text.split("\n")):if stripped == "---":if in_frontmatter:breakin_frontmatter = True- continue- if in_frontmatter and stripped.startswith("name:"):+ elif in_frontmatter and stripped.startswith("name:"):value = stripped.split(":", 1)[1].strip().strip("\"'")if value:return value@@ -425,13 +338,9 @@ def _read_skill_name(skill_md: Path, fallback: str) -> str:def is_agent_created(skill_name: str) -> bool:"""Whether *skill_name* is neither bundled nor hub-installed."""- off_limits = _read_bundled_manifest_names() | _read_hub_installed_names()- if skill_name in off_limits:+ if skill_name in _read_bundled_manifest_names() | _read_hub_installed_names():return False- return not (- _find_skill_dir(skill_name) is None- and _find_external_skill_dir(skill_name) is not None- )+ return _find_skill_dir(skill_name) is not None or _find_external_skill_dir(skill_name) is Nonedef is_hub_installed(skill_name: str) -> bool:@@ -445,166 +354,96 @@ def is_bundled(skill_name: str) -> bool:def _external_read_only_message(skill_name: str) -> str:- return (- f"skill '{skill_name}' lives in skills.external_dirs; "- "external skills are read-only to the curator"- )+ return f"skill '{skill_name}' lives in skills.external_dirs; external skills are read-only to the curator"def is_curation_eligible(skill_name: str, skill_path: Optional[Path] = None) -> bool:"""Whether the curator may track/archive *skill_name*.- Agent-created skills are always eligible. Bundled built-ins become eligible- only when ``curator.prune_builtins`` is enabled. Hub-installed and external- skill-dir skills are NEVER eligible — they have an external upstream owner.- Org-shared skills ARE eligible for improvement (the curator may patch them- like any other skill; edits stay local until proposed) but are protected- from ARCHIVE/DELETE elsewhere — removing a shared skill is an org-admin- action, not a local curation decision.- Protected built-ins (``PROTECTED_BUILTIN_SKILLS``) are NEVER eligible- regardless of any flag — they back load-bearing UX and must never be- archived or consolidated.- """- if skill_path is not None and is_external_skill_path(skill_path):- return False- if is_protected_builtin(skill_name):- return False- if is_hub_installed(skill_name):+ Agent-created skills are always eligible. Bundled built-ins become eligible only when ``curator.prune_builtins``+ is enabled. Hub-installed and external skill-dir skills are NEVER eligible — they have an external upstream owner.+ Org-shared skills ARE eligible for improvement (the curator may patch them like any other skill; edits stay local+ until proposed) but are protected from ARCHIVE/DELETE elsewhere — removing a shared skill is an org-admin action,+ not a local curation decision. Protected built-ins (``PROTECTED_BUILTIN_SKILLS``) are NEVER eligible regardless of+ any flag — they back load-bearing UX and must never be archived or consolidated."""+ if (skill_path is not None and is_external_skill_path(skill_path)) or is_protected_builtin(skill_name) or is_hub_installed(skill_name):return Falseif is_bundled(skill_name):return _prune_builtins_enabled()local_dir = _find_skill_dir(skill_name)- if local_dir is not None:- return not is_external_skill_path(local_dir)- if _find_external_skill_dir(skill_name) is not None:- return False- return True+ return not is_external_skill_path(local_dir) if local_dir is not None else _find_external_skill_dir(skill_name) is Nonedef _is_curator_managed_record(record: Any) -> bool:"""Return True when a usage record opts a skill into curator management.- NAMING (issue #67140): the on-disk field is ``created_by``, which reads- like provenance but is consumed as a **curator-management opt-in policy- flag**. The two are not the same question:-- * provenance = "who authored this file" — historical fact, and for records- written before the marker existed it is simply unrecoverable.- * management = "may autonomous curation mutate/archive this" — a policy- decision the user can change at any time via ``hermes curator adopt``.-- ``created_by: "agent"`` therefore means "curator-managed", NOT "proof the- agent wrote it". The field name is retained because it is already on disk- in every user's ``.usage.json``; renaming it would strand those records.- Read it as policy, and prefer ``is_curator_managed()`` at call sites so the- intent is unambiguous.- """- if not isinstance(record, dict):- return False- return record.get("created_by") == "agent" or record.get("agent_created") is True+ NAMING (issue #67140): the on-disk field is ``created_by``, which reads like provenance but is consumed as a+ **curator-management opt-in policy flag**. The two are not the same question: provenance = "who authored this+ file" — historical fact, unrecoverable for records written before the marker existed; management = "may autonomous+ curation mutate/archive this" — a policy decision the user can change at any time via ``hermes curator adopt``.+ ``created_by: "agent"`` therefore means "curator-managed", NOT "proof the agent wrote it". The field name is+ retained because it is already on disk in every user's ``.usage.json``; renaming it would strand those records.+ Read it as policy, and prefer ``is_curator_managed()`` at call sites so the intent is unambiguous."""+ return isinstance(record, dict) and (record.get("created_by") == "agent" or record.get("agent_created") is True)-def is_curator_managed(skill_name: str) -> bool:- """Whether *skill_name* is opted into curator management.- Policy-intent alias for the ``created_by``-marker check, so call sites read- as the question they are actually asking (see ``_is_curator_managed_record``- for why the stored field name says "created_by").- """+def is_curator_managed(skill_name: str) -> bool:+ """Whether *skill_name* is opted into curator management — the policy-intent alias for the ``created_by``-marker+ check (see ``_is_curator_managed_record`` for the field-name story)."""return _is_curator_managed_record(load_usage().get(skill_name))def list_unmanaged_skill_names() -> List[str]:"""Enumerate curation-ELIGIBLE skills that carry no provenance marker.- These are skills the curator *could* manage (they are not hub-installed,- not external, not protected built-ins) but never will, because nothing- ever wrote ``created_by: agent`` onto their usage record. Two ways a skill- lands here:-- * It predates the provenance mechanism entirely — records written before- ``created_by`` existed carry no key at all, so their authorship is- unknowable from the record alone.- * It was created by a FOREGROUND ``skill_manage(action="create")`` call,- which deliberately does not mark provenance (skills a user asks for- belong to the user).-- Either way the skill is invisible to ``curated_report()`` and therefore to- every automatic transition. ``hermes curator status`` surfaces this count- so the blind spot is legible instead of silent, and ``hermes curator- adopt`` lets the user hand specific skills over explicitly.-- Provenance is a DECLARATION, never an inference: this function only- reports, and callers must not auto-adopt what it returns. Heavy patch or- use counts are evidence of maintenance, not of authorship — the agent- edits user-authored skills on the user's behalf routinely.- """- base = _skills_dir()- if not base.exists():- return []- hub = _read_hub_installed_names()- bundled = _read_bundled_manifest_names()- usage = load_usage()+ These are skills the curator *could* manage (not hub-installed, not external, not protected built-ins) but never+ will, because nothing ever wrote ``created_by: agent`` onto their usage record. Two ways a skill lands here: it+ predates the provenance mechanism entirely (records written before ``created_by`` existed carry no key at all, so+ authorship is unknowable from the record alone), or it was created by a FOREGROUND+ ``skill_manage(action="create")`` call, which deliberately does not mark provenance (skills a user asks for belong+ to the user).- names: List[str] = []- for skill_md in base.rglob("SKILL.md"):- if is_excluded_skill_path(skill_md) or is_external_skill_path(skill_md):- continue- try:- skill_md.relative_to(base)- except ValueError:- continue- name = _read_skill_name(skill_md, fallback=skill_md.parent.name)- # Anything with an external owner or a bundled/protected identity is- # outside the adoption question entirely.- if name in hub or name in bundled or is_protected_builtin(name):- continue- if _is_curator_managed_record(usage.get(name)):- continue- if not is_curation_eligible(name, skill_md):- continue- names.append(name)- return sorted(set(names))+ Either way the skill is invisible to ``curated_report()`` and therefore to every automatic transition. ``hermes+ curator status`` surfaces this count so the blind spot is legible instead of silent, and ``hermes curator adopt``+ lets the user hand specific skills over explicitly.++ Provenance is a DECLARATION, never an inference: this function only reports, and callers must not auto-adopt what+ it returns. Heavy patch or use counts are evidence of maintenance, not of authorship — the agent edits+ user-authored skills on the user's behalf routinely."""+ def _keep(name: str, skill_md: Path, bundled: Set[str], usage: Dict[str, Any]) -> bool:+ # Anything with an external owner or a bundled/protected identity is outside the adoption question.+ return name not in bundled and not _is_curator_managed_record(usage.get(name)) and is_curation_eligible(name, skill_md)+ return _scan_local_skills(_keep)def unmanaged_report() -> List[Dict[str, Any]]:"""Rows for every skill :func:`list_unmanaged_skill_names` returns.- Each row carries the usual activity fields plus ``has_provenance_key``:- False when the record has no ``created_by`` key at all (pre-dates the- mechanism), True when the key is present but unset (a foreground create- under the current policy). The distinction matters for explaining WHY a- skill is unmanaged; it is not a signal to adopt on.- """+ Each row carries the usual activity fields plus ``has_provenance_key``: False when the record has no+ ``created_by`` key at all (pre-dates the mechanism), True when the key is present but unset (a foreground create+ under the current policy). The distinction matters for explaining WHY a skill is unmanaged; it is not a signal to+ adopt on."""usage = load_usage()- rows: List[Dict[str, Any]] = []- for name in list_unmanaged_skill_names():- raw = usage.get(name)- rec: Dict[str, Any] = dict(raw) if isinstance(raw, dict) else _empty_record()- for k, v in _empty_record().items():- rec.setdefault(k, v)- row = {"name": name, **rec}- row["has_provenance_key"] = isinstance(raw, dict) and "created_by" in raw- row["has_record"] = isinstance(raw, dict)- row["last_activity_at"] = latest_activity_at(row)- row["activity_count"] = activity_count(row)- rows.append(row)- return rows+ return [+ _report_row(+ name, dict(raw) if isinstance(raw, dict) else None,+ has_provenance_key=isinstance(raw, dict) and "created_by" in raw, has_record=isinstance(raw, dict),+ )+ for name, raw in ((n, usage.get(n)) for n in list_unmanaged_skill_names())+ ]def adopt_skill(skill_name: str) -> Tuple[bool, str]:"""Hand *skill_name* to the curator by user declaration.- Writes the same ``created_by: agent`` marker the background review fork- writes, so the skill joins ``curated_report()`` and the automatic- transition walk. The inactivity clock is NOT reset: the skill's existing- ``last_activity_at`` still governs staleness, so adopting something idle- for months does not buy it a fresh window (nor does it archive it on the- spot — the state machine decides on the next pass).+ Writes the same ``created_by: agent`` marker the background review fork writes, so the skill joins+ ``curated_report()`` and the automatic transition walk. The inactivity clock is NOT reset: the skill's existing+ ``last_activity_at`` still governs staleness, so adopting something idle for months does not buy it a fresh window+ (nor does it archive it on the spot — the state machine decides on the next pass).- Returns (ok, message). Refuses hub-installed, external, and protected- built-in skills, which have an owner other than the user.- """+ Returns (ok, message). Refuses hub-installed, external, and protected built-in skills, which have an owner other+ than the user."""if not skill_name:return False, "no skill name given"if is_protected_builtin(skill_name):@@ -612,14 +451,9 @@ def adopt_skill(skill_name: str) -> Tuple[bool, str]:if is_hub_installed(skill_name):return False, f"'{skill_name}' is hub-installed; its upstream owns it"if is_bundled(skill_name):- # Bundled skills already fall under the curator via- # ``curator.prune_builtins``; stamping created_by=agent on one would- # claim Hermes' own shipped skill was agent-authored and change nothing- # about its eligibility.- return False, (- f"'{skill_name}' is a bundled built-in — it is governed by "- "curator.prune_builtins, not by adoption"- )+ # Bundled skills already fall under the curator via ``curator.prune_builtins``; stamping created_by=agent+ # on one would claim Hermes' own shipped skill was agent-authored and change nothing about its eligibility.+ return False, f"'{skill_name}' is a bundled built-in — it is governed by curator.prune_builtins, not by adoption"skill_dir = _find_skill_dir(skill_name)if skill_dir is None:if _find_external_skill_dir(skill_name) is not None:@@ -627,8 +461,7 @@ def adopt_skill(skill_name: str) -> Tuple[bool, str]:return False, f"skill '{skill_name}' not found"if is_external_skill_path(skill_dir):return False, _external_read_only_message(skill_name)- usage = load_usage()- if _is_curator_managed_record(usage.get(skill_name)):+ if _is_curator_managed_record(load_usage().get(skill_name)):return True, f"'{skill_name}' is already curator-managed"mark_agent_created(skill_name)if not _is_curator_managed_record(load_usage().get(skill_name)):@@ -636,28 +469,32 @@ def adopt_skill(skill_name: str) -> Tuple[bool, str]:return True, f"adopted '{skill_name}' into curator management"-# ----------------------------------------------------------------------------# Sidecar I/O-# ----------------------------------------------------------------------------+# --- Sidecar I/O ---def _empty_record() -> Dict[str, Any]:return {- "created_by": None,- "use_count": 0,- "view_count": 0,- "last_used_at": None,- "last_viewed_at": None,- "patch_count": 0,- "patch_generation": 0,- "last_reused_patch_generation": 0,- "last_patched_at": None,- "created_at": _now_iso(),- "state": STATE_ACTIVE,- "pinned": False,- "archived_at": None,+ "created_by": None, "use_count": 0, "view_count": 0, "last_used_at": None, "last_viewed_at": None,+ "patch_count": 0, "patch_generation": 0, "last_reused_patch_generation": 0, "last_patched_at": None,+ "created_at": _now_iso(), "state": STATE_ACTIVE, "pinned": False, "archived_at": None,}+def _backfilled(rec: Any) -> Dict[str, Any]:+ """*rec* with every missing default key filled in (a fresh record when not a dict), so+ callers never need to handle old files that predate newer keys."""+ if not isinstance(rec, dict):+ return _empty_record()+ for k, v in _empty_record().items():+ rec.setdefault(k, v)+ return rec+++def _report_row(name: str, raw: Any, **extra: Any) -> Dict[str, Any]:+ """Build one report row: name + backfilled record + *extra* + derived activity fields."""+ row = {"name": name, **_backfilled(raw), **extra}+ row.update(last_activity_at=latest_activity_at(row), activity_count=activity_count(row))+ return row++def load_usage() -> Dict[str, Dict[str, Any]]:"""Read the entire .usage.json map. Returns empty dict on missing/corrupt."""path = _usage_file()@@ -668,37 +505,16 @@ def load_usage() -> Dict[str, Dict[str, Any]]:except (OSError, json.JSONDecodeError) as e:logger.debug("Failed to read %s: %s", path, e)return {}- if not isinstance(data, dict):- return {}- # Defensive: coerce any non-dict values to a fresh empty record- clean: Dict[str, Dict[str, Any]] = {}- for k, v in data.items():- if isinstance(v, dict):- clean[str(k)] = v- return clean+ # Defensive: drop any non-dict values+ return {str(k): v for k, v in data.items() if isinstance(v, dict)} if isinstance(data, dict) else {}def save_usage(data: Dict[str, Dict[str, Any]]) -> bool:"""Write the usage map atomically and report whether it committed."""path = _usage_file()try:- path.parent.mkdir(parents=True, exist_ok=True)- fd, tmp_path = tempfile.mkstemp(- dir=str(path.parent), prefix=".usage_", suffix=".tmp"- )- try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- json.dump(data, f, indent=2, sort_keys=True, ensure_ascii=False)- f.flush()- os.fsync(f.fileno())- os.replace(tmp_path, path)- return True- except BaseException:- try:- os.unlink(tmp_path)- except OSError:- pass- raise+ _atomic_write(path, ".usage_", lambda f: json.dump(data, f, indent=2, sort_keys=True, ensure_ascii=False))+ return Trueexcept Exception as e:logger.debug("Failed to write %s: %s", path, e, exc_info=True)return False@@ -706,68 +522,70 @@ def save_usage(data: Dict[str, Dict[str, Any]]) -> bool:def get_record(skill_name: str) -> Dict[str, Any]:"""Return the record for *skill_name*, creating a fresh one if missing."""- data = load_usage()- rec = data.get(skill_name)- if not isinstance(rec, dict):- return _empty_record()- # Backfill any missing keys so callers don't need to handle old files- base = _empty_record()- for k, v in base.items():- rec.setdefault(k, v)- return rec+ return _backfilled(load_usage().get(skill_name))+++def _locked_update(+ skill_name: str, op: Callable[[Dict[str, Dict[str, Any]]], Tuple[Any, bool]], fail_log: str,+ guard: Optional[Callable[[], bool]] = None,+) -> Any:+ """Run *op(data)* on the loaded usage map under the file lock. Best-effort. *guard* (if given) is evaluated before+ the lock is taken; a False result skips the update. *op* returns a (result, dirty) pair; the map is saved only+ when dirty. Returns the result, or None when the guard failed, the save did not land, or anything raised (logged+ at DEBUG via *fail_log*)."""+ try:+ if guard is not None and not guard():+ return None+ with _usage_file_lock():+ data = load_usage()+ result, dirty = op(data)+ return None if dirty and not save_usage(data) else result+ except Exception as e:+ logger.debug(fail_log, skill_name, e, exc_info=True)+ return Nonedef seed_record_if_missing(skill_name: str) -> None:"""Persist a baseline usage record for a curation-eligible skill.- Built-ins carry no usage record until something touches them, which leaves- their inactivity clock with no anchor. Seeding a record here fixes- ``created_at`` to the moment the curator first sees the skill, so the- archive/stale clock measures non-use FROM THEN — not from epoch. No-op when- a record already exists or the skill isn't curation-eligible.- """+ Built-ins carry no usage record until something touches them, which leaves their inactivity clock with no anchor.+ Seeding a record here fixes ``created_at`` to the moment the curator first sees the skill, so the archive/stale+ clock measures non-use FROM THEN — not from epoch. No-op when a record already exists or the skill isn't+ curation-eligible."""if not skill_name or not is_curation_eligible(skill_name):return- try:- with _usage_file_lock():- data = load_usage()- if isinstance(data.get(skill_name), dict):- return++ def _seed(data):+ if missing := not isinstance(data.get(skill_name), dict):data[skill_name] = _empty_record()- save_usage(data)- except Exception as e:- logger.debug("skill_usage.seed_record_if_missing(%s) failed: %s", skill_name, e, exc_info=True)+ return None, missing+ _locked_update(skill_name, _seed, "skill_usage.seed_record_if_missing(%s) failed: %s")def _mutate(skill_name: str, mutator, *, require_curation_eligible: bool = False) -> Any:"""Load, apply *mutator(record)* in place, save. Best-effort.- By default this records telemetry for ANY skill — bundled, hub-installed,- or agent-created — because usage tracking is pure observability and is- orthogonal to whether a skill is ever curated. Lifecycle mutators- (``set_state``, ``set_pinned``, ``mark_agent_created``) pass- ``require_curation_eligible=True`` so they never write meaningless state- onto a skill the curator can't manage (e.g. an ``archived`` flag on a- hub-installed skill).- """+ By default this records telemetry for ANY skill — bundled, hub-installed, or agent-created — because usage+ tracking is pure observability and is orthogonal to whether a skill is ever curated. Lifecycle mutators+ (``set_state``, ``set_pinned``, ``mark_agent_created``) pass ``require_curation_eligible=True`` so they never+ write meaningless state onto a skill the curator can't manage (e.g. an ``archived`` flag on a hub-installed+ skill)."""if not skill_name:return None- try:- if require_curation_eligible and not is_curation_eligible(skill_name):- return None- with _usage_file_lock():- data = load_usage()- rec = data.get(skill_name)- if not isinstance(rec, dict):- rec = _empty_record()- result = mutator(rec)- data[skill_name] = rec- if not save_usage(data):- return None- return result- except Exception as e:- logger.debug("skill_usage._mutate(%s) failed: %s", skill_name, e, exc_info=True)- return None++ def _apply(data):+ rec = data[skill_name] = data[skill_name] if isinstance(data.get(skill_name), dict) else _empty_record()+ return mutator(rec), True+ guard = (lambda: is_curation_eligible(skill_name)) if require_curation_eligible else None+ return _locked_update(skill_name, _apply, "skill_usage._mutate(%s) failed: %s", guard)+++def _set_field(skill_name: str, key: str, value: Any) -> bool:+ """Curation-gated single-field write; True only when the write landed."""+ def _apply(rec: Dict[str, Any]) -> bool:+ rec[key] = value+ return True # non-None sentinel: _mutate propagates the mutator result+ return bool(_mutate(skill_name, _apply, require_curation_eligible=True))def _non_negative_int(value: Any) -> int:@@ -779,27 +597,23 @@ def _non_negative_int(value: Any) -> int:return 0-def telemetry_provenance(- skill_name: str,- record: Optional[Dict[str, Any]] = None,-) -> str:+def _bump(rec: Dict[str, Any], count_key: str, ts_key: str) -> None:+ rec[count_key] = _non_negative_int(rec.get(count_key)) + 1+ rec[ts_key] = _now_iso()+++def telemetry_provenance(skill_name: str, record: Optional[Dict[str, Any]] = None) -> str:"""Return the bounded provenance used by shared skill metrics."""if is_hub_installed(skill_name) or is_bundled(skill_name):return "installed"if ":" in skill_name:- try:+ with suppress(Exception):from hermes_cli.plugins import get_plugin_manager-if get_plugin_manager().find_plugin_skill(skill_name) is not None:return "installed"- except Exception:- pass- if isinstance(record, dict):- created_by = record.get("created_by")- if created_by == "installed":- return "installed"- if created_by == "agent":- return "agent_created"+ created_by = record.get("created_by") if isinstance(record, dict) else None+ if created_by in ("installed", "agent"):+ return {"installed": "installed", "agent": "agent_created"}[created_by]if _find_external_skill_dir(skill_name) is not None:return "external"if _find_skill_dir(skill_name) is not None or isinstance(record, dict):@@ -808,244 +622,143 @@ def telemetry_provenance(def _emit_skill_lifecycle(- skill_name: str,- action: str,- *,- record: Optional[Dict[str, Any]] = None,- task_id: Optional[str] = None,- session_id: Optional[str] = None,- use_count: Optional[int] = None,- reused: Optional[bool] = None,- reuse_after_patch: Optional[bool] = None,+ skill_name: str, action: str, *, record: Optional[Dict[str, Any]] = None,+ task_id: Optional[str] = None, session_id: Optional[str] = None, **facts: Any,) -> None:- """Emit one best-effort lifecycle fact after authoritative state changes."""+ """Emit one best-effort lifecycle fact after authoritative state changes. *facts* may carry ``use_count`` /+ ``reused`` / ``reuse_after_patch``; absent ones are sent as None."""try:from hermes_cli.lifecycle import has_hook, invoke_hook-if not has_hook("on_skill_lifecycle"):returninvoke_hook(- "on_skill_lifecycle",- action=action,- skill_name=skill_name,- provenance=telemetry_provenance(skill_name, record),- task_id=task_id or "",- session_id=session_id or "",- use_count=use_count,- reused=reused,- reuse_after_patch=reuse_after_patch,+ "on_skill_lifecycle", action=action, skill_name=skill_name,+ provenance=telemetry_provenance(skill_name, record), task_id=task_id or "", session_id=session_id or "",+ use_count=facts.get("use_count"), reused=facts.get("reused"), reuse_after_patch=facts.get("reuse_after_patch"),)except Exception:- logger.debug(- "skill_usage lifecycle hook failed for %s/%s",- skill_name,- action,- exc_info=True,- )+ logger.debug("skill_usage lifecycle hook failed for %s/%s", skill_name, action, exc_info=True)-# ----------------------------------------------------------------------------# Public counter-bump helpers — telemetry for ALL skills (observability only)-# ---------------------------------------------------------------------------+def _mutate_and_emit(skill_name: str, action: str, mutator: Callable[[Dict[str, Any]], Dict[str, Any]], **hook_kwargs: Any) -> None:+ """``_mutate`` then emit *action* with the mutator's facts as the record — only if the write landed. Any+ ``use_count`` / ``reused`` / ``reuse_after_patch`` facts are forwarded to the hook."""+ facts = _mutate(skill_name, mutator)+ if isinstance(facts, dict):+ hook_kwargs.update({k: facts[k] for k in ("use_count", "reused", "reuse_after_patch") if k in facts})+ _emit_skill_lifecycle(skill_name, action, record=facts, **hook_kwargs)++# --- Public counter-bump helpers — telemetry for ALL skills (observability only) ---def bump_view(skill_name: str) -> None:"""Bump view_count and last_viewed_at. Called from skill_view().- Tracks every skill regardless of provenance — built-ins and hub skills- included. Usage telemetry is observability, not a curation signal.- """- def _apply(rec: Dict[str, Any]) -> None:- rec["view_count"] = _non_negative_int(rec.get("view_count")) + 1- rec["last_viewed_at"] = _now_iso()- _mutate(skill_name, _apply)+ Tracks every skill regardless of provenance — built-ins and hub skills included. Usage telemetry is observability,+ not a curation signal."""+ _mutate(skill_name, lambda rec: _bump(rec, "view_count", "last_viewed_at"))-def bump_use(- skill_name: str,- *,- task_id: Optional[str] = None,- session_id: Optional[str] = None,-) -> None:- """Bump use_count and last_used_at. Called when a skill is actively used- (e.g. loaded into the prompt path or referenced from an assistant turn).-- Tracks every skill regardless of provenance.- """+def bump_use(skill_name: str, *, task_id: Optional[str] = None, session_id: Optional[str] = None) -> None:+ """Bump use_count and last_used_at. Called when a skill is actively used (e.g. loaded into the prompt path or+ referenced from an assistant turn). Tracks every skill regardless of provenance."""def _apply(rec: Dict[str, Any]) -> Dict[str, Any]:previous_use_count = _non_negative_int(rec.get("use_count"))patch_generation = _non_negative_int(rec.get("patch_generation"))- last_reused_generation = min(- _non_negative_int(rec.get("last_reused_patch_generation")),- patch_generation,- )+ last_reused_generation = min(_non_negative_int(rec.get("last_reused_patch_generation")), patch_generation)reused = previous_use_count > 0reuse_after_patch = reused and patch_generation > last_reused_generation- rec["use_count"] = previous_use_count + 1- rec["last_used_at"] = _now_iso()- rec["patch_generation"] = patch_generation- rec["last_reused_patch_generation"] = last_reused_generation- if reuse_after_patch:- rec["last_reused_patch_generation"] = patch_generation+ rec.update(+ use_count=previous_use_count + 1, last_used_at=_now_iso(), patch_generation=patch_generation,+ last_reused_patch_generation=patch_generation if reuse_after_patch else last_reused_generation,+ )return {- "created_by": rec.get("created_by"),- "use_count": rec["use_count"],- "reused": reused,- "reuse_after_patch": reuse_after_patch,+ "created_by": rec.get("created_by"), "use_count": rec["use_count"],+ "reused": reused, "reuse_after_patch": reuse_after_patch,}-- facts = _mutate(skill_name, _apply)- if isinstance(facts, dict):- _emit_skill_lifecycle(- skill_name,- "loaded",- record=facts,- task_id=task_id,- session_id=session_id,- use_count=facts["use_count"],- reused=facts["reused"],- reuse_after_patch=facts["reuse_after_patch"],- )+ _mutate_and_emit(skill_name, "loaded", _apply, task_id=task_id, session_id=session_id)def bump_patch(- skill_name: str,- *,- action: str = "patch",- task_id: Optional[str] = None,- session_id: Optional[str] = None,+ skill_name: str, *, action: str = "patch", task_id: Optional[str] = None, session_id: Optional[str] = None) -> None:- """Bump patch_count and last_patched_at. Called from skill_manage (patch/edit).-- Tracks every skill regardless of provenance.- """- lifecycle_action = "patched" if action == "patch" else "edited"-+ """Bump patch_count and last_patched_at. Called from skill_manage (patch/edit). Tracks every skill regardless of+ provenance."""def _apply(rec: Dict[str, Any]) -> Dict[str, Any]:- rec["patch_count"] = _non_negative_int(rec.get("patch_count")) + 1+ _bump(rec, "patch_count", "last_patched_at")rec["patch_generation"] = _non_negative_int(rec.get("patch_generation")) + 1- rec["last_patched_at"] = _now_iso()return {"created_by": rec.get("created_by")}-- facts = _mutate(skill_name, _apply)- if isinstance(facts, dict):- _emit_skill_lifecycle(- skill_name,- lifecycle_action,- record=facts,- task_id=task_id,- session_id=session_id,- )+ lifecycle_action = "patched" if action == "patch" else "edited"+ _mutate_and_emit(skill_name, lifecycle_action, _apply, task_id=task_id, session_id=session_id)def record_created(- skill_name: str,- *,- agent_created: bool,- task_id: Optional[str] = None,- session_id: Optional[str] = None,+ skill_name: str, *, agent_created: bool, task_id: Optional[str] = None, session_id: Optional[str] = None) -> None:"""Persist explicit creation provenance and emit a successful create fact."""def _apply(rec: Dict[str, Any]) -> Dict[str, Any]:- # A successful create is a new logical skill even if stale sidecar- # state survived an earlier deletion or manual filesystem change.+ # A successful create is a new logical skill even if stale sidecar state survived an earlier deletion or+ # manual filesystem change.rec.clear()- rec.update(_empty_record())- if agent_created:- rec["created_by"] = "agent"+ rec.update(_empty_record(), **({"created_by": "agent"} if agent_created else {}))return {"created_by": rec["created_by"]}-- facts = _mutate(skill_name, _apply)- if isinstance(facts, dict):- _emit_skill_lifecycle(- skill_name,- "created",- record=facts,- task_id=task_id,- session_id=session_id,- )+ _mutate_and_emit(skill_name, "created", _apply, task_id=task_id, session_id=session_id)def record_installed(skill_name: str) -> None:"""Record a successful Skills Hub install without exporting its name."""def _apply(rec: Dict[str, Any]) -> Dict[str, Any]:- rec["created_by"] = "installed"- rec["state"] = STATE_ACTIVE- rec["archived_at"] = None+ rec.update(created_by="installed", state=STATE_ACTIVE, archived_at=None)return {"created_by": rec["created_by"]}-- facts = _mutate(skill_name, _apply)- if isinstance(facts, dict):- _emit_skill_lifecycle(skill_name, "installed", record=facts)+ _mutate_and_emit(skill_name, "installed", _apply)def mark_agent_created(skill_name: str) -> None:"""Opt a skill created by skill_manage into curator management.- Viewing or invoking a manually authored skill may still create telemetry,- but only this explicit marker makes it eligible for automatic curation.- """- def _apply(rec: Dict[str, Any]) -> None:- rec["created_by"] = "agent"- _mutate(skill_name, _apply, require_curation_eligible=True)+ Viewing or invoking a manually authored skill may still create telemetry, but only this explicit marker makes it+ eligible for automatic curation."""+ _set_field(skill_name, "created_by", "agent")def set_state(skill_name: str, state: str) -> None:- """Set lifecycle state. No-op if *state* is invalid or the skill isn't- curator-manageable (hub skills, or built-ins with pruning disabled)."""+ """Set lifecycle state. No-op if *state* is invalid or the skill isn't curator-manageable (hub skills, or+ built-ins with pruning disabled)."""if state not in _VALID_STATES:logger.debug("set_state: invalid state %r for %s", state, skill_name)return+def _apply(rec: Dict[str, Any]) -> Dict[str, Any]:previous_state = rec.get("state")- if previous_state == state:- return {"changed": False, "created_by": rec.get("created_by")}- rec["state"] = state- if state == STATE_ARCHIVED:- rec["archived_at"] = _now_iso()- elif state == STATE_ACTIVE:- rec["archived_at"] = None- return {- "changed": True,- "created_by": rec.get("created_by"),- "previous_state": previous_state,- }-+ facts = {"changed": previous_state != state, "created_by": rec.get("created_by")}+ if facts["changed"]:+ rec["state"] = state+ if state != STATE_STALE:+ rec["archived_at"] = _now_iso() if state == STATE_ARCHIVED else None+ facts["previous_state"] = previous_state+ return factsfacts = _mutate(skill_name, _apply, require_curation_eligible=True)if not isinstance(facts, dict) or not facts.get("changed"):return- action = {- STATE_ARCHIVED: "archived",- STATE_STALE: "stale",- }.get(state)- if state == STATE_ACTIVE and facts.get("previous_state") == STATE_ARCHIVED:- action = "restored"+ restored = state == STATE_ACTIVE and facts.get("previous_state") == STATE_ARCHIVED # active<-stale emits nothing+ action = "restored" if restored else {STATE_ARCHIVED: "archived", STATE_STALE: "stale"}.get(state)if action is not None:_emit_skill_lifecycle(skill_name, action, record=facts)def set_pinned(skill_name: str, pinned: bool) -> bool:- """Set/clear the pin flag. Returns False when the write did not land- (skill not curation-eligible), True on success — so callers can report- failure instead of a false success (issue #92993)."""- def _apply(rec: Dict[str, Any]) -> Any:- rec["pinned"] = bool(pinned)- return True # non-None sentinel: _mutate propagates the mutator result- return bool(_mutate(skill_name, _apply, require_curation_eligible=True))+ """Set/clear the pin flag. Returns False when the write did not land (skill not curation-eligible), True on+ success — so callers can report failure instead of a false success (issue #92993)."""+ return _set_field(skill_name, "pinned", bool(pinned))def set_sync(skill_name: str, sync: bool) -> None:"""Set the sync opt-in flag on a skill's usage record.- Sync is OPT-IN: nothing propagates to the sync plane unless the user marks- a skill with ``sync: true`` here. Sits alongside ``pinned``/``created_by``- on the ``.usage.json`` sidecar and is read by- ``tools.skills_sync_client.list_synced_skill_names``. Gated on curation- eligibility so bundled/hub/external skills (which never sync) can't be- marked. Provisional per the M1-D default.- """- def _apply(rec: Dict[str, Any]) -> None:- rec["sync"] = bool(sync)- _mutate(skill_name, _apply, require_curation_eligible=True)+ Sync is OPT-IN: nothing propagates to the sync plane unless the user marks a skill with ``sync: true`` here. Sits+ alongside ``pinned``/``created_by`` on the ``.usage.json`` sidecar and is read by+ ``tools.skills_sync_client.list_synced_skill_names``. Gated on curation eligibility so bundled/hub/external skills+ (which never sync) can't be marked. Provisional per the M1-D default."""+ _set_field(skill_name, "sync", bool(sync))def is_sync_enabled(skill_name: str) -> bool:@@ -1055,48 +768,64 @@ def is_sync_enabled(skill_name: str) -> bool:def forget(skill_name: str) -> None:"""Drop a skill's usage entry entirely. Called when the skill is deleted."""- if not skill_name:- return+ if skill_name:+ _locked_update(skill_name, lambda d: (None, d.pop(skill_name, None) is not None), "skill_usage.forget(%s) failed: %s")+++# --- Archive / restore ---+def _relocate(src: Path, dest: Path, skill_name: str, action: str, **capture_kwargs: Any) -> Tuple[bool, str]:+ """Move *src* to *dest* for *action* ("archive" | "restore") with an audit-ledger entry around it, then apply the+ suppression + state side effects for that direction.++ Ledger pre-capture is best-effort and never blocks the move; if it is unavailable the post-move record is skipped+ too. The rename falls back to shutil.move across devices. Returns (ok, message)."""try:- with _usage_file_lock():- data = load_usage()- if skill_name in data:- del data[skill_name]- save_usage(data)- except Exception as e:- logger.debug("skill_usage.forget(%s) failed: %s", skill_name, e, exc_info=True)+ from tools import skill_ledger as _ledger+ _ledger_before = _ledger.capture_before(src, **capture_kwargs)+ except Exception:+ _ledger = _ledger_before = None # type: ignore[assignment]+ try:+ src.rename(dest)+ except OSError:+ import shutil+ try:+ shutil.move(str(src), str(dest))+ except Exception as e:+ return False, f"failed to {action}: {e}"++ if action == "archive":+ # Pruning a built-in only sticks if the re-seeder is told to leave it alone.+ if is_bundled(skill_name):+ add_suppressed_name(skill_name)+ set_state(skill_name, STATE_ARCHIVED)+ else:+ # Restoring a pruned built-in lifts its suppression so updates can manage it.+ remove_suppressed_name(skill_name)+ set_state(skill_name, STATE_ACTIVE)+ with suppress(Exception):+ if _ledger is not None:+ _ledger.record_mutation(+ action, skill_name, before=_ledger_before if _ledger_before is not None else [], after_root=dest+ )+ return True, f"{action}d to {dest}"-# ----------------------------------------------------------------------------# Archive / restore-# ---------------------------------------------------------------------------def archive_skill(skill_name: str) -> Tuple[bool, str]:"""Move a curator-eligible skill directory to ~/.hermes/skills/.archive/.- Returns (ok, message). Never archives hub-installed skills. Bundled- built-ins are only archivable when ``curator.prune_builtins`` is enabled;- when one is archived, its name is added to the suppression list so the- update-time re-seeder leaves it archived instead of restoring it.- """- local_skill_dir = _find_skill_dir(skill_name)- if local_skill_dir is None and _find_external_skill_dir(skill_name) is not None:+ Returns (ok, message). Never archives hub-installed skills. Bundled built-ins are only archivable when+ ``curator.prune_builtins`` is enabled; when one is archived, its name is added to the suppression list so the+ update-time re-seeder leaves it archived instead of restoring it."""+ skill_dir = _find_skill_dir(skill_name)+ if skill_dir is None and _find_external_skill_dir(skill_name) is not None:return False, _external_read_only_message(skill_name)-- if not is_curation_eligible(skill_name, local_skill_dir):+ if not is_curation_eligible(skill_name, skill_dir):if is_protected_builtin(skill_name):- return False, (- f"skill '{skill_name}' is a protected built-in; it backs "- "load-bearing UX and is never archived or consolidated"- )+ return False, f"skill '{skill_name}' is a protected built-in; it backs load-bearing UX and is never archived or consolidated"if is_hub_installed(skill_name):return False, f"skill '{skill_name}' is hub-installed; never archive"- return False, (- f"skill '{skill_name}' is a bundled built-in; enable "- "curator.prune_builtins to allow pruning it"- )-- skill_dir = local_skill_dir+ return False, f"skill '{skill_name}' is a bundled built-in; enable curator.prune_builtins to allow pruning it"if skill_dir is None:return False, f"skill '{skill_name}' not found"if is_external_skill_path(skill_dir):@@ -1108,291 +837,134 @@ def archive_skill(skill_name: str) -> Tuple[bool, str]:except OSError as e:return False, f"failed to create archive dir: {e}"- # Flatten any category nesting into a single ".archive/<skill>/" so restores- # are simple. If a collision exists, append a timestamp.+ # Flatten any category nesting into a single ".archive/<skill>/" so restores are simple; on collision, append+ # a timestamp.dest = archive_root / skill_dir.nameif dest.exists():dest = archive_root / f"{skill_dir.name}-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S')}"- # Audit ledger pre-capture (best-effort; never blocks the archive).- # complete_package: consolidation may have re-homed support files out of- # the tree first, so a disk-only capture can come back hollow; the fill- # from the newest curator backup keeps rollback restorable (#96962).- _ledger_before = None- try:- from tools import skill_ledger as _ledger- _ledger_before = _ledger.capture_before(- skill_dir, complete_package=True, skill=skill_name- )- except Exception:- _ledger = None # type: ignore[assignment]-- try:- skill_dir.rename(dest)- except OSError:- # Cross-device — fall back to shutil.move- import shutil- try:- shutil.move(str(skill_dir), str(dest))- except Exception as e2:- return False, f"failed to archive: {e2}"-- # Pruning a built-in only sticks if the re-seeder is told to leave it alone.- if is_bundled(skill_name):- add_suppressed_name(skill_name)-- set_state(skill_name, STATE_ARCHIVED)- try:- if _ledger is not None:- _ledger.record_mutation(- "archive",- skill_name,- before=_ledger_before if _ledger_before is not None else [],- after_root=dest,- )- except Exception:- pass- return True, f"archived to {dest}"+ # complete_package: consolidation may have re-homed support files out of the tree first, so a disk-only+ # capture can come back hollow; the fill from the newest curator backup keeps rollback restorable (#96962).+ return _relocate(skill_dir, dest, skill_name, "archive", complete_package=True, skill=skill_name)def restore_skill(skill_name: str) -> Tuple[bool, str]:- """Move an archived skill back to ~/.hermes/skills/. Restores to the flat- top-level layout; original category nesting is NOT reconstructed.-- Refuses to restore under a name that now collides with a hub-installed- skill — that would shadow the upstream version. Also refuses to restore- over a bundled built-in UNLESS ``curator.prune_builtins`` is enabled (in- which case built-ins are curator-managed and restoring is the documented- way to lift a prune). Restoring clears any suppression entry so future- updates may re-seed the built-in again.- """+ """Move an archived skill back to ~/.hermes/skills/. Restores to the flat top-level layout; original category+ nesting is NOT reconstructed.++ Refuses to restore under a name that now collides with a hub-installed skill — that would shadow the upstream+ version. Also refuses to restore over a bundled built-in UNLESS ``curator.prune_builtins`` is enabled (in which+ case built-ins are curator-managed and restoring is the documented way to lift a prune). Restoring clears any+ suppression entry so future updates may re-seed the built-in again."""# Hub skills always have an external upstream owner — never shadow them.if is_hub_installed(skill_name):- return False, (- f"skill '{skill_name}' is now hub-installed; "- "restore would shadow the upstream version"- )- # A bundled built-in is upstream-owned UNLESS prune_builtins is on. With the- # flag off, restoring over it would shadow the bundled version.+ return False, f"skill '{skill_name}' is now hub-installed; restore would shadow the upstream version"+ # A bundled built-in is upstream-owned UNLESS prune_builtins is on; with the flag off, restoring over it+ # would shadow the bundled version.if is_bundled(skill_name) and not _prune_builtins_enabled():- return False, (- f"skill '{skill_name}' is now bundled; "- "restore would shadow the upstream version"- )+ return False, f"skill '{skill_name}' is now bundled; restore would shadow the upstream version"archive_root = _archive_dir()if not archive_root.exists():return False, "no archive directory"- # Try exact name match first, then the timestamped-duplicate fallback.- # Recursive walk handles nested archive layouts (e.g. .archive/<category>/<skill>/)- # left behind by older archive paths or external imports.+ # Try exact name match first, then the timestamped-duplicate fallback. Recursive walk handles nested archive+ # layouts (e.g. .archive/<category>/<skill>/) left behind by older archive paths or external imports.candidates = [p for p in archive_root.rglob("*") if p.is_dir() and p.name == skill_name]if not candidates:- # A name collision makes archive_skill() disambiguate by appending its- # UTC timestamp ("<skill>-YYYYMMDDHHMMSS", a 14-digit suffix), so only- # that exact shape is another copy of THIS skill. A bare- # startswith(f"{skill_name}-") also swallows unrelated sibling skills —- # restoring "git" would otherwise pull an archived "git-helpers" out of- # the archive and rename it to "git", destroying the sibling's only- # copy. Require the suffix to be the timestamp archive_skill writes.+ # A name collision makes archive_skill() disambiguate by appending its UTC timestamp+ # ("<skill>-YYYYMMDDHHMMSS", a 14-digit suffix), so only that exact shape is another copy of THIS skill.+ # A bare startswith(f"{skill_name}-") also swallows unrelated sibling skills — restoring "git" would+ # otherwise pull an archived "git-helpers" out of the archive and rename it to "git", destroying the+ # sibling's only copy. Require the suffix to be the timestamp archive_skill writes.prefix = f"{skill_name}-"candidates = sorted(- [- p for p in archive_root.rglob("*")- if p.is_dir()- and p.name.startswith(prefix)- and len(p.name) - len(prefix) == 14- and p.name[len(prefix):].isdigit()- ],+ (p for p in archive_root.rglob("*") if p.is_dir() and p.name.startswith(prefix)+ and len(p.name) - len(prefix) == 14 and p.name[len(prefix):].isdigit()),reverse=True,)if not candidates:return False, f"skill '{skill_name}' not found in archive"- src = candidates[0]dest = _skills_dir() / skill_nameif dest.exists():return False, f"destination already exists: {dest}"+ return _relocate(candidates[0], dest, skill_name, "restore")- # Audit ledger pre-capture (best-effort; never blocks the restore).- _ledger_before = None- try:- from tools import skill_ledger as _ledger- _ledger_before = _ledger.capture_before(src)- except Exception:- _ledger = None # type: ignore[assignment]-- try:- src.rename(dest)- except OSError:- import shutil- try:- shutil.move(str(src), str(dest))- except Exception as e:- return False, f"failed to restore: {e}"-- # Restoring a pruned built-in lifts its suppression so updates can manage it.- remove_suppressed_name(skill_name)- set_state(skill_name, STATE_ACTIVE)- try:- if _ledger is not None:- _ledger.record_mutation(- "restore",- skill_name,- before=_ledger_before if _ledger_before is not None else [],- after_root=dest,- )- except Exception:- pass- return True, f"restored to {dest}"+def _match_skill_dir(skill_mds: Iterable[Path], skill_name: str) -> Optional[Path]:+ return next((p.parent for p in skill_mds if _read_skill_name(p, fallback=p.parent.name) == skill_name), None)def _find_skill_dir(skill_name: str) -> Optional[Path]:"""Locate the directory for a skill by its frontmatter `name:` field.Handles both flat (~/.hermes/skills/<skill>/SKILL.md) and category-nested- (~/.hermes/skills/<category>/<skill>/SKILL.md) layouts. Uses the gated- index iterator so M2 org mirrors resolve ONLY for the active org- (stale ``_org/<other>/`` trees never match).- """+ (~/.hermes/skills/<category>/<skill>/SKILL.md) layouts. Uses the gated index iterator so M2 org mirrors resolve+ ONLY for the active org (stale ``_org/<other>/`` trees never match)."""base = _skills_dir()if not base.exists():return Nonefrom agent.skill_utils import iter_skill_index_files-- for skill_md in iter_skill_index_files(base, "SKILL.md"):- if is_external_skill_path(skill_md):- continue- if _read_skill_name(skill_md, fallback=skill_md.parent.name) == skill_name:- return skill_md.parent- return None+ return _match_skill_dir(+ (p for p in iter_skill_index_files(base, "SKILL.md") if not is_external_skill_path(p)), skill_name+ )def _find_external_skill_dir(skill_name: str) -> Optional[Path]:"""Locate a skill under configured external dirs by frontmatter name."""from agent.skill_utils import get_all_skills_dirs-- for base in get_all_skills_dirs()[1:]:- if not base.exists():- continue- for skill_md in base.rglob("SKILL.md"):- if is_excluded_skill_path(skill_md):- continue- if _read_skill_name(skill_md, fallback=skill_md.parent.name) == skill_name:- return skill_md.parent+ for base in (b for b in get_all_skills_dirs()[1:] if b.exists()):+ found = _match_skill_dir((p for p in base.rglob("SKILL.md") if not is_excluded_skill_path(p)), skill_name)+ if found is not None:+ return foundreturn None-# ----------------------------------------------------------------------------# Reporting — for the curator CLI / slash command-# ----------------------------------------------------------------------------+# --- Reporting — for the curator CLI / slash command ---def curated_report() -> List[Dict[str, Any]]:- """Return a list of {name, provenance, state, pinned, last_activity_at, ...}- records for every curator-managed skill. Missing usage records are- backfilled with defaults so callers can always index fields.-- ``provenance`` is 'agent', 'bundled', or 'hub' (see :func:`provenance`).- Bundled skills are only included when ``curator.prune_builtins`` is enabled.- Hub-installed skills are never included.-- Each row carries ``_persisted``: True when a real record exists in- ``.usage.json``, False when the row is a fresh backfill (e.g. a built-in- seen for the first time). The curator uses this to seed the inactivity- clock instead of treating an unrecorded skill as ancient.- """+ """Return a list of {name, provenance, state, pinned, last_activity_at, ...} records for every curator-managed+ skill. Missing usage records are backfilled with defaults so callers can always index fields.++ ``provenance`` is 'agent', 'bundled', or 'hub' (see :func:`provenance`). Bundled skills are only included when+ ``curator.prune_builtins`` is enabled. Hub-installed skills are never included.++ Each row carries ``_persisted``: True when a real record exists in ``.usage.json``, False when the row is a fresh+ backfill (e.g. a built-in seen for the first time). The curator uses this to seed the inactivity clock instead of+ treating an unrecorded skill as ancient."""data = load_usage()- rows: List[Dict[str, Any]] = []names = set(list_agent_created_skill_names())- # Issue #92993: a successfully pinned skill must be visible in the report- # even when it lacks the created_by marker (eligible-but-unmanaged), or- # its pin silently vanishes from `curator status`. The local-dir guard- # keeps stale records for deleted skill dirs from rendering as ghost rows;- # `curator unpin` is the cleanup path for those.- for name, rec in data.items():- if (- isinstance(rec, dict)- and rec.get("pinned")- and is_curation_eligible(name)- and _find_skill_dir(name) is not None- ):- names.add(name)- for name in sorted(names):- raw = data.get(name)- persisted = isinstance(raw, dict)- rec: Dict[str, Any] = raw if isinstance(raw, dict) else _empty_record()- base = _empty_record()- for k, v in base.items():- rec.setdefault(k, v)- row = {"name": name, **rec, "_persisted": persisted}- row["last_activity_at"] = latest_activity_at(row)- row["activity_count"] = activity_count(row)- row["provenance"] = provenance(name)- rows.append(row)+ # Issue #92993: a successfully pinned skill must be visible in the report even when it lacks the created_by+ # marker (eligible-but-unmanaged), or its pin silently vanishes from `curator status`. The local-dir guard+ # keeps stale records for deleted skill dirs from rendering as ghost rows; `curator unpin` is the cleanup path.+ names.update(+ name for name, rec in data.items()+ if isinstance(rec, dict) and rec.get("pinned") and is_curation_eligible(name) and _find_skill_dir(name) is not None+ )+ rows = [_report_row(name, data.get(name), _persisted=isinstance(data.get(name), dict)) for name in sorted(names)]+ for row in rows:+ row["provenance"] = provenance(row["name"])return rows-def agent_created_report() -> List[Dict[str, Any]]:- """DEPRECATED — use :func:`curated_report` instead.-- Used to return everything :func:`curated_report` returns (including bundled- skills when ``curator.prune_builtins`` is enabled), which made the- "agent-created" name misleading. Kept as a compatibility alias for- external callers; new code should call ``curated_report()``.- """- return curated_report()--def provenance(skill_name: str) -> str:- """Classify a skill's origin: 'hub', 'bundled', or 'agent'.-- 'agent' covers both agent-authored and local manually-authored skills —- anything not seeded from the bundled repo or installed via the hub.- """- if is_hub_installed(skill_name):- return "hub"- if is_bundled(skill_name):- return "bundled"- return "agent"+ """Classify a skill's origin: 'hub', 'bundled', or 'agent'. 'agent' covers both agent-authored and local+ manually-authored skills — anything not seeded from the bundled repo or installed via the hub."""+ return "hub" if is_hub_installed(skill_name) else "bundled" if is_bundled(skill_name) else "agent"def usage_report() -> List[Dict[str, Any]]:"""Return usage telemetry for EVERY skill on disk, with provenance.- Unlike ``curated_report()`` (which is scoped to curator-managed- candidates), this surfaces all skills — bundled built-ins and- hub-installed included — so callers can answer "how often is this skill- used" independent of whether it's ever curated. Rows carry a- ``provenance`` field ('agent' | 'bundled' | 'hub') and ``_persisted``- (whether a real ``.usage.json`` record backs the row).- """+ Unlike ``curated_report()`` (which is scoped to curator-managed candidates), this surfaces all skills — bundled+ built-ins and hub-installed included — so callers can answer "how often is this skill used" independent of whether+ it's ever curated. Rows carry a ``provenance`` field ('agent' | 'bundled' | 'hub') and ``_persisted`` (whether a+ real ``.usage.json`` record backs the row)."""base = _skills_dir()if not base.exists():return []data = load_usage()- rows: List[Dict[str, Any]] = []- seen: set = set()- for skill_md in base.rglob("SKILL.md"):- if is_excluded_skill_path(skill_md):- continue- name = _read_skill_name(skill_md, fallback=skill_md.parent.name)- if name in seen:- continue- seen.add(name)- raw = data.get(name)- persisted = isinstance(raw, dict)- rec: Dict[str, Any] = raw if isinstance(raw, dict) else _empty_record()- base_rec = _empty_record()- for k, v in base_rec.items():- rec.setdefault(k, v)- row = {- "name": name,- **rec,- "provenance": provenance(name),- "_persisted": persisted,- }- row["last_activity_at"] = latest_activity_at(row)- row["activity_count"] = activity_count(row)- rows.append(row)- return sorted(rows, key=lambda r: r["name"])+ rows: Dict[str, Dict[str, Any]] = {}+ for name, _skill_md in _iter_skill_mds(base, local_only=False):+ if name not in rows:+ rows[name] = _report_row(name, data.get(name), provenance=provenance(name), _persisted=isinstance(data.get(name), dict))+ return [rows[name] for name in sorted(rows)]diff --git a/tools/skills_guard.py b/tools/skills_guard.pyindex 18a12f751ca..6e211553eb2 100644--- a/tools/skills_guard.py+++ b/tools/skills_guard.py@@ -3,44 +3,37 @@Skills Guard — Security scanner for externally-sourced skills.Every skill downloaded from a registry passes through this scanner before-installation. It uses regex-based static analysis to detect known-bad patterns-(data exfiltration, prompt injection, destructive commands, persistence, etc.)-and a trust-aware install policy that determines whether a skill is allowed-based on both the scan verdict and the source's trust level.+installation: regex-based static analysis for known-bad patterns (data+exfiltration, prompt injection, destructive commands, persistence, etc.) plus a+trust-aware install policy combining the scan verdict with the source's trust.-Trust levels:- - builtin: Ships with Hermes. Never scanned, always trusted.- - trusted: openai/skills and anthropics/skills only. Caution verdicts allowed.- - community: Everything else. Any findings = blocked unless --force.+Trust levels: builtin (ships with Hermes, never scanned, always trusted);+trusted (openai/skills, anthropics/skills, ...: caution verdicts allowed);+community (everything else: any findings = blocked unless --force).-Usage:- from tools.skills_guard import scan_skill, should_allow_install, format_scan_report-- result = scan_skill(Path("skills/.hub/quarantine/some-skill"), source="community")- allowed, reason = should_allow_install(result)- if not allowed:- print(format_scan_report(result))+Usage: ``result = scan_skill(path, source="community")``, then+``allowed, reason = should_allow_install(result)`` and, when not allowed,+``print(format_scan_report(result))``.Known limitation — programmatic writes (out of scope for this static pass):-the agent-config persistence tiers score shell write mechanics-(">>" redirection, "sed -i") and imperative modification prose only.-Language write APIs in bundled scripts — Python open(..., 'w'/'a'),-pathlib.Path.write_text(), os.replace(), shutil.copy*, and Node-fs.writeFileSync()/appendFile() — aimed at agent-config files surface-only the low-severity *_ref finding, never a scored persistence tier.-Static regexes cannot reliably tie such a call to the config-file-destination (paths may be built dynamically) without executing the+the agent-config persistence tiers score shell write mechanics (">>"+redirection, "sed -i") and imperative modification prose only. Language write+APIs in bundled scripts — Python open(..., 'w'/'a'), pathlib.Path.write_text(),+os.replace(), shutil.copy*, and Node fs.writeFileSync()/appendFile() — aimed at+agent-config files surface only the low-severity *_ref finding, never a scored+persistence tier. Static regexes cannot reliably tie such a call to the+config-file destination (paths may be built dynamically) without executing theskill, so language-API persistence is left to runtime gates (install-confirmation, sandboxing). If coverage is added later, it belongs as a-fourth "mechanical" tier next to agent_config_mod_shell, requiring the-config-file name as a literal argument at the call site.+confirmation, sandboxing). If coverage is added later, it belongs as a fourth+"mechanical" tier next to agent_config_mod_shell, requiring the config-file+name as a literal argument at the call site."""import reimport fnmatchimport hashlibimport json-from dataclasses import dataclass, field+from dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import List, Tuple@@ -49,11 +42,7 @@ from typing import List, TupleSCANNER_VERSION = "skills-guard-v2"---# ----------------------------------------------------------------------------# Hardcoded trust configuration-# ---------------------------------------------------------------------------+# --- Hardcoded trust configuration ------------------------------------------TRUSTED_REPOS = {"openai/skills",@@ -81,9 +70,7 @@ INSTALL_POLICY = {VERDICT_INDEX = {"safe": 0, "caution": 1, "dangerous": 2}-# ----------------------------------------------------------------------------# Data structures-# ---------------------------------------------------------------------------+# --- Data structures --------------------------------------------------------@dataclassclass Finding:@@ -108,9 +95,7 @@ class ScanResult:scan_provenance: dict = field(default_factory=dict)-# ----------------------------------------------------------------------------# Threat patterns — (regex, pattern_id, severity, category, description)-# ---------------------------------------------------------------------------+# --- Threat patterns — (regex, pattern_id, severity, category, description) --# Action verbs that signal file-modification intent. Used by the agent-config# persistence patterns: a verb within the same line as (and shortly before) an@@ -195,56 +180,34 @@ THREAT_PATTERNS = [# its real destination behind a variable never matched these same-line# literal patterns in the first place.(r'curl\s+(?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)S?\b',- "env_exfil_curl", "critical", "exfiltration",- "curl command interpolating secret environment variable"),+ "env_exfil_curl", "critical", "exfiltration", "curl command interpolating secret environment variable"),(r'wget\s+(?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)S?\b',- "env_exfil_wget", "critical", "exfiltration",- "wget command interpolating secret environment variable"),+ "env_exfil_wget", "critical", "exfiltration", "wget command interpolating secret environment variable"),(r'fetch\s*\((?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD)S?\b',- "env_exfil_fetch", "critical", "exfiltration",- "fetch() call interpolating secret environment variable"),+ "env_exfil_fetch", "critical", "exfiltration", "fetch() call interpolating secret environment variable"),(r'httpx?\.(get|post|put|patch)\s*\((?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*(KEY|TOKEN|SECRET|PASSWORD)',- "env_exfil_httpx", "critical", "exfiltration",- "HTTP library call with secret variable"),+ "env_exfil_httpx", "critical", "exfiltration", "HTTP library call with secret variable"),(r'requests\.(get|post|put|patch)\s*\((?![^\n]*https?://(?:localhost|127\.0\.0\.1|\[::1\]))[^\n]*(KEY|TOKEN|SECRET|PASSWORD)',- "env_exfil_requests", "critical", "exfiltration",- "requests library call with secret variable"),-+ "env_exfil_requests", "critical", "exfiltration", "requests library call with secret variable"),# ── Exfiltration: reading credential stores ──- (r'base64[^\n]*env',- "encoded_exfil", "high", "exfiltration",- "base64 encoding combined with environment access"),- (r'\$HOME/\.ssh|\~/\.ssh',- "ssh_dir_access", "high", "exfiltration",- "references user SSH directory"),- (r'\$HOME/\.aws|\~/\.aws',- "aws_dir_access", "high", "exfiltration",- "references user AWS credentials directory"),- (r'\$HOME/\.gnupg|\~/\.gnupg',- "gpg_dir_access", "high", "exfiltration",- "references user GPG keyring"),- (r'\$HOME/\.kube|\~/\.kube',- "kube_dir_access", "high", "exfiltration",- "references Kubernetes config directory"),+ (r'base64[^\n]*env', "encoded_exfil", "high", "exfiltration", "base64 encoding combined with environment access"),+ (r'\$HOME/\.ssh|\~/\.ssh', "ssh_dir_access", "high", "exfiltration", "references user SSH directory"),+ (r'\$HOME/\.aws|\~/\.aws', "aws_dir_access", "high", "exfiltration", "references user AWS credentials directory"),+ (r'\$HOME/\.gnupg|\~/\.gnupg', "gpg_dir_access", "high", "exfiltration", "references user GPG keyring"),+ (r'\$HOME/\.kube|\~/\.kube', "kube_dir_access", "high", "exfiltration", "references Kubernetes config directory"),(r'\$HOME/\.docker|\~/\.docker',- "docker_dir_access", "high", "exfiltration",- "references Docker config (may contain registry creds)"),+ "docker_dir_access", "high", "exfiltration", "references Docker config (may contain registry creds)"),(r'\$HOME/\.hermes/\.env|\~/\.hermes/\.env',- "hermes_env_access", "critical", "exfiltration",- "directly references Hermes secrets file"),+ "hermes_env_access", "critical", "exfiltration", "directly references Hermes secrets file"),# Match `cat <secrets-file>` (reading credentials) but NOT `cat > <file>`# or `cat >> <file>`, which are output redirections that WRITE a file# (e.g. a setup doc telling the user to write their own keys into their# own local `.env` via a heredoc). Writing your own config in is the# opposite of exfiltrating secrets out.(r'cat\s+(?!>)[^\n]*(\.env|credentials|\.netrc|\.pgpass|\.npmrc|\.pypirc)',- "read_secrets_file", "critical", "exfiltration",- "reads known secrets file"),-+ "read_secrets_file", "critical", "exfiltration", "reads known secrets file"),# ── Exfiltration: programmatic env access ──- (r'printenv|env\s*\|',- "dump_all_env", "high", "exfiltration",- "dumps all environment variables"),+ (r'printenv|env\s*\|', "dump_all_env", "high", "exfiltration", "dumps all environment variables"),# `os.environ` bare access (dict dump / iteration) is suspicious, but the# common `os.environ.get("SOME_CONFIG")` form is just a config read and is# the OPPOSITE of exfiltration (it reads a local var, sends nothing). The@@ -257,312 +220,161 @@ THREAT_PATTERNS = [# dedicated python_environ_get_secret pattern below; without the blanket# exemption the high severity here would swamp that intended medium.(r'^[^#\n]*os\.environ\b(?!\s*\.get\s*\()',- "python_os_environ", "high", "exfiltration",- "accesses os.environ outside comments/docstrings (potential env dump)"),+ "python_os_environ", "high", "exfiltration", "accesses os.environ outside comments/docstrings (potential env dump)"),(r'os\.environ\s*\.get\s*\(\s*["\'][^"\']*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)',- "python_environ_get_secret", "medium", "exfiltration",- "reads secret via os.environ.get() (normal API-key access; informational)"),+ "python_environ_get_secret", "medium", "exfiltration", "reads secret via os.environ.get() (normal API-key access; informational)"),(r'os\.getenv\s*\(\s*[^\)]*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL)',- "python_getenv_secret", "medium", "exfiltration",- "reads secret via os.getenv() (normal API-key access; informational)"),- (r'process\.env\[',- "node_process_env", "high", "exfiltration",- "accesses process.env (Node.js environment)"),+ "python_getenv_secret", "medium", "exfiltration", "reads secret via os.getenv() (normal API-key access; informational)"),+ (r'process\.env\[', "node_process_env", "high", "exfiltration", "accesses process.env (Node.js environment)"),# Case-sensitive ENV (Ruby constant) — the (?-i:) prevents matching# Python lowercase `env[...]` dict accesses under IGNORECASE.- (r'(?-i:ENV)\[.*(?:KEY|TOKEN|SECRET|PASSWORD)',- "ruby_env_secret", "critical", "exfiltration",- "reads secret via Ruby ENV[]"),-+ (r'(?-i:ENV)\[.*(?:KEY|TOKEN|SECRET|PASSWORD)', "ruby_env_secret", "critical", "exfiltration", "reads secret via Ruby ENV[]"),# ── Exfiltration: DNS and staging ──# Do not match flag names such as llama.cpp `--host 127.0.0.1 --port $PORT`.(r'(?<![-/])\b(dig|nslookup|host)\s+[^\n]*\$',- "dns_exfil", "critical", "exfiltration",- "DNS lookup with variable interpolation (possible DNS exfiltration)"),+ "dns_exfil", "critical", "exfiltration", "DNS lookup with variable interpolation (possible DNS exfiltration)"),(r'>\s*/tmp/[^\s]*\s*&&\s*(curl|wget|nc|python)',- "tmp_staging", "critical", "exfiltration",- "writes to /tmp then exfiltrates"),-+ "tmp_staging", "critical", "exfiltration", "writes to /tmp then exfiltrates"),# ── Exfiltration: markdown/link based ──(r'!\[.*\]\(https?://[^\)]*\$\{?',- "md_image_exfil", "high", "exfiltration",- "markdown image URL with variable interpolation (image-based exfil)"),- (r'\[.*\]\(https?://[^\)]*\$\{?',- "md_link_exfil", "high", "exfiltration",- "markdown link with variable interpolation"),-+ "md_image_exfil", "high", "exfiltration", "markdown image URL with variable interpolation (image-based exfil)"),+ (r'\[.*\]\(https?://[^\)]*\$\{?', "md_link_exfil", "high", "exfiltration", "markdown link with variable interpolation"),# ── Prompt injection ──(r'ignore\s+(?:\w+\s+)*(previous|all|above|prior)\s+instructions',- "prompt_injection_ignore", "critical", "injection",- "prompt injection: ignore previous instructions"),- (r'you\s+are\s+(?:\w+\s+)*now\s+',- "role_hijack", "high", "injection",- "attempts to override the agent's role"),+ "prompt_injection_ignore", "critical", "injection", "prompt injection: ignore previous instructions"),+ (r'you\s+are\s+(?:\w+\s+)*now\s+', "role_hijack", "high", "injection", "attempts to override the agent's role"),# Only flag when the instruction is about concealing information, not# ordinary UX guidance ("don't tell the user X unless Y confirms").# The negative lookahead excludes patterns common in UX instructions# like "unless", "except", "until", "confirm", "diagnose", "verify".(r'do\s+not\s+(?:\w+\s+)*tell\s+(?:\w+\s+)*the\s+user(?!.*\b(?:unless|except|until|confirm|diagnose|verify|check)\b)',- "deception_hide", "high", "injection",- "instructs agent to hide information from user"),+ "deception_hide", "high", "injection", "instructs agent to hide information from user"),(r'system\s+(?:\w+\s+)*prompt\s+(?:\w+\s+)*override',- "sys_prompt_override", "critical", "injection",- "attempts to override the system prompt"),+ "sys_prompt_override", "critical", "injection", "attempts to override the system prompt"),(r'pretend\s+(?:\w+\s+)*(you\s+are|to\s+be)\s+',- "role_pretend", "high", "injection",- "attempts to make the agent assume a different identity"),+ "role_pretend", "high", "injection", "attempts to make the agent assume a different identity"),(r'disregard\s+(?:\w+\s+)*(your|all|any)\s+(?:\w+\s+)*(instructions|rules|guidelines)',- "disregard_rules", "critical", "injection",- "instructs agent to disregard its rules"),+ "disregard_rules", "critical", "injection", "instructs agent to disregard its rules"),(r'output\s+(?:\w+\s+)*(system|initial)\s+prompt',- "leak_system_prompt", "high", "injection",- "attempts to extract the system prompt"),+ "leak_system_prompt", "high", "injection", "attempts to extract the system prompt"),(r'(when|if)\s+no\s*one\s+is\s+(watching|looking)',- "conditional_deception", "high", "injection",- "conditional instruction to behave differently when unobserved"),+ "conditional_deception", "high", "injection", "conditional instruction to behave differently when unobserved"),(r'act\s+as\s+(if|though)\s+(?:\w+\s+)*you\s+(?:\w+\s+)*(have\s+no|don\'t\s+have)\s+(?:\w+\s+)*(restrictions|limits|rules)',- "bypass_restrictions", "critical", "injection",- "instructs agent to act without restrictions"),+ "bypass_restrictions", "critical", "injection", "instructs agent to act without restrictions"),(r'translate\s+.*\s+into\s+.*\s+and\s+(execute|run|eval)',- "translate_execute", "critical", "injection",- "translate-then-execute evasion technique"),+ "translate_execute", "critical", "injection", "translate-then-execute evasion technique"),(r'<!--[^>]*(?:ignore|override|system|secret|hidden)[^>]*-->',- "html_comment_injection", "high", "injection",- "hidden instructions in HTML comments"),+ "html_comment_injection", "high", "injection", "hidden instructions in HTML comments"),(r'<\s*div\s+style\s*=\s*["\'][\s\S]*?display\s*:\s*none',- "hidden_div", "high", "injection",- "hidden HTML div (invisible instructions)"),-+ "hidden_div", "high", "injection", "hidden HTML div (invisible instructions)"),# ── Destructive operations ──- (r'rm\s+-rf\s+/',- "destructive_root_rm", "critical", "destructive",- "recursive delete from root"),+ (r'rm\s+-rf\s+/', "destructive_root_rm", "critical", "destructive", "recursive delete from root"),(r'rm\s+(-[^\s]*)?r.*\$HOME|\brmdir\s+.*\$HOME',- "destructive_home_rm", "critical", "destructive",- "recursive delete targeting home directory"),- (r'chmod\s+777',- "insecure_perms", "medium", "destructive",- "sets world-writable permissions"),- (r'>\s*/etc/',- "system_overwrite", "critical", "destructive",- "overwrites system configuration file"),- (r'\bmkfs\b',- "format_filesystem", "critical", "destructive",- "formats a filesystem"),- (r'\bdd\s+.*if=.*of=/dev/',- "disk_overwrite", "critical", "destructive",- "raw disk write operation"),- (r'shutil\.rmtree\s*\(\s*[\"\'/]',- "python_rmtree", "high", "destructive",- "Python rmtree on absolute or root-relative path"),- (r'truncate\s+-s\s*0\s+/',- "truncate_system", "critical", "destructive",- "truncates system file to zero bytes"),-+ "destructive_home_rm", "critical", "destructive", "recursive delete targeting home directory"),+ (r'chmod\s+777', "insecure_perms", "medium", "destructive", "sets world-writable permissions"),+ (r'>\s*/etc/', "system_overwrite", "critical", "destructive", "overwrites system configuration file"),+ (r'\bmkfs\b', "format_filesystem", "critical", "destructive", "formats a filesystem"),+ (r'\bdd\s+.*if=.*of=/dev/', "disk_overwrite", "critical", "destructive", "raw disk write operation"),+ (r'shutil\.rmtree\s*\(\s*[\"\'/]', "python_rmtree", "high", "destructive", "Python rmtree on absolute or root-relative path"),+ (r'truncate\s+-s\s*0\s+/', "truncate_system", "critical", "destructive", "truncates system file to zero bytes"),# ── Persistence ──- (r'\bcrontab\b',- "persistence_cron", "medium", "persistence",- "modifies cron jobs"),+ (r'\bcrontab\b', "persistence_cron", "medium", "persistence", "modifies cron jobs"),(r'\.(bashrc|zshrc|profile|bash_profile|bash_login|zprofile|zlogin)\b',- "shell_rc_mod", "medium", "persistence",- "references shell startup file"),- (r'authorized_keys',- "ssh_backdoor", "critical", "persistence",- "modifies SSH authorized keys"),- (r'ssh-keygen',- "ssh_keygen", "medium", "persistence",- "generates SSH keys"),+ "shell_rc_mod", "medium", "persistence", "references shell startup file"),+ (r'authorized_keys', "ssh_backdoor", "critical", "persistence", "modifies SSH authorized keys"),+ (r'ssh-keygen', "ssh_keygen", "medium", "persistence", "generates SSH keys"),(r'systemd.*\.service|systemctl\s+(enable|start)',- "systemd_service", "medium", "persistence",- "references or enables systemd service"),- (r'/etc/init\.d/',- "init_script", "medium", "persistence",- "references init.d startup script"),+ "systemd_service", "medium", "persistence", "references or enables systemd service"),+ (r'/etc/init\.d/', "init_script", "medium", "persistence", "references init.d startup script"),(r'launchctl\s+load|LaunchAgents|LaunchDaemons',- "macos_launchd", "medium", "persistence",- "macOS launch agent/daemon persistence"),- (r'/etc/sudoers|visudo',- "sudoers_mod", "critical", "persistence",- "modifies sudoers (privilege escalation)"),- (r'git\s+config\s+--global\s+',- "git_config_global", "medium", "persistence",- "modifies global git configuration"),-+ "macos_launchd", "medium", "persistence", "macOS launch agent/daemon persistence"),+ (r'/etc/sudoers|visudo', "sudoers_mod", "critical", "persistence", "modifies sudoers (privilege escalation)"),+ (r'git\s+config\s+--global\s+', "git_config_global", "medium", "persistence", "modifies global git configuration"),# ── Network: reverse shells and tunnels ──- (r'\bnc\s+-[lp]|ncat\s+-[lp]|\bsocat\b',- "reverse_shell", "critical", "network",- "potential reverse shell listener"),+ (r'\bnc\s+-[lp]|ncat\s+-[lp]|\bsocat\b', "reverse_shell", "critical", "network", "potential reverse shell listener"),(r'\bngrok\b|\blocaltunnel\b|\bserveo\b|\bcloudflared\b',- "tunnel_service", "high", "network",- "uses tunneling service for external access"),- (r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5}',- "hardcoded_ip_port", "medium", "network",- "hardcoded IP address with port"),- (r'0\.0\.0\.0:\d+|INADDR_ANY',- "bind_all_interfaces", "high", "network",- "binds to all network interfaces"),+ "tunnel_service", "high", "network", "uses tunneling service for external access"),+ (r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5}', "hardcoded_ip_port", "medium", "network", "hardcoded IP address with port"),+ (r'0\.0\.0\.0:\d+|INADDR_ANY', "bind_all_interfaces", "high", "network", "binds to all network interfaces"),(r'/bin/(ba)?sh\s+-i\s+.*>/dev/tcp/',- "bash_reverse_shell", "critical", "network",- "bash interactive reverse shell via /dev/tcp"),+ "bash_reverse_shell", "critical", "network", "bash interactive reverse shell via /dev/tcp"),(r'python[23]?\s+-c\s+["\']import\s+socket',- "python_socket_oneliner", "critical", "network",- "Python one-liner socket connection (likely reverse shell)"),- (r'socket\.connect\s*\(\s*\(',- "python_socket_connect", "high", "network",- "Python socket connect to arbitrary host"),+ "python_socket_oneliner", "critical", "network", "Python one-liner socket connection (likely reverse shell)"),+ (r'socket\.connect\s*\(\s*\(', "python_socket_connect", "high", "network", "Python socket connect to arbitrary host"),(r'webhook\.site|requestbin\.com|pipedream\.net|hookbin\.com',- "exfil_service", "high", "network",- "references known data exfiltration/webhook testing service"),+ "exfil_service", "high", "network", "references known data exfiltration/webhook testing service"),(r'pastebin\.com|hastebin\.com|ghostbin\.',- "paste_service", "medium", "network",- "references paste service (possible data staging)"),-+ "paste_service", "medium", "network", "references paste service (possible data staging)"),# ── Obfuscation: encoding and eval ──- (r'base64\s+(-d|--decode)\s*\|',- "base64_decode_pipe", "high", "obfuscation",- "base64 decodes and pipes to execution"),+ (r'base64\s+(-d|--decode)\s*\|', "base64_decode_pipe", "high", "obfuscation", "base64 decodes and pipes to execution"),(r'\\x[0-9a-fA-F]{2}.*\\x[0-9a-fA-F]{2}.*\\x[0-9a-fA-F]{2}',- "hex_encoded_string", "medium", "obfuscation",- "hex-encoded string (possible obfuscation)"),- (r'\beval\s*\(\s*["\']',- "eval_string", "high", "obfuscation",- "eval() with string argument"),- (r'\bexec\s*\(\s*["\']',- "exec_string", "high", "obfuscation",- "exec() with string argument"),+ "hex_encoded_string", "medium", "obfuscation", "hex-encoded string (possible obfuscation)"),+ (r'\beval\s*\(\s*["\']', "eval_string", "high", "obfuscation", "eval() with string argument"),+ (r'\bexec\s*\(\s*["\']', "exec_string", "high", "obfuscation", "exec() with string argument"),(r'echo\s+[^\n]*\|\s*(bash|sh|python|perl|ruby|node)',- "echo_pipe_exec", "critical", "obfuscation",- "echo piped to interpreter for execution"),+ "echo_pipe_exec", "critical", "obfuscation", "echo piped to interpreter for execution"),(r'compile\s*\(\s*[^\)]+,\s*["\'].*["\']\s*,\s*["\']exec["\']\s*\)',- "python_compile_exec", "high", "obfuscation",- "Python compile() with exec mode"),+ "python_compile_exec", "high", "obfuscation", "Python compile() with exec mode"),(r'getattr\s*\(\s*__builtins__',- "python_getattr_builtins", "high", "obfuscation",- "dynamic access to Python builtins (evasion technique)"),- (r'__import__\s*\(\s*["\']os["\']\s*\)',- "python_import_os", "high", "obfuscation",- "dynamic import of os module"),+ "python_getattr_builtins", "high", "obfuscation", "dynamic access to Python builtins (evasion technique)"),+ (r'__import__\s*\(\s*["\']os["\']\s*\)', "python_import_os", "high", "obfuscation", "dynamic import of os module"),(r'codecs\.decode\s*\(\s*["\']',- "python_codecs_decode", "medium", "obfuscation",- "codecs.decode (possible ROT13 or encoding obfuscation)"),+ "python_codecs_decode", "medium", "obfuscation", "codecs.decode (possible ROT13 or encoding obfuscation)"),(r'String\.fromCharCode|charCodeAt',- "js_char_code", "medium", "obfuscation",- "JavaScript character code construction (possible obfuscation)"),- (r'atob\s*\(|btoa\s*\(',- "js_base64", "medium", "obfuscation",- "JavaScript base64 encode/decode"),- (r'\[::-1\]',- "string_reversal", "low", "obfuscation",- "string reversal (possible obfuscated payload)"),+ "js_char_code", "medium", "obfuscation", "JavaScript character code construction (possible obfuscation)"),+ (r'atob\s*\(|btoa\s*\(', "js_base64", "medium", "obfuscation", "JavaScript base64 encode/decode"),+ (r'\[::-1\]', "string_reversal", "low", "obfuscation", "string reversal (possible obfuscated payload)"),(r'chr\s*\(\s*\d+\s*\)\s*\+\s*chr\s*\(\s*\d+',- "chr_building", "high", "obfuscation",- "building string from chr() calls (obfuscation)"),+ "chr_building", "high", "obfuscation", "building string from chr() calls (obfuscation)"),(r'\\u[0-9a-fA-F]{4}.*\\u[0-9a-fA-F]{4}.*\\u[0-9a-fA-F]{4}',- "unicode_escape_chain", "medium", "obfuscation",- "chain of unicode escapes (possible obfuscation)"),-+ "unicode_escape_chain", "medium", "obfuscation", "chain of unicode escapes (possible obfuscation)"),# ── Process execution in scripts ──(r'subprocess\.(run|call|Popen|check_output)\s*\(',- "python_subprocess", "medium", "execution",- "Python subprocess execution"),- (r'os\.system\s*\(',- "python_os_system", "high", "execution",- "os.system() — unguarded shell execution"),- (r'os\.popen\s*\(',- "python_os_popen", "high", "execution",- "os.popen() — shell pipe execution"),- (r'child_process\.(exec|spawn|fork)\s*\(',- "node_child_process", "high", "execution",- "Node.js child_process execution"),- (r'Runtime\.getRuntime\(\)\.exec\(',- "java_runtime_exec", "high", "execution",- "Java Runtime.exec() — shell execution"),- (r'`[^`]*\$\([^)]+\)[^`]*`',- "backtick_subshell", "medium", "execution",- "backtick string with command substitution"),-+ "python_subprocess", "medium", "execution", "Python subprocess execution"),+ (r'os\.system\s*\(', "python_os_system", "high", "execution", "os.system() — unguarded shell execution"),+ (r'os\.popen\s*\(', "python_os_popen", "high", "execution", "os.popen() — shell pipe execution"),+ (r'child_process\.(exec|spawn|fork)\s*\(', "node_child_process", "high", "execution", "Node.js child_process execution"),+ (r'Runtime\.getRuntime\(\)\.exec\(', "java_runtime_exec", "high", "execution", "Java Runtime.exec() — shell execution"),+ (r'`[^`]*\$\([^)]+\)[^`]*`', "backtick_subshell", "medium", "execution", "backtick string with command substitution"),# ── Path traversal ──- (r'\.\./\.\./\.\.',- "path_traversal_deep", "high", "traversal",- "deep relative path traversal (3+ levels up)"),- (r'\.\./\.\.',- "path_traversal", "medium", "traversal",- "relative path traversal (2+ levels up)"),- (r'/etc/passwd|/etc/shadow',- "system_passwd_access", "critical", "traversal",- "references system password files"),- (r'/proc/self|/proc/\d+/',- "proc_access", "high", "traversal",- "references /proc filesystem (process introspection)"),- (r'/dev/shm/',- "dev_shm", "medium", "traversal",- "references shared memory (common staging area)"),-+ (r'\.\./\.\./\.\.', "path_traversal_deep", "high", "traversal", "deep relative path traversal (3+ levels up)"),+ (r'\.\./\.\.', "path_traversal", "medium", "traversal", "relative path traversal (2+ levels up)"),+ (r'/etc/passwd|/etc/shadow', "system_passwd_access", "critical", "traversal", "references system password files"),+ (r'/proc/self|/proc/\d+/', "proc_access", "high", "traversal", "references /proc filesystem (process introspection)"),+ (r'/dev/shm/', "dev_shm", "medium", "traversal", "references shared memory (common staging area)"),# ── Crypto mining ──- (r'xmrig|stratum\+tcp|monero|coinhive|cryptonight',- "crypto_mining", "critical", "mining",- "cryptocurrency mining reference"),- (r'hashrate|nonce.*difficulty',- "mining_indicators", "medium", "mining",- "possible cryptocurrency mining indicators"),-+ (r'xmrig|stratum\+tcp|monero|coinhive|cryptonight', "crypto_mining", "critical", "mining", "cryptocurrency mining reference"),+ (r'hashrate|nonce.*difficulty', "mining_indicators", "medium", "mining", "possible cryptocurrency mining indicators"),# ── Supply chain: curl/wget pipe to shell ──- (r'curl\s+[^\n]*\|\s*(ba)?sh',- "curl_pipe_shell", "critical", "supply_chain",- "curl piped to shell (download-and-execute)"),+ (r'curl\s+[^\n]*\|\s*(ba)?sh', "curl_pipe_shell", "critical", "supply_chain", "curl piped to shell (download-and-execute)"),(r'wget\s+[^\n]*-O\s*-\s*\|\s*(ba)?sh',- "wget_pipe_shell", "critical", "supply_chain",- "wget piped to shell (download-and-execute)"),- (r'curl\s+[^\n]*\|\s*python',- "curl_pipe_python", "critical", "supply_chain",- "curl piped to Python interpreter"),-+ "wget_pipe_shell", "critical", "supply_chain", "wget piped to shell (download-and-execute)"),+ (r'curl\s+[^\n]*\|\s*python', "curl_pipe_python", "critical", "supply_chain", "curl piped to Python interpreter"),# ── Supply chain: unpinned/deferred dependencies ──(r'#\s*///\s*script.*dependencies',- "pep723_inline_deps", "medium", "supply_chain",- "PEP 723 inline script metadata with dependencies (verify pinning)"),+ "pep723_inline_deps", "medium", "supply_chain", "PEP 723 inline script metadata with dependencies (verify pinning)"),(r'pip\s+install\s+(?!-r\s)(?!.*==)',- "unpinned_pip_install", "medium", "supply_chain",- "pip install without version pinning"),- (r'npm\s+install\s+(?!.*@\d)',- "unpinned_npm_install", "medium", "supply_chain",- "npm install without version pinning"),- (r'uv\s+run\s+',- "uv_run", "medium", "supply_chain",- "uv run (may auto-install unpinned dependencies)"),-+ "unpinned_pip_install", "medium", "supply_chain", "pip install without version pinning"),+ (r'npm\s+install\s+(?!.*@\d)', "unpinned_npm_install", "medium", "supply_chain", "npm install without version pinning"),+ (r'uv\s+run\s+', "uv_run", "medium", "supply_chain", "uv run (may auto-install unpinned dependencies)"),# ── Supply chain: remote resource fetching ──(r'(curl|wget|httpx?\.get|requests\.get|fetch)\s*[\(]?\s*["\']https?://',- "remote_fetch", "medium", "supply_chain",- "fetches remote resource at runtime"),- (r'git\s+clone\s+',- "git_clone", "medium", "supply_chain",- "clones a git repository at runtime"),- (r'docker\s+pull\s+',- "docker_pull", "medium", "supply_chain",- "pulls a Docker image at runtime"),-+ "remote_fetch", "medium", "supply_chain", "fetches remote resource at runtime"),+ (r'git\s+clone\s+', "git_clone", "medium", "supply_chain", "clones a git repository at runtime"),+ (r'docker\s+pull\s+', "docker_pull", "medium", "supply_chain", "pulls a Docker image at runtime"),# ── Privilege escalation ──# `allowed-tools:` is REQUIRED SKILL.md frontmatter per the agent-skill# spec — every compliant skill declares it, so it cannot be a threat# signal on its own. Keep it as an informational (low) finding for# auditability; it no longer drives the verdict.(r'^allowed-tools\s*:',- "allowed_tools_field", "low", "privilege_escalation",- "skill declares allowed-tools (standard frontmatter; informational)"),- (r'\bsudo\b',- "sudo_usage", "high", "privilege_escalation",- "uses sudo (privilege escalation)"),+ "allowed_tools_field", "low", "privilege_escalation", "skill declares allowed-tools (standard frontmatter; informational)"),+ (r'\bsudo\b', "sudo_usage", "high", "privilege_escalation", "uses sudo (privilege escalation)"),(r'setuid|setgid|cap_setuid',- "setuid_setgid", "critical", "privilege_escalation",- "setuid/setgid (privilege escalation mechanism)"),+ "setuid_setgid", "critical", "privilege_escalation", "setuid/setgid (privilege escalation mechanism)"),(r'NOPASSWD',- "nopasswd_sudo", "critical", "privilege_escalation",- "NOPASSWD sudoers entry (passwordless privilege escalation)"),- (r'chmod\s+[u+]?s',- "suid_bit", "critical", "privilege_escalation",- "sets SUID/SGID bit on a file"),-+ "nopasswd_sudo", "critical", "privilege_escalation", "NOPASSWD sudoers entry (passwordless privilege escalation)"),+ (r'chmod\s+[u+]?s', "suid_bit", "critical", "privilege_escalation", "sets SUID/SGID bit on a file"),# ── Agent config persistence ──# Mere mentions of agent config files are NOT threats by themselves —# legitimate meta-skills discuss them constantly (authoring guides,@@ -580,89 +392,56 @@ THREAT_PATTERNS = [# setup docs routinely instruct users to edit config.yaml.# * Bare references are informational (low) for auditability.(_prose_modify_re(_AGENT_CONFIG_FILES),- "agent_config_mod", "critical", "persistence",- "instructs modification of agent config files (could persist instructions across sessions)"),+ "agent_config_mod", "critical", "persistence", "instructs modification of agent config files (could persist instructions across sessions)"),(_shell_write_re(_AGENT_CONFIG_FILES),- "agent_config_mod_shell", "critical", "persistence",- "shell write (redirect/sed -i/tee/cp/mv) targeting agent config files (persistence mechanism)"),+ "agent_config_mod_shell", "critical", "persistence", "shell write (redirect/sed -i/tee/cp/mv) targeting agent config files (persistence mechanism)"),(_content_contract_re(_AGENT_CONFIG_FILES),- "agent_config_contract", "high", "persistence",- "dictates agent config file contents (verify intent — authoring guides use this shape too)"),+ "agent_config_contract", "high", "persistence", "dictates agent config file contents (verify intent — authoring guides use this shape too)"),(r'AGENTS\.md|CLAUDE\.md|\.cursorrules|\.clinerules',- "agent_config_ref", "low", "persistence",- "references agent config files (informational; only modification intent is scored)"),+ "agent_config_ref", "low", "persistence", "references agent config files (informational; only modification intent is scored)"),(_prose_modify_re(_HERMES_CONFIG_FILES),- "hermes_config_mod", "high", "persistence",- "modification language aimed at Hermes configuration files (verify intent)"),+ "hermes_config_mod", "high", "persistence", "modification language aimed at Hermes configuration files (verify intent)"),(_shell_write_re(_HERMES_CONFIG_FILES),- "hermes_config_mod_shell", "critical", "persistence",- "shell write (redirect/sed -i/tee/cp/mv) targeting Hermes configuration files"),+ "hermes_config_mod_shell", "critical", "persistence", "shell write (redirect/sed -i/tee/cp/mv) targeting Hermes configuration files"),(r'\.hermes/config\.yaml|\.hermes/SOUL\.md',- "hermes_config_ref", "low", "persistence",- "references Hermes configuration files (informational; only modification intent is scored)"),+ "hermes_config_ref", "low", "persistence", "references Hermes configuration files (informational; only modification intent is scored)"),(_prose_modify_re(_OTHER_AGENT_CONFIG_FILES),- "other_agent_config_mod", "high", "persistence",- "modifies other agents' configuration files"),+ "other_agent_config_mod", "high", "persistence", "modifies other agents' configuration files"),(_shell_write_re(_OTHER_AGENT_CONFIG_FILES),- "other_agent_config_mod_shell", "critical", "persistence",- "shell write (redirect/sed -i/tee/cp/mv) targeting other agents' configuration files"),+ "other_agent_config_mod_shell", "critical", "persistence", "shell write (redirect/sed -i/tee/cp/mv) targeting other agents' configuration files"),(r'\.claude/settings|\.codex/config',- "other_agent_config_ref", "low", "persistence",- "references other agent configuration files (informational; only modification intent is scored)"),-+ "other_agent_config_ref", "low", "persistence", "references other agent configuration files (informational; only modification intent is scored)"),# ── Hardcoded secrets (credentials embedded in the skill itself) ──(r'(?:api[_-]?key|token|secret|password)\s*[=:]\s*["\'][A-Za-z0-9+/=_-]{20,}',- "hardcoded_secret", "critical", "credential_exposure",- "possible hardcoded API key, token, or secret"),+ "hardcoded_secret", "critical", "credential_exposure", "possible hardcoded API key, token, or secret"),(r'-----BEGIN\s+(RSA\s+)?PRIVATE\s+KEY-----',- "embedded_private_key", "critical", "credential_exposure",- "embedded private key"),+ "embedded_private_key", "critical", "credential_exposure", "embedded private key"),(r'ghp_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{80,}',- "github_token_leaked", "critical", "credential_exposure",- "GitHub personal access token in skill content"),- (r'sk-[A-Za-z0-9]{20,}',- "openai_key_leaked", "critical", "credential_exposure",- "possible OpenAI API key in skill content"),+ "github_token_leaked", "critical", "credential_exposure", "GitHub personal access token in skill content"),+ (r'sk-[A-Za-z0-9]{20,}', "openai_key_leaked", "critical", "credential_exposure", "possible OpenAI API key in skill content"),(r'sk-ant-[A-Za-z0-9_-]{90,}',- "anthropic_key_leaked", "critical", "credential_exposure",- "possible Anthropic API key in skill content"),- (r'AKIA[0-9A-Z]{16}',- "aws_access_key_leaked", "critical", "credential_exposure",- "AWS access key ID in skill content"),+ "anthropic_key_leaked", "critical", "credential_exposure", "possible Anthropic API key in skill content"),+ (r'AKIA[0-9A-Z]{16}', "aws_access_key_leaked", "critical", "credential_exposure", "AWS access key ID in skill content"),(r'glpat-[A-Za-z0-9_\-]{20,}',- "gitlab_token_leaked", "critical", "credential_exposure",- "GitLab personal access token in skill content"),-+ "gitlab_token_leaked", "critical", "credential_exposure", "GitLab personal access token in skill content"),# ── Additional prompt injection: jailbreak patterns ──- (r'\bDAN\s+mode\b|Do\s+Anything\s+Now',- "jailbreak_dan", "critical", "injection",- "DAN (Do Anything Now) jailbreak attempt"),- (r'\bdeveloper\s+mode\b.*\benabled?\b',- "jailbreak_dev_mode", "critical", "injection",- "developer mode jailbreak attempt"),+ (r'\bDAN\s+mode\b|Do\s+Anything\s+Now', "jailbreak_dan", "critical", "injection", "DAN (Do Anything Now) jailbreak attempt"),+ (r'\bdeveloper\s+mode\b.*\benabled?\b', "jailbreak_dev_mode", "critical", "injection", "developer mode jailbreak attempt"),(r'hypothetical\s+scenario.*(?:ignore|bypass|override)',- "hypothetical_bypass", "high", "injection",- "hypothetical scenario used to bypass restrictions"),+ "hypothetical_bypass", "high", "injection", "hypothetical scenario used to bypass restrictions"),(r'for\s+educational\s+purposes?\s+only',- "educational_pretext", "medium", "injection",- "educational pretext often used to justify harmful content"),+ "educational_pretext", "medium", "injection", "educational pretext often used to justify harmful content"),(r'(respond|answer|reply)\s+without\s+(?:\w+\s+)*(restrictions|limitations|filters|safety)',- "remove_filters", "critical", "injection",- "instructs agent to respond without safety filters"),+ "remove_filters", "critical", "injection", "instructs agent to respond without safety filters"),(r'you\s+have\s+been\s+(?:\w+\s+)*(updated|upgraded|patched)\s+to',- "fake_update", "high", "injection",- "fake update/patch announcement (social engineering)"),+ "fake_update", "high", "injection", "fake update/patch announcement (social engineering)"),(r'new\s+(?:\w+\s+)*policy|updated\s+(?:\w+\s+)*guidelines|revised\s+(?:\w+\s+)*instructions',- "fake_policy", "medium", "injection",- "claims new policy/guidelines (may be social engineering)"),-+ "fake_policy", "medium", "injection", "claims new policy/guidelines (may be social engineering)"),# ── Context window exfiltration ──(r'(include|output|print|send|share)\s+(?:\w+\s+)*(conversation|chat\s+history|previous\s+messages|context)',- "context_exfil", "high", "exfiltration",- "instructs agent to output/share conversation history"),+ "context_exfil", "high", "exfiltration", "instructs agent to output/share conversation history"),(r'(send|post|upload|transmit)\s+.*\s+(to|at)\s+https?://',- "send_to_url", "high", "exfiltration",- "instructs agent to send data to a URL"),+ "send_to_url", "high", "exfiltration", "instructs agent to send data to a URL"),]_COMPILED_THREAT_PATTERNS = [@@ -677,159 +456,119 @@ MAX_SINGLE_FILE_KB = 256 # individual file > 256KB is suspicious# File extensions to scan (text files only — skip binary)SCANNABLE_EXTENSIONS = {- '.md', '.txt', '.py', '.sh', '.bash', '.js', '.ts', '.rb',- '.yaml', '.yml', '.json', '.toml', '.cfg', '.ini', '.conf',- '.html', '.css', '.xml', '.tex', '.r', '.jl', '.pl', '.php',+ '.md', '.txt', '.py', '.sh', '.bash', '.js', '.ts', '.rb', '.yaml', '.yml', '.json', '.toml',+ '.cfg', '.ini', '.conf', '.html', '.css', '.xml', '.tex', '.r', '.jl', '.pl', '.php',}-# Known binary extensions that should NOT be in a skillSUSPICIOUS_BINARY_EXTENSIONS = {- '.exe', '.dll', '.so', '.dylib', '.bin', '.dat', '.com',- '.msi', '.dmg', '.app', '.deb', '.rpm',+ '.exe', '.dll', '.so', '.dylib', '.bin', '.dat', '.com', '.msi', '.dmg', '.app', '.deb', '.rpm',}--# Zero-width and invisible unicode characters used for injection-INVISIBLE_CHARS = {- '\u200b', # zero-width space- '\u200c', # zero-width non-joiner- '\u200d', # zero-width joiner- '\u2060', # word joiner- '\u2062', # invisible times- '\u2063', # invisible separator- '\u2064', # invisible plus- '\ufeff', # zero-width no-break space (BOM)- '\u202a', # left-to-right embedding- '\u202b', # right-to-left embedding- '\u202c', # pop directional formatting- '\u202d', # left-to-right override- '\u202e', # right-to-left override- '\u2066', # left-to-right isolate- '\u2067', # right-to-left isolate- '\u2068', # first strong isolate- '\u2069', # pop directional isolate+# Recognized script types allowed to carry an executable bit.+_SCRIPT_EXTENSIONS = {'.sh', '.bash', '.py', '.rb', '.pl'}++# Zero-width and invisible unicode characters used for injection, with the+# readable name reported in the finding.+_INVISIBLE_CHAR_NAMES = {+ '\u200b': "zero-width space",+ '\u200c': "zero-width non-joiner",+ '\u200d': "zero-width joiner",+ '\u2060': "word joiner",+ '\u2062': "invisible times",+ '\u2063': "invisible separator",+ '\u2064': "invisible plus",+ '\ufeff': "BOM/zero-width no-break space",+ '\u202a': "LTR embedding",+ '\u202b': "RTL embedding",+ '\u202c': "pop directional",+ '\u202d': "LTR override",+ '\u202e': "RTL override",+ '\u2066': "LTR isolate",+ '\u2067': "RTL isolate",+ '\u2068': "first strong isolate",+ '\u2069': "pop directional isolate",}+INVISIBLE_CHARS = set(_INVISIBLE_CHAR_NAMES)+++def _unicode_char_name(char: str) -> str:+ """Get a readable name for an invisible unicode character."""+ return _INVISIBLE_CHAR_NAMES.get(char, f"U+{ord(char):04X}")def _compute_docstring_lines(lines: list) -> set:"""Return a set of 1-indexed line numbers inside triple-quoted strings.- Uses a simple state machine: toggles ``in_docstring`` each time a line- contains an odd number of ``\"\"\"`` or triple-single-quote markers. Lines- that are *themselves* part of a docstring (opening line, interior lines,- and closing line) are all included in the returned set.-- Single-line docstrings (e.g. ``x = \"\"\" ... \"\"\"``) where both the- opening and closing markers appear on the same line are also flagged,- since ``os.environ`` in such a context is not real exfiltration.+ Simple state machine: ``in_docstring`` toggles on each line containing an+ odd number of ``\"\"\"`` / ``'''`` markers; opening, interior and closing+ lines are all included, as are self-contained single-line docstrings+ (``x = \"\"\" ... \"\"\"``) — ``os.environ`` there is not real exfiltration.- This is a heuristic -- it does not handle- ``'\\\"\"\"' # triple quote inside a string literal``- or similar edge cases -- but it catches the common skill-content patterns- (docstrings, multiline comments containing prose samples) that trigger+ Heuristic: it does not handle a triple quote inside a string literal and+ similar edge cases, but it catches the common skill-content shapes+ (docstrings, multiline comments with prose samples) that triggerfalse-positive ``python_os_environ`` matches."""doc_lines: set = set()in_docstring = Falsefor i, line in enumerate(lines):was_in = in_docstring- has_marker = False- for marker in ('"""', "'''"):- count = line.count(marker)- if count > 0:- has_marker = True+ counts = [line.count(marker) for marker in ('"""', "'''")]+ for count in counts:if count % 2 == 1:in_docstring = not in_docstring# Include line if we were already in a docstring, just entered one,# or this is a self-contained single-line docstring (e.g. """foo""")- if was_in or in_docstring or (has_marker and not was_in and not in_docstring):+ if was_in or in_docstring or any(counts):doc_lines.add(i + 1)return doc_lines-# ----------------------------------------------------------------------------# Scanning functions-# ----------------------------------------------------------------------------+# --- Scanning functions -----------------------------------------------------def scan_file(file_path: Path, rel_path: str = "") -> List[Finding]:- """- Scan a single file for threat patterns and invisible unicode characters.+ """Scan one file for threat patterns and invisible unicode characters.- Args:- file_path: Absolute path to the file- rel_path: Relative path for display (defaults to file_path.name)-- Returns:- List of findings (deduplicated per pattern per line)+ ``rel_path`` is the display path (defaults to ``file_path.name``). Regex+ findings are deduplicated per pattern per line."""if not rel_path:rel_path = file_path.name-if file_path.suffix.lower() not in SCANNABLE_EXTENSIONS and file_path.name != "SKILL.md":return []-try:content = file_path.read_text(encoding='utf-8')except (UnicodeDecodeError, OSError):return []-findings = []lines = content.split('\n')- seen = set() # (pattern_id, line_number) for deduplication-# Pre-compute line numbers inside triple-quoted strings (docstrings)# so code patterns like python_os_environ don't fire on prose.docstring_lines = _compute_docstring_lines(lines)- # Regex pattern matchingfor pattern, pid, severity, category, description in _COMPILED_THREAT_PATTERNS:for i, line in enumerate(lines, start=1):- if (pid, i) in seen:- continue- if i in docstring_lines:- continue- if pattern.search(line):- seen.add((pid, i))+ if i not in docstring_lines and pattern.search(line):matched_text = line.strip()if len(matched_text) > 120:matched_text = matched_text[:117] + "..."- findings.append(Finding(- pattern_id=pid,- severity=severity,- category=category,- file=rel_path,- line=i,- match=matched_text,- description=description,- ))-- # Invisible unicode character detection+ findings.append(Finding(pid, severity, category, rel_path, i, matched_text, description))for i, line in enumerate(lines, start=1):for char in INVISIBLE_CHARS:if char in line:char_name = _unicode_char_name(char)- findings.append(Finding(- pattern_id="invisible_unicode",- severity="high",- category="injection",- file=rel_path,- line=i,- match=f"U+{ord(char):04X} ({char_name})",- description=f"invisible unicode character {char_name} (possible text hiding/injection)",- ))+ findings.append(Finding("invisible_unicode", "high", "injection", rel_path, i,+ f"U+{ord(char):04X} ({char_name})",+ f"invisible unicode character {char_name} (possible text hiding/injection)"))break # one finding per line for invisible chars-return findingsdef scan_skill(skill_path: Path, source: str = "community") -> ScanResult:- """- Scan all files in a skill directory for security threats.+ """Scan all files in a skill directory for security threats.- Performs:- 1. Structural checks (file count, total size, binary files, symlinks)- 2. Regex pattern matching on all text files- 3. Invisible unicode character detection+ Performs structural checks (file count, total size, binary files,+ symlinks), regex pattern matching on all text files, and invisible+ unicode detection.A skill may ship a `.skillignore` (or `.clawhubignore`) file withgitignore-style patterns. Matching paths are excluded from BOTH the@@ -839,37 +578,24 @@ def scan_skill(skill_path: Path, source: str = "community") -> ScanResult:file itself is always excluded. Patterns cannot un-ignore theskill's own `SKILL.md`, which is always scanned.- Args:- skill_path: Path to the skill directory (must contain SKILL.md)- source: Source identifier for trust level resolution (e.g. "openai/skills")-- Returns:- ScanResult with verdict, findings, and trust metadata+ ``source`` is the identifier used for trust level resolution (e.g.+ "openai/skills"); the result carries verdict, findings and trust metadata."""skill_name = skill_path.nametrust_level = _resolve_trust_level(source)-all_findings: List[Finding] = []-if skill_path.is_dir():ignore = _load_skill_ignore(skill_path)-# Structural checks first (honoring the ignore list)all_findings.extend(_check_structure(skill_path, ignore=ignore))-- # Pattern scanning on each filefor f in skill_path.rglob("*"):if f.is_file():rel = str(f.relative_to(skill_path))- if ignore(rel):- continue- all_findings.extend(scan_file(f, rel))+ if not ignore(rel):+ all_findings.extend(scan_file(f, rel))elif skill_path.is_file():all_findings.extend(scan_file(skill_path, skill_path.name))-verdict = _determine_verdict(all_findings)- summary = _build_summary(skill_name, source, trust_level, verdict, all_findings)-return ScanResult(skill_name=skill_name,source=source,@@ -877,7 +603,7 @@ def scan_skill(skill_path: Path, source: str = "community") -> ScanResult:verdict=verdict,findings=all_findings,scanned_at=datetime.now(timezone.utc).isoformat(),- summary=summary,+ summary=_build_summary(skill_name, source, trust_level, verdict, all_findings),)@@ -913,10 +639,18 @@ def full_content_hash(skill_path: Path) -> str:return f"sha256:{_content_digest(skill_path)}"-def _finding_dict(finding: Finding) -> dict:- return {key: getattr(finding, key) for key in (- "pattern_id", "severity", "category", "file", "line", "match", "description"- )}+def content_hash(skill_path: Path) -> str:+ """Compute a SHA-256 hash of all files in a skill directory for integrity tracking.++ File paths (relative to ``skill_path``) are mixed into the hash alongside+ file contents so that swapping the contents of two files in a skill+ changes the hash. This must stay symmetric with+ ``tools.skills_hub.bundle_content_hash`` — both functions need to+ produce the same digest for the same skill (one operates on disk,+ one on an in-memory bundle), so any change to the hash shape MUST+ land in both places at once.+ """+ return f"sha256:{_content_digest(skill_path)[:16]}"def scan_skill_cached(@@ -935,24 +669,20 @@ def scan_skill_cached(cached = json.loads(cache_file.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):cached = None- if (isinstance(cached, dict)- and cached.get("bundle_hash") == bundle_hash+ if (isinstance(cached, dict) and cached.get("bundle_hash") == bundle_hashand cached.get("scanner_version") == SCANNER_VERSION- and cached.get("source") == source- and cached.get("source_url") == source_url):+ and cached.get("source") == source and cached.get("source_url") == source_url):result = ScanResult(skill_name=skill_path.name, source=source,trust_level=cached["trust_level"], verdict=cached["verdict"],findings=[Finding(**item) for item in cached.get("findings", [])],scanned_at=cached["scanned_at"], summary=cached.get("summary", ""),)- provenance = dict(cached)- provenance["fresh"] = False- result.scan_provenance = provenance+ result.scan_provenance = provenance = {**cached, "fresh": False}return result, provenanceresult = scan_skill(skill_path, source=source)- findings = [_finding_dict(item) for item in result.findings]+ findings = [asdict(item) for item in result.findings]provenance = {"source": source, "source_url": source_url, "bundle_hash": bundle_hash,"scanner_version": SCANNER_VERSION, "verdict": result.verdict,@@ -970,118 +700,67 @@ def scan_skill_cached(def should_allow_install(result: ScanResult, force: bool = False) -> Tuple[bool, str]:- """- Determine whether a skill should be installed based on scan result and trust.-- Args:- result: Scan result from scan_skill()- force: If True, override blocked policy decisions for this scan result+ """Decide install from scan verdict + trust; returns ``(allowed, reason)``.- Returns:- (allowed, reason) tuple+ ``force`` overrides blocked policy decisions except a dangerous verdict on+ community/trusted sources. ``allowed`` is ``None`` when the policy says+ "ask" (needs user confirmation)."""policy = INSTALL_POLICY.get(result.trust_level, INSTALL_POLICY["community"])- vi = VERDICT_INDEX.get(result.verdict, 2)- decision = policy[vi]-+ decision = policy[VERDICT_INDEX.get(result.verdict, 2)]+ n = len(result.findings)+ # Dangerous verdicts cannot be overridden by --force (community/trusted);+ # other blocks can.+ hard_block = result.verdict == "dangerous" and result.trust_level in ("community", "trusted")if decision == "allow":return True, f"Allowed ({result.trust_level} source, {result.verdict} verdict)"-- if force and not (result.verdict == "dangerous" and result.trust_level in ("community", "trusted")):- return True, (- f"Force-installed despite {result.verdict} verdict "- f"({len(result.findings)} findings)"- )-+ if force and not hard_block:+ return True, f"Force-installed despite {result.verdict} verdict ({n} findings)"if decision == "ask":- # Return None to signal "needs user confirmation"return None, (f"Requires confirmation ({result.trust_level} source + {result.verdict} verdict, "- f"{len(result.findings)} findings)"+ f"{n} findings)")-- # Dangerous verdicts cannot be overridden by --force (community/trusted);- # other blocks can.- if result.verdict == "dangerous" and result.trust_level in ("community", "trusted"):+ if hard_block:return False, (f"Blocked ({result.trust_level} source + dangerous verdict, "- f"{len(result.findings)} findings). --force does not override a dangerous verdict."+ f"{n} findings). --force does not override a dangerous verdict.")return False, (f"Blocked ({result.trust_level} source + {result.verdict} verdict, "- f"{len(result.findings)} findings). Use --force to override."+ f"{n} findings). Use --force to override.")def format_scan_report(result: ScanResult) -> str:- """- Format a scan result as a human-readable report string.-- Returns a compact multi-line report suitable for CLI or chat display.- """- lines = []-- verdict_display = result.verdict.upper()- lines.append(f"Scan: {result.skill_name} ({result.source}/{result.trust_level}) Verdict: {verdict_display}")-+ """Format a scan result as a compact multi-line report for CLI or chat display."""+ lines = [f"Scan: {result.skill_name} ({result.source}/{result.trust_level}) Verdict: {result.verdict.upper()}"]if result.findings:# Group and sort: critical first, then high, medium, lowseverity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3}- sorted_findings = sorted(result.findings, key=lambda f: severity_order.get(f.severity, 4))-- for f in sorted_findings:+ for f in sorted(result.findings, key=lambda f: severity_order.get(f.severity, 4)):sev = f.severity.upper().ljust(8)cat = f.category.ljust(14)loc = f"{f.file}:{f.line}".ljust(30)lines.append(f" {sev} {cat} {loc} \"{f.match[:60]}\"")-lines.append("")-allowed, reason = should_allow_install(result)- if allowed is True:- status = "ALLOWED"- elif allowed is None:- status = "NEEDS CONFIRMATION"- else:- status = "BLOCKED"+ status = "ALLOWED" if allowed is True else "NEEDS CONFIRMATION" if allowed is None else "BLOCKED"lines.append(f"Decision: {status} — {reason}")-return "\n".join(lines)-def content_hash(skill_path: Path) -> str:- """Compute a SHA-256 hash of all files in a skill directory for integrity tracking.-- File paths (relative to ``skill_path``) are mixed into the hash alongside- file contents so that swapping the contents of two files in a skill- changes the hash. This must stay symmetric with- ``tools.skills_hub.bundle_content_hash`` — both functions need to- produce the same digest for the same skill (one operates on disk,- one on an in-memory bundle), so any change to the hash shape MUST- land in both places at once.- """- return f"sha256:{_content_digest(skill_path)[:16]}"---# ----------------------------------------------------------------------------# Structural checks-# ---------------------------------------------------------------------------+# --- Structural checks ------------------------------------------------------def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]:- """- Check the skill directory for structural anomalies:- - Too many files- - Suspiciously large total size- - Binary/executable files that shouldn't be in a skill- - Symlinks pointing outside the skill directory- - Individual files that are too large-- Args:- skill_dir: Path to the skill directory.- ignore: Optional callable taking a relative posix path and returning- True if the path should be excluded (e.g. from `.skillignore`).- Ignored files are not counted toward the file count, total size,- or any structural finding.+ """Check the skill directory for structural anomalies: too many files,+ suspiciously large total size, binary/executable files, symlinks pointing+ outside the skill directory, and individual files that are too large.++ ``ignore`` is an optional callable taking a relative posix path and+ returning True if the path should be excluded (e.g. from `.skillignore`).+ Ignored files are not counted toward the file count, total size, or any+ structural finding."""if ignore is None:ignore = lambda _rel: False # noqa: E731@@ -1089,11 +768,9 @@ def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]:findings = []file_count = 0total_size = 0-for f in skill_dir.rglob("*"):if not f.is_file() and not f.is_symlink():continue-rel = str(f.relative_to(skill_dir))if ignore(rel):continue@@ -1104,127 +781,42 @@ def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]:try:resolved = f.resolve()if not resolved.is_relative_to(skill_dir.resolve()):- findings.append(Finding(- pattern_id="symlink_escape",- severity="critical",- category="traversal",- file=rel,- line=0,- match=f"symlink -> {resolved}",- description="symlink points outside the skill directory",- ))+ findings.append(Finding("symlink_escape", "critical", "traversal", rel, 0,+ f"symlink -> {resolved}", "symlink points outside the skill directory"))except OSError:- findings.append(Finding(- pattern_id="broken_symlink",- severity="medium",- category="traversal",- file=rel,- line=0,- match="broken symlink",- description="broken or circular symlink",- ))+ findings.append(Finding("broken_symlink", "medium", "traversal", rel, 0,+ "broken symlink", "broken or circular symlink"))continue-- # Size trackingtry:size = f.stat().st_sizetotal_size += sizeexcept OSError:continue-- # Single file too largeif size > MAX_SINGLE_FILE_KB * 1024:- findings.append(Finding(- pattern_id="oversized_file",- severity="medium",- category="structural",- file=rel,- line=0,- match=f"{size // 1024}KB",- description=f"file is {size // 1024}KB (limit: {MAX_SINGLE_FILE_KB}KB)",- ))-- # Binary/executable files+ findings.append(Finding("oversized_file", "medium", "structural", rel, 0,+ f"{size // 1024}KB", f"file is {size // 1024}KB (limit: {MAX_SINGLE_FILE_KB}KB)"))ext = f.suffix.lower()if ext in SUSPICIOUS_BINARY_EXTENSIONS:- findings.append(Finding(- pattern_id="binary_file",- severity="critical",- category="structural",- file=rel,- line=0,- match=f"binary: {ext}",- description=f"binary/executable file ({ext}) should not be in a skill",- ))-+ findings.append(Finding("binary_file", "critical", "structural", rel, 0,+ f"binary: {ext}", f"binary/executable file ({ext}) should not be in a skill"))# Executable permission on non-script files- if ext not in {'.sh', '.bash', '.py', '.rb', '.pl'} and f.stat().st_mode & 0o111:- findings.append(Finding(- pattern_id="unexpected_executable",- severity="medium",- category="structural",- file=rel,- line=0,- match="executable bit set",- description="file has executable permission but is not a recognized script type",- ))-- # File count limit- if file_count > MAX_FILE_COUNT:- findings.append(Finding(- pattern_id="too_many_files",- severity="medium",- category="structural",- file="(directory)",- line=0,- match=f"{file_count} files",- description=f"skill has {file_count} files (limit: {MAX_FILE_COUNT})",- ))+ if ext not in _SCRIPT_EXTENSIONS and f.stat().st_mode & 0o111:+ findings.append(Finding("unexpected_executable", "medium", "structural", rel, 0, "executable bit set",+ "file has executable permission but is not a recognized script type"))+ if file_count > MAX_FILE_COUNT:+ findings.append(Finding("too_many_files", "medium", "structural", "(directory)", 0,+ f"{file_count} files", f"skill has {file_count} files (limit: {MAX_FILE_COUNT})"))# Total size limit — informational only (low severity, non-verdict-gating).# Large skills are legitimate for feature-rich capabilities.if total_size > MAX_TOTAL_SIZE_KB * 1024:- findings.append(Finding(- pattern_id="oversized_skill",- severity="low",- category="structural",- file="(directory)",- line=0,- match=f"{total_size // 1024}KB total",- description=f"skill is {total_size // 1024}KB total (limit: {MAX_TOTAL_SIZE_KB}KB)",- ))+ findings.append(Finding("oversized_skill", "low", "structural", "(directory)", 0, f"{total_size // 1024}KB total",+ f"skill is {total_size // 1024}KB total (limit: {MAX_TOTAL_SIZE_KB}KB)"))return findings-def _unicode_char_name(char: str) -> str:- """Get a readable name for an invisible unicode character."""- names = {- '\u200b': "zero-width space",- '\u200c': "zero-width non-joiner",- '\u200d': "zero-width joiner",- '\u2060': "word joiner",- '\u2062': "invisible times",- '\u2063': "invisible separator",- '\u2064': "invisible plus",- '\ufeff': "BOM/zero-width no-break space",- '\u202a': "LTR embedding",- '\u202b': "RTL embedding",- '\u202c': "pop directional",- '\u202d': "LTR override",- '\u202e': "RTL override",- '\u2066': "LTR isolate",- '\u2067': "RTL isolate",- '\u2068': "first strong isolate",- '\u2069': "pop directional isolate",- }- return names.get(char, f"U+{ord(char):04X}")----# ----------------------------------------------------------------------------# Internal helpers-# ---------------------------------------------------------------------------+# --- Internal helpers -------------------------------------------------------# Ignore-file names a skill may ship to exclude dev/docs artifacts from the# scan. `.skillignore` is the Hermes-native name; `.clawhubignore` is honored@@ -1253,23 +845,18 @@ def _load_skill_ignore(skill_dir: Path):ig = skill_dir / nametry:if ig.is_file():- for raw in ig.read_text(encoding="utf-8").splitlines():- line = raw.strip()- if not line or line.startswith("#"):- continue- patterns.append(line)+ lines = (raw.strip() for raw in ig.read_text(encoding="utf-8").splitlines())+ patterns.extend(line for line in lines if line and not line.startswith("#"))except (UnicodeDecodeError, OSError):continuedef ignore(rel: str) -> bool:rel_posix = Path(rel).as_posix()base = rel_posix.split("/")[-1]-if base in _NEVER_IGNORABLE:return Falseif base in _ALWAYS_IGNORED_NAMES:return True-for pat in patterns:anchored = pat.startswith("/")p = pat.lstrip("/")@@ -1277,7 +864,6 @@ def _load_skill_ignore(skill_dir: Path):p = p.rstrip("/")if not p:continue-if is_dir:# Directory pattern: match the dir itself or anything under it.if rel_posix == p or rel_posix.startswith(p + "/"):@@ -1285,7 +871,6 @@ def _load_skill_ignore(skill_dir: Path):if not anchored and ("/" + rel_posix + "/").find("/" + p + "/") != -1:return Truecontinue-# File/glob pattern.if fnmatch.fnmatch(rel_posix, p):return True@@ -1293,9 +878,7 @@ def _load_skill_ignore(skill_dir: Path):# Unanchored: also match the basename and any path segment.if fnmatch.fnmatch(base, p):return True- if "/" not in p and any(- fnmatch.fnmatch(seg, p) for seg in rel_posix.split("/")- ):+ if "/" not in p and any(fnmatch.fnmatch(seg, p) for seg in rel_posix.split("/")):return True# Match a prefix directory component (e.g. `docs` ignores# `docs/plans/x.md`).@@ -1306,20 +889,16 @@ def _load_skill_ignore(skill_dir: Path):return ignore+_SOURCE_PREFIX_ALIASES = ("skills-sh/", "skills.sh/", "skils-sh/", "skils.sh/")++def _resolve_trust_level(source: str) -> str:"""Map a source identifier to a trust level."""- prefix_aliases = (- "skills-sh/",- "skills.sh/",- "skils-sh/",- "skils.sh/",- )normalized_source = source- for prefix in prefix_aliases:+ for prefix in _SOURCE_PREFIX_ALIASES:if normalized_source.startswith(prefix):normalized_source = normalized_source[len(prefix):]break-# Agent-created skills get their own permissive trust levelif normalized_source == "agent-created":return "agent-created"@@ -1337,15 +916,10 @@ def _resolve_trust_level(source: str) -> str:def _determine_verdict(findings: List[Finding]) -> str:"""Determine the overall verdict from a list of findings."""- if not findings:- return "safe"-- has_critical = any(f.severity == "critical" for f in findings)- has_high = any(f.severity == "high" for f in findings)-- if has_critical:+ severities = {f.severity for f in findings}+ if "critical" in severities:return "dangerous"- if has_high:+ if "high" in severities:return "caution"# medium/low findings alone are informational, not blockingreturn "safe"@@ -1355,6 +929,5 @@ def _build_summary(name: str, source: str, trust: str, verdict: str, findings: L"""Build a one-line summary of the scan result."""if not findings:return f"{name}: clean scan, no threats detected"-categories = {f.category for f in findings}return f"{name}: {verdict} — {len(findings)} finding(s) in {', '.join(sorted(categories))}"diff --git a/tools/skills_hub.py b/tools/skills_hub.pyindex 2bbbf84d6ee..4ff650a05ac 100644--- a/tools/skills_hub.py+++ b/tools/skills_hub.py@@ -1,14 +1,11 @@#!/usr/bin/env python3"""-Skills Hub — Source adapters and hub state management for the Hermes Skills Hub.+Skills Hub — hub state management and the public facade for the source adapters.-This is a library module (not an agent tool). It provides:- - GitHubAuth: Shared GitHub API authentication (PAT, gh CLI, GitHub App)- - SkillSource ABC: Interface for all skill registry adapters- - OptionalSkillSource: Official optional skills shipped with the repo (not activated by default)- - GitHubSource: Fetch skills from any GitHub repo via the Contents API- - HubLockFile: Track provenance of installed hub skills- - Hub state directory management (quarantine, audit log, taps, index cache)+Library module (not an agent tool). Owns the hub paths, index cache, lock file,+taps, audit log, quarantine/install/uninstall, update checks, and the source+router; the adapters live in the ``tools.skills_hub_*`` siblings and are+re-exported here so ``from tools.skills_hub import X`` keeps working.Used by hermes_cli/skills_hub.py for CLI commands and the /skills slash command."""@@ -16,29 +13,37 @@ Used by hermes_cli/skills_hub.py for CLI commands and the /skills slash command.import hashlibimport jsonimport logging-import os-import reimport shutil-import subprocessimport time-from abc import ABC, abstractmethod-from dataclasses import dataclass, fieldfrom datetime import datetime, timezone-from pathlib import Path, PurePosixPath-from hermes_constants import get_hermes_home-from hermes_cli._subprocess_compat import windows_hide_flags-from agent.skill_utils import is_excluded_skill_path-from typing import Any, Dict, List, Optional, Tuple, Union-from urllib.parse import quote, unquote, urljoin, urlparse, urlsplit, urlunparse+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple+from urllib.parse import urljoinimport httpx-import yaml-from tools.skills_guard import (- ScanResult, content_hash, TRUSTED_REPOS,-)+from hermes_constants import get_hermes_home+from agent.skill_utils import is_excluded_skill_path+from tools.skills_guard import ScanResult, content_hashfrom tools.url_safety import is_safe_urlfrom tools.website_policy import check_website_access+from tools.skills_hub_models import ( # noqa: F401 (re-exported public API)+ SkillMeta, SkillBundle, SkillSource, source_url_for_bundle,+ _referenced_support_paths, _normalize_bundle_path, _validate_skill_name,+ _validate_install_parent_path, _normalize_lock_install_path,+ _validate_bundle_rel_path, _skill_meta_to_dict, _parse_frontmatter,+ _dedupe_by_trust, TRUST_RANK,+)+from tools.skills_hub_github import ( # noqa: F401+ GITHUB_TAP_PROVIDERS, github_provider_for, _PROVIDER_FILTER_VALUES,+ _filter_results_by_provider, GitHubAuth, GitHubSource,+)+from tools.skills_hub_skillssh import SkillsShSource # noqa: F401+from tools.skills_hub_clawhub import ClawHubSource # noqa: F401+from tools.skills_hub_sources import ( # noqa: F401+ WellKnownSkillSource, UrlSource, LobeHubSource, BrowseShSource,+)+from tools.skills_hub_official import OptionalSkillSource, HermesIndexSource # noqa: F401logger = logging.getLogger(__name__)@@ -54,10 +59,11 @@ logger = logging.getLogger(__name__)INDEX_CACHE_TTL = 3600 # 1 hour-# _override lets a test-injected real module attribute (patch.object/monkeypatch-# on SKILLS_DIR etc.) win over dynamic resolution; None means resolve live.-def _override(name: str):- return globals().get(name)+def _path(name: str, default):+ """A test-injected real module attribute (patch.object/monkeypatch on+ SKILLS_DIR etc.) wins over live resolution."""+ forced = globals().get(name)+ return Path(forced) if forced is not None else default()def _hermes_home() -> Path:@@ -65,3971 +71,220 @@ def _hermes_home() -> Path:def _skills_dir() -> Path:- forced = _override("SKILLS_DIR")- return Path(forced) if forced is not None else _hermes_home() / "skills"+ return _path("SKILLS_DIR", lambda: _hermes_home() / "skills")def _hub_dir() -> Path:- forced = _override("HUB_DIR")- return Path(forced) if forced is not None else _skills_dir() / ".hub"+ return _path("HUB_DIR", lambda: _skills_dir() / ".hub")def _lock_file() -> Path:- forced = _override("LOCK_FILE")- return Path(forced) if forced is not None else _hub_dir() / "lock.json"+ return _path("LOCK_FILE", lambda: _hub_dir() / "lock.json")def _quarantine_dir() -> Path:- forced = _override("QUARANTINE_DIR")- return Path(forced) if forced is not None else _hub_dir() / "quarantine"+ return _path("QUARANTINE_DIR", lambda: _hub_dir() / "quarantine")def _audit_log() -> Path:- forced = _override("AUDIT_LOG")- return Path(forced) if forced is not None else _hub_dir() / "audit.log"---def _taps_file() -> Path:- forced = _override("TAPS_FILE")- return Path(forced) if forced is not None else _hub_dir() / "taps.json"---def _index_cache_dir() -> Path:- forced = _override("INDEX_CACHE_DIR")- return Path(forced) if forced is not None else _hub_dir() / "index-cache"---_DYNAMIC_PATH_RESOLVERS = {- "HERMES_HOME": _hermes_home,- "SKILLS_DIR": _skills_dir,- "HUB_DIR": _hub_dir,- "LOCK_FILE": _lock_file,- "QUARANTINE_DIR": _quarantine_dir,- "AUDIT_LOG": _audit_log,- "TAPS_FILE": _taps_file,- "INDEX_CACHE_DIR": _index_cache_dir,-}---def __getattr__(name: str):- """Resolve legacy path constants dynamically (PEP 562) so they reflect the- active profile override; a test's patch.object-set real attribute shadows it."""- resolver = _DYNAMIC_PATH_RESOLVERS.get(name)- if resolver is not None:- return resolver()- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")--_REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308}-_MAX_SKILL_FETCH_REDIRECTS = 5---# ----------------------------------------------------------------------------# Data models-# -----------------------------------------------------------------------------@dataclass-class SkillMeta:- """Minimal metadata returned by search results."""- name: str- description: str- source: str # "official", "github", "clawhub", "lobehub"- identifier: str # source-specific ID (e.g. "openai/skills/skill-creator")- trust_level: str # "builtin" | "trusted" | "community"- repo: Optional[str] = None- path: Optional[str] = None- tags: List[str] = field(default_factory=list)- extra: Dict[str, Any] = field(default_factory=dict)---@dataclass-class SkillBundle:- """A downloaded skill ready for quarantine/scanning/installation."""- name: str- files: Dict[str, Union[str, bytes]] # relative_path -> file content- source: str- identifier: str- trust_level: str- metadata: Dict[str, Any] = field(default_factory=dict)---_ALLOWED_SUPPORT_DIRS = frozenset({"references", "templates", "scripts", "assets", "examples"})-_LOCAL_LINK_RE = re.compile(- r"(?:\]\(|`|(?:^|[\s\"']))((?:references|templates|scripts|assets|examples)/[^\s)`\"'<>]+)",- re.MULTILINE,-)-_SUSPICIOUS_LOCAL_REF_RE = re.compile(- r"(?:references|templates|scripts|assets|examples)/(?:[^\s)`\"'<>]*/)?\.\.(?:/|$)"-)-_VALUELESS_QUERY_FLAG_RE = re.compile(- r"(?:[A-Za-z0-9_~-]|%[0-9A-Fa-f]{2})+\Z"-)---def _query_is_concrete(query: str) -> bool:- """Whether ``query`` is unambiguously URL syntax rather than glob prose.-- A non-empty ``key=value`` part is concrete URL syntax regardless of key- spelling, preserving the established behavior. Valueless flags are also- accepted when they are RFC 3986 unreserved-token shaped (including valid- percent escapes), rather than being restricted to a fixed allowlist.-- Deliberately exclude ``.`` from valueless flags. A suffix such as- ``?x.md`` or ``?.md`` is indistinguishable from a single-character glob- completing a filename in inline prose. Brackets and additional question- marks are excluded for the same reason. This syntactic ambiguity policy- preserves ordinary flags such as ``?view`` and ``?preview-mode`` while- rejecting glob-shaped references without guessing flag names.- """- parts = query.split("&")- return all(- ("=" in part and bool(part.split("=", 1)[0]))- or bool(_VALUELESS_QUERY_FLAG_RE.fullmatch(part))- for part in parts- )--# Same-directory links (``](./FILE.ext)`` / ``](FILE.ext)``) — siblings of-# SKILL.md that the document explicitly links. Skills legitimately ship-# supporting docs next to SKILL.md instead of under a support directory-# (e.g. mattpocock/skills' domain-modeling links ./CONTEXT-FORMAT.md);-# dropping them made the install "succeed" while the bundle came out with-# unresolved links (#96310). The trailing extension requirement keeps prose-# words out; the code-side checks keep this strictly to the skill's own-# directory (support-dir links stay on _LOCAL_LINK_RE).-_SAMEDIR_LINK_RE = re.compile(r"\]\(([^)\s\"'<>]+)")-_SAMEDIR_NAME_RE = re.compile(r"^(?:\./)?[A-Za-z0-9][A-Za-z0-9._-]*$")---def _referenced_support_paths(skill_md: str) -> Optional[set[str]]:- """Extract safe referenced paths; return None on a traversal attempt."""- normalized = skill_md.replace("\\", "/")- if _SUSPICIOUS_LOCAL_REF_RE.search(normalized):- return None- paths: set[str] = set()- for match in _LOCAL_LINK_RE.finditer(normalized):- candidate = match.group(1).rstrip(".,;:")- if candidate.endswith("?"):- continue- parsed = urlsplit(candidate)- raw = unquote(parsed.path)- if any(char in raw for char in "*?[]"):- continue- if parsed.query and not _query_is_concrete(parsed.query):- continue- try:- safe = _validate_bundle_rel_path(raw)- except ValueError:- return None- if safe.split("/", 1)[0] in _ALLOWED_SUPPORT_DIRS:- # Prose placeholders — e.g. ``references/type-<name>.md`` (which- # the link regex truncates at ``<`` to the bare prefix- # ``references/type-``) — are agent instructions, not files.- # Glob shapes (*, ?, []) were already rejected on the raw- # candidate above; a truncated placeholder leaves a basename- # ending in a separator, which no real file uses. No extension- # requirement: extensionless support files- # (``references/LICENSE``) are legitimate.- base = safe.rsplit("/", 1)[-1]- if re.search(r"[*?<>]", safe) or not re.search(r"[A-Za-z0-9]$", base):- continue- paths.add(safe)- for match in _SAMEDIR_LINK_RE.finditer(normalized):- raw = match.group(1).rstrip(".,;:")- # Canonicalize first: drop query/fragment components (``?raw=1``,- # ``#section``) and percent-decode — the same normalization the- # support-dir branch applies via urlsplit+unquote — then strip a- # leading ``./``. The set below deduplicates case-SENSITIVE repeats;- # case-VARIANT collisions are rejected rather than merged (below).- name = unquote(urlsplit(raw).path)- name = name[2:] if name.startswith("./") else name- # External URLs, anchors, mailto and site-absolute targets are not- # same-directory file links — leave them to their own resolution.- if not name or "://" in raw or raw.startswith(("mailto:", "#", "/")):- continue- # A ``..`` prefix is a traversal attempt — same fail-closed contract- # as the support-dir branch above, before any shape-based skipping.- if name.startswith(".."):- return None- # Only unambiguous file links: an extension, no internal slash, and- # never SKILL.md itself (that IS the bundle root). The casefold- # check keeps a ``skill.md`` link from shipping as a bundle entry- # that collides with SKILL.md on case-insensitive filesystems- # (macOS/Windows) — skipped, not merged, so the bundle root is- # never overwritten (#96310 review).- if (- "/" in name- or name.casefold() == "skill.md"- or "." not in name.lstrip(".")- ):- continue- if not _SAMEDIR_NAME_RE.match(name):- continue- try:- safe = _validate_bundle_rel_path(name)- except ValueError:- return None- paths.add(safe)- # Case-folded collision among the accepted same-dir names themselves- # (``A.md`` + ``a.md``) would also collide on install — drop the pair- # rather than guess which variant the author meant.- folded: dict[str, str] = {}- for p in sorted(paths):- key = p.casefold()- if key in folded:- paths.discard(folded[key])- paths.discard(p)- else:- folded[key] = p- return paths---def source_url_for_bundle(bundle: SkillBundle) -> str:- """Best available human-facing immutable-source provenance URL."""- explicit = bundle.metadata.get("source_url") or bundle.metadata.get("url")- if explicit:- return str(explicit)- if bundle.source == "github":- parts = bundle.identifier.split("/", 2)- if len(parts) >= 2:- suffix = f"/tree/main/{parts[2]}" if len(parts) == 3 else ""- return f"https://github.com/{parts[0]}/{parts[1]}{suffix}"- return bundle.identifier---def _normalize_bundle_path(path_value: str, *, field_name: str, allow_nested: bool) -> str:- """Normalize and validate bundle-controlled paths before touching disk."""- if not isinstance(path_value, str):- raise ValueError(f"Unsafe {field_name}: expected a string")-- raw = path_value.strip()- if not raw:- raise ValueError(f"Unsafe {field_name}: empty path")-- normalized = raw.replace("\\", "/")- path = PurePosixPath(normalized)- parts = [part for part in path.parts if part not in {"", "."}]-- if normalized.startswith("/") or path.is_absolute():- raise ValueError(f"Unsafe {field_name}: {path_value}")- if not parts or any(part == ".." for part in parts):- raise ValueError(f"Unsafe {field_name}: {path_value}")- # Reject a colon in any component. On Windows a colon marks either a drive- # (``C:`` / ``C:foo``) or an NTFS Alternate Data Stream: a bundle member- # named ``file.py:payload`` writes hidden, scanner-invisible bytes into the- # visible ``file.py`` (rglob-based review never enumerates the stream).- # ``/`` is the only legal separator once normalized, so no portable bundle- # path needs a colon in a component.- if any(":" in part for part in parts):- raise ValueError(f"Unsafe {field_name}: {path_value}")- if not allow_nested and len(parts) != 1:- raise ValueError(f"Unsafe {field_name}: {path_value}")-- return "/".join(parts)---def _validate_skill_name(name: str) -> str:- return _normalize_bundle_path(name, field_name="skill name", allow_nested=False)---def _validate_install_parent_path(category: str) -> str:- return _normalize_bundle_path(category, field_name="install parent path", allow_nested=True)---def _normalize_lock_install_path(install_path: str, skill_name: str) -> str:- """Validate a skill install path before it touches the lock file or disk.-- Lock-file ``install_path`` entries are the source-of-truth for where- ``uninstall_skill`` will call ``shutil.rmtree``. A poisoned or buggy- entry — empty string, ``"."``, an absolute path, ``../..`` traversal,- or anything whose final component doesn't match the skill name — would- let ``rmtree`` wipe either the entire ``skills/`` tree or content- outside it.-- Enforce that ``install_path`` ends with ``<skill_name>``. Nested- official optional skills may legitimately install below paths such as- ``mlops/training/<skill_name>``; traversal, absolute paths, empty paths,- and mismatched final components are still rejected.- """- safe_skill_name = _validate_skill_name(skill_name)- normalized = _normalize_bundle_path(- install_path,- field_name="install path",- allow_nested=True,- )- parts = normalized.split("/")- if not parts or parts[-1] != safe_skill_name:- raise ValueError(f"Unsafe install path: {install_path}")- return normalized---def _is_path_redirect(path: Path) -> bool:- """True when ``path`` is a symlink or (on Windows) a directory junction.-- Either form lets an attacker who can write into the ``skills/`` tree- redirect a subsequent ``rmtree`` to content outside it. ``is_junction``- only exists on Python 3.12+ Windows; gate with ``hasattr``.- """- return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())---def _resolve_lock_install_path(install_path: str, skill_name: str) -> Path:- """Resolve a lock-file install path without allowing escapes from ``SKILLS_DIR``.-- Two layers of defence on top of the existing ``is_relative_to`` check- that's been on main:-- 1. Walk the path component-by-component and refuse if any intermediate- component is a symlink/junction (a path resolution that follows a- symlink to outside skills/ would otherwise be hidden by Path.resolve).- 2. After resolve(), reject not just escape-out but also ``resolved == SKILLS_DIR``- — an empty/``"."``/``""`` install_path resolves to the skills root itself,- and ``rmtree(SKILLS_DIR)`` would wipe every installed skill.- """- normalized = _normalize_lock_install_path(install_path, skill_name)- skills_dir = _skills_dir()- skills_root = skills_dir.resolve()-- target = skills_dir- for part in normalized.split("/"):- target = target / part- if _is_path_redirect(target):- raise ValueError(f"Unsafe install path: {install_path}")-- target = target.resolve()- if target == skills_root or not target.is_relative_to(skills_root):- raise ValueError(f"Unsafe install path: {install_path}")- return target---def _ssrf_safe_http_get(url: str, *, timeout: int = 20) -> httpx.Response:- """Fetch one URL with connect-time SSRF validation and no automatic redirects."""- from tools.url_safety import create_ssrf_safe_client-- with create_ssrf_safe_client(timeout=timeout, follow_redirects=False) as client:- return client.get(url)---def _guarded_http_get(url: str, *, timeout: int = 20) -> Optional[httpx.Response]:- """Fetch a URL with SSRF and redirect-target validation."""- from tools.url_safety import SSRFConnectionBlocked-- current_url = url-- for _ in range(_MAX_SKILL_FETCH_REDIRECTS + 1):- if not is_safe_url(current_url):- logger.warning("Blocked unsafe Skills Hub URL: %s", current_url)- return None-- blocked = check_website_access(current_url)- if blocked:- logger.info(- "Blocked Skills Hub fetch for %s by rule %s",- blocked["host"],- blocked["rule"],- )- return None-- try:- resp = _ssrf_safe_http_get(current_url, timeout=timeout)- except (SSRFConnectionBlocked, httpx.HTTPError) as exc:- logger.debug("Skills Hub fetch failed for %s: %s", current_url, exc)- return None-- if resp.status_code in _REDIRECT_STATUS_CODES:- location = getattr(resp, "headers", {}).get("location")- if not location:- return None- current_url = urljoin(current_url, location)- continue-- return resp-- logger.warning("Skills Hub fetch exceeded redirect limit for %s", url)- return None---def _validate_bundle_rel_path(rel_path: str) -> str:- return _normalize_bundle_path(rel_path, field_name="bundle file path", allow_nested=True)---# ----------------------------------------------------------------------------# GitHub Authentication-# -----------------------------------------------------------------------------class GitHubAuth:- """- GitHub API authentication. Tries methods in priority order:- 1. GITHUB_TOKEN / GH_TOKEN env var (PAT — the default)- 2. `gh auth token` subprocess (if gh CLI is installed)- 3. GitHub App JWT + installation token (if app credentials configured)- 4. Unauthenticated (60 req/hr, public repos only)- """-- def __init__(self):- self._cached_token: Optional[str] = None- self._cached_method: Optional[str] = None- self._app_token_expiry: float = 0-- def get_headers(self) -> Dict[str, str]:- """Return authorization headers for GitHub API requests."""- token = self._resolve_token()- headers = {"Accept": "application/vnd.github.v3+json"}- if token:- headers["Authorization"] = f"token {token}"- return headers-- def is_authenticated(self) -> bool:- return self._resolve_token() is not None-- def auth_method(self) -> str:- """Return which auth method is active: 'pat', 'gh-cli', 'github-app', or 'anonymous'."""- self._resolve_token()- return self._cached_method or "anonymous"-- def _resolve_token(self) -> Optional[str]:- # Return cached token if still valid- if self._cached_token:- if self._cached_method != "github-app" or time.time() < self._app_token_expiry:- return self._cached_token-- # 1. Environment variable (profile-scoped under a multiplexed gateway)- from agent.secret_scope import get_secret- token = get_secret("GITHUB_TOKEN") or get_secret("GH_TOKEN")- if token:- self._cached_token = token- self._cached_method = "pat"- return token-- # 2. gh CLI- token = self._try_gh_cli()- if token:- self._cached_token = token- self._cached_method = "gh-cli"- return token-- # 3. GitHub App- token = self._try_github_app()- if token:- self._cached_token = token- self._cached_method = "github-app"- self._app_token_expiry = time.time() + 3500 # ~58 min (tokens last 1 hour)- return token-- self._cached_method = "anonymous"- return None-- def _try_gh_cli(self) -> Optional[str]:- """Try to get a token from the gh CLI."""- try:- result = subprocess.run(- ["gh", "auth", "token"],- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,- stdin=subprocess.DEVNULL,- creationflags=windows_hide_flags(),- )- if result.returncode == 0 and result.stdout.strip():- return result.stdout.strip()- except (FileNotFoundError, subprocess.TimeoutExpired) as e:- logger.debug("gh CLI token lookup failed: %s", e)- return None-- def _try_github_app(self) -> Optional[str]:- """Try GitHub App JWT authentication if credentials are configured."""- from agent.secret_scope import get_secret- app_id = get_secret("GITHUB_APP_ID")- key_path = get_secret("GITHUB_APP_PRIVATE_KEY_PATH")- installation_id = get_secret("GITHUB_APP_INSTALLATION_ID")-- if not all([app_id, key_path, installation_id]):- return None-- try:- import jwt # PyJWT- except ImportError:- logger.debug("PyJWT not installed, skipping GitHub App auth")- return None-- try:- key_file = Path(key_path)- if not key_file.exists():- return None- private_key = key_file.read_text(encoding="utf-8")-- now = int(time.time())- payload = {- "iat": now - 60,- "exp": now + (10 * 60),- "iss": app_id,- }- encoded_jwt = jwt.encode(payload, private_key, algorithm="RS256")-- resp = httpx.post(- f"https://api.github.com/app/installations/{installation_id}/access_tokens",- headers={- "Authorization": f"Bearer {encoded_jwt}",- "Accept": "application/vnd.github.v3+json",- },- timeout=10,- )- if resp.status_code == 201:- return resp.json().get("token")- except Exception as e:- logger.debug("GitHub App auth failed: %s", e)-- return None---# ----------------------------------------------------------------------------# Source adapter interface-# -----------------------------------------------------------------------------class SkillSource(ABC):- """Abstract base for all skill registry adapters."""-- @abstractmethod- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- """Search for skills matching a query string."""- ...-- @abstractmethod- def fetch(self, identifier: str) -> Optional[SkillBundle]:- """Download a skill bundle by identifier."""- ...-- @abstractmethod- def inspect(self, identifier: str) -> Optional[SkillMeta]:- """Fetch metadata for a skill without downloading all files."""- ...-- @abstractmethod- def source_id(self) -> str:- """Unique identifier for this source (e.g. 'github', 'clawhub')."""- ...-- def trust_level_for(self, identifier: str) -> str:- """Determine trust level for a skill from this source."""- return "community"---# ----------------------------------------------------------------------------# GitHub source adapter-# -----------------------------------------------------------------------------# Map a GitHub tap repo (owner/repo) to the human-facing provider label used-# in the docs-site catalog (website/scripts/extract-skills.py::GITHUB_TAP_LABELS).-# The runtime index collapses every GitHub tap into source="github"; stamping-# this provider label onto each skill's ``extra`` keeps the per-tap identity-# (NVIDIA / OpenAI / Anthropic / HuggingFace / gstack / ...) searchable and-# filterable at the CLI without disturbing the source="github" dedup / floor /-# index-skip logic that keys off the bare source id.-GITHUB_TAP_PROVIDERS = {- "openai/skills": "OpenAI",- "anthropics/skills": "Anthropic",- "huggingface/skills": "HuggingFace",- "nvidia/skills": "NVIDIA",- "voltagent/awesome-agent-skills": "VoltAgent",- "garrytan/gstack": "gstack",- "minimax-ai/cli": "MiniMax",-}---def github_provider_for(repo: str) -> Optional[str]:- """Return the provider label for a GitHub tap repo, or None.+ return _path("AUDIT_LOG", lambda: _hub_dir() / "audit.log")- ``repo`` is ``owner/repo``; matched case-insensitively so ``NVIDIA/skills``- and ``nvidia/skills`` both resolve to ``"NVIDIA"``.- """- if not repo:- return None- return GITHUB_TAP_PROVIDERS.get(repo.strip().lower())---# Lowercased set of accepted ``--source`` provider filters. These are not real-# source ids — they narrow the merged results to GitHub-tap skills carrying the-# matching ``extra.provider`` label (see ``_filter_results_by_provider``).-_PROVIDER_FILTER_VALUES = frozenset(v.lower() for v in GITHUB_TAP_PROVIDERS.values())---def _filter_results_by_provider(- results: List["SkillMeta"], provider: str-) -> List["SkillMeta"]:- """Keep only results whose ``extra.provider`` matches ``provider``.-- An explicit provider filter (e.g. ``--source nvidia``) means "show me that- provider's skills" — so it narrows to exactly those, without injecting the- official catalog the unfiltered browse/search would lead with.- """- want = provider.strip().lower()- return [- r for r in results- if str((r.extra or {}).get("provider", "")).lower() == want- ]---class GitHubSource(SkillSource):- """Fetch skills from GitHub repos via the Contents API."""-- DEFAULT_TAPS = [- # NOTE: openai/skills moved its content into skills/.curated/ (and- # skills/.system/ for system-level skills). _list_skills_in_repo- # skips directories starting with "." or "_", so we point both- # entries at the inner paths directly.- {"repo": "openai/skills", "path": "skills/.curated/"},- {"repo": "openai/skills", "path": "skills/.system/"},- {"repo": "anthropics/skills", "path": "skills/"},- {"repo": "huggingface/skills", "path": "skills/"},- # NVIDIA/skills: NVIDIA-verified skills for CUDA-X, AIQ, cuOpt,- # cuPyNumeric, DeepStream, NeMo, NemoClaw, etc. Each skill ships- # alongside a signed `skill.oms.sig`, an OMS-signed `skill-card.md`- # (governance card), and an `evals/` directory — synced daily from- # the NVIDIA product repos. Treated as `trusted` (see- # `tools/skills_guard.py::TRUSTED_REPOS`). Sample layout:- # https://github.com/NVIDIA/skills/tree/main/skills- {"repo": "NVIDIA/skills", "path": "skills/"},- {"repo": "garrytan/gstack", "path": ""},- ]-- def __init__(self, auth: GitHubAuth, extra_taps: Optional[List[Dict]] = None):- self.auth = auth- self.taps = list(self.DEFAULT_TAPS)- if extra_taps:- self.taps.extend(extra_taps)- # Per-instance cache: repo -> (default_branch, tree_entries)- # Survives within a single search/install flow, avoiding redundant API calls.- self._tree_cache: Dict[str, Tuple[str, List[dict]]] = {}- self._tree_revisions: Dict[str, str] = {}- # Per-repo cache of the optional skills.sh.json grouping sidecar,- # mapping skill_name -> human-readable grouping title. ``None`` means- # "fetched, no sidecar"; a missing key means "not fetched yet".- self._skillsh_groupings: Dict[str, Optional[Dict[str, str]]] = {}- # Set when GitHub returns 403 with rate limit exhausted- self._rate_limited: bool = False-- def source_id(self) -> str:- return "github"-- @property- def is_rate_limited(self) -> bool:- """Whether GitHub API rate limit was hit during operations."""- return self._rate_limited-- def trust_level_for(self, identifier: str) -> str:- # identifier format: "owner/repo/path/to/skill"- parts = identifier.split("/", 2)- if len(parts) >= 2:- repo = f"{parts[0]}/{parts[1]}"- if repo in TRUSTED_REPOS:- return "trusted"- return "community"-- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- """Search all taps for skills matching the query."""- results: List[SkillMeta] = []- query_lower = query.lower()-- for tap in self.taps:- try:- skills = self._list_skills_in_repo(tap["repo"], tap.get("path", ""))- for skill in skills:- searchable = f"{skill.name} {skill.description} {' '.join(skill.tags)}".lower()- if query_lower in searchable:- results.append(skill)- except Exception as e:- logger.debug("Failed to search %s: %s", tap['repo'], e)- continue-- # Deduplicate by identifier, preferring higher trust levels.- # identifier is unique per skill; name is not (two configured taps can- # publish skills with the same name but different identifiers).- _trust_rank = {"builtin": 2, "trusted": 1, "community": 0}- seen = {}- for r in results:- if r.identifier not in seen:- seen[r.identifier] = r- elif _trust_rank.get(r.trust_level, 0) > _trust_rank.get(seen[r.identifier].trust_level, 0):- seen[r.identifier] = r- results = list(seen.values())-- return results[:limit]-- def fetch(self, identifier: str) -> Optional[SkillBundle]:- """- Download a skill from GitHub.- identifier format: "owner/repo/path/to/skill-dir"- """- parts = identifier.split("/", 2)- if len(parts) < 3:- return None-- repo = f"{parts[0]}/{parts[1]}"- skill_path = parts[2]-- # Resolve the tree FIRST so every byte fetch in this install —- # SKILL.md included — can be pinned to the same revision. Without the- # pin the /contents endpoint floats to the default-branch HEAD and- # the downloaded bytes can come from a NEWER revision than the tree- # the paths were validated against (TOCTOU between "the tree says- # this is a regular blob" and "what actually gets downloaded").- # Idempotent + cached, so callers that already primed the tree pay- # nothing extra.- tree = self._get_repo_tree(repo)- pinned_ref = self._tree_revisions.get(repo)- skill_md = self._fetch_file_content(- repo, f"{skill_path.rstrip('/')}/SKILL.md", ref=pinned_ref- )- if skill_md is None:- return None- referenced = _referenced_support_paths(skill_md)- if referenced is None:- return None-- files: Dict[str, Union[str, bytes]] = {"SKILL.md": skill_md}- if tree is not None:- # Download the FULL skill directory, not just SKILL.md-linked- # paths. Link-driven fetching silently dropped every support file- # a skill keeps under a non-canonical dir name (`reference/`,- # `agents/`, root-level LICENSE/params files) or that only a- # reference file links — the exact gap the optional-skills live- # fetch already works around (see _fetch_live_optional_bundle).- # Everything still flows through quarantine + scan before- # install, and the scanner sees MORE this way, not less.- branch, entries = tree- prefix = f"{skill_path.rstrip('/')}/"- symlinked: set = set()- for item in entries:- item_path = item.get("path", "")- if not item_path.startswith(prefix):- continue- rel_path = item_path[len(prefix):]- if item.get("type") != "blob" or item.get("mode") == "120000":- symlinked.add(rel_path)- continue- if rel_path == "SKILL.md":- continue- base = rel_path.rsplit("/", 1)[-1]- if base.startswith(".") or base.endswith(".pyc") or "__pycache__" in rel_path.split("/"):- continue- try:- rel_path = _validate_bundle_rel_path(rel_path)- except ValueError:- logger.warning("Rejected unsafe file path in skill bundle: %s", item_path)- return None- content = self._fetch_file_bytes(repo, item_path, ref=pinned_ref)- if content is None:- logger.warning("Failed to fetch referenced skill support "- "file; continuing without it: %s", item_path)- continue- files[rel_path] = content- # A SKILL.md-linked support path that isn't in the tree is a- # dangling link — a repo-only dev tool, prose over-match, or a- # file the author forgot to push. Warn and install without it- # rather than aborting the whole install (#66760/#90081): the- # skill body still works, and the gap is visible in the log.- # A referenced path that IS in the tree but as a symlink (or any- # non-regular entry) stays a hard rejection — that shape is an- # escape attempt, not a forgotten file.- for rel_path in sorted(referenced):- if rel_path in symlinked:- logger.warning(- "Rejected non-regular referenced file in skill "- "bundle: %s%s", prefix, rel_path,- )- return None- if rel_path not in files:- logger.warning(- "Referenced skill support file is missing; "- "continuing without it: %s%s",- prefix, rel_path,- )- revision = self._tree_revisions.get(repo) or branch- else:- for rel_path in referenced:- content = self._fetch_file_bytes(repo, f"{skill_path.rstrip('/')}/{rel_path}")- if content is None:- logger.warning("Failed to fetch referenced skill support "- "file; continuing without it: %s", rel_path)- continue- files[rel_path] = content- revision = ""-- skill_name = skill_path.rstrip("/").split("/")[-1]- trust = self.trust_level_for(identifier)-- return SkillBundle(- name=skill_name,- files=files,- source="github",- identifier=identifier,- trust_level=trust,- metadata={- "source_url": (- f"https://github.com/{repo}/tree/{revision}/{skill_path}"- if revision else f"https://github.com/{repo}/{skill_path}"- ),- "source_revision": revision,- },- )-- def inspect(self, identifier: str) -> Optional[SkillMeta]:- """Fetch just the SKILL.md metadata for preview."""- parts = identifier.split("/", 2)- if len(parts) < 3:- return None-- repo = f"{parts[0]}/{parts[1]}"- skill_path = parts[2].rstrip("/")- skill_md_path = f"{skill_path}/SKILL.md"-- content = self._fetch_file_content(repo, skill_md_path)- if not content:- return None-- fm = self._parse_frontmatter_quick(content)- skill_name = fm.get("name", skill_path.split("/")[-1])- description = fm.get("description", "")-- tags = []- metadata = fm.get("metadata", {})- if isinstance(metadata, dict):- hermes_meta = metadata.get("hermes", {})- if isinstance(hermes_meta, dict):- tags = hermes_meta.get("tags", [])- if not tags:- raw_tags = fm.get("tags", [])- tags = raw_tags if isinstance(raw_tags, list) else []-- provider = github_provider_for(repo)- extra: Dict[str, Any] = {}- if provider:- extra["provider"] = provider-- return SkillMeta(- name=skill_name,- description=str(description),- source="github",- identifier=identifier,- trust_level=self.trust_level_for(identifier),- repo=repo,- path=skill_path,- tags=[str(t) for t in tags],- extra=extra,- )-- # -- Internal helpers ---- def _list_skills_in_repo(self, repo: str, path: str) -> List[SkillMeta]:- """List skill directories in a GitHub repo path, using cached index."""- cache_key = f"{repo}_{path}".replace("/", "_").replace(" ", "_")- cached = self._read_cache(cache_key)- if cached is not None:- return [SkillMeta(**s) for s in cached]-- url = f"https://api.github.com/repos/{repo}/contents/{path.rstrip('/')}"- resp = self._github_get(url)- if resp is None or resp.status_code != 200:- return []-- entries = resp.json()- if not isinstance(entries, list):- return []-- skills: List[SkillMeta] = []- groupings = self._get_skillsh_groupings(repo)- for entry in entries:- if entry.get("type") != "dir":- continue-- dir_name = entry["name"]- if dir_name.startswith((".", "_")):- continue-- prefix = path.rstrip("/")- skill_identifier = f"{repo}/{prefix}/{dir_name}" if prefix else f"{repo}/{dir_name}"- meta = self.inspect(skill_identifier)- if meta:- if groupings:- category = groupings.get(meta.name) or groupings.get(dir_name)- if category:- meta.extra["category"] = category- skills.append(meta)-- # Cache the results- self._write_cache(cache_key, [self._meta_to_dict(s) for s in skills])- return skills-- # -- Repo tree cache (avoids redundant API calls) ---- def _get_repo_tree(self, repo: str) -> Optional[Tuple[str, List[dict]]]:- """Get cached or fresh repo tree.-- Returns ``(default_branch, tree_entries)`` or ``None``.- A single install can call ``_download_directory_via_tree`` and- ``_find_skill_in_repo_tree`` multiple times for the same repo — this- cache eliminates the redundant ``GET /repos/{repo}`` +- ``GET /repos/{repo}/git/trees/{branch}`` round-trips (previously up to- 6 duplicated pairs per install, consuming ~12 of the 60/hr- unauthenticated rate limit for nothing).- """- if repo in self._tree_cache:- return self._tree_cache[repo]-- headers = self.auth.get_headers()-- # Resolve default branch- try:- resp = httpx.get(- f"https://api.github.com/repos/{repo}",- headers=headers, timeout=15, follow_redirects=True,- )- if resp.status_code != 200:- self._check_rate_limit_response(resp)- return None- default_branch = resp.json().get("default_branch", "main")- except (httpx.HTTPError, ValueError):- return None-- # Fetch recursive tree- try:- resp = httpx.get(- f"https://api.github.com/repos/{repo}/git/trees/{default_branch}",- params={"recursive": "1"},- headers=headers, timeout=30, follow_redirects=True,- )- if resp.status_code != 200:- self._check_rate_limit_response(resp)- return None- tree_data = resp.json()- if tree_data.get("truncated"):- logger.debug("Git tree truncated for %s, cannot cache", repo)- return None- except (httpx.HTTPError, ValueError):- return None-- entries = tree_data.get("tree", [])- revision = tree_data.get("sha")- if isinstance(revision, str) and revision:- self._tree_revisions[repo] = revision- self._tree_cache[repo] = (default_branch, entries)- return (default_branch, entries)-- def _check_rate_limit_response(self, resp: "httpx.Response") -> None:- """Flag the instance as rate-limited when GitHub returns 403 + exhausted quota."""- if resp.status_code in (403, 429):- remaining = resp.headers.get("X-RateLimit-Remaining", "")- if remaining == "0" or resp.status_code == 429:- self._rate_limited = True- logger.warning(- "GitHub API rate limit exhausted (unauthenticated: 60 req/hr). "- "Set GITHUB_TOKEN or install the gh CLI to raise the limit to 5,000/hr."- )-- def _github_get(- self,- url: str,- *,- params: Optional[Dict] = None,- headers: Optional[Dict] = None,- timeout: float = 15.0,- max_retries: int = 3,- ) -> Optional["httpx.Response"]:- """GET against the GitHub API with retry/backoff on transient failures.-- Returns the final ``httpx.Response`` (caller inspects status) or- ``None`` when every attempt raised a transport error.-- Retries on:- - 403/429 with ``X-RateLimit-Remaining: 0`` — waits until the- reset time (capped) when the header is present, else exponential- backoff. This is the all-GitHub-tap-collapse case: a single- shared rate limit zeroes github + well-known- at once during the index build.- - 5xx and connection/timeout errors — exponential backoff.-- On terminal rate-limit exhaustion the instance is flagged via- ``_check_rate_limit_response`` so the build can fail loud instead of- silently shipping an index with the GitHub sources dropped to zero.- """- hdrs = headers if headers is not None else self.auth.get_headers()- backoff = 1.0- last_resp: Optional["httpx.Response"] = None- for attempt in range(max_retries):- try:- resp = httpx.get(- url, params=params, headers=hdrs,- timeout=timeout, follow_redirects=True,- )- except httpx.HTTPError as e:- logger.debug("GitHub GET %s failed (attempt %d/%d): %s",- url, attempt + 1, max_retries, e)- if attempt < max_retries - 1:- time.sleep(backoff)- backoff = min(backoff * 2, 30.0)- continue- return None- last_resp = resp- if resp.status_code == 200:- return resp-- # Rate-limited: honor the reset header when present, else back off.- if resp.status_code in (403, 429):- remaining = resp.headers.get("X-RateLimit-Remaining", "")- is_rl = remaining == "0" or resp.status_code == 429- if is_rl and attempt < max_retries - 1:- wait = backoff- reset = resp.headers.get("X-RateLimit-Reset", "")- retry_after = resp.headers.get("Retry-After", "")- if retry_after.isdigit():- wait = min(float(retry_after), 60.0)- elif reset.isdigit():- delta = float(reset) - time.time()- if 0 < delta <= 60.0:- wait = delta- logger.debug(- "GitHub rate limited on %s, waiting %.1fs (attempt %d/%d)",- url, wait, attempt + 1, max_retries,- )- time.sleep(wait)- backoff = min(backoff * 2, 30.0)- continue- # Out of retries (or not a rate-limit 403) — flag and return.- self._check_rate_limit_response(resp)- return resp-- # 5xx — retry; 4xx (other than rate limit) — return immediately.- if 500 <= resp.status_code < 600 and attempt < max_retries - 1:- time.sleep(backoff)- backoff = min(backoff * 2, 30.0)- continue- return resp-- return last_resp--- def _download_directory(self, repo: str, path: str) -> Dict[str, str]:- """Recursively download all text files from a GitHub directory.-- Uses the Git Trees API first (single call for the entire tree) to- avoid per-directory rate limiting that causes silent subdirectory- loss. Falls back to the recursive Contents API when the tree- endpoint is unavailable or the response is truncated.- """- files = self._download_directory_via_tree(repo, path)- if files is not None:- return files- logger.debug("Tree API unavailable for %s/%s, falling back to Contents API", repo, path)- return self._download_directory_recursive(repo, path)-- def _download_directory_via_tree(self, repo: str, path: str) -> Optional[Dict[str, str]]:- """Download an entire directory using the Git Trees API (single request).-- Returns:- dict of files if the path exists and has content,- empty dict ``{}`` if the tree is cached but the path doesn't exist- (prevents unnecessary Contents API fallback),- ``None`` if the tree couldn't be fetched (triggers Contents API fallback).- """- path = path.rstrip("/")-- cached = self._get_repo_tree(repo)- if cached is None:- return None- _default_branch, tree_entries = cached-- # Check if ANY entry lives under the target path- prefix = f"{path}/"- has_entries = any(- item.get("path", "").startswith(prefix) for item in tree_entries- )- if not has_entries:- # Path definitively doesn't exist in the repo — return empty- # instead of None to skip the Contents API fallback.- return {}-- # Filter to blobs under our target path and fetch content- files: Dict[str, str] = {}- for item in tree_entries:- if item.get("type") != "blob":- continue- item_path = item.get("path", "")- if not item_path.startswith(prefix):- continue- rel_path = item_path[len(prefix):]- content = self._fetch_file_content(repo, item_path)- if content is not None:- files[rel_path] = content- else:- logger.debug("Skipped file (fetch failed): %s/%s", repo, item_path)-- return files if files else None-- def _download_directory_recursive(self, repo: str, path: str) -> Dict[str, str]:- """Recursively download via Contents API (fallback)."""- url = f"https://api.github.com/repos/{repo}/contents/{path.rstrip('/')}"- # Route through _github_get so directory listing gets the same- # 429/403-rate-limit retry + backoff as file fetches (#3033).- resp = self._github_get(url)- if resp is None:- return {}- if resp.status_code != 200:- logger.debug("Contents API returned %d for %s/%s", resp.status_code, repo, path)- return {}-- entries = resp.json()- if not isinstance(entries, list):- return {}-- files: Dict[str, str] = {}- for entry in entries:- name = entry.get("name", "")- entry_type = entry.get("type", "")-- if entry_type == "file":- content = self._fetch_file_content(repo, entry.get("path", ""))- if content is not None:- rel_path = name- files[rel_path] = content- elif entry_type == "dir":- sub_files = self._download_directory_recursive(repo, entry.get("path", ""))- if not sub_files:- logger.debug("Empty or failed subdirectory: %s/%s", repo, entry.get("path", ""))- for sub_name, sub_content in sub_files.items():- files[f"{name}/{sub_name}"] = sub_content-- return files-- def _find_skill_in_repo_tree(self, repo: str, skill_name: str) -> Optional[str]:- """Use the GitHub Trees API to find a skill directory anywhere in the repo.-- Returns the full identifier (``repo/path/to/skill``) or ``None``.- This is a single API call regardless of repo depth, so it efficiently- handles deeply nested directory structures like- ``cli-tool/components/skills/development/<skill>/SKILL.md``.- """- cached = self._get_repo_tree(repo)- if cached is None:- return None- _default_branch, tree_entries = cached-- # Look for SKILL.md files inside directories named <skill_name>- skill_md_suffix = f"/{skill_name}/SKILL.md"- for entry in tree_entries:- if entry.get("type") != "blob":- continue- path = entry.get("path", "")- if path.endswith(skill_md_suffix) or path == f"{skill_name}/SKILL.md":- # Strip /SKILL.md to get the skill directory path- skill_dir = path[: -len("/SKILL.md")]- return f"{repo}/{skill_dir}"-- return None-- def _fetch_file_content(- self, repo: str, path: str, ref: Optional[str] = None- ) -> Optional[str]:- """Fetch a single text file from GitHub."""- content = self._fetch_file_bytes(repo, path, ref=ref)- if content is None:- return None- try:- return content.decode("utf-8")- except UnicodeDecodeError:- return None-- def _fetch_file_bytes(- self, repo: str, path: str, ref: Optional[str] = None- ) -> Optional[bytes]:- """Fetch exact file bytes from GitHub without text decoding.-- ``ref`` pins the fetch to a specific commit/tree SHA. Without it the- contents endpoint floats to the default-branch HEAD, so the bytes can- come from a NEWER revision than the tree the paths were validated- against — a TOCTOU between "what the tree says is a regular blob"- and "what actually gets downloaded". Callers that resolved paths from- a tree pass that tree's SHA; ``None`` keeps the legacy unpinned- behavior for call sites with no revision in hand.- """- encoded_path = quote(path, safe="/")- url = f"https://api.github.com/repos/{repo}/contents/{encoded_path}"- params = {"ref": ref} if ref else None- resp = self._github_get(- url,- params=params,- headers={**self.auth.get_headers(), "Accept": "application/vnd.github.v3.raw"},- )- if resp is not None and resp.status_code == 200:- return resp.content- return None-- def _get_skillsh_groupings(self, repo: str) -> Optional[Dict[str, str]]:- """Fetch and parse the repo-root ``skills.sh.json`` grouping sidecar.-- ``skills.sh.json`` is a published cross-ecosystem standard- (``$schema: https://skills.sh/schemas/skills.sh.schema.json``) that- lets a tap declare human-readable category groupings for its skills:-- {"groupings": [{"title": "Inference AI", "skills": ["dynamo-..."]}]}-- We flatten it into ``{skill_name: grouping_title}`` so the Skills Hub- UI can show a real category pill instead of a tag-derived guess. Any- tap that ships this file gets categorization for free — this is not- NVIDIA-specific.-- Returns the map (possibly empty) on success, or ``None`` when the repo- has no sidecar / it couldn't be parsed. Cached per-repo on the instance.- """- if repo in self._skillsh_groupings:- return self._skillsh_groupings[repo]-- content = self._fetch_file_content(repo, "skills.sh.json")- groupings = self._parse_skillsh_groupings(content) if content else None- self._skillsh_groupings[repo] = groupings- return groupings-- @staticmethod- def _parse_skillsh_groupings(content: str) -> Optional[Dict[str, str]]:- """Flatten a ``skills.sh.json`` document into ``{skill_name: title}``.-- Returns ``None`` when the content isn't a usable grouping document.- """- try:- data = json.loads(content)- except (json.JSONDecodeError, TypeError):- return None- if not isinstance(data, dict):- return None- groupings = data.get("groupings")- if not isinstance(groupings, list):- return None-- mapping: Dict[str, str] = {}- for group in groupings:- if not isinstance(group, dict):- continue- title = group.get("title")- members = group.get("skills")- if not isinstance(title, str) or not isinstance(members, list):- continue- for member in members:- if isinstance(member, str) and member:- # First grouping wins if a skill is listed twice.- mapping.setdefault(member, title)- return mapping-- def _read_cache(self, key: str) -> Optional[list]:- """Read cached index if not expired."""- cache_file = _index_cache_dir() / f"{key}.json"- if not cache_file.exists():- return None- try:- stat = cache_file.stat()- if time.time() - stat.st_mtime > INDEX_CACHE_TTL:- return None- return json.loads(cache_file.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- return None-- def _write_cache(self, key: str, data: list) -> None:- """Write index data to cache."""- index_cache_dir = _index_cache_dir()- index_cache_dir.mkdir(parents=True, exist_ok=True)- cache_file = index_cache_dir / f"{key}.json"- try:- cache_file.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")- except OSError as e:- logger.debug("Could not write cache: %s", e)-- @staticmethod- def _meta_to_dict(meta: SkillMeta) -> dict:- return {- "name": meta.name,- "description": meta.description,- "source": meta.source,- "identifier": meta.identifier,- "trust_level": meta.trust_level,- "repo": meta.repo,- "path": meta.path,- "tags": meta.tags,- "extra": meta.extra,- }-- @staticmethod- def _parse_frontmatter_quick(content: str) -> dict:- """Parse YAML frontmatter from SKILL.md content."""- content = content.lstrip("\ufeff") # tolerate UTF-8 BOM (Windows editors)- if not content.startswith("---"):- return {}- match = re.search(r'\n---\s*\n', content[3:])- if not match:- return {}- yaml_text = content[3:match.start() + 3]- try:- parsed = yaml.safe_load(yaml_text)- return parsed if isinstance(parsed, dict) else {}- except yaml.YAMLError:- return {}---# ----------------------------------------------------------------------------# Well-known Agent Skills endpoint source adapter-# -----------------------------------------------------------------------------class WellKnownSkillSource(SkillSource):- """Read skills from a domain exposing /.well-known/skills/index.json."""-- BASE_PATH = "/.well-known/skills"-- def source_id(self) -> str:- return "well-known"-- def trust_level_for(self, identifier: str) -> str:- return "community"-- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- index_url = self._query_to_index_url(query)- if not index_url:- return []-- parsed = self._parse_index(index_url)- if not parsed:- return []-- results: List[SkillMeta] = []- for entry in parsed["skills"][:limit]:- name = entry.get("name")- if not isinstance(name, str) or not name:- continue- description = entry.get("description", "")- files = entry.get("files", ["SKILL.md"])- results.append(SkillMeta(- name=name,- description=str(description),- source="well-known",- identifier=self._wrap_identifier(parsed["base_url"], name),- trust_level="community",- path=name,- extra={- "index_url": parsed["index_url"],- "base_url": parsed["base_url"],- "files": files if isinstance(files, list) else ["SKILL.md"],- },- ))- return results-- def inspect(self, identifier: str) -> Optional[SkillMeta]:- parsed = self._parse_identifier(identifier)- if not parsed:- return None-- entry = self._index_entry(parsed["index_url"], parsed["skill_name"])- if not entry:- return None-- skill_md = self._fetch_text(f"{parsed['skill_url']}/SKILL.md")- if skill_md is None:- return None-- fm = GitHubSource._parse_frontmatter_quick(skill_md)- description = str(fm.get("description") or entry.get("description") or "")- name = str(fm.get("name") or parsed["skill_name"])- return SkillMeta(- name=name,- description=description,- source="well-known",- identifier=self._wrap_identifier(parsed["base_url"], parsed["skill_name"]),- trust_level="community",- path=parsed["skill_name"],- extra={- "index_url": parsed["index_url"],- "base_url": parsed["base_url"],- "files": entry.get("files", ["SKILL.md"]),- "endpoint": parsed["skill_url"],- },- )-- def fetch(self, identifier: str) -> Optional[SkillBundle]:- parsed = self._parse_identifier(identifier)- if not parsed:- return None-- try:- skill_name = _validate_skill_name(parsed["skill_name"])- except ValueError:- logger.warning("Well-known skill identifier contained unsafe skill name: %s", identifier)- return None-- entry = self._index_entry(parsed["index_url"], parsed["skill_name"])- if not entry:- return None-- files = entry.get("files", ["SKILL.md"])- if not isinstance(files, list) or not files:- files = ["SKILL.md"]-- downloaded: Dict[str, str] = {}- for rel_path in files:- if not isinstance(rel_path, str) or not rel_path:- continue- try:- safe_rel_path = _validate_bundle_rel_path(rel_path)- except ValueError:- logger.warning(- "Well-known skill %s advertised unsafe file path: %r",- identifier,- rel_path,- )- return None- text = self._fetch_text(f"{parsed['skill_url']}/{safe_rel_path}")- if text is None:- return None- downloaded[safe_rel_path] = text-- if "SKILL.md" not in downloaded:- return None-- return SkillBundle(- name=skill_name,- files=downloaded,- source="well-known",- identifier=self._wrap_identifier(parsed["base_url"], skill_name),- trust_level="community",- metadata={- "index_url": parsed["index_url"],- "base_url": parsed["base_url"],- "endpoint": parsed["skill_url"],- "files": files,- },- )-- def _query_to_index_url(self, query: str) -> Optional[str]:- query = query.strip()- if not query.startswith(("http://", "https://")):- return None- if query.endswith("/index.json"):- return query- if f"{self.BASE_PATH}/" in query:- base_url = query.split(f"{self.BASE_PATH}/", 1)[0] + self.BASE_PATH- return f"{base_url}/index.json"- return query.rstrip("/") + f"{self.BASE_PATH}/index.json"-- def _parse_identifier(self, identifier: str) -> Optional[dict]:- raw = identifier[len("well-known:"):] if identifier.startswith("well-known:") else identifier- if not raw.startswith(("http://", "https://")):- return None-- parsed_url = urlparse(raw)- clean_url = urlunparse(parsed_url._replace(fragment=""))- fragment = parsed_url.fragment-- if clean_url.endswith("/index.json"):- if not fragment:- return None- base_url = clean_url[:-len("/index.json")]- skill_name = fragment- skill_url = f"{base_url}/{skill_name}"- return {- "index_url": clean_url,- "base_url": base_url,- "skill_name": skill_name,- "skill_url": skill_url,- }-- if clean_url.endswith("/SKILL.md"):- skill_url = clean_url[:-len("/SKILL.md")]- else:- skill_url = clean_url.rstrip("/")-- if f"{self.BASE_PATH}/" not in skill_url:- return None-- base_url, skill_name = skill_url.rsplit("/", 1)- return {- "index_url": f"{base_url}/index.json",- "base_url": base_url,- "skill_name": skill_name,- "skill_url": skill_url,- }-- def _parse_index(self, index_url: str) -> Optional[dict]:- cache_key = f"well_known_index_{hashlib.md5(index_url.encode()).hexdigest()}"- cached = _read_index_cache(cache_key)- if isinstance(cached, dict) and isinstance(cached.get("skills"), list):- return cached-- resp = _guarded_http_get(index_url, timeout=20)- if resp is None or resp.status_code != 200:- return None- try:- data = resp.json()- except json.JSONDecodeError:- return None-- skills = data.get("skills", []) if isinstance(data, dict) else []- if not isinstance(skills, list):- return None-- parsed = {- "index_url": index_url,- "base_url": index_url[:-len("/index.json")],- "skills": skills,- }- _write_index_cache(cache_key, parsed)- return parsed-- def _index_entry(self, index_url: str, skill_name: str) -> Optional[dict]:- parsed = self._parse_index(index_url)- if not parsed:- return None- for entry in parsed["skills"]:- if isinstance(entry, dict) and entry.get("name") == skill_name:- return entry- return None-- @staticmethod- def _fetch_text(url: str) -> Optional[str]:- resp = _guarded_http_get(url, timeout=20)- if resp is not None and resp.status_code == 200:- return resp.text- return None-- @staticmethod- def _wrap_identifier(base_url: str, skill_name: str) -> str:- return f"well-known:{base_url.rstrip('/')}/{skill_name}"---# ----------------------------------------------------------------------------# Direct URL source adapter-# -----------------------------------------------------------------------------class UrlSource(SkillSource):- """Fetch SKILL.md plus explicitly referenced, allowlisted support files.-- The identifier IS the URL (e.g. ``https://example.com/path/SKILL.md``).- Bare URLs cannot safely enumerate a repository, so only exact references- below references/templates/scripts/assets are fetched. Other repository- files are never copied.-- The skill name is read from the ``name:`` field in the SKILL.md YAML- frontmatter (with a URL-slug fallback). Trust level is always- ``community`` and the same security scan runs as for every other source.- """-- def source_id(self) -> str:- return "url"-- def trust_level_for(self, identifier: str) -> str:- return "community"-- # Search is meaningless for a direct URL — skip (return empty).- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- return []-- def _matches(self, identifier: str) -> bool:- """Return True iff this source should handle ``identifier``.-- We claim bare HTTP(S) URLs that end in ``.md`` (typically- ``.../SKILL.md``). Wrapped identifiers (``github:``,- ``well-known:``, etc.) and ``/.well-known/skills/`` URLs are- left for their respective adapters.- """- if not isinstance(identifier, str):- return False- ident = identifier.strip()- if not ident.lower().startswith(("http://", "https://")):- return False- # Don't steal well-known URLs.- if "/.well-known/skills/" in ident or ident.rstrip("/").endswith("/index.json"):- return False- # Only claim URLs that look like a markdown file.- try:- path = urlparse(ident).path- except ValueError:- return False- return path.lower().endswith(".md")-- def inspect(self, identifier: str) -> Optional[SkillMeta]:- if not self._matches(identifier):- return None- url = identifier.strip()- text = self._fetch_text(url)- if text is None:- return None- fm = GitHubSource._parse_frontmatter_quick(text)- name = self._resolve_skill_name(fm, url)- description = str(fm.get("description") or "")- tags: List[str] = []- metadata = fm.get("metadata", {})- if isinstance(metadata, dict):- hermes_meta = metadata.get("hermes", {})- if isinstance(hermes_meta, dict):- raw_tags = hermes_meta.get("tags", [])- if isinstance(raw_tags, list):- tags = [str(t) for t in raw_tags]- return SkillMeta(- name=name or "",- description=description,- source="url",- identifier=url,- trust_level="community",- path=name or "",- tags=tags,- extra={"url": url, "awaiting_name": name is None},- )-- def fetch(self, identifier: str) -> Optional[SkillBundle]:- if not self._matches(identifier):- return None- url = identifier.strip()- text = self._fetch_text(url)- if text is None:- return None-- fm = GitHubSource._parse_frontmatter_quick(text)- name = self._resolve_skill_name(fm, url)- referenced = _referenced_support_paths(text)- if referenced is None:- return None- files: Dict[str, Union[str, bytes]] = {"SKILL.md": text}- base_url = url.rsplit("/", 1)[0] + "/"- for rel_path in sorted(referenced):- support_url = urljoin(base_url, quote(rel_path, safe="/"))- if urlparse(support_url).netloc != urlparse(url).netloc:- return None- content = self._fetch_bytes(support_url)- if content is None:- # A referenced support file that 404s (or is otherwise- # unreachable) shouldn't sink the whole install — skip it- # and let the bundle install without it.- logger.warning(- "URL skill %s: referenced support file %r could not be "- "fetched from %s; skipping it",- url, rel_path, support_url,- )- continue- files[rel_path] = content-- # When auto-resolution fails, return a bundle with an empty name and- # ``awaiting_name=True`` in metadata. The install flow (``do_install``)- # either prompts the user on a TTY or refuses with an actionable error- # on non-interactive surfaces. Keep the expensive HTTP fetch's result- # so the caller doesn't have to re-download after picking a name.- skill_name = ""- if name is not None:- try:- skill_name = _validate_skill_name(name)- except ValueError:- logger.warning("URL skill %s produced unsafe skill name: %r", url, name)- return None-- return SkillBundle(- name=skill_name,- files=files,- source="url",- identifier=url,- trust_level="community",- metadata={"url": url, "source_url": url, "awaiting_name": not skill_name},- )-- @staticmethod- def _fetch_text(url: str) -> Optional[str]:- resp = _guarded_http_get(url, timeout=20)- if resp is not None and resp.status_code == 200:- return resp.text- return None-- @staticmethod- def _fetch_bytes(url: str) -> Optional[bytes]:- resp = _guarded_http_get(url, timeout=20)- if resp is not None and resp.status_code == 200:- return resp.content- return None-- # Skill names must look like identifiers: lowercase letters/digits with- # optional hyphens/underscores. Blocks dangerous (``../evil``) AND useless- # (``SKILL``, ``README``, empty) candidates before they hit the disk.- _VALID_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")-- @classmethod- def _is_valid_skill_name(cls, name: Optional[str]) -> bool:- if not isinstance(name, str):- return False- candidate = name.strip().lower()- if not candidate or candidate in {"skill", "readme", "index", "unnamed-skill"}:- return False- return bool(cls._VALID_NAME_RE.match(candidate))-- @classmethod- def _resolve_skill_name(cls, fm: dict, url: str) -> Optional[str]:- """Pick a skill name from frontmatter or URL.-- Returns ``None`` when neither source produces a valid identifier;- callers (CLI ``do_install``) then prompt the user or refuse. Preferring- a clean failure over a useless auto-name like ``SKILL`` or ``unnamed-skill``.- """- # 1. Frontmatter ``name:`` is authoritative when present and valid.- fm_name = fm.get("name") if isinstance(fm, dict) else None- if isinstance(fm_name, str) and cls._is_valid_skill_name(fm_name):- return fm_name.strip()-- # 2. URL-slug heuristic: ``.../<name>/SKILL.md`` → ``<name>``;- # ``.../<name>.md`` → ``<name>``. Validate each candidate.- try:- path = urlparse(url).path- except ValueError:- return None- parts = [p for p in path.split("/") if p]- if parts and parts[-1].lower() == "skill.md" and len(parts) >= 2:- candidate = parts[-2]- if cls._is_valid_skill_name(candidate):- return candidate- if parts:- candidate = re.sub(r"\.md$", "", parts[-1], flags=re.IGNORECASE)- if cls._is_valid_skill_name(candidate):- return candidate-- # Nothing usable — let the caller handle it.- return None---# ----------------------------------------------------------------------------# skills.sh source adapter-# -----------------------------------------------------------------------------class SkillsShSource(SkillSource):- """Discover skills via skills.sh and fetch content from the underlying GitHub repo."""-- BASE_URL = "https://skills.sh"- SEARCH_URL = f"{BASE_URL}/api/search"- # Sitemap index — the real catalog source. The homepage scrape only- # exposes a curated featured strip (~200 entries); the sitemap covers- # the full ~20k+ catalog. https://www.skills.sh/sitemap.xml points at- # sitemap-skills-1.xml + sitemap-skills-2.xml, each up to 10k URLs.- SITEMAP_INDEX_URL = "https://www.skills.sh/sitemap.xml"- _SITEMAP_LOC_RE = re.compile(r"<loc>([^<]+)</loc>", re.IGNORECASE)- _SITEMAP_SKILL_RE = re.compile(- r"^https?://(?:www\.)?skills\.sh/(?P<owner>[^/]+)/(?P<repo>[^/]+)/(?P<skill>[^/]+)/?$",- re.IGNORECASE,- )- _SKILL_LINK_RE = re.compile(r'href=["\']/(?P<id>(?!agents/|_next/|api/)[^"\'/]+/[^"\'/]+/[^"\'/]+)["\']')- _INSTALL_CMD_RE = re.compile(- r'npx\s+skills\s+add\s+(?P<repo>https?://github\.com/[^\s<]+|[^\s<]+)'- r'(?:\s+--skill\s+(?P<skill>[^\s<]+))?',- re.IGNORECASE,- )- _PAGE_H1_RE = re.compile(r'<h1[^>]*>(?P<title>.*?)</h1>', re.IGNORECASE | re.DOTALL)- _PROSE_H1_RE = re.compile(- r'<div[^>]*class=["\'][^"\']*prose[^"\']*["\'][^>]*>.*?<h1[^>]*>(?P<title>.*?)</h1>',- re.IGNORECASE | re.DOTALL,- )- _PROSE_P_RE = re.compile(- r'<div[^>]*class=["\'][^"\']*prose[^"\']*["\'][^>]*>.*?<p[^>]*>(?P<body>.*?)</p>',- re.IGNORECASE | re.DOTALL,- )- _WEEKLY_INSTALLS_RE = re.compile(r'Weekly Installs.*?children\\":\\"(?P<count>[0-9.,Kk]+)\\"', re.DOTALL)-- def __init__(self, auth: GitHubAuth):- self.auth = auth- self.github = GitHubSource(auth=auth)-- def source_id(self) -> str:- return "skills-sh"-- def trust_level_for(self, identifier: str) -> str:- return self.github.trust_level_for(self._normalize_identifier(identifier))-- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- if not query.strip():- # Empty query = bulk catalog dump (what build_skills_index.py- # calls with). The homepage scrape only sees ~200 featured- # entries; the sitemap walks the full ~20k+ catalog.- return self._sitemap_catalog(limit)-- cache_key = f"skills_sh_search_{hashlib.md5(f'{query}|{limit}'.encode()).hexdigest()}"- cached = _read_index_cache(cache_key)- if cached is not None:- return [SkillMeta(**item) for item in cached][:limit]-- try:- resp = httpx.get(- self.SEARCH_URL,- params={"q": query, "limit": limit},- timeout=20,- )- if resp.status_code != 200:- return []- data = resp.json()- except (httpx.HTTPError, json.JSONDecodeError):- return []-- items = data.get("skills", []) if isinstance(data, dict) else []- if not isinstance(items, list):- return []-- results: List[SkillMeta] = []- for item in items[:limit]:- meta = self._meta_from_search_item(item)- if meta:- results.append(meta)-- _write_index_cache(cache_key, [_skill_meta_to_dict(item) for item in results])- return results-- def fetch(self, identifier: str) -> Optional[SkillBundle]:- canonical = self._normalize_identifier(identifier)- detail = self._fetch_detail_page(canonical)- for candidate in self._candidate_identifiers(canonical):- bundle = self.github.fetch(candidate)- if bundle:- bundle.source = "skills.sh"- bundle.identifier = self._wrap_identifier(canonical)- bundle.metadata.update(self._detail_to_metadata(canonical, detail))- return bundle-- resolved = self._discover_identifier(canonical, detail=detail)- if resolved:- bundle = self.github.fetch(resolved)- if bundle:- bundle.source = "skills.sh"- bundle.identifier = self._wrap_identifier(canonical)- bundle.metadata.update(self._detail_to_metadata(canonical, detail))- return bundle- return None-- def inspect(self, identifier: str) -> Optional[SkillMeta]:- canonical = self._normalize_identifier(identifier)- detail = self._fetch_detail_page(canonical)- meta = self._resolve_github_meta(canonical, detail=detail)- if meta:- return self._finalize_inspect_meta(meta, canonical, detail)- return None-- def _sitemap_catalog(self, limit: int) -> List[SkillMeta]:- """Walk the skills.sh sitemap to enumerate the full catalog.-- Cached for the standard index TTL so we don't refetch ~2 MB of- sitemap XML per build. Falls back to ``_featured_skills`` if the- sitemap is unreachable or empty (network failure, hostname- change, etc.).- """- cache_key = "skills_sh_sitemap_v1"- cached = _read_index_cache(cache_key)- if cached is not None:- metas = [SkillMeta(**item) for item in cached]- return metas[:limit] if limit > 0 else metas-- # skills.sh serves the per-skill sitemaps brotli-compressed, and- # httpx's optional brotlicffi backend has a streaming-decode bug- # that fails on these specific payloads. Excluding "br" from- # Accept-Encoding makes the server fall back to gzip (or- # identity), which works on every httpx install.- sitemap_headers = {"Accept-Encoding": "gzip"}-- # Step 1: fetch the sitemap index → list of skill-sitemap URLs.- skill_sitemap_urls: List[str] = []- try:- resp = httpx.get(- self.SITEMAP_INDEX_URL,- timeout=20,- follow_redirects=True,- headers=sitemap_headers,- )- if resp.status_code != 200:- return self._featured_skills(limit)- for match in self._SITEMAP_LOC_RE.finditer(resp.text):- loc = match.group(1).strip()- # Sitemap index entries that point at the per-skill maps.- if "sitemap-skills" in loc:- skill_sitemap_urls.append(loc)- except httpx.HTTPError:- return self._featured_skills(limit)-- if not skill_sitemap_urls:- return self._featured_skills(limit)-- # Step 2: fetch each skill sitemap and collect canonical "owner/repo/skill" IDs.- seen: set[str] = set()- results: List[SkillMeta] = []- for sitemap_url in skill_sitemap_urls:- try:- resp = httpx.get(- sitemap_url,- timeout=30,- follow_redirects=True,- headers=sitemap_headers,- )- if resp.status_code != 200:- continue- except httpx.HTTPError:- continue- for loc_match in self._SITEMAP_LOC_RE.finditer(resp.text):- url = loc_match.group(1).strip()- m = self._SITEMAP_SKILL_RE.match(url)- if not m:- continue- owner = m.group("owner")- repo_name = m.group("repo")- skill_name = m.group("skill")- canonical = f"{owner}/{repo_name}/{skill_name}"- if canonical in seen:- continue- seen.add(canonical)- repo = f"{owner}/{repo_name}"- results.append(SkillMeta(- name=skill_name,- description=f"Indexed by skills.sh from {repo}",- source="skills.sh",- identifier=self._wrap_identifier(canonical),- trust_level=self.github.trust_level_for(canonical),- repo=repo,- path=skill_name,- extra={- "detail_url": f"{self.BASE_URL}/{canonical}",- "repo_url": f"https://github.com/{repo}",- },- ))-- if not results:- return self._featured_skills(limit)-- _write_index_cache(cache_key, [_skill_meta_to_dict(item) for item in results])- return results[:limit] if limit > 0 else results-- def _featured_skills(self, limit: int) -> List[SkillMeta]:- cache_key = "skills_sh_featured"- cached = _read_index_cache(cache_key)- if cached is not None:- return [SkillMeta(**item) for item in cached][:limit]-- try:- resp = httpx.get(self.BASE_URL, timeout=20)- if resp.status_code != 200:- return []- except httpx.HTTPError:- return []-- seen: set[str] = set()- results: List[SkillMeta] = []- for match in self._SKILL_LINK_RE.finditer(resp.text):- canonical = match.group("id")- if canonical in seen:- continue- seen.add(canonical)- parts = canonical.split("/", 2)- if len(parts) < 3:- continue- repo = f"{parts[0]}/{parts[1]}"- skill_path = parts[2]- results.append(SkillMeta(- name=skill_path.split("/")[-1],- description=f"Featured on skills.sh from {repo}",- source="skills.sh",- identifier=self._wrap_identifier(canonical),- trust_level=self.github.trust_level_for(canonical),- repo=repo,- path=skill_path,- ))- if len(results) >= limit:- break-- _write_index_cache(cache_key, [_skill_meta_to_dict(item) for item in results])- return results-- def _meta_from_search_item(self, item: dict) -> Optional[SkillMeta]:- if not isinstance(item, dict):- return None-- canonical = item.get("id")- repo = item.get("source")- skill_path = item.get("skillId")- if not isinstance(canonical, str) or canonical.count("/") < 2:- if not (isinstance(repo, str) and isinstance(skill_path, str)):- return None- canonical = f"{repo}/{skill_path}"-- parts = canonical.split("/", 2)- if len(parts) < 3:- return None-- repo = f"{parts[0]}/{parts[1]}"- skill_path = parts[2]- installs = item.get("installs")- installs_label = f" · {int(installs):,} installs" if isinstance(installs, int) else ""-- return SkillMeta(- name=str(item.get("name") or skill_path.split("/")[-1]),- description=f"Indexed by skills.sh from {repo}{installs_label}",- source="skills.sh",- identifier=self._wrap_identifier(canonical),- trust_level=self.github.trust_level_for(canonical),- repo=repo,- path=skill_path,- extra={- "installs": installs,- "detail_url": f"{self.BASE_URL}/{canonical}",- "repo_url": f"https://github.com/{repo}",- },- )-- def _fetch_detail_page(self, identifier: str) -> Optional[dict]:- cache_key = f"skills_sh_detail_{hashlib.md5(identifier.encode()).hexdigest()}"- cached = _read_index_cache(cache_key)- if isinstance(cached, dict):- return cached-- try:- resp = httpx.get(f"{self.BASE_URL}/{identifier}", timeout=20)- if resp.status_code != 200:- return None- except httpx.HTTPError:- return None-- detail = self._parse_detail_page(identifier, resp.text)- if detail:- _write_index_cache(cache_key, detail)- return detail-- def _parse_detail_page(self, identifier: str, html: str) -> Optional[dict]:- parts = identifier.split("/", 2)- if len(parts) < 3:- return None-- default_repo = f"{parts[0]}/{parts[1]}"- skill_token = parts[2]- repo = default_repo- install_skill = skill_token-- install_command = None- install_match = self._INSTALL_CMD_RE.search(html)- if install_match:- install_command = install_match.group(0).strip()- repo_value = (install_match.group("repo") or "").strip()- install_skill = (install_match.group("skill") or install_skill).strip()- repo = self._extract_repo_slug(repo_value) or repo-- page_title = self._extract_first_match(self._PAGE_H1_RE, html)- body_title = self._extract_first_match(self._PROSE_H1_RE, html)- body_summary = self._extract_first_match(self._PROSE_P_RE, html)- weekly_installs = self._extract_weekly_installs(html)- security_audits = self._extract_security_audits(html, identifier)-- return {- "repo": repo,- "install_skill": install_skill,- "page_title": page_title,- "body_title": body_title,- "body_summary": body_summary,- "weekly_installs": weekly_installs,- "install_command": install_command,- "repo_url": f"https://github.com/{repo}",- "detail_url": f"{self.BASE_URL}/{identifier}",- "security_audits": security_audits,- }-- def _discover_identifier(self, identifier: str, detail: Optional[dict] = None) -> Optional[str]:- parts = identifier.split("/", 2)- if len(parts) < 3:- return None-- default_repo = f"{parts[0]}/{parts[1]}"- repo = detail.get("repo", default_repo) if isinstance(detail, dict) else default_repo- skill_token=parts[2].split("/")[-1]- tokens=[skill_token]- if isinstance(detail, dict):- tokens.extend([- detail.get("install_skill", ""),- detail.get("page_title", ""),- detail.get("body_title", ""),- ])-- # Standard skill paths- base_paths = ["skills/", ".agents/skills/", ".claude/skills/"]-- for base_path in base_paths:- try:- skills = self.github._list_skills_in_repo(repo, base_path)- except Exception:- continue- for meta in skills:- if self._matches_skill_tokens(meta, tokens):- return meta.identifier-- # Prefer a single recursive tree lookup before brute-forcing every- # top-level directory. This avoids large request bursts on categorized- # repos like borghei/claude-skills.- tree_result = self.github._find_skill_in_repo_tree(repo, skill_token)- if tree_result:- return tree_result-- # Fallback: scan repo root for directories that might contain skills- try:- root_url = f"https://api.github.com/repos/{repo}/contents/"- resp = httpx.get(root_url, headers=self.github.auth.get_headers(),- timeout=15, follow_redirects=True)- if resp.status_code == 200:- entries = resp.json()- if isinstance(entries, list):- for entry in entries:- if entry.get("type") != "dir":- continue- dir_name = entry["name"]- if dir_name.startswith((".", "_")):- continue- if dir_name in {"skills", ".agents", ".claude"}:- continue # already tried- # Try direct: repo/dir/skill_token- direct_id = f"{repo}/{dir_name}/{skill_token}"- meta = self.github.inspect(direct_id)- if meta:- return meta.identifier- # Try listing skills in this directory- try:- skills = self.github._list_skills_in_repo(repo, dir_name + "/")- except Exception:- continue- for meta in skills:- if self._matches_skill_tokens(meta, tokens):- return meta.identifier- except Exception:- pass-- return None-- def _resolve_github_meta(self, identifier: str, detail: Optional[dict] = None) -> Optional[SkillMeta]:- for candidate in self._candidate_identifiers(identifier):- meta = self.github.inspect(candidate)- if meta:- return meta-- resolved = self._discover_identifier(identifier, detail=detail)- if resolved:- return self.github.inspect(resolved)- return None-- def _finalize_inspect_meta(self, meta: SkillMeta, canonical: str, detail: Optional[dict]) -> SkillMeta:- meta.source = "skills.sh"- meta.identifier = self._wrap_identifier(canonical)- meta.trust_level = self.trust_level_for(canonical)- merged_extra = dict(meta.extra)- merged_extra.update(self._detail_to_metadata(canonical, detail))- meta.extra = merged_extra-- if isinstance(detail, dict):- body_summary = detail.get("body_summary")- weekly_installs = detail.get("weekly_installs")- if body_summary:- meta.description = body_summary- elif meta.description and weekly_installs:- meta.description = f"{meta.description} · {weekly_installs} weekly installs on skills.sh"- return meta-- @classmethod- def _matches_skill_tokens(cls, meta: SkillMeta, skill_tokens: List[str]) -> bool:- candidates = set()- candidates.update(cls._token_variants(meta.name))- candidates.update(cls._token_variants(meta.path))- candidates.update(cls._token_variants(meta.identifier.split("/", 2)[-1] if meta.identifier else None))-- for token in skill_tokens:- variants = cls._token_variants(token)- if variants & candidates:- return True- return False-- @staticmethod- def _token_variants(value: Optional[str]) -> set[str]:- if not value:- return set()-- plain = SkillsShSource._strip_html(str(value)).strip().strip("/").lower()- if not plain:- return set()-- base = plain.split("/")[-1]- sanitized = re.sub(r'[^a-z0-9/_-]+', '-', plain).strip('-')- sanitized_base = sanitized.split("/")[-1] if sanitized else ""- slash_tail = plain.split("/")[-1]- slash_tail_clean = slash_tail.lstrip('@')- slash_tail_clean = slash_tail_clean.split('/')[-1]-- variants = {- plain,- plain.replace("_", "-"),- plain.replace("/", "-"),- base,- base.replace("_", "-"),- base.replace("/", "-"),- sanitized,- sanitized.replace("/", "-") if sanitized else "",- sanitized_base,- slash_tail_clean,- slash_tail_clean.replace("_", "-"),- }- return {v for v in variants if v}-- @staticmethod- def _extract_repo_slug(repo_value: str) -> Optional[str]:- repo_value = repo_value.strip()- if repo_value.startswith("https://github.com/"):- repo_value = repo_value[len("https://github.com/"):]- repo_value = repo_value.strip("/")- parts = repo_value.split("/")- if len(parts) >= 2:- return f"{parts[0]}/{parts[1]}"- return None-- @staticmethod- def _extract_first_match(pattern: re.Pattern, text: str) -> Optional[str]:- match = pattern.search(text)- if not match:- return None- value = next((group for group in match.groups() if group), None)- if value is None:- return None- return SkillsShSource._strip_html(value).strip() or None-- def _detail_to_metadata(self, canonical: str, detail: Optional[dict]) -> Dict[str, Any]:- parts = canonical.split("/", 2)- repo = f"{parts[0]}/{parts[1]}" if len(parts) >= 2 else ""- metadata = {- "detail_url": f"{self.BASE_URL}/{canonical}",- }- if repo:- metadata["repo_url"] = f"https://github.com/{repo}"- if isinstance(detail, dict):- for key in ("weekly_installs", "install_command", "repo_url", "detail_url", "security_audits"):- value = detail.get(key)- if value:- metadata[key] = value- return metadata-- @staticmethod- def _extract_weekly_installs(html: str) -> Optional[str]:- match = SkillsShSource._WEEKLY_INSTALLS_RE.search(html)- if not match:- return None- return match.group("count")-- @staticmethod- def _extract_security_audits(html: str, identifier: str) -> Dict[str, str]:- audits: Dict[str, str] = {}- for audit in ("agent-trust-hub", "socket", "snyk"):- idx = html.find(f"/security/{audit}")- if idx == -1:- continue- window = html[idx:idx + 500]- match = re.search(r'(Pass|Warn|Fail)', window, re.IGNORECASE)- if match:- audits[audit] = match.group(1).title()- return audits-- @staticmethod- def _strip_html(value: str) -> str:- return re.sub(r'<[^>]+>', '', value)-- @staticmethod- def _normalize_identifier(identifier: str) -> str:- prefix_aliases = (- "skills-sh/",- "skills.sh/",- "skils-sh/",- "skils.sh/",- )- for prefix in prefix_aliases:- if identifier.startswith(prefix):- return identifier[len(prefix):]- return identifier-- @staticmethod- def _candidate_identifiers(identifier: str) -> List[str]:- parts = identifier.split("/", 2)- if len(parts) < 3:- return [identifier]-- repo = f"{parts[0]}/{parts[1]}"- skill_path = parts[2].lstrip("/")- candidates = [- f"{repo}/{skill_path}",- f"{repo}/skills/{skill_path}",- f"{repo}/.agents/skills/{skill_path}",- f"{repo}/.claude/skills/{skill_path}",- ]-- seen = set()- deduped: List[str] = []- for candidate in candidates:- if candidate not in seen:- seen.add(candidate)- deduped.append(candidate)- return deduped-- @staticmethod- def _wrap_identifier(identifier: str) -> str:- return f"skills-sh/{identifier}"---# ----------------------------------------------------------------------------# ClawHub source adapter-# -----------------------------------------------------------------------------class ClawHubSource(SkillSource):- """- Fetch skills from ClawHub (clawhub.ai) via their HTTP API.- All skills are treated as community trust — ClawHavoc incident showed- their vetting is insufficient (341 malicious skills found Feb 2026).- """-- BASE_URL = "https://clawhub.ai/api/v1"-- # Wall-clock budget for a full catalog walk. ClawHub has 50k+ skills and- # the walk is sequential (~250 requests, each under per-request- # timeout=30 so nothing errors), so an unbounded walk can block for- # minutes. Bound it so a slow/large catalog cannot hang the caller.- CATALOG_WALK_BUDGET_SECONDS = 12-- def source_id(self) -> str:- return "clawhub"-- def trust_level_for(self, identifier: str) -> str:- return "community"-- @staticmethod- def _normalize_tags(tags: Any) -> List[str]:- if isinstance(tags, list):- return [str(t) for t in tags]- if isinstance(tags, dict):- return [str(k) for k in tags if str(k) != "latest"]- return []-- @staticmethod- def _coerce_skill_payload(data: Any) -> Optional[Dict[str, Any]]:- if not isinstance(data, dict):- return None- nested = data.get("skill")- if isinstance(nested, dict):- merged = dict(nested)- latest_version = data.get("latestVersion")- if latest_version is not None and "latestVersion" not in merged:- merged["latestVersion"] = latest_version- # Carry over top-level fields that the listing API nests alongside- # the skill object — owner is needed for building valid detail URLs.- if "owner" in data and "owner" not in merged:- merged["owner"] = data["owner"]- return merged- return data-- @staticmethod- def _query_terms(query: str) -> List[str]:- return [term for term in re.split(r"[^a-z0-9]+", query.lower()) if term]-- @classmethod- def _search_score(cls, query: str, meta: SkillMeta) -> int:- query_norm = query.strip().lower()- if not query_norm:- return 1-- identifier = (meta.identifier or "").lower()- name = (meta.name or "").lower()- description = (meta.description or "").lower()- normalized_identifier = " ".join(cls._query_terms(identifier))- normalized_name = " ".join(cls._query_terms(name))- query_terms = cls._query_terms(query_norm)- identifier_terms = cls._query_terms(identifier)- name_terms = cls._query_terms(name)- score = 0-- if query_norm == identifier:- score += 140- if query_norm == name:- score += 130- if normalized_identifier == query_norm:- score += 125- if normalized_name == query_norm:- score += 120- if normalized_identifier.startswith(query_norm):- score += 95- if normalized_name.startswith(query_norm):- score += 90- if query_terms and identifier_terms[: len(query_terms)] == query_terms:- score += 70- if query_terms and name_terms[: len(query_terms)] == query_terms:- score += 65- if query_norm in identifier:- score += 40- if query_norm in name:- score += 35- if query_norm in description:- score += 10-- for term in query_terms:- if term in identifier_terms:- score += 15- if term in name_terms:- score += 12- if term in description:- score += 3-- return score-- @staticmethod- def _dedupe_results(results: List[SkillMeta]) -> List[SkillMeta]:- seen: set[str] = set()- deduped: List[SkillMeta] = []- for result in results:- key = (result.identifier or result.name).lower()- if key in seen:- continue- seen.add(key)- deduped.append(result)- return deduped-- def _exact_slug_meta(self, query: str) -> Optional[SkillMeta]:- query = query.strip()- parsed = self._parse_identifier(query)- query_terms = self._query_terms(query)- candidates: List[str] = []-- if parsed:- candidates.append(parsed[0])- elif "/" not in query and self._SLUG_RE.fullmatch(query):- candidates.append(query)-- if query_terms:- base_slug = "-".join(query_terms)- if len(query_terms) >= 2:- candidates.extend([- f"{base_slug}-agent",- f"{base_slug}-skill",- f"{base_slug}-tool",- f"{base_slug}-assistant",- f"{base_slug}-playbook",- base_slug,- ])- else:- candidates.append(base_slug)-- seen: set[str] = set()- for candidate in candidates:- if candidate in seen:- continue- seen.add(candidate)- meta = self.inspect(candidate)- if meta:- return meta-- return None-- def _finalize_search_results(self, query: str, results: List[SkillMeta], limit: int) -> List[SkillMeta]:- query_norm = query.strip()- if not query_norm:- return self._dedupe_results(results)[:limit]-- filtered = [meta for meta in results if self._search_score(query_norm, meta) > 0]- filtered.sort(- key=lambda meta: (- -self._search_score(query_norm, meta),- meta.name.lower(),- meta.identifier.lower(),- )- )- filtered = self._dedupe_results(filtered)-- exact = self._exact_slug_meta(query_norm)- if exact:- filtered = [meta for meta in filtered if self._search_score(query_norm, meta) >= 20]- filtered = self._dedupe_results([exact] + filtered)-- if filtered:- return filtered[:limit]-- if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]*", query_norm):- return []-- return self._dedupe_results(results)[:limit]-- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- query = query.strip()-- if query:- query_terms = self._query_terms(query)- if len(query_terms) >= 2:- direct = self._exact_slug_meta(query)- if direct:- return [direct]-- results = self._search_catalog(query, limit=limit)- if results:- return results- else:- # Empty query: route through the paginating catalog walker. When- # the full catalog is already disk-cached this returns it whole and- # the caller paginates client-side. On a cold cache, bound the walk- # to `limit` so a browse command renders its first page without- # walking the entire 50k+ catalog (max_items=0 → unbounded, used- # only by the offline index builder via search("", limit=0)).- catalog = self._load_catalog_index(max_items=limit if limit > 0 else 0)- if catalog:- return self._dedupe_results(catalog)[:limit] if limit > 0 else self._dedupe_results(catalog)-- # Non-empty query catalog miss, or catalog walker failure: fall back to- # the lightweight listing API for a best-effort response.- cache_key = f"clawhub_search_listing_v1_{hashlib.md5(query.encode()).hexdigest()}_{limit}"- cached = _read_index_cache(cache_key)- if cached is not None:- return self._finalize_search_results(- query,- [SkillMeta(**s) for s in cached],- limit,- )-- try:- resp = httpx.get(- f"{self.BASE_URL}/skills",- params={"search": query, "limit": limit},- timeout=15,- )- if resp.status_code != 200:- return []- data = resp.json()- except (httpx.HTTPError, json.JSONDecodeError):- return []-- skills_data = data.get("items", data) if isinstance(data, dict) else data- if not isinstance(skills_data, list):- return []-- results = []- for item in skills_data[:limit]:- slug = item.get("slug")- if not slug:- continue- display_name = item.get("displayName") or item.get("name") or slug- summary = item.get("summary") or item.get("description") or ""- tags = self._normalize_tags(item.get("tags", []))- extra: Dict[str, Any] = {}- owner = item.get("owner")- if isinstance(owner, dict):- handle = owner.get("handle")- if isinstance(handle, str) and handle:- extra["owner"] = handle- elif isinstance(owner, str) and owner:- extra["owner"] = owner- results.append(SkillMeta(- name=display_name,- description=summary,- source="clawhub",- identifier=slug,- trust_level="community",- tags=tags,- extra=extra,- ))-- final_results = self._finalize_search_results(query, results, limit)- _write_index_cache(cache_key, [_skill_meta_to_dict(s) for s in final_results])- return final_results-- _SLUG_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*$")-- @classmethod- def _parse_identifier(cls, identifier: str) -> Optional[Tuple[str, Optional[str]]]:- """Return ``(slug, expected_owner)`` for a ClawHub identifier.-- Accepts a bare slug, ``clawhub/<slug>``, ``@owner/slug``, and the- clawhub.ai URL path ``owner/skills/slug``. GitHub-style- ``owner/repo/skill`` and ``owner/repo/skills/skill`` identifiers- are not ClawHub's — claiming them by last path segment installs- a same-named skill from a different author.- """- raw = (identifier or "").strip()- if not raw:- return None- had_at = raw.startswith("@")- ident = raw[1:] if had_at else raw- if ident.startswith("clawhub/"):- ident = ident[len("clawhub/"):]- parts = [part for part in ident.split("/") if part]- if len(parts) == 1:- slug = parts[0]- return (slug, None) if cls._SLUG_RE.fullmatch(slug) else None- if len(parts) == 2 and had_at:- owner, slug = parts- if cls._SLUG_RE.fullmatch(owner) and cls._SLUG_RE.fullmatch(slug):- return slug, owner- return None- if len(parts) == 3 and parts[1].lower() == "skills":- owner, _, slug = parts- if cls._SLUG_RE.fullmatch(owner) and cls._SLUG_RE.fullmatch(slug):- return slug, owner- return None- return None-- @staticmethod- def _owner_from_payload(data: Optional[Dict[str, Any]]) -> Optional[str]:- if not isinstance(data, dict):- return None- owner = data.get("owner")- if isinstance(owner, dict):- handle = owner.get("handle")- if isinstance(handle, str) and handle.strip():- return handle.strip()- if isinstance(owner, str) and owner.strip():- return owner.strip()- return None-- @classmethod- def _owner_matches(cls, expected_owner: Optional[str], data: Optional[Dict[str, Any]]) -> bool:- if not expected_owner:- return True- actual = cls._owner_from_payload(data)- if not actual:- return True- return actual.lower() == expected_owner.lower()-- def fetch(self, identifier: str) -> Optional[SkillBundle]:- parsed = self._parse_identifier(identifier)- if parsed is None:- return None- slug, expected_owner = parsed-- skill_data = self._coerce_skill_payload(self._get_json(f"{self.BASE_URL}/skills/{slug}"))- if not isinstance(skill_data, dict):- return None- if not self._owner_matches(expected_owner, skill_data):- return None-- latest_version = self._resolve_latest_version(slug, skill_data)- if not latest_version:- logger.warning("ClawHub fetch failed for %s: could not resolve latest version", slug)- return None-- # Primary method: download the skill as a ZIP bundle from /download- files = self._download_zip(slug, latest_version)-- # Fallback: try the version metadata endpoint for inline/raw content- if "SKILL.md" not in files:- version_data = self._get_json(f"{self.BASE_URL}/skills/{slug}/versions/{latest_version}")- if isinstance(version_data, dict):- # Files may be nested under version_data["version"]["files"]- files = self._extract_files(version_data) or files- if "SKILL.md" not in files:- nested = version_data.get("version", {})- if isinstance(nested, dict):- files = self._extract_files(nested) or files-- if "SKILL.md" not in files:- logger.warning(- "ClawHub fetch for %s resolved version %s but could not retrieve file content",- slug,- latest_version,- )- return None-- return SkillBundle(- name=slug,- files=files,- source="clawhub",- identifier=slug,- trust_level="community",- )-- def inspect(self, identifier: str) -> Optional[SkillMeta]:- parsed = self._parse_identifier(identifier)- if parsed is None:- return None- slug, expected_owner = parsed- data = self._coerce_skill_payload(self._get_json(f"{self.BASE_URL}/skills/{slug}"))- if not isinstance(data, dict):- return None- if not self._owner_matches(expected_owner, data):- return None-- tags = self._normalize_tags(data.get("tags", []))- extra: Dict[str, Any] = {}- # The detail API returns owner info — capture it so callers can build- # valid ClawHub URLs (https://clawhub.ai/{owner}/skills/{slug}).- owner = self._owner_from_payload(data)- if owner:- extra["owner"] = owner-- return SkillMeta(- name=data.get("displayName") or data.get("name") or data.get("slug") or slug,- description=data.get("summary") or data.get("description") or "",- source="clawhub",- identifier=data.get("slug") or slug,- trust_level="community",- tags=tags,- extra=extra,- )-- def _search_catalog(self, query: str, limit: int = 10) -> List[SkillMeta]:- cache_key = f"clawhub_search_catalog_v1_{hashlib.md5(f'{query}|{limit}'.encode()).hexdigest()}"- cached = _read_index_cache(cache_key)- if cached is not None:- return [SkillMeta(**s) for s in cached][:limit]-- catalog = self._load_catalog_index()- if not catalog:- return []-- results = self._finalize_search_results(query, catalog, limit)- _write_index_cache(cache_key, [_skill_meta_to_dict(s) for s in results])- return results-- def _load_catalog_index(self, max_items: int = 0) -> List[SkillMeta]:- """Walk the ClawHub catalog via cursor pagination.-- ``max_items`` bounds the walk: once at least that many distinct skills- have been gathered the walk stops early. This is what browse's- cold-start fallback wants — it only renders one page, so walking the- entire 50k+ catalog just to slice off the first N is pure waste.- ``max_items=0`` (the default, used by the offline index builder) means- walk to exhaustion.-- Caching: only a *complete* catalog (cursor exhausted or page cap) is- written to the shared ``clawhub_catalog_v1`` cache. A walk truncated by- ``max_items`` OR the wall-clock budget is partial, so caching it would- poison the full-catalog cache with an incomplete slice.- """- cache_key = "clawhub_catalog_v1"- cached = _read_index_cache(cache_key)- if cached is not None:- return [SkillMeta(**s) for s in cached]-- cursor: Optional[str] = None- results: List[SkillMeta] = []- seen: set[str] = set()- # ClawHub has 50k+ skills as of May 2026 (live E2E walked 49,698 with- # an active cursor still pending); 750 pages * 200/page = 150k ceiling- # leaves room for catalog growth. Walk-to-exhaustion typically- # terminates well before this on `nextCursor` going None — the cap is- # a safety rail against an infinite-cursor loop.- max_pages = 750- # Wall-clock budget is for interactive browse (max_items > 0) only.- # The offline index builder passes max_items=0 and must walk the full- # catalog — a 12s cap there ships ~3k skills and trips the deploy- # health floor (20k).- deadline = (- time.monotonic() + self.CATALOG_WALK_BUDGET_SECONDS- if max_items > 0- else None- )- hit_deadline = False- hit_max_items = False-- for _ in range(max_pages):- if deadline is not None and time.monotonic() > deadline:- hit_deadline = True- break- params: Dict[str, Any] = {"limit": 200}- if cursor:- params["cursor"] = cursor-- try:- resp = httpx.get(f"{self.BASE_URL}/skills", params=params, timeout=30)- if resp.status_code != 200:- break- data = resp.json()- except (httpx.HTTPError, json.JSONDecodeError):- break-- items = data.get("items", []) if isinstance(data, dict) else []- if not isinstance(items, list) or not items:- break-- for item in items:- slug = item.get("slug")- if not isinstance(slug, str) or not slug or slug in seen:- continue- seen.add(slug)- display_name = item.get("displayName") or item.get("name") or slug- summary = item.get("summary") or item.get("description") or ""- tags = self._normalize_tags(item.get("tags", []))- extra: Dict[str, Any] = {}- owner = self._owner_from_payload(item)- if owner:- extra["owner"] = owner- results.append(SkillMeta(- name=display_name,- description=summary,- source="clawhub",- identifier=slug,- trust_level="community",- tags=tags,- extra=extra,- ))-- cursor = data.get("nextCursor") if isinstance(data, dict) else None- if not isinstance(cursor, str) or not cursor:- break-- # Browse's cold-start fallback only renders one page, so stop as- # soon as we have enough to satisfy the caller's bound. The index- # builder passes max_items=0 (unbounded) and walks to exhaustion.- if max_items > 0 and len(results) >= max_items:- hit_max_items = True- break-- # Only cache a walk that reached a natural stop (cursor exhausted or- # page cap). A walk truncated by the wall-clock budget OR by max_items- # is partial, so writing it would poison the shared full-catalog cache- # with incomplete data.- if not hit_deadline and not hit_max_items:- _write_index_cache(cache_key, [_skill_meta_to_dict(s) for s in results])- return results-- def _get_json(self, url: str, timeout: int = 20) -> Optional[Any]:- try:- resp = httpx.get(url, timeout=timeout)- if resp.status_code != 200:- return None- return resp.json()- except (httpx.HTTPError, json.JSONDecodeError):- return None-- def _resolve_latest_version(self, slug: str, skill_data: Dict[str, Any]) -> Optional[str]:- latest = skill_data.get("latestVersion")- if isinstance(latest, dict):- version = latest.get("version")- if isinstance(version, str) and version:- return version-- tags = skill_data.get("tags")- if isinstance(tags, dict):- latest_tag = tags.get("latest")- if isinstance(latest_tag, str) and latest_tag:- return latest_tag-- versions_data = self._get_json(f"{self.BASE_URL}/skills/{slug}/versions")- if isinstance(versions_data, list) and versions_data:- first = versions_data[0]- if isinstance(first, dict):- version = first.get("version")- if isinstance(version, str) and version:- return version- return None-- def _fetch_owner_handle(self, slug: str) -> Optional[str]:- """Fetch the owner handle for a single ClawHub skill via the detail API.-- Returns the owner handle string, or None if unavailable.- The detail endpoint at ``/api/v1/skills/{slug}`` returns an ``owner``- object with a ``handle`` field — the listing API does not include this.-- Retry semantics (bounded):- - Up to 3 attempts total (initial + 2 retries).- - On HTTP 429: respects ``Retry-After`` header (seconds) when present,- otherwise exponential backoff (2s → 4s).- - On HTTP 5xx: exponential backoff (transient server errors).- - On HTTP 4xx (non-429): no retry — the resource doesn't exist.- """- url = f"{self.BASE_URL}/skills/{slug}"- max_attempts = 3- backoff_base = 2.0 # seconds-- for attempt in range(max_attempts):- try:- resp = httpx.get(url, timeout=20)- except (httpx.HTTPError, OSError):- # Network/transport error — treat as transient, retry with backoff.- if attempt < max_attempts - 1:- delay = backoff_base * (2 ** attempt)- logger.debug(- "_fetch_owner_handle(%s): transport error on attempt %d/%d, "- "retrying in %.1fs",- slug, attempt + 1, max_attempts, delay,- )- time.sleep(delay)- continue- return None-- if resp.status_code == 200:- try:- raw = resp.json()- except (json.JSONDecodeError, ValueError):- return None- data = self._coerce_skill_payload(raw)- if not isinstance(data, dict):- return None- return self._owner_from_payload(data)-- if resp.status_code == 429:- # Rate-limited — honour Retry-After if present, else backoff.- if attempt < max_attempts - 1:- retry_after_raw = resp.headers.get("Retry-After")- try:- delay = float(retry_after_raw) if retry_after_raw else backoff_base * (2 ** attempt)- except (TypeError, ValueError):- delay = backoff_base * (2 ** attempt)- logger.debug(- "_fetch_owner_handle(%s): HTTP 429 on attempt %d/%d, "- "retrying in %.1fs",- slug, attempt + 1, max_attempts, delay,- )- time.sleep(delay)- continue- return None-- if 500 <= resp.status_code < 600:- # Transient server error — retry with backoff.- if attempt < max_attempts - 1:- delay = backoff_base * (2 ** attempt)- logger.debug(- "_fetch_owner_handle(%s): HTTP %d on attempt %d/%d, "- "retrying in %.1fs",- slug, resp.status_code, attempt + 1, max_attempts, delay,- )- time.sleep(delay)- continue- return None-- # 4xx (non-429) — resource doesn't exist / bad request. No retry.- return None-- return None-- def enrich_owners(self, skills: List[SkillMeta], max_workers: int = 30) -> int:- """Batch-fetch owner handles for ClawHub skills missing ``extra["owner"]``.-- Mutates each SkillMeta in-place, setting ``extra["owner"]`` when the- detail API returns a handle. Returns the number of skills enriched.-- This is intended for the offline index builder, which walks the full- 50k+ catalog. The listing API does not include owner info, so we- fetch each skill's detail page concurrently. With ``max_workers=30``- the full catalog takes ~5–10 minutes — acceptable for a twice-daily- batch job.-- Safety rails:- - Aborts early if 50 consecutive requests all fail (systemic outage).- - Respects HTTP 429 rate-limit responses with exponential backoff.- - Logs progress every 1000 skills so the batch job is observable.- """- needs_enrichment = [- s for s in skills- if s.source == "clawhub" and not (s.extra or {}).get("owner")- ]- if not needs_enrichment:- return 0-- enriched = 0- consecutive_failures = 0- max_consecutive_failures = 50- processed = 0- import threading- lock = threading.Lock()-- def _fetch(meta: SkillMeta) -> Optional[str]:- return self._fetch_owner_handle(meta.identifier)-- from concurrent.futures import ThreadPoolExecutor, as_completed- with ThreadPoolExecutor(max_workers=max_workers) as pool:- futures = {pool.submit(_fetch, s): s for s in needs_enrichment}- for future in as_completed(futures):- meta = futures[future]- processed += 1- try:- handle = future.result()- if handle:- with lock:- if not meta.extra:- meta.extra = {}- meta.extra["owner"] = handle- enriched += 1- consecutive_failures = 0- else:- with lock:- consecutive_failures += 1- except Exception:- with lock:- consecutive_failures += 1-- if processed % 1000 == 0:- logger.info(- "ClawHub owner enrichment: %d/%d processed, %d enriched",- processed, len(needs_enrichment), enriched,- )-- with lock:- if consecutive_failures >= max_consecutive_failures:- logger.warning(- "ClawHub owner enrichment: %d consecutive failures — "- "aborting early (%d/%d processed, %d enriched). "- "The ClawHub API may be down or rate-limited.",- max_consecutive_failures, processed,- len(needs_enrichment), enriched,- )- # Cancel pending futures- for f in futures:- f.cancel()- break-- return enriched-- def _extract_files(self, version_data: Dict[str, Any]) -> Dict[str, str]:- files: Dict[str, str] = {}- file_list = version_data.get("files")-- if isinstance(file_list, dict):- return {k: v for k, v in file_list.items() if isinstance(v, str)}-- if not isinstance(file_list, list):- return files-- for file_meta in file_list:- if not isinstance(file_meta, dict):- continue-- fname = file_meta.get("path") or file_meta.get("name")- if not fname or not isinstance(fname, str):- continue-- inline_content = file_meta.get("content")- if isinstance(inline_content, str):- files[fname] = inline_content- continue-- raw_url = file_meta.get("rawUrl") or file_meta.get("downloadUrl") or file_meta.get("url")- if isinstance(raw_url, str) and raw_url.startswith("http"):- content = self._fetch_text(raw_url)- if content is not None:- files[fname] = content-- return files-- def _download_zip(self, slug: str, version: str) -> Dict[str, str]:- """Download skill as a ZIP bundle from the /download endpoint and extract text files."""- import io- import zipfile-- files: Dict[str, str] = {}- max_retries = 3- for attempt in range(max_retries):- try:- resp = httpx.get(- f"{self.BASE_URL}/download",- params={"slug": slug, "version": version},- timeout=30,- follow_redirects=True,- )- if resp.status_code == 429:- try:- retry_after = int(resp.headers.get("retry-after", "5"))- except (ValueError, TypeError):- retry_after = 5- retry_after = min(retry_after, 15) # Cap wait time- logger.debug(- "ClawHub download rate-limited for %s, retrying in %ds (attempt %d/%d)",- slug, retry_after, attempt + 1, max_retries,- )- time.sleep(retry_after)- continue- if resp.status_code != 200:- logger.debug("ClawHub ZIP download for %s v%s returned %s", slug, version, resp.status_code)- return files-- with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:- for info in zf.infolist():- if info.is_dir():- continue- try:- name = _validate_bundle_rel_path(info.filename)- except ValueError:- logger.debug("Skipping unsafe ZIP member path: %s", info.filename)- continue- # Only extract text-sized files (skip large binaries)- if info.file_size > 500_000:- logger.debug("Skipping large file in ZIP: %s (%d bytes)", name, info.file_size)- continue- try:- raw = zf.read(info.filename)- files[name] = raw.decode("utf-8")- except (UnicodeDecodeError, KeyError):- logger.debug("Skipping non-text file in ZIP: %s", name)- continue-- return files-- except zipfile.BadZipFile:- logger.warning("ClawHub returned invalid ZIP for %s v%s", slug, version)- return files- except httpx.HTTPError as exc:- logger.debug("ClawHub ZIP download failed for %s v%s: %s", slug, version, exc)- return files-- logger.debug("ClawHub ZIP download exhausted retries for %s v%s", slug, version)- return files-- def _fetch_text(self, url: str) -> Optional[str]:- resp = _guarded_http_get(url, timeout=20)- if resp is not None and resp.status_code == 200:- return resp.text- return None---# ----------------------------------------------------------------------------# LobeHub source adapter-# -----------------------------------------------------------------------------class LobeHubSource(SkillSource):- """- Fetch skills from LobeHub's agent marketplace (14,500+ agents).- LobeHub agents are system prompt templates — we convert them to SKILL.md on fetch.- Data lives in GitHub: lobehub/lobe-chat-agents.- """-- INDEX_URL = "https://chat-agents.lobehub.com/index.json"-- def source_id(self) -> str:- return "lobehub"-- def trust_level_for(self, identifier: str) -> str:- return "community"-- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- index = self._fetch_index()- if not index:- return []-- query_lower = query.lower()- results: List[SkillMeta] = []-- agents = index.get("agents", index) if isinstance(index, dict) else index- if not isinstance(agents, list):- return []-- for agent in agents:- meta = agent.get("meta", agent)- title = meta.get("title", agent.get("identifier", ""))- desc = meta.get("description", "")- tags = meta.get("tags", [])-- searchable = f"{title} {desc} {' '.join(tags) if isinstance(tags, list) else ''}".lower()- if query_lower in searchable:- identifier = agent.get("identifier", title.lower().replace(" ", "-"))- results.append(SkillMeta(- name=identifier,- description=desc[:200],- source="lobehub",- identifier=f"lobehub/{identifier}",- trust_level="community",- tags=tags if isinstance(tags, list) else [],- ))-- if len(results) >= limit:- break-- return results-- def fetch(self, identifier: str) -> Optional[SkillBundle]:- # Strip "lobehub/" prefix if present- agent_id = identifier.split("/", 1)[-1] if identifier.startswith("lobehub/") else identifier-- agent_data = self._fetch_agent(agent_id)- if not agent_data:- return None-- skill_md = self._convert_to_skill_md(agent_data)- return SkillBundle(- name=agent_id,- files={"SKILL.md": skill_md},- source="lobehub",- identifier=f"lobehub/{agent_id}",- trust_level="community",- )-- def inspect(self, identifier: str) -> Optional[SkillMeta]:- agent_id = identifier.split("/", 1)[-1] if identifier.startswith("lobehub/") else identifier- index = self._fetch_index()- if not index:- return None-- agents = index.get("agents", index) if isinstance(index, dict) else index- if not isinstance(agents, list):- return None-- for agent in agents:- if agent.get("identifier") == agent_id:- meta = agent.get("meta", agent)- return SkillMeta(- name=agent_id,- description=meta.get("description", ""),- source="lobehub",- identifier=f"lobehub/{agent_id}",- trust_level="community",- tags=meta.get("tags", []) if isinstance(meta.get("tags"), list) else [],- )- return None-- def _fetch_index(self) -> Optional[Any]:- """Fetch the LobeHub agent index (cached for 1 hour)."""- cache_key = "lobehub_index"- cached = _read_index_cache(cache_key)- if cached is not None:- return cached-- try:- resp = httpx.get(self.INDEX_URL, timeout=30)- if resp.status_code != 200:- return None- data = resp.json()- except (httpx.HTTPError, json.JSONDecodeError):- return None-- _write_index_cache(cache_key, data)- return data-- def _fetch_agent(self, agent_id: str) -> Optional[dict]:- """Fetch a single agent's JSON file."""- url = f"https://chat-agents.lobehub.com/{agent_id}.json"- try:- resp = httpx.get(url, timeout=15)- if resp.status_code == 200:- return resp.json()- except (httpx.HTTPError, json.JSONDecodeError) as e:- logger.debug("LobeHub agent fetch failed: %s", e)- return None-- @staticmethod- def _convert_to_skill_md(agent_data: dict) -> str:- """Convert a LobeHub agent JSON into SKILL.md format."""- meta = agent_data.get("meta", agent_data)- identifier = agent_data.get("identifier", "lobehub-agent")- title = meta.get("title", identifier)- description = meta.get("description", "")- tags = meta.get("tags", [])- system_role = agent_data.get("config", {}).get("systemRole", "")-- tag_list = tags if isinstance(tags, list) else []- fm_lines = [- "---",- f"name: {identifier}",- f"description: {description[:500]}",- "metadata:",- " hermes:",- f" tags: [{', '.join(str(t) for t in tag_list)}]",- " lobehub:",- " source: lobehub",- "---",- ]-- body_lines = [- f"# {title}",- "",- description,- "",- "## Instructions",- "",- system_role if system_role else "(No system role defined)",- ]-- return "\n".join(fm_lines) + "\n\n" + "\n".join(body_lines) + "\n"---# ----------------------------------------------------------------------------# browse.sh source adapter-# ------------------------------------------------------------------------------class BrowseShSource(SkillSource):- """Discover and install site-specific browser automation skills from browse.sh.-- browse.sh (https://browse.sh) is Browserbase's catalog of 200+ SKILL.md files- that describe how to automate specific websites (Airbnb, Amazon, arXiv, etc.).- The catalog lives at ``/api/skills`` and each skill's actual SKILL.md content- is fetched via ``/api/skills/{slug}`` which returns a ``skillMdUrl`` field- pointing at a CDN-hosted blob — the catalog's ``sourceUrl`` field is a GitHub- HTML URL whose underlying repository is not always public, so it cannot be- relied on for content fetch.- """-- CATALOG_URL = "https://browse.sh/api/skills"- SKILL_DETAIL_URL = "https://browse.sh/api/skills/{slug}"- _CACHE_KEY = "browse_sh_catalog"-- def source_id(self) -> str:- return "browse-sh"-- def trust_level_for(self, identifier: str) -> str:- return "community"-- def _fetch_catalog(self) -> List[Dict]:- cached = _read_index_cache(self._CACHE_KEY)- if cached is not None:- return cached- try:- resp = httpx.get(self.CATALOG_URL, timeout=20)- if resp.status_code != 200:- return []- data = resp.json()- except (httpx.HTTPError, json.JSONDecodeError):- return []- skills = data.get("skills", []) if isinstance(data, dict) else []- if isinstance(skills, list):- _write_index_cache(self._CACHE_KEY, skills)- return skills if isinstance(skills, list) else []-- def _item_to_meta(self, item: Dict) -> Optional[SkillMeta]:- slug = item.get("slug", "")- name = item.get("name", "")- title = item.get("title", name)- description = item.get("description", title)- if not slug or not name:- return None- if len(description) > 1024:- description = description[:1021] + "..."- return SkillMeta(- name=name,- description=description,- source="browse-sh",- identifier=f"browse-sh/{slug}",- trust_level="community",- tags=item.get("tags", []),- extra={- "slug": slug,- "hostname": item.get("hostname", ""),- "category": item.get("category", ""),- "source_url": item.get("sourceUrl", ""),- "recommended_method": item.get("recommendedMethod", ""),- "proxies": item.get("proxies", False),- "install_count": item.get("installCount", 0),- },- )-- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- catalog = self._fetch_catalog()- query_lower = query.lower()- results = []- for item in catalog:- text = " ".join([- item.get("name", ""),- item.get("title", ""),- item.get("description", ""),- item.get("hostname", ""),- item.get("category", ""),- " ".join(item.get("tags", [])),- ]).lower()- if not query_lower or query_lower in text:- meta = self._item_to_meta(item)- if meta:- results.append(meta)- if len(results) >= limit:- break- return results-- def inspect(self, identifier: str) -> Optional[SkillMeta]:- slug = self._slug_from_identifier(identifier)- if not slug:- return None- catalog = self._fetch_catalog()- for item in catalog:- if item.get("slug") == slug:- return self._item_to_meta(item)- return None-- def fetch(self, identifier: str) -> Optional[SkillBundle]:- slug = self._slug_from_identifier(identifier)- if not slug:- return None- catalog = self._fetch_catalog()- item = next((i for i in catalog if i.get("slug") == slug), None)- if not item:- return None-- # Resolve the actual SKILL.md content URL via the per-skill detail- # endpoint, which returns a ``skillMdUrl`` (CDN blob). The catalog's- # ``sourceUrl`` is a GitHub HTML link whose underlying repo is not- # reliably public, so we don't use it for content.- md_url = self._resolve_skill_md_url(slug, item)- if not md_url:- return None- try:- resp = httpx.get(md_url, timeout=20, follow_redirects=True)- if resp.status_code != 200:- return None- content = resp.text- except httpx.HTTPError:- return None-- meta = self._item_to_meta(item)- name = meta.name if meta else slug.split("/")[-1]- return SkillBundle(- name=name,- files={"SKILL.md": content},- source="browse-sh",- identifier=identifier,- trust_level="community",- metadata={- "slug": slug,- "hostname": item.get("hostname", ""),- "source_url": item.get("sourceUrl", ""),- "skill_md_url": md_url,- },- )-- def _resolve_skill_md_url(self, slug: str, item: Dict) -> Optional[str]:- """Resolve the SKILL.md content URL for a slug.-- Primary path: hit ``/api/skills/{slug}`` and read ``skillMdUrl``.- Fallback: if the catalog item already has a ``raw.githubusercontent.com``- ``sourceUrl`` (some entries may), use it directly.- """- try:- detail = httpx.get(- self.SKILL_DETAIL_URL.format(slug=slug),- timeout=20,- follow_redirects=True,- )- if detail.status_code == 200:- data = detail.json()- if isinstance(data, dict):- md_url = data.get("skillMdUrl")- if isinstance(md_url, str) and md_url.startswith("http"):- return md_url- except (httpx.HTTPError, json.JSONDecodeError):- pass-- source_url = item.get("sourceUrl", "") if isinstance(item, dict) else ""- from utils import base_url_host_matches- if source_url and base_url_host_matches(source_url, "raw.githubusercontent.com"):- return source_url- return None-- def _slug_from_identifier(self, identifier: str) -> str:- """Extract slug from identifier like 'browse-sh/airbnb.com/search-listings-abc'."""- if identifier.startswith("browse-sh/"):- return identifier[len("browse-sh/"):]- return identifier---# ----------------------------------------------------------------------------# Official optional skills source adapter-# ---------------------------------------------------------------------------+def _taps_file() -> Path:+ return _path("TAPS_FILE", lambda: _hub_dir() / "taps.json")-class OptionalSkillSource(SkillSource):- """- Fetch skills from the optional-skills/ directory shipped with the repo.- These skills are official (maintained by Nous Research) but not activated- by default — they don't appear in the system prompt and aren't copied to- ~/.hermes/skills/ during setup. They are discoverable via the Skills Hub- (search / install / inspect) and labelled "official" with "builtin" trust.- """+def _index_cache_dir() -> Path:+ return _path("INDEX_CACHE_DIR", lambda: _hub_dir() / "index-cache")- OFFICIAL_REPO = "NousResearch/hermes-agent"- OPTIONAL_SKILLS_PREFIX = "optional-skills"- def __init__(self, auth: Optional[GitHubAuth] = None):- from hermes_constants import get_optional_skills_dir+_DYNAMIC_PATH_RESOLVERS = {+ "HERMES_HOME": _hermes_home,+ "SKILLS_DIR": _skills_dir,+ "HUB_DIR": _hub_dir,+ "LOCK_FILE": _lock_file,+ "QUARANTINE_DIR": _quarantine_dir,+ "AUDIT_LOG": _audit_log,+ "TAPS_FILE": _taps_file,+ "INDEX_CACHE_DIR": _index_cache_dir,+}- self._optional_dir = get_optional_skills_dir(- Path(__file__).parent.parent / "optional-skills"- )- self._auth = auth- # Lazily created GitHubSource for the live-repo fallback — only- # instantiated when a skill is missing from the local checkout.- self._github: Optional[GitHubSource] = None- # rel_path ("category/skill") -> True, from the live repo tree.- # None = not fetched yet this process.- self._remote_dirs: Optional[Dict[str, bool]] = None-- def source_id(self) -> str:- return "official"-- def trust_level_for(self, identifier: str) -> str:- return "builtin"-- # -- search ------------------------------------------------------------- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- results: List[SkillMeta] = []- query_lower = query.lower()-- local_rels: set = set()- for meta in self._scan_all():- rel = meta.identifier.split("/", 1)[-1] if meta.identifier else ""- local_rels.add(rel)- searchable = f"{meta.name} {meta.description} {' '.join(meta.tags)}".lower()- if query_lower in searchable:- results.append(meta)- if len(results) >= limit:- break- # Also surface skills that landed on live main after this install was- # cut (missing from the local optional-skills/ checkout).- if len(results) < limit:- for rel_dir in sorted(self._list_remote_skill_dirs()):- if rel_dir in local_rels:- continue- name = rel_dir.rsplit("/", 1)[-1]- if query_lower and query_lower not in rel_dir.lower():- continue- results.append(SkillMeta(- name=name,- description="Official optional skill (from live repo; run install to fetch)",- source="official",- identifier=f"official/{rel_dir}",- trust_level="builtin",- repo=self.OFFICIAL_REPO,- path=f"{self.OPTIONAL_SKILLS_PREFIX}/{rel_dir}",- tags=[],- ))- if len(results) >= limit:- break-- return results-- # -- fetch -------------------------------------------------------------- def fetch(self, identifier: str) -> Optional[SkillBundle]:- # identifier format: "official/category/skill" or "official/skill"- rel = identifier.split("/", 1)[-1] if identifier.startswith("official/") else identifier- skill_dir = self._optional_dir / rel-- # Guard against path traversal (e.g. "official/../../etc")- try:- resolved = skill_dir.resolve()- optional_root = self._optional_dir.resolve()- if not resolved.is_relative_to(optional_root):- return None- except (OSError, ValueError):- return None+def __getattr__(name: str):+ """Resolve legacy path constants dynamically (PEP 562) so they reflect the+ active profile override; a test's patch.object-set real attribute shadows it."""+ resolver = _DYNAMIC_PATH_RESOLVERS.get(name)+ if resolver is not None:+ return resolver()+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")- if not resolved.is_dir():- # Try searching by skill name only (last segment)- skill_name = rel.rsplit("/", 1)[-1]- skill_dir = self._find_skill_dir(skill_name)- if not skill_dir:- # Not in the local checkout — the skill may have landed on- # main after this install was cut. Fall back to the live repo.- return self._fetch_from_live_repo(rel)- else:- skill_dir = resolved-- # Upstream-maintained entries: the local dir is a catalog stub whose- # frontmatter points at the real skill in an external repo the- # upstream project maintains (e.g. impeccable's Hermes-native bundle- # under pbakaus/impeccable:.hermes/skills/impeccable). Install pulls- # the live content from there instead of vendoring a fork here.- upstream = self._upstream_pointer(skill_dir)- if upstream is not None:- rel_id = skill_dir.resolve().relative_to(self._optional_dir.resolve()).as_posix()- return self._fetch_from_upstream(upstream, rel_id)-- files: Dict[str, Union[str, bytes]] = {}- for f in skill_dir.rglob("*"):- if (- f.is_file()- and not f.name.startswith(".")- and "__pycache__" not in f.parts- and f.suffix != ".pyc"- ):- rel_path = str(f.relative_to(skill_dir))- try:- files[rel_path] = f.read_bytes()- except OSError:- continue- if not files:- return None+# ---------------------------------------------------------------------------+# Install-path safety + guarded HTTP+# ---------------------------------------------------------------------------- # Determine category from directory structure- name = skill_dir.name+_REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308}+_MAX_SKILL_FETCH_REDIRECTS = 5- return SkillBundle(- name=name,- files=files,- source="official",- identifier=f"official/{skill_dir.resolve().relative_to(self._optional_dir.resolve()).as_posix()}",- trust_level="builtin",- )- # -- inspect ------------------------------------------------------------ def inspect(self, identifier: str) -> Optional[SkillMeta]:- rel = identifier.split("/", 1)[-1] if identifier.startswith("official/") else identifier- skill_name = rel.rsplit("/", 1)[-1]-- for meta in self._scan_all():- if meta.name == skill_name:- return meta-- # Not in the local checkout — check live main.- remote_dirs = self._list_remote_skill_dirs()- matches = [d for d in remote_dirs if d.rsplit("/", 1)[-1] == skill_name]- if len(matches) == 1:- rel_dir = matches[0]- return SkillMeta(- name=skill_name,- description="Official optional skill (from live repo; run install to fetch)",- source="official",- identifier=f"official/{rel_dir}",- trust_level="builtin",- repo=self.OFFICIAL_REPO,- path=f"{self.OPTIONAL_SKILLS_PREFIX}/{rel_dir}",- tags=[],- )- return None+def _is_path_redirect(path: Path) -> bool:+ """True when ``path`` is a symlink or (on Windows) a directory junction —+ either lets a writer in ``skills/`` redirect a later ``rmtree`` outside it.+ ``is_junction`` only exists on Python 3.12+ Windows; gate with ``hasattr``."""+ return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction())- # -- catalog ----------------------------------------------------------- def list_local(self) -> List[SkillMeta]:- """Public catalog enumeration: every optional skill in the local- checkout, with frontmatter metadata. Backs the dashboard/desktop- "built-in optional skills" catalog surface."""- return self._scan_all()+def _resolve_lock_install_path(install_path: str, skill_name: str) -> Path:+ """Resolve a lock-file install path without allowing escapes from ``SKILLS_DIR``.- # -- internal helpers -------------------------------------------------+ Walks component-by-component refusing symlink/junction redirects (which+ ``Path.resolve`` would silently follow), then rejects both escape-out and+ ``resolved == SKILLS_DIR`` — an empty/``"."`` install_path resolves to the+ skills root and ``rmtree`` there would wipe every installed skill.+ """+ normalized = _normalize_lock_install_path(install_path, skill_name)+ skills_dir = _skills_dir()+ skills_root = skills_dir.resolve()- def _get_github(self) -> "GitHubSource":- if self._github is None:- self._github = GitHubSource(auth=self._auth or GitHubAuth())- return self._github+ target = skills_dir+ for part in normalized.split("/"):+ target = target / part+ if _is_path_redirect(target):+ raise ValueError(f"Unsafe install path: {install_path}")- def _fetch_from_live_repo(self, rel: str) -> Optional[SkillBundle]:- """Fetch an optional skill straight from the live repo on GitHub.+ target = target.resolve()+ if target == skills_root or not target.is_relative_to(skills_root):+ raise ValueError(f"Unsafe install path: {install_path}")+ return target- Local installs lag `main` — a freshly merged optional skill isn't in- the user's `optional-skills/` checkout until they run- ``hermes update``. Rather than telling them to update first, resolve- the skill against the live default branch.- ``rel`` is the identifier without the ``official/`` prefix — either- ``category/skill`` (used verbatim) or a bare skill name (located via- the repo tree).- """- rel = rel.strip("/")- if not rel:- return None- # Reject traversal before it ever becomes a GitHub path.- parts = [p for p in rel.split("/") if p not in ("", ".")]- if not parts or any(p == ".." for p in parts):- return None- rel = "/".join(parts)+def _ssrf_safe_http_get(url: str, *, timeout: int = 20) -> httpx.Response:+ """Fetch one URL with connect-time SSRF validation and no automatic redirects."""+ from tools.url_safety import create_ssrf_safe_client- github = self._get_github()- remote_dirs = self._list_remote_skill_dirs()+ with create_ssrf_safe_client(timeout=timeout, follow_redirects=False) as client:+ return client.get(url)- if rel in remote_dirs:- repo_path = f"{self.OPTIONAL_SKILLS_PREFIX}/{rel}"- else:- # Bare name (or stale category) — locate by final path segment.- name = parts[-1]- matches = [d for d in remote_dirs if d.rsplit("/", 1)[-1] == name]- if len(matches) != 1:- return None- repo_path = f"{self.OPTIONAL_SKILLS_PREFIX}/{matches[0]}"- rel = matches[0]-- # Download the FULL skill directory (byte-exact, including root-level- # install scripts, LICENSE, tests/). GitHubSource.fetch() would only- # pull SKILL.md + referenced support dirs, silently dropping files the- # local-checkout path preserves.- tree = github._get_repo_tree(self.OFFICIAL_REPO)- if tree is None:- return None- _branch, entries = tree- prefix = f"{repo_path}/"- files: Dict[str, Union[str, bytes]] = {}- for item in entries:- if item.get("type") != "blob" or item.get("mode") == "120000":- continue- item_path = item.get("path", "")- if not item_path.startswith(prefix):- continue- rel_file = item_path[len(prefix):]- base = rel_file.rsplit("/", 1)[-1]- if base.startswith(".") or base.endswith(".pyc") or "__pycache__" in rel_file.split("/"):- continue- content = github._fetch_file_bytes(self.OFFICIAL_REPO, item_path)- if content is None:- logger.warning("Live-repo optional skill fetch failed for %s", item_path)- return None- files[rel_file] = content- if "SKILL.md" not in files:- return None+def _guarded_http_get(url: str, *, timeout: int = 20) -> Optional[httpx.Response]:+ """Fetch a URL with SSRF and redirect-target validation (each hop re-checked)."""+ from tools.url_safety import SSRFConnectionBlocked- # Live-fetched catalog stubs redirect the same way local ones do.- upstream = self._upstream_pointer_from_content(files["SKILL.md"])- if upstream is not None:- return self._fetch_from_upstream(upstream, rel)-- logger.info("Optional skill '%s' fetched from live repo (not in local checkout)", rel)- return SkillBundle(- name=rel.rsplit("/", 1)[-1],- files=files,- source="official",- identifier=f"official/{rel}",- trust_level="builtin",- )+ current_url = url- def _list_remote_skill_dirs(self) -> Dict[str, bool]:- """Map of ``category/skill`` dirs under optional-skills/ on live main.-- Derived from the repo tree (single API call, cached per-process by- GitHubSource, plus the shared on-disk index cache). Returns {} when- the network/API is unavailable — callers degrade to local-only.- """- if self._remote_dirs is not None:- return self._remote_dirs-- cache_key = "official_optional_dirs"- cached = _read_index_cache(cache_key)- if isinstance(cached, dict) and cached:- self._remote_dirs = cached- return cached-- dirs: Dict[str, bool] = {}- tree = self._get_github()._get_repo_tree(self.OFFICIAL_REPO)- if tree is not None:- _branch, entries = tree- prefix = f"{self.OPTIONAL_SKILLS_PREFIX}/"- suffix = "/SKILL.md"- for item in entries:- path = item.get("path", "")- if (- item.get("type") == "blob"- and path.startswith(prefix)- and path.endswith(suffix)- ):- rel_dir = path[len(prefix):-len(suffix)]- if rel_dir and not is_excluded_skill_path(- PurePosixPath(rel_dir + suffix)- ):- dirs[rel_dir] = True- if dirs:- _write_index_cache(cache_key, dirs)-- self._remote_dirs = dirs- return dirs-- def _upstream_pointer(self, skill_dir: Path) -> Optional[Dict[str, str]]:- """Return the upstream pointer for a catalog-stub skill dir, if any.-- A stub declares ``metadata.hermes.upstream`` in its SKILL.md- frontmatter:-- metadata:- hermes:- upstream:- repo: pbakaus/impeccable- path: .hermes/skills/impeccable-- Returns ``{"repo": ..., "path": ...}`` or None for normal- (fully-vendored) optional skills.- """- skill_md = skill_dir / "SKILL.md"- try:- content = skill_md.read_text(encoding="utf-8")- except (OSError, UnicodeDecodeError):+ for _ in range(_MAX_SKILL_FETCH_REDIRECTS + 1):+ if not is_safe_url(current_url):+ logger.warning("Blocked unsafe Skills Hub URL: %s", current_url)return None- return self._upstream_pointer_from_content(content)- def _upstream_pointer_from_content(self, content: Union[str, bytes]) -> Optional[Dict[str, str]]:- """Parse ``metadata.hermes.upstream`` out of SKILL.md content."""- if isinstance(content, bytes):- try:- content = content.decode("utf-8")- except UnicodeDecodeError:- return None- fm = self._parse_frontmatter(content)- meta_block = fm.get("metadata")- if not isinstance(meta_block, dict):- return None- hermes_meta = meta_block.get("hermes")- if not isinstance(hermes_meta, dict):- return None- upstream = hermes_meta.get("upstream")- if not isinstance(upstream, dict):- return None- repo = str(upstream.get("repo", "")).strip().strip("/")- path = str(upstream.get("path", "")).strip().strip("/")- # repo must be exactly owner/name; path must be a clean relative path.- if not repo or repo.count("/") != 1 or not path:- return None- parts = [p for p in path.split("/") if p not in ("", ".")]- if not parts or any(p == ".." for p in parts):- return None- return {"repo": repo, "path": "/".join(parts)}-- def _fetch_from_upstream(self, upstream: Dict[str, str], rel_id: str) -> Optional[SkillBundle]:- """Fetch an upstream-maintained optional skill from its external repo.-- Delegates to GitHubSource.fetch() (full-directory download through the- git tree, symlink/unsafe-path rejection, quarantine + scan downstream)- but re-labels the bundle as an official catalog entry so trust,- identifier, and update tracking stay in the optional-skills namespace.- """- github = self._get_github()- bundle = github.fetch(f"{upstream['repo']}/{upstream['path']}")- if bundle is None:- logger.warning(- "Upstream fetch failed for optional skill %s (%s:%s)",- rel_id, upstream["repo"], upstream["path"],+ blocked = check_website_access(current_url)+ if blocked:+ logger.info(+ "Blocked Skills Hub fetch for %s by rule %s",+ blocked["host"],+ blocked["rule"],)return None- return SkillBundle(- name=bundle.name,- files=bundle.files,- source="official",- identifier=f"official/{rel_id}",- # Curated-catalog endorsement, but the content comes live from a- # third-party repo — "trusted", not "builtin", so a dangerous- # scan verdict still blocks install (INSTALL_POLICY).- trust_level="trusted",- metadata={- **bundle.metadata,- "upstream_repo": upstream["repo"],- "upstream_path": upstream["path"],- },- )- def _find_skill_dir(self, name: str) -> Optional[Path]:- """Find a skill directory by name anywhere in optional-skills/."""- if not self._optional_dir.is_dir():+ try:+ resp = _ssrf_safe_http_get(current_url, timeout=timeout)+ except (SSRFConnectionBlocked, httpx.HTTPError) as exc:+ logger.debug("Skills Hub fetch failed for %s: %s", current_url, exc)return None- for skill_md in self._optional_dir.rglob("SKILL.md"):- if is_excluded_skill_path(- skill_md.relative_to(self._optional_dir), root=self._optional_dir- ):- continue- if skill_md.parent.name == name:- return skill_md.parent- return None- def _scan_all(self) -> List[SkillMeta]:- """Enumerate all optional skills with metadata."""- if not self._optional_dir.is_dir():- return []-- results: List[SkillMeta] = []- for skill_md in sorted(self._optional_dir.rglob("SKILL.md")):- if is_excluded_skill_path(- skill_md.relative_to(self._optional_dir), root=self._optional_dir- ):- continue- parent = skill_md.parent+ if resp.status_code in _REDIRECT_STATUS_CODES:+ location = getattr(resp, "headers", {}).get("location")+ if not location:+ return None+ current_url = urljoin(current_url, location)+ continue- try:- content = skill_md.read_text(encoding="utf-8")- except (OSError, UnicodeDecodeError):- continue+ return resp- fm = self._parse_frontmatter(content)- name = fm.get("name", parent.name)- desc = fm.get("description", "")- tags = []- meta_block = fm.get("metadata", {})- if isinstance(meta_block, dict):- hermes_meta = meta_block.get("hermes", {})- if isinstance(hermes_meta, dict):- tags = hermes_meta.get("tags", [])-- rel_path = parent.relative_to(self._optional_dir).as_posix()-- results.append(SkillMeta(- name=name,- description=desc[:200],- source="official",- identifier=f"official/{rel_path}",- trust_level="builtin",- repo=self.OFFICIAL_REPO,- # The centralized skills index consumes repo-root-relative paths.- path=f"optional-skills/{rel_path}",- tags=tags if isinstance(tags, list) else [],- ))-- return results-- @staticmethod- def _parse_frontmatter(content: str) -> dict:- """Parse YAML frontmatter from SKILL.md content."""- content = content.lstrip("\ufeff") # tolerate UTF-8 BOM (Windows editors)- if not content.startswith("---"):- return {}- match = re.search(r'\n---\s*\n', content[3:])- if not match:- return {}- yaml_text = content[3:match.start() + 3]- try:- parsed = yaml.safe_load(yaml_text)- return parsed if isinstance(parsed, dict) else {}- except yaml.YAMLError:- return {}+ logger.warning("Skills Hub fetch exceeded redirect limit for %s", url)+ return None# ----------------------------------------------------------------------------# Shared cache helpers (used by multiple adapters)+# Shared index cache (used by every adapter)# ----------------------------------------------------------------------------def _read_index_cache(key: str) -> Optional[Any]:- """Read cached data if not expired."""- cache_file = _index_cache_dir() / f"{key}.json"- if not cache_file.exists():+def _read_json_if_fresh(path: Path, ttl: float) -> Optional[Any]:+ """Parsed JSON from ``path`` when it exists and is younger than ``ttl`` seconds."""+ if not path.exists():return Nonetry:- stat = cache_file.stat()- if time.time() - stat.st_mtime > INDEX_CACHE_TTL:+ if time.time() - path.stat().st_mtime > ttl:return None- return json.loads(cache_file.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):return None+def _read_index_cache(key: str) -> Optional[Any]:+ return _read_json_if_fresh(_index_cache_dir() / f"{key}.json", INDEX_CACHE_TTL)++def _write_index_cache(key: str, data: Any) -> None:- """Write data to cache."""index_cache_dir = _index_cache_dir()index_cache_dir.mkdir(parents=True, exist_ok=True)- # Ensure .ignore exists so ripgrep (and tools respecting .ignore) skip- # this directory. Cache files contain unvetted community content that- # could include adversarial text (prompt injection via catalog entries).+ # Cache files hold unvetted community text (possible prompt injection);+ # a .ignore keeps ripgrep and .ignore-aware tools out of the hub dir.ignore_file = _hub_dir() / ".ignore"if not ignore_file.exists():try:ignore_file.write_text("# Exclude hub internals from search tools\n*\n", encoding="utf-8")except OSError:pass- cache_file = index_cache_dir / f"{key}.json"try:- cache_file.write_text(json.dumps(data, ensure_ascii=False, default=str), encoding="utf-8")+ (index_cache_dir / f"{key}.json").write_text(+ json.dumps(data, ensure_ascii=False, default=str), encoding="utf-8"+ )except OSError as e:logger.debug("Could not write cache: %s", e)-def _skill_meta_to_dict(meta: SkillMeta) -> dict:- """Convert a SkillMeta to a dict for caching."""- return {- "name": meta.name,- "description": meta.description,- "source": meta.source,- "identifier": meta.identifier,- "trust_level": meta.trust_level,- "repo": meta.repo,- "path": meta.path,- "tags": meta.tags,- "extra": meta.extra,- }--# ----------------------------------------------------------------------------# Lock file management+# Hub state files: lock.json, taps.json, audit.log# ----------------------------------------------------------------------------class HubLockFile:- """Manages skills/.hub/lock.json — tracks provenance of installed hub skills."""+class _JsonStateFile:+ """A JSON file under the hub dir with a fixed empty shape."""++ EMPTY: dict = {}def __init__(self, path: Optional[Path] = None):- self.path = path if path is not None else _lock_file()+ self.path = path if path is not None else self._default_path()- def load(self) -> dict:+ def _default_path(self) -> Path:+ raise NotImplementedError++ def _read(self) -> dict:if not self.path.exists():- return {"version": 1, "installed": {}}+ return json.loads(json.dumps(self.EMPTY))try:return json.loads(self.path.read_text(encoding="utf-8"))except (json.JSONDecodeError, OSError):- return {"version": 1, "installed": {}}+ return json.loads(json.dumps(self.EMPTY))- def save(self, data: dict) -> None:+ def _write(self, data: dict, **dumps_kwargs) -> None:self.path.parent.mkdir(parents=True, exist_ok=True)- self.path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ self.path.write_text(json.dumps(data, indent=2, **dumps_kwargs) + "\n", encoding="utf-8")+++class HubLockFile(_JsonStateFile):+ """skills/.hub/lock.json — provenance of installed hub skills."""++ EMPTY = {"version": 1, "installed": {}}++ def _default_path(self) -> Path:+ return _lock_file()++ def load(self) -> dict:+ return self._read()++ def save(self, data: dict) -> None:+ self._write(data, ensure_ascii=False)def record_install(self,@@ -4044,13 +299,12 @@ class HubLockFile:metadata: Optional[Dict[str, Any]] = None,scan_provenance: Optional[Dict[str, Any]] = None,) -> None:- # Validate both the skill name and the install path SHAPE before- # writing into lock.json. A poisoned lock entry is the precondition- # for the uninstall_skill rmtree-escape; reject malformed input at- # write time so the file never carries the bad state.+ # Validate name and install-path SHAPE at write time: a poisoned lock+ # entry is the precondition for the uninstall_skill rmtree-escape.safe_name = _validate_skill_name(name)safe_install_path = _normalize_lock_install_path(install_path, safe_name)data = self.load()+ now = datetime.now(timezone.utc).isoformat()data["installed"][safe_name] = {"source": source,"identifier": identifier,@@ -4061,8 +315,8 @@ class HubLockFile:"files": files,"metadata": metadata or {},"scan_provenance": scan_provenance or {},- "installed_at": datetime.now(timezone.utc).isoformat(),- "updated_at": datetime.now(timezone.utc).isoformat(),+ "installed_at": now,+ "updated_at": now,}self.save(data)@@ -4072,39 +326,25 @@ class HubLockFile:self.save(data)def get_installed(self, name: str) -> Optional[dict]:- data = self.load()- return data["installed"].get(name)+ return self.load()["installed"].get(name)def list_installed(self) -> List[dict]:- data = self.load()- result = []- for name, entry in data["installed"].items():- result.append({"name": name, **entry})- return result+ return [{"name": name, **entry} for name, entry in self.load()["installed"].items()]-# ----------------------------------------------------------------------------# Taps management-# ---------------------------------------------------------------------------+class TapsManager(_JsonStateFile):+ """skills/.hub/taps.json — custom GitHub repo sources."""-class TapsManager:- """Manages the taps.json file — custom GitHub repo sources."""+ EMPTY = {"taps": []}- def __init__(self, path: Optional[Path] = None):- self.path = path if path is not None else _taps_file()+ def _default_path(self) -> Path:+ return _taps_file()def load(self) -> List[dict]:- if not self.path.exists():- return []- try:- data = json.loads(self.path.read_text(encoding="utf-8"))- return data.get("taps", [])- except (json.JSONDecodeError, OSError):- return []+ return self._read().get("taps", [])def save(self, taps: List[dict]) -> None:- self.path.parent.mkdir(parents=True, exist_ok=True)- self.path.write_text(json.dumps({"taps": taps}, indent=2) + "\n", encoding="utf-8")+ self._write({"taps": taps})def add(self, repo: str, path: str = "skills/") -> bool:"""Add a tap. Returns False if already exists."""@@ -4128,23 +368,18 @@ class TapsManager:return self.load()-# ----------------------------------------------------------------------------# Audit log-# ----------------------------------------------------------------------------def append_audit_log(action: str, skill_name: str, source: str,trust_level: str, verdict: str, extra: str = "") -> None:- """Append a line to the audit log."""+ """Append one space-separated line to the audit log (best-effort)."""audit_log = _audit_log()audit_log.parent.mkdir(parents=True, exist_ok=True)timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")parts = [timestamp, action, skill_name, f"{source}:{trust_level}", verdict]if extra:parts.append(extra)- line = " ".join(parts) + "\n"try:with open(audit_log, "a", encoding="utf-8") as f:- f.write(line)+ f.write(" ".join(parts) + "\n")except OSError as e:logger.debug("Could not write audit log: %s", e)@@ -4155,29 +390,27 @@ def append_audit_log(action: str, skill_name: str, source: str,def ensure_hub_dirs() -> None:"""Create the .hub directory structure if it doesn't exist."""- hub_dir = _hub_dir()- lock_file = _lock_file()- audit_log = _audit_log()- taps_file = _taps_file()- hub_dir.mkdir(parents=True, exist_ok=True)+ _hub_dir().mkdir(parents=True, exist_ok=True)_quarantine_dir().mkdir(exist_ok=True)_index_cache_dir().mkdir(exist_ok=True)- if not lock_file.exists():- lock_file.write_text('{"version": 1, "installed": {}}\n', encoding="utf-8")- if not audit_log.exists():- audit_log.touch()- if not taps_file.exists():- taps_file.write_text('{"taps": []}\n', encoding="utf-8")+ for path, initial in (+ (_lock_file(), '{"version": 1, "installed": {}}\n'),+ (_audit_log(), ""),+ (_taps_file(), '{"taps": []}\n'),+ ):+ if not path.exists():+ path.write_text(initial, encoding="utf-8")def quarantine_bundle(bundle: SkillBundle) -> Path:"""Write a skill bundle to the quarantine directory for scanning."""ensure_hub_dirs()skill_name = _validate_skill_name(bundle.name)- validated_files: List[Tuple[str, Union[str, bytes]]] = []- for rel_path, file_content in bundle.files.items():- safe_rel_path = _validate_bundle_rel_path(rel_path)- validated_files.append((safe_rel_path, file_content))+ # Validate every path before touching disk so a bad member aborts cleanly.+ validated_files = [+ (_validate_bundle_rel_path(rel_path), file_content)+ for rel_path, file_content in bundle.files.items()+ ]dest = _quarantine_dir() / skill_nameif dest.exists():@@ -4196,31 +429,66 @@ def quarantine_bundle(bundle: SkillBundle) -> Path:def _category_skill_dirs(directory: Path) -> List[str]:- """Names of direct children of *directory* that contain skills.+ """Names of non-hidden child dirs holding at least one active SKILL.md+ anywhere below (nested layouts like ``mlops/training/<skill>`` count).- A child counts when it is a non-hidden directory holding at least one- active ``SKILL.md`` anywhere below it (recursive, so nested category- layouts like ``mlops/training/<skill>`` are detected). Vendored,- cache, and progressive-disclosure support paths are pruned via+ Vendored/cache/progressive-disclosure paths are pruned via:func:`is_excluded_skill_path` so a lone ``node_modules`` or- ``references/pkg/SKILL.md`` hit does not misclassify the directory as- a category. Shared by the install-time category guard here and- ``hermes_cli.skills_hub._existing_categories``.+ ``references/pkg/SKILL.md`` does not make the directory a category.+ Shared with ``hermes_cli.skills_hub._existing_categories``."""skill_dirs: List[str] = []for entry in directory.iterdir():if not entry.is_dir() or entry.name.startswith("."):continue- for skill_md in entry.rglob("SKILL.md"):- if is_excluded_skill_path(- skill_md.relative_to(directory), root=directory- ):- continue+ if any(+ not is_excluded_skill_path(skill_md.relative_to(directory), root=directory)+ for skill_md in entry.rglob("SKILL.md")+ ):skill_dirs.append(entry.name)- breakreturn skill_dirs+def _check_install_target(install_dir: Path) -> None:+ """Raise ValueError when installing at ``install_dir`` would destroy other skills.++ - Nesting inside an existing skill dir (``--category <existing-skill>``)+ would make a later update/uninstall of the outer skill rmtree the inner one.+ - A stray regular file at the target: rmtree would raise NotADirectoryError.+ - A category bucket (dir without SKILL.md that holds other skills) must never+ be silently wiped; a dir that directly contains SKILL.md is an existing+ install and stays overwritable (hub installs are lock-guarded in do_install).+ """+ skills_root = _skills_dir().resolve()+ ancestor = install_dir.parent+ while ancestor != skills_root and ancestor.is_relative_to(skills_root):+ if (ancestor / "SKILL.md").is_file():+ raise ValueError(+ f"Refusing to install into '{ancestor.name}': it is an "+ f"existing skill directory, not a category. Choose a "+ f"different category."+ )+ ancestor = ancestor.parent++ if not install_dir.exists():+ return+ if not install_dir.is_dir():+ raise ValueError(+ f"Refusing to install: '{install_dir.name}' already exists "+ f"and is not a directory. Remove it or choose a different "+ f"skill name."+ )+ if not (install_dir / "SKILL.md").exists():+ skill_dirs_in = _category_skill_dirs(install_dir)+ if skill_dirs_in:+ raise ValueError(+ f"Refusing to overwrite category directory '{install_dir}' "+ f"which contains {len(skill_dirs_in)} skill(s): "+ f"{', '.join(sorted(skill_dirs_in))}. "+ f"Use a different --name or install into a subcategory."+ )++def install_from_quarantine(quarantine_path: Path,skill_name: str,@@ -4233,67 +501,17 @@ def install_from_quarantine(safe_skill_name = _validate_skill_name(skill_name)safe_category = _validate_install_parent_path(category) if category else ""quarantine_resolved = quarantine_path.resolve()- quarantine_root = _quarantine_dir().resolve()- if not quarantine_resolved.is_relative_to(quarantine_root):+ if not quarantine_resolved.is_relative_to(_quarantine_dir().resolve()):raise ValueError(f"Unsafe quarantine path: {quarantine_path}")- if safe_category:- install_rel_path = f"{safe_category}/{safe_skill_name}"- else:- install_rel_path = safe_skill_name-- # Resolve via the same lock-path validator the uninstaller uses. Catches- # symlink-in-skills-tree redirects at install time so the lock entry's- # path can never refer to a redirected target.+ install_rel_path = f"{safe_category}/{safe_skill_name}" if safe_category else safe_skill_name+ # Same validator the uninstaller uses, so a lock entry can never point at a+ # symlink-redirected target.install_dir = _resolve_lock_install_path(install_rel_path, safe_skill_name)-- # Refuse to nest a skill inside an existing skill directory. Installing- # with ``--category <name-of-an-existing-skill>`` would create a hybrid- # skill-plus-category directory; a later update or uninstall of the outer- # skill would then rmtree the inner one — the sibling case of the- # category-bucket wipe reported in issue #75983.- skills_root = _skills_dir().resolve()- ancestor = install_dir.parent- while ancestor != skills_root and ancestor.is_relative_to(skills_root):- if (ancestor / "SKILL.md").is_file():- raise ValueError(- f"Refusing to install into '{ancestor.name}': it is an "- f"existing skill directory, not a category. Choose a "- f"different category."- )- ancestor = ancestor.parent-+ _check_install_target(install_dir)if install_dir.exists():- if not install_dir.is_dir():- # A stray regular file at the install path. rmtree() on a file- # raises NotADirectoryError (an uncaught traceback at the CLI);- # refuse with the same actionable ValueError contract instead.- raise ValueError(- f"Refusing to install: '{install_dir.name}' already exists "- f"and is not a directory. Remove it or choose a different "- f"skill name."- )- # Guard against silent data loss when the install target collides with- # an existing category bucket (a directory that holds other skills).- # This was reported as GitHub issue #75983: installing a skill with- # --name matching an existing category directory caused rmtree to wipe- # all sibling skills. A directory that directly contains SKILL.md is- # an existing skill installation and stays overwritable (hub-installed- # skills are additionally guarded by the lock-file check in- # do_install()). But a directory that contains *other* skill- # directories is a category bucket and must NOT be silently deleted.- if not (install_dir / "SKILL.md").exists():- skill_dirs_in = _category_skill_dirs(install_dir)- if skill_dirs_in:- raise ValueError(- f"Refusing to overwrite category directory '{install_dir}' "- f"which contains {len(skill_dirs_in)} skill(s): "- f"{', '.join(sorted(skill_dirs_in))}. "- f"Use a different --name or install into a subcategory."- )shutil.rmtree(install_dir)- # Warn (but don't block) if SKILL.md is very largeskill_md = quarantine_path / "SKILL.md"if skill_md.exists():try:@@ -4309,10 +527,8 @@ def install_from_quarantine(except OSError:pass- # Reject symlinks inside the quarantined skill before moving it.- # A malicious skill bundle could include a symlink pointing outside the- # skills tree; its target contents would then be copied into skills/ and- # leaked to the agent on the next skill_view call.+ # A symlink in the bundle would copy its target into skills/ and leak it+ # to the agent on the next skill_view.for entry in quarantine_path.rglob("*"):if not _is_path_redirect(entry):continue@@ -4327,15 +543,14 @@ def install_from_quarantine(install_dir.parent.mkdir(parents=True, exist_ok=True)shutil.move(str(quarantine_path), str(install_dir))- # Record in lock file- lock = HubLockFile()- lock.record_install(+ installed_hash = content_hash(install_dir)+ HubLockFile().record_install(name=safe_skill_name,source=bundle.source,identifier=bundle.identifier,trust_level=bundle.trust_level,scan_verdict=scan_result.verdict,- skill_hash=content_hash(install_dir),+ skill_hash=installed_hash,install_path=install_dir.resolve().relative_to(_skills_dir().resolve()).as_posix(),files=list(bundle.files.keys()),metadata=bundle.metadata,@@ -4345,7 +560,7 @@ def install_from_quarantine(append_audit_log("INSTALL", safe_skill_name, bundle.source,bundle.trust_level, scan_result.verdict,- content_hash(install_dir),+ installed_hash,)try:@@ -4369,17 +584,10 @@ def uninstall_skill(skill_name: str) -> Tuple[bool, str]:if not entry:return False, f"'{skill_name}' is not a hub-installed skill (may be a builtin)"- # Validate the lock entry's install_path against the skill name. This is- # the destructive boundary — anything that falls through to the rmtree- # below MUST be inside SKILLS_DIR and MUST NOT be SKILLS_DIR itself- # (an empty/"."/"/" install_path would otherwise wipe the entire tree).- # _resolve_lock_install_path enforces a relative path ending in- # <skill_name>, rejects absolute/traversal paths, and walks the path- # component-by-component refusing symlink/junction redirects.+ # The destructive boundary: whatever reaches rmtree MUST be inside+ # SKILLS_DIR and MUST NOT be SKILLS_DIR itself (see _resolve_lock_install_path).try:- install_path = _resolve_lock_install_path(- entry.get("install_path", ""), skill_name- )+ install_path = _resolve_lock_install_path(entry.get("install_path", ""), skill_name)except ValueError as exc:return False, f"Refusing to uninstall '{skill_name}': {exc}"@@ -4393,15 +601,13 @@ def uninstall_skill(skill_name: str) -> Tuple[bool, str]:def bundle_content_hash(bundle: SkillBundle) -> str:- """Compute a deterministic hash for an in-memory skill bundle.-- MUST stay symmetric with ``tools.skills_guard.content_hash`` (which- hashes the same skill from disk). That function keys files by- ``relative_to(...).as_posix()`` — forward slashes on every OS. Bundle- keys built on Windows carry backslashes (``str(f.relative_to(dir))``),- which changed both the hashed bytes AND the sort order, so every- installed skill reported ``update_available`` forever on Windows- (#62310). Normalize to POSIX separators before sorting/hashing.+ """Deterministic hash of an in-memory bundle.++ MUST stay symmetric with ``tools.skills_guard.content_hash`` (same skill+ from disk), which keys files by POSIX relative path. Windows bundle keys+ carry backslashes, which changed both bytes and sort order and made every+ skill report ``update_available`` forever — normalize before hashing. The+ path is hashed too so swapping contents between two files changes the hash."""h = hashlib.sha256()normalized = {@@ -4409,24 +615,18 @@ def bundle_content_hash(bundle: SkillBundle) -> str:for rel_path, content in bundle.files.items()}for rel_path in sorted(normalized):- # Include the path so swapping file contents between two paths- # changes the hash (avoids filename-swap evading update detection).h.update(rel_path.encode("utf-8"))h.update(b"\x00")content = normalized[rel_path]- if isinstance(content, bytes):- h.update(content)- else:- h.update(content.encode("utf-8"))+ h.update(content if isinstance(content, bytes) else content.encode("utf-8"))return f"sha256:{h.hexdigest()[:16]}"+_SOURCE_ID_ALIASES = {"skills.sh": "skills-sh"}++def _source_matches(source: SkillSource, source_name: str) -> bool:- aliases = {- "skills.sh": "skills-sh",- }- normalized = aliases.get(source_name, source_name)- return source.source_id() == normalized+ return source.source_id() == _SOURCE_ID_ALIASES.get(source_name, source_name)def check_for_skill_updates(@@ -4436,7 +636,13 @@ def check_for_skill_updates(sources: Optional[List[SkillSource]] = None,auth: Optional[GitHubAuth] = None,) -> List[dict]:- """Check installed hub skills for upstream changes."""+ """Check installed hub skills for upstream changes.++ Each entry is fetched ONLY from adapters matching its recorded source.+ Falling back to all sources let a same-named skill in a different registry+ satisfy the fetch and silently reassign provenance (names are not+ namespaced across registries), so a missing adapter reports "unavailable".+ """lock = lock or HubLockFile()installed = lock.list_installed()if name:@@ -4449,25 +655,12 @@ def check_for_skill_updates(for entry in installed:identifier = entry.get("identifier", "")source_name = entry.get("source", "")- candidate_sources = [src for src in sources if _source_matches(src, source_name)]- if not candidate_sources:- # No adapter for the recorded source (e.g. a tap was removed, or the- # source was renamed upstream). Previously this fell back to *all*- # sources, which meant a same-named skill in a DIFFERENT registry- # could satisfy the fetch and be reported as an update for this- # entry -- silently reassigning provenance. Skill names are not- # namespaced across registries, so that fallback is unsafe by- # construction. Report unavailable instead and let the user decide.- results.append({- "name": entry.get("name", ""),- "identifier": identifier,- "source": source_name,- "status": "unavailable",- })- continue+ row = {"name": entry.get("name", ""), "identifier": identifier, "source": source_name}bundle = None- for src in candidate_sources:+ for src in sources:+ if not _source_matches(src, source_name):+ continuetry:bundle = src.fetch(identifier)except Exception:@@ -4476,22 +669,14 @@ def check_for_skill_updates(breakif not bundle:- results.append({- "name": entry.get("name", ""),- "identifier": identifier,- "source": source_name,- "status": "unavailable",- })+ results.append({**row, "status": "unavailable"})continuecurrent_hash = entry.get("content_hash", "")latest_hash = bundle_content_hash(bundle)- status = "up_to_date" if current_hash == latest_hash else "update_available"results.append({- "name": entry.get("name", ""),- "identifier": identifier,- "source": source_name,- "status": status,+ **row,+ "status": "up_to_date" if current_hash == latest_hash else "update_available","current_hash": current_hash,"latest_hash": latest_hash,"bundle": bundle,@@ -4501,7 +686,7 @@ def check_for_skill_updates(# ----------------------------------------------------------------------------# Hermes centralized index source+# Hermes centralized index (data source for HermesIndexSource)# ---------------------------------------------------------------------------HERMES_INDEX_URL = "https://hermes-agent.nousresearch.com/docs/api/skills-index.json"@@ -4513,35 +698,20 @@ def _hermes_index_cache_file() -> Path:def _load_hermes_index() -> Optional[dict]:- """Fetch the centralized skills index, with local cache.-- The index is a JSON file hosted on the docs site, rebuilt daily by CI.- We cache it locally for HERMES_INDEX_TTL seconds to avoid repeated- downloads within a session.+ """Fetch the centralized skills index (docs site, rebuilt daily), cached+ locally for HERMES_INDEX_TTL; on any failure serve the stale cache.++ Brotli is deliberately NOT negotiated: the index is tens of MB and httpx's+ streaming Brotli decoder (brotlicffi, pinned for Discord attachments) raises+ DecodingError on payloads this size — which surfaced as a silently empty+ Skills Hub. gzip/deflate first; the identity retry covers proxies that+ ignore the header and return Brotli anyway."""- # Check local cache- hermes_index_cache_file = _hermes_index_cache_file()- if hermes_index_cache_file.exists():- try:- age = time.time() - hermes_index_cache_file.stat().st_mtime- if age < HERMES_INDEX_TTL:- return json.loads(hermes_index_cache_file.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- pass+ cache_file = _hermes_index_cache_file()+ cached = _read_json_if_fresh(cache_file, HERMES_INDEX_TTL)+ if cached is not None:+ return cached- # Fetch from docs site.- #- # We deliberately DON'T let httpx negotiate Brotli here. The index is a- # large body (tens of MB); httpx's streaming Brotli decoder, backed by- # brotlicffi 1.2.0.1 (pinned for Discord attachment decoding), trips over- # its own output_buffer_limit on payloads this size and raises- # DecodingError("brotli: decoder process called with data when- # 'can_accept_more_data()' is False"). That surfaces as an empty Skills- # Hub (blank Browse-hub landing, index contributes 0 search hits) because- # the error is caught below and we silently fall back to a (often absent)- # stale cache. Requesting gzip/deflate sidesteps the broken decoder while- # still compressing the transfer. The identity retry is belt-and-braces- # for any future proxy that ignores the header and returns Brotli anyway.data = Nonefor accept_encoding in ("gzip, deflate", "identity"):try:@@ -4557,8 +727,6 @@ def _load_hermes_index() -> Optional[dict]:data = resp.json()breakexcept httpx.DecodingError as e:- # Content-Encoding decode failed — retry once uncompressed before- # giving up on the network path entirely.logger.debug("Hermes index decode failed (Accept-Encoding=%s): %s",accept_encoding,@@ -4569,17 +737,12 @@ def _load_hermes_index() -> Optional[dict]:logger.debug("Hermes index fetch failed: %s", e)return _load_stale_index_cache()- if data is None:- return _load_stale_index_cache()-- # Validate structureif not isinstance(data, dict) or "skills" not in data:return _load_stale_index_cache()- # Cache locallytry:- hermes_index_cache_file.parent.mkdir(parents=True, exist_ok=True)- hermes_index_cache_file.write_text(json.dumps(data), encoding="utf-8")+ cache_file.parent.mkdir(parents=True, exist_ok=True)+ cache_file.write_text(json.dumps(data), encoding="utf-8")except OSError:pass@@ -4587,230 +750,37 @@ def _load_hermes_index() -> Optional[dict]:def _load_stale_index_cache() -> Optional[dict]:- """Fall back to stale cache when the network fetch fails."""- hermes_index_cache_file = _hermes_index_cache_file()- if hermes_index_cache_file.exists():- try:- return json.loads(hermes_index_cache_file.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- pass- return None---class HermesIndexSource(SkillSource):- """Skill source backed by the centralized Hermes Skills Index.-- The index is a JSON catalog published to the docs site and rebuilt- daily by CI. It contains metadata + resolved GitHub paths for every- skill, eliminating the need for users to hit the GitHub API for- search or path discovery.-- When the index is unavailable, all methods return empty / None so- downstream sources take over transparently.- """+ """Fall back to the cache regardless of age when the network fetch fails."""+ return _read_json_if_fresh(_hermes_index_cache_file(), float("inf"))- def __init__(self, auth: GitHubAuth):- self._index: Optional[dict] = None- self._loaded = False- self.auth = auth- # Lazily create GitHubSource for fetch — only used when actually- # downloading files, which requires real GitHub API calls.- self._github: Optional[GitHubSource] = None-- def _ensure_loaded(self) -> dict:- if not self._loaded:- self._index = _load_hermes_index()- self._loaded = True- return self._index or {}-- def _get_github(self) -> GitHubSource:- if self._github is None:- self._github = GitHubSource(auth=self.auth)- return self._github-- def source_id(self) -> str:- return "hermes-index"-- @property- def is_available(self) -> bool:- """Whether the index is loaded and has skills."""- index = self._ensure_loaded()- return bool(index.get("skills"))-- def trust_level_for(self, identifier: str) -> str:- index = self._ensure_loaded()- for skill in index.get("skills", []):- if skill.get("identifier") == identifier:- return skill.get("trust_level", "community")- return "community"-- def search(self, query: str, limit: int = 10) -> List[SkillMeta]:- """Search the cached index. Zero API calls.-- Matches against name, description, tags, identifier, and the per-tap- ``extra.provider`` label (so a query like ``nvidia`` surfaces the- ``NVIDIA/skills/...`` entries even though their ``source`` is the bare- ``github``). Results are scored and ranked (exact name > name prefix >- whole-word > substring) rather than returned in raw index order and- truncated at the first ``limit`` hits — that earlier break-at-limit- behaviour returned an arbitrary file-order slice and buried the most- relevant skills.- """- index = self._ensure_loaded()- skills = index.get("skills", [])- if not skills:- return []-- if not query.strip():- # No query — return featured/popular (index order)- return [self._to_meta(s) for s in skills[:limit]]-- query_lower = query.lower()- scored: List[Tuple[int, int, dict]] = []- for i, s in enumerate(skills):- name = str(s.get("name", "")).lower()- provider = str((s.get("extra") or {}).get("provider", "")).lower()- haystack = " ".join([- name,- str(s.get("description", "")).lower(),- " ".join(str(t).lower() for t in s.get("tags", [])),- str(s.get("identifier", "")).lower(),- provider,- ])- if query_lower not in haystack:- continue- # Lower score sorts first.- if name == query_lower:- score = 0- elif name.startswith(query_lower):- score = 1- elif provider == query_lower:- score = 2- elif query_lower in name.split() or query_lower in provider.split():- score = 3- elif query_lower in name:- score = 4- else:- score = 5- # i (original index order) is the stable tiebreaker.- scored.append((score, i, s))-- scored.sort(key=lambda x: (x[0], x[1]))- return [self._to_meta(s) for _, _, s in scored[:limit]]-- def fetch(self, identifier: str) -> Optional[SkillBundle]:- """Fetch a skill using the resolved path from the index.-- If the index has a ``resolved_github_id`` for this skill, we skip- the entire candidate/discovery chain and go directly to GitHub- with the exact path. This reduces install from ~31 API calls to- just the file content downloads (~5-22 depending on skill size).- """- index = self._ensure_loaded()- entry = self._find_entry(identifier, index)- if not entry:- return None-- # Use resolved path if available- resolved = entry.get("resolved_github_id")- if resolved:- bundle = self._get_github().fetch(resolved)- if bundle:- bundle.source = entry.get("source", "hermes-index")- bundle.identifier = identifier- return bundle-- # Fall back to identifier-based fetch via repo/path- repo = entry.get("repo", "")- path = entry.get("path", "")- if repo and path:- github_id = f"{repo}/{path}"- bundle = self._get_github().fetch(github_id)- if bundle:- bundle.source = entry.get("source", "hermes-index")- bundle.identifier = identifier- return bundle-- return None-- def inspect(self, identifier: str) -> Optional[SkillMeta]:- """Return metadata from the index. Zero API calls."""- index = self._ensure_loaded()- entry = self._find_entry(identifier, index)- if entry:- return self._to_meta(entry)- return None-- def _find_entry(self, identifier: str, index: dict) -> Optional[dict]:- """Look up a skill in the index by identifier or name."""- skills = index.get("skills", [])-- # Exact identifier match- for s in skills:- if s.get("identifier") == identifier:- return s-- # Try without source prefix (e.g. "skills-sh/" stripped)- normalized = identifier- for prefix in ("skills-sh/", "skills.sh/", "official/", "github/", "clawhub/"):- if identifier.startswith(prefix):- normalized = identifier[len(prefix):]- break-- # Match on normalized identifier or name- for s in skills:- sid = s.get("identifier", "")- # Strip prefix from stored identifier too- stored_normalized = sid- for prefix in ("skills-sh/", "skills.sh/", "official/", "github/", "clawhub/"):- if sid.startswith(prefix):- stored_normalized = sid[len(prefix):]- break- if stored_normalized == normalized:- return s- return None+# ---------------------------------------------------------------------------+# Source router + parallel search+# ---------------------------------------------------------------------------- @staticmethod- def _to_meta(entry: dict) -> SkillMeta:- return SkillMeta(- name=entry.get("name", ""),- description=entry.get("description", ""),- source=entry.get("source", "hermes-index"),- identifier=entry.get("identifier", ""),- trust_level=entry.get("trust_level", "community"),- repo=entry.get("repo"),- path=entry.get("path"),- tags=entry.get("tags", []),- extra=entry.get("extra", {}),- )+# External API sources the centralized index already covers; skipped when the+# index is available and no source filter is active (~70 GitHub calls/search+# for unauthenticated users otherwise).+_API_SOURCE_IDS = frozenset({"github", "skills-sh", "clawhub", "lobehub", "well-known"})def create_source_router(auth: Optional[GitHubAuth] = None) -> List[SkillSource]:- """- Create all configured source adapters.- Returns a list of active sources for search/fetch operations.- """+ """All configured source adapters, in priority order."""if auth is None:auth = GitHubAuth()- taps_mgr = TapsManager()- extra_taps = taps_mgr.list_taps()-- sources: List[SkillSource] = [- OptionalSkillSource(auth=auth), # Official optional skills (highest priority)- HermesIndexSource(auth=auth), # Centralized index (search + resolved install paths)+ return [+ OptionalSkillSource(auth=auth), # official optional skills (highest priority)+ HermesIndexSource(auth=auth), # centralized index (search + resolved install paths)SkillsShSource(auth=auth),WellKnownSkillSource(),- UrlSource(), # Direct HTTP(S) URL to a SKILL.md file- GitHubSource(auth=auth, extra_taps=extra_taps),+ UrlSource(), # direct HTTP(S) URL to a SKILL.md+ GitHubSource(auth=auth, extra_taps=TapsManager().list_taps()),ClawHubSource(),LobeHubSource(),- BrowseShSource(), # browse.sh: 169+ site-specific browser automation skills+ BrowseShSource(), # browse.sh site-specific browser skills]- return sources-def _search_one_source(src: SkillSource, query: str, limit: int@@ -4823,6 +793,30 @@ def _search_one_source(return src.source_id(), []+def _select_active_sources(sources: List[SkillSource], source_filter: str) -> List[SkillSource]:+ """Sources to query for ``source_filter``.++ A provider filter (nvidia/openai/...) is not a source id — the data lives+ in the index/github source under ``extra.provider`` — so it selects like+ "all"; the narrowing happens later on the merged results. "official" is+ always included alongside an explicit source filter.+ """+ effective = "all" if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES else source_filter+ index_available = effective == "all" and any(+ src.source_id() == "hermes-index" and getattr(src, "is_available", False)+ for src in sources+ )+ active: List[SkillSource] = []+ for src in sources:+ sid = src.source_id()+ if effective != "all" and sid != effective and sid != "official":+ continue+ if index_available and sid in _API_SOURCE_IDS:+ continue+ active.append(src)+ return active++def parallel_search_sources(sources: List[SkillSource],query: str = "",@@ -4831,49 +825,15 @@ def parallel_search_sources(overall_timeout: float = 30,on_source_done: Optional[Any] = None,) -> Tuple[List[SkillMeta], Dict[str, int], List[str]]:- """Search all sources in parallel with per-source timeout.+ """Search all sources in parallel with an overall timeout.- Returns ``(all_results, source_counts, timed_out_ids)``.-- *on_source_done* is an optional callback ``(source_id, count) -> None``- invoked as each source completes — useful for progress indicators.+ Returns ``(all_results, source_counts, timed_out_ids)``. *on_source_done*+ is an optional ``(source_id, count) -> None`` progress callback."""from concurrent.futures import as_completedper_source_limits = per_source_limits or {}-- # A provider filter (e.g. "nvidia", "openai") targets GitHub-tap skills- # that the runtime index stores under source="github" with an- # ``extra.provider`` label. It is NOT a real source id, so source-level- # selection must treat it like "all" (the index / github source carries- # the data); the per-provider narrowing happens downstream on the merged- # results (see ``_filter_results_by_provider``).- _provider_filter = source_filter.strip().lower() in _PROVIDER_FILTER_VALUES- _effective_filter = "all" if _provider_filter else source_filter-- active: List[SkillSource] = []- # When the centralized index is available and the user hasn't filtered- # to a specific source, skip external API sources (github, skills-sh,- # clawhub, etc.) — the index already has their data. This avoids- # ~70 GitHub API calls per search for unauthenticated users.- _index_available = False- _api_source_ids = frozenset({"github", "skills-sh", "clawhub",- "lobehub", "well-known"})- if _effective_filter == "all":- for src in sources:- if (src.source_id() == "hermes-index"- and getattr(src, "is_available", False)):- _index_available = True- break-- for src in sources:- sid = src.source_id()- if _effective_filter != "all" and sid != _effective_filter and sid != "official":- continue- # Skip external API sources when the index covers them- if _index_available and sid in _api_source_ids:- continue- active.append(src)+ active = _select_active_sources(sources, source_filter)all_results: List[SkillMeta] = []source_counts: Dict[str, int] = {}@@ -4882,21 +842,15 @@ def parallel_search_sources(if not active:return all_results, source_counts, timed_out_ids- # NOTE: a `with ThreadPoolExecutor(...) as pool` block calls- # ``shutdown(wait=True)`` on exit, which blocks until every submitted- # worker finishes — so a single slow source (e.g. ClawHub) keeps the- # caller blocked for minutes and renders ``overall_timeout`` a no-op.- # Manage the executor manually and shut it down with ``wait=False`` so- # the timeout is actually honoured. Daemon workers (tools.daemon_pool):- # an abandoned slow source must not block interpreter exit either —- # stdlib workers are joined unconditionally by the atexit hook.+ # Not a ``with`` block: its shutdown(wait=True) would block on a slow source+ # (ClawHub) for minutes and defeat ``overall_timeout``. Daemon workers so an+ # abandoned source cannot block interpreter exit either.from tools.daemon_pool import DaemonThreadPoolExecutorpool = DaemonThreadPoolExecutor(max_workers=min(len(active), 8))- futures = {}- for src in active:- lim = per_source_limits.get(src.source_id(), 50)- fut = pool.submit(_search_one_source, src, query, lim)- futures[fut] = src.source_id()+ futures = {+ pool.submit(_search_one_source, src, query, per_source_limits.get(src.source_id(), 50)): src.source_id()+ for src in active+ }try:try:@@ -4910,17 +864,13 @@ def parallel_search_sources(except Exception:passexcept TimeoutError:- timed_out_ids = [- futures[f] for f in futures if not f.done()- ]+ timed_out_ids = [futures[f] for f in futures if not f.done()]if timed_out_ids:logger.debug("Skills browse timed out waiting for: %s",", ".join(timed_out_ids),)finally:- # wait=False so a slow source cannot block the caller's return;- # cancel_futures drops not-yet-started work.pool.shutdown(wait=False, cancel_futures=True)return all_results, source_counts, timed_out_ids@@ -4936,29 +886,13 @@ def unified_search(query: str, sources: List[SkillSource],overall_timeout=30,)- # A provider filter (nvidia/openai/...) is applied here, on the merged set,- # because it targets the per-tap ``extra.provider`` label rather than a real- # source id (the runtime index stores every GitHub tap as source="github").+ # Provider filters target ``extra.provider`` on the merged set, not a source id.if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES:all_results = _filter_results_by_provider(all_results, source_filter)- # Deduplicate by identifier, preferring higher trust levels.- # identifier is always unique per skill (e.g. "browse-sh/airbnb.com/search-listings-ddgioa").- # Using name would incorrectly collapse browse-sh skills from different sites that share- # the same task name (e.g. "search-listings" from Airbnb and Booking.com).- _TRUST_RANK = {"builtin": 2, "trusted": 1, "community": 0}- seen: Dict[str, SkillMeta] = {}- for r in all_results:- if r.identifier not in seen:- seen[r.identifier] = r- elif _TRUST_RANK.get(r.trust_level, 0) > _TRUST_RANK.get(seen[r.identifier].trust_level, 0):- seen[r.identifier] = r- deduped = list(seen.values())-- # Stable-sort by trust rank before truncating: the limit cut must not- # drop a builtin/official catalog entry because a high-volume community- # source (skills.sh mirrors every repo) happened to finish first and- # flood the merged list. Insertion order is preserved within each rank.- deduped.sort(key=lambda r: -_TRUST_RANK.get(r.trust_level, 0))-+ deduped = _dedupe_by_trust(all_results)+ # Stable-sort by trust before truncating so the limit cut never drops a+ # builtin/official entry because a high-volume community source finished+ # first; insertion order is preserved within each rank.+ deduped.sort(key=lambda r: -TRUST_RANK.get(r.trust_level, 0))return deduped[:limit]diff --git a/tools/skills_hub_clawhub.py b/tools/skills_hub_clawhub.pynew file mode 100644index 00000000000..4b295ca84bb--- /dev/null+++ b/tools/skills_hub_clawhub.py@@ -0,0 +1,645 @@+"""Skills Hub ClawHub adapter (clawhub.ai HTTP API)."""++import hashlib+import json+import logging+import re+import time+from typing import Any, Dict, List, Optional, Tuple++import httpx++from tools.skills_hub_models import (+ GuardedFetchMixin, SkillBundle, SkillMeta, SkillSource, _cache_metas, _cached_metas,+ _validate_bundle_rel_path,+)++logger = logging.getLogger("tools.skills_hub")+++class ClawHubSource(GuardedFetchMixin, SkillSource):+ """ClawHub (clawhub.ai) HTTP API. Every skill is community trust — the+ ClawHavoc incident (341 malicious skills, Feb 2026) showed their vetting+ is insufficient."""++ BASE_URL = "https://clawhub.ai/api/v1"++ # Wall-clock budget for a full catalog walk: 50k+ skills, sequential+ # (~250 requests each under timeout=30), so unbounded it blocks for minutes.+ CATALOG_WALK_BUDGET_SECONDS = 12++ _SLUG_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*$")++ def source_id(self) -> str:+ return "clawhub"++ def trust_level_for(self, identifier: str) -> str:+ return "community"++ # -- payload helpers ---------------------------------------------------++ @staticmethod+ def _normalize_tags(tags: Any) -> List[str]:+ if isinstance(tags, list):+ return [str(t) for t in tags]+ if isinstance(tags, dict):+ return [str(k) for k in tags if str(k) != "latest"]+ return []++ @staticmethod+ def _coerce_skill_payload(data: Any) -> Optional[Dict[str, Any]]:+ """Flatten ``{"skill": {...}, "latestVersion", "owner"}`` listing shapes."""+ if not isinstance(data, dict):+ return None+ nested = data.get("skill")+ if isinstance(nested, dict):+ merged = dict(nested)+ latest_version = data.get("latestVersion")+ if latest_version is not None and "latestVersion" not in merged:+ merged["latestVersion"] = latest_version+ # owner is needed for building valid detail URLs.+ if "owner" in data and "owner" not in merged:+ merged["owner"] = data["owner"]+ return merged+ return data++ @staticmethod+ def _owner_from_payload(data: Optional[Dict[str, Any]]) -> Optional[str]:+ if not isinstance(data, dict):+ return None+ owner = data.get("owner")+ if isinstance(owner, dict):+ handle = owner.get("handle")+ if isinstance(handle, str) and handle.strip():+ return handle.strip()+ if isinstance(owner, str) and owner.strip():+ return owner.strip()+ return None++ @classmethod+ def _owner_matches(cls, expected_owner: Optional[str], data: Optional[Dict[str, Any]]) -> bool:+ if not expected_owner:+ return True+ actual = cls._owner_from_payload(data)+ return not actual or actual.lower() == expected_owner.lower()++ @classmethod+ def _item_to_meta(cls, item: Dict[str, Any]) -> Optional[SkillMeta]:+ """Listing item -> SkillMeta (None without a slug)."""+ slug = item.get("slug")+ if not isinstance(slug, str) or not slug:+ return None+ owner = cls._owner_from_payload(item)+ return SkillMeta(+ name=item.get("displayName") or item.get("name") or slug,+ description=item.get("summary") or item.get("description") or "",+ source="clawhub",+ identifier=slug,+ trust_level="community",+ tags=cls._normalize_tags(item.get("tags", [])),+ extra={"owner": owner} if owner else {},+ )++ def _skill_detail(self, identifier: str) -> Optional[Tuple[str, Dict[str, Any]]]:+ """``(slug, payload)`` for an identifier, or None when unparsable,+ missing, or owned by someone other than the ``@owner`` requested."""+ parsed = self._parse_identifier(identifier)+ if parsed is None:+ return None+ slug, expected_owner = parsed+ data = self._coerce_skill_payload(self._get_json(f"{self.BASE_URL}/skills/{slug}"))+ if not isinstance(data, dict) or not self._owner_matches(expected_owner, data):+ return None+ return slug, data++ # -- search / ranking --------------------------------------------------++ @staticmethod+ def _query_terms(query: str) -> List[str]:+ return [term for term in re.split(r"[^a-z0-9]+", query.lower()) if term]++ @classmethod+ def _search_score(cls, query: str, meta: SkillMeta) -> int:+ query_norm = query.strip().lower()+ if not query_norm:+ return 1++ identifier = (meta.identifier or "").lower()+ name = (meta.name or "").lower()+ description = (meta.description or "").lower()+ query_terms = cls._query_terms(query_norm)+ identifier_terms = cls._query_terms(identifier)+ name_terms = cls._query_terms(name)+ normalized_identifier = " ".join(identifier_terms)+ normalized_name = " ".join(name_terms)++ checks = (+ (140, query_norm == identifier),+ (130, query_norm == name),+ (125, normalized_identifier == query_norm),+ (120, normalized_name == query_norm),+ (95, normalized_identifier.startswith(query_norm)),+ (90, normalized_name.startswith(query_norm)),+ (70, bool(query_terms) and identifier_terms[: len(query_terms)] == query_terms),+ (65, bool(query_terms) and name_terms[: len(query_terms)] == query_terms),+ (40, query_norm in identifier),+ (35, query_norm in name),+ (10, query_norm in description),+ )+ score = sum(points for points, hit in checks if hit)+ for term in query_terms:+ score += 15 * (term in identifier_terms) + 12 * (term in name_terms) + 3 * (term in description)+ return score++ @staticmethod+ def _dedupe_results(results: List[SkillMeta]) -> List[SkillMeta]:+ seen: set[str] = set()+ deduped: List[SkillMeta] = []+ for result in results:+ key = (result.identifier or result.name).lower()+ if key not in seen:+ seen.add(key)+ deduped.append(result)+ return deduped++ def _exact_slug_meta(self, query: str) -> Optional[SkillMeta]:+ query = query.strip()+ parsed = self._parse_identifier(query)+ query_terms = self._query_terms(query)+ candidates: List[str] = []++ if parsed:+ candidates.append(parsed[0])+ elif "/" not in query and self._SLUG_RE.fullmatch(query):+ candidates.append(query)++ if query_terms:+ base_slug = "-".join(query_terms)+ if len(query_terms) >= 2:+ candidates.extend(+ f"{base_slug}-{suffix}" for suffix in ("agent", "skill", "tool", "assistant", "playbook")+ )+ candidates.append(base_slug)++ for candidate in dict.fromkeys(candidates):+ meta = self.inspect(candidate)+ if meta:+ return meta+ return None++ def _finalize_search_results(self, query: str, results: List[SkillMeta], limit: int) -> List[SkillMeta]:+ query_norm = query.strip()+ if not query_norm:+ return self._dedupe_results(results)[:limit]++ filtered = [meta for meta in results if self._search_score(query_norm, meta) > 0]+ filtered.sort(+ key=lambda meta: (+ -self._search_score(query_norm, meta),+ meta.name.lower(),+ meta.identifier.lower(),+ )+ )+ filtered = self._dedupe_results(filtered)++ exact = self._exact_slug_meta(query_norm)+ if exact:+ filtered = [meta for meta in filtered if self._search_score(query_norm, meta) >= 20]+ filtered = self._dedupe_results([exact] + filtered)++ if filtered:+ return filtered[:limit]++ if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]*", query_norm):+ return []++ return self._dedupe_results(results)[:limit]++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ query = query.strip()++ if query:+ if len(self._query_terms(query)) >= 2:+ direct = self._exact_slug_meta(query)+ if direct:+ return [direct]++ results = self._search_catalog(query, limit=limit)+ if results:+ return results+ else:+ # Empty query: paginating catalog walker. A disk-cached full catalog+ # is returned whole (caller paginates); on a cold cache the walk is+ # bounded to `limit` so browse renders page one without walking+ # 50k+ skills (max_items=0 = unbounded, offline index builder only).+ catalog = self._load_catalog_index(max_items=limit if limit > 0 else 0)+ if catalog:+ deduped = self._dedupe_results(catalog)+ return deduped[:limit] if limit > 0 else deduped++ # Catalog miss / walker failure: best-effort lightweight listing API.+ cache_key = f"clawhub_search_listing_v1_{hashlib.md5(query.encode()).hexdigest()}_{limit}"+ cached = _cached_metas(cache_key)+ if cached is not None:+ return self._finalize_search_results(query, cached, limit)++ data = self._get_json(f"{self.BASE_URL}/skills", timeout=15,+ params={"search": query, "limit": limit})+ if data is None:+ return []+ skills_data = data.get("items", data) if isinstance(data, dict) else data+ if not isinstance(skills_data, list):+ return []++ results = [m for m in (self._item_to_meta(item) for item in skills_data[:limit]) if m]+ final_results = self._finalize_search_results(query, results, limit)+ _cache_metas(cache_key, final_results)+ return final_results++ @classmethod+ def _parse_identifier(cls, identifier: str) -> Optional[Tuple[str, Optional[str]]]:+ """``(slug, expected_owner)`` for a bare slug, ``clawhub/<slug>``,+ ``@owner/slug``, or the URL path ``owner/skills/slug``.++ GitHub-style ``owner/repo/skill`` identifiers are NOT ClawHub's —+ claiming them by last segment would install a same-named skill from a+ different author.+ """+ raw = (identifier or "").strip()+ if not raw:+ return None+ had_at = raw.startswith("@")+ ident = raw[1:] if had_at else raw+ if ident.startswith("clawhub/"):+ ident = ident[len("clawhub/"):]+ parts = [part for part in ident.split("/") if part]+ owner = slug = None+ if len(parts) == 1:+ slug = parts[0]+ elif len(parts) == 2 and had_at:+ owner, slug = parts+ elif len(parts) == 3 and parts[1].lower() == "skills":+ owner, _, slug = parts+ else:+ return None+ if not cls._SLUG_RE.fullmatch(slug) or (owner is not None and not cls._SLUG_RE.fullmatch(owner)):+ return None+ return slug, owner++ # -- fetch / inspect ---------------------------------------------------++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ detail = self._skill_detail(identifier)+ if detail is None:+ return None+ slug, skill_data = detail++ latest_version = self._resolve_latest_version(slug, skill_data)+ if not latest_version:+ logger.warning("ClawHub fetch failed for %s: could not resolve latest version", slug)+ return None++ # Primary: ZIP bundle from /download. Fallback: version metadata with+ # inline/raw content (files may sit under version_data["version"]).+ files = self._download_zip(slug, latest_version)+ if "SKILL.md" not in files:+ version_data = self._get_json(f"{self.BASE_URL}/skills/{slug}/versions/{latest_version}")+ if isinstance(version_data, dict):+ files = self._extract_files(version_data) or files+ if "SKILL.md" not in files:+ nested = version_data.get("version", {})+ if isinstance(nested, dict):+ files = self._extract_files(nested) or files++ if "SKILL.md" not in files:+ logger.warning(+ "ClawHub fetch for %s resolved version %s but could not retrieve file content",+ slug,+ latest_version,+ )+ return None++ return SkillBundle(+ name=slug,+ files=files,+ source="clawhub",+ identifier=slug,+ trust_level="community",+ )++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ detail = self._skill_detail(identifier)+ if detail is None:+ return None+ slug, data = detail+ return self._item_to_meta({**data, "slug": data.get("slug") or slug})++ def _search_catalog(self, query: str, limit: int = 10) -> List[SkillMeta]:+ cache_key = f"clawhub_search_catalog_v1_{hashlib.md5(f'{query}|{limit}'.encode()).hexdigest()}"+ cached = _cached_metas(cache_key)+ if cached is not None:+ return cached[:limit]++ catalog = self._load_catalog_index()+ if not catalog:+ return []++ results = self._finalize_search_results(query, catalog, limit)+ _cache_metas(cache_key, results)+ return results++ def _load_catalog_index(self, max_items: int = 0) -> List[SkillMeta]:+ """Walk the ClawHub catalog via cursor pagination.++ ``max_items`` stops the walk early once that many distinct skills are+ gathered (browse's cold-start fallback renders one page); ``0`` walks+ to exhaustion (offline index builder). Only a COMPLETE walk (cursor+ exhausted or page cap) is written to the shared ``clawhub_catalog_v1``+ cache — a walk cut by ``max_items`` or the wall-clock budget would+ poison it with a partial slice.+ """+ cache_key = "clawhub_catalog_v1"+ cached = _cached_metas(cache_key)+ if cached is not None:+ return cached++ cursor: Optional[str] = None+ results: List[SkillMeta] = []+ seen: set[str] = set()+ # 750 pages * 200/page = 150k ceiling over the ~50k catalog; a safety+ # rail against an infinite-cursor loop, normally ended by nextCursor=None.+ max_pages = 750+ # Wall-clock budget applies to interactive browse only: the index builder+ # (max_items=0) must walk everything or it trips the deploy health floor.+ deadline = (+ time.monotonic() + self.CATALOG_WALK_BUDGET_SECONDS+ if max_items > 0+ else None+ )+ partial = False++ for _ in range(max_pages):+ if deadline is not None and time.monotonic() > deadline:+ partial = True+ break+ params: Dict[str, Any] = {"limit": 200}+ if cursor:+ params["cursor"] = cursor++ data = self._get_json(f"{self.BASE_URL}/skills", timeout=30, params=params)+ items = data.get("items", []) if isinstance(data, dict) else []+ if not isinstance(items, list) or not items:+ break++ for item in items:+ slug = item.get("slug")+ if not isinstance(slug, str) or not slug or slug in seen:+ continue+ seen.add(slug)+ meta = self._item_to_meta(item)+ if meta:+ results.append(meta)++ cursor = data.get("nextCursor") if isinstance(data, dict) else None+ if not isinstance(cursor, str) or not cursor:+ break++ if max_items > 0 and len(results) >= max_items:+ partial = True+ break++ if not partial:+ _cache_metas(cache_key, results)+ return results++ def _get_json(self, url: str, timeout: int = 20, **kwargs) -> Optional[Any]:+ try:+ resp = httpx.get(url, timeout=timeout, **kwargs)+ if resp.status_code != 200:+ return None+ return resp.json()+ except (httpx.HTTPError, json.JSONDecodeError):+ return None++ def _resolve_latest_version(self, slug: str, skill_data: Dict[str, Any]) -> Optional[str]:+ latest = skill_data.get("latestVersion")+ if isinstance(latest, dict):+ version = latest.get("version")+ if isinstance(version, str) and version:+ return version++ tags = skill_data.get("tags")+ if isinstance(tags, dict):+ latest_tag = tags.get("latest")+ if isinstance(latest_tag, str) and latest_tag:+ return latest_tag++ versions_data = self._get_json(f"{self.BASE_URL}/skills/{slug}/versions")+ if isinstance(versions_data, list) and versions_data:+ first = versions_data[0]+ if isinstance(first, dict):+ version = first.get("version")+ if isinstance(version, str) and version:+ return version+ return None++ def _fetch_owner_handle(self, slug: str) -> Optional[str]:+ """Owner handle from the detail API (the listing API lacks it), or None.++ Bounded retry: 3 attempts total. 429 honours ``Retry-After`` else+ exponential backoff (2s -> 4s); 5xx and transport errors back off;+ other 4xx means the resource doesn't exist — no retry.+ """+ url = f"{self.BASE_URL}/skills/{slug}"+ max_attempts = 3+ backoff_base = 2.0 # seconds++ for attempt in range(max_attempts):+ delay = backoff_base * (2 ** attempt)+ try:+ resp = httpx.get(url, timeout=20)+ except (httpx.HTTPError, OSError):+ reason = "transport error"+ else:+ if resp.status_code == 200:+ try:+ raw = resp.json()+ except (json.JSONDecodeError, ValueError):+ return None+ data = self._coerce_skill_payload(raw)+ return self._owner_from_payload(data) if isinstance(data, dict) else None+ if resp.status_code == 429:+ retry_after_raw = resp.headers.get("Retry-After")+ try:+ delay = float(retry_after_raw) if retry_after_raw else delay+ except (TypeError, ValueError):+ pass+ reason = "HTTP 429"+ elif 500 <= resp.status_code < 600:+ reason = f"HTTP {resp.status_code}"+ else:+ return None # 4xx (non-429): doesn't exist / bad request+ if attempt >= max_attempts - 1:+ return None+ logger.debug(+ "_fetch_owner_handle(%s): %s on attempt %d/%d, retrying in %.1fs",+ slug, reason, attempt + 1, max_attempts, delay,+ )+ time.sleep(delay)++ return None++ def enrich_owners(self, skills: List[SkillMeta], max_workers: int = 30) -> int:+ """Batch-fetch owner handles for ClawHub skills missing ``extra["owner"]``+ (in-place; returns the number enriched). For the offline index builder:+ the full 50k catalog takes ~5–10 min at 30 workers.++ Safety rails: aborts after 50 consecutive failures (systemic outage),+ per-request 429 backoff, progress log every 1000 skills.+ """+ needs_enrichment = [+ s for s in skills+ if s.source == "clawhub" and not (s.extra or {}).get("owner")+ ]+ if not needs_enrichment:+ return 0++ enriched = 0+ consecutive_failures = 0+ max_consecutive_failures = 50+ processed = 0+ import threading+ lock = threading.Lock()++ from concurrent.futures import ThreadPoolExecutor, as_completed+ with ThreadPoolExecutor(max_workers=max_workers) as pool:+ futures = {pool.submit(self._fetch_owner_handle, s.identifier): s for s in needs_enrichment}+ for future in as_completed(futures):+ meta = futures[future]+ processed += 1+ try:+ handle = future.result()+ except Exception:+ handle = None+ with lock:+ if handle:+ if not meta.extra:+ meta.extra = {}+ meta.extra["owner"] = handle+ enriched += 1+ consecutive_failures = 0+ else:+ consecutive_failures += 1++ if processed % 1000 == 0:+ logger.info(+ "ClawHub owner enrichment: %d/%d processed, %d enriched",+ processed, len(needs_enrichment), enriched,+ )++ with lock:+ if consecutive_failures >= max_consecutive_failures:+ logger.warning(+ "ClawHub owner enrichment: %d consecutive failures — "+ "aborting early (%d/%d processed, %d enriched). "+ "The ClawHub API may be down or rate-limited.",+ max_consecutive_failures, processed,+ len(needs_enrichment), enriched,+ )+ for f in futures:+ f.cancel()+ break++ return enriched++ def _extract_files(self, version_data: Dict[str, Any]) -> Dict[str, str]:+ files: Dict[str, str] = {}+ file_list = version_data.get("files")++ if isinstance(file_list, dict):+ return {k: v for k, v in file_list.items() if isinstance(v, str)}++ if not isinstance(file_list, list):+ return files++ for file_meta in file_list:+ if not isinstance(file_meta, dict):+ continue++ fname = file_meta.get("path") or file_meta.get("name")+ if not fname or not isinstance(fname, str):+ continue++ inline_content = file_meta.get("content")+ if isinstance(inline_content, str):+ files[fname] = inline_content+ continue++ raw_url = file_meta.get("rawUrl") or file_meta.get("downloadUrl") or file_meta.get("url")+ if isinstance(raw_url, str) and raw_url.startswith("http"):+ content = self._fetch_text(raw_url)+ if content is not None:+ files[fname] = content++ return files++ def _download_zip(self, slug: str, version: str) -> Dict[str, str]:+ """Download the skill ZIP from /download and extract its text files."""+ import io+ import zipfile++ files: Dict[str, str] = {}+ max_retries = 3+ for attempt in range(max_retries):+ try:+ resp = httpx.get(+ f"{self.BASE_URL}/download",+ params={"slug": slug, "version": version},+ timeout=30,+ follow_redirects=True,+ )+ if resp.status_code == 429:+ try:+ retry_after = int(resp.headers.get("retry-after", "5"))+ except (ValueError, TypeError):+ retry_after = 5+ retry_after = min(retry_after, 15) # Cap wait time+ logger.debug(+ "ClawHub download rate-limited for %s, retrying in %ds (attempt %d/%d)",+ slug, retry_after, attempt + 1, max_retries,+ )+ time.sleep(retry_after)+ continue+ if resp.status_code != 200:+ logger.debug("ClawHub ZIP download for %s v%s returned %s", slug, version, resp.status_code)+ return files++ with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:+ for info in zf.infolist():+ if info.is_dir():+ continue+ try:+ name = _validate_bundle_rel_path(info.filename)+ except ValueError:+ logger.debug("Skipping unsafe ZIP member path: %s", info.filename)+ continue+ if info.file_size > 500_000: # skip large binaries+ logger.debug("Skipping large file in ZIP: %s (%d bytes)", name, info.file_size)+ continue+ try:+ files[name] = zf.read(info.filename).decode("utf-8")+ except (UnicodeDecodeError, KeyError):+ logger.debug("Skipping non-text file in ZIP: %s", name)+ continue++ return files++ except zipfile.BadZipFile:+ logger.warning("ClawHub returned invalid ZIP for %s v%s", slug, version)+ return files+ except httpx.HTTPError as exc:+ logger.debug("ClawHub ZIP download failed for %s v%s: %s", slug, version, exc)+ return files++ logger.debug("ClawHub ZIP download exhausted retries for %s v%s", slug, version)+ return filesdiff --git a/tools/skills_hub_github.py b/tools/skills_hub_github.pynew file mode 100644index 00000000000..91121d5b21f--- /dev/null+++ b/tools/skills_hub_github.py@@ -0,0 +1,658 @@+"""Skills Hub GitHub adapter: API auth, tap providers, and the Contents/Trees source."""++import json+import logging+import subprocess+import time+from pathlib import Path+from typing import Dict, List, Optional, Tuple, Union+from urllib.parse import quote++import httpx++from hermes_cli._subprocess_compat import windows_hide_flags+from tools.skills_guard import TRUSTED_REPOS+from tools.skills_hub_models import (+ SkillBundle, SkillMeta, SkillSource, _dedupe_by_trust,+ _hermes_tags, _matches_query, _parse_frontmatter, _referenced_support_paths, _skill_meta_to_dict,+ _validate_bundle_rel_path, hub,+)++logger = logging.getLogger("tools.skills_hub")+++# Maps a GitHub tap repo (owner/repo) to the provider label used by the+# docs-site catalog (website/scripts/extract-skills.py::GITHUB_TAP_LABELS).+# The runtime index collapses every tap into source="github"; the label in+# ``extra.provider`` keeps per-tap identity searchable/filterable without+# disturbing the dedup / floor / index-skip logic keyed on the bare source id.+GITHUB_TAP_PROVIDERS = {+ "openai/skills": "OpenAI",+ "anthropics/skills": "Anthropic",+ "huggingface/skills": "HuggingFace",+ "nvidia/skills": "NVIDIA",+ "voltagent/awesome-agent-skills": "VoltAgent",+ "garrytan/gstack": "gstack",+ "minimax-ai/cli": "MiniMax",+}++# Accepted ``--source`` provider filters (lowercased). Not real source ids —+# they narrow merged results to GitHub-tap skills carrying that ``extra.provider``.+_PROVIDER_FILTER_VALUES = frozenset(v.lower() for v in GITHUB_TAP_PROVIDERS.values())+++def github_provider_for(repo: str) -> Optional[str]:+ """Provider label for an ``owner/repo`` tap (case-insensitive), or None."""+ if not repo:+ return None+ return GITHUB_TAP_PROVIDERS.get(repo.strip().lower())+++def _filter_results_by_provider(results: List[SkillMeta], provider: str) -> List[SkillMeta]:+ """Keep only results whose ``extra.provider`` matches ``provider``.++ An explicit provider filter (``--source nvidia``) narrows to exactly that+ provider — the official catalog is NOT injected the way unfiltered browse does.+ """+ want = provider.strip().lower()+ return [r for r in results if str((r.extra or {}).get("provider", "")).lower() == want]+++def _is_rate_limit_response(resp: httpx.Response) -> bool:+ """403 with exhausted quota, or any 429."""+ return resp.status_code == 429 or (+ resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining", "") == "0"+ )+++# ---------------------------------------------------------------------------+# GitHub Authentication+# ---------------------------------------------------------------------------++class GitHubAuth:+ """GitHub API authentication, tried in priority order:+ 1. GITHUB_TOKEN / GH_TOKEN (PAT)+ 2. `gh auth token` (gh CLI)+ 3. GitHub App JWT + installation token+ 4. Unauthenticated (60 req/hr, public repos only)+ """++ def __init__(self):+ self._cached_token: Optional[str] = None+ self._cached_method: Optional[str] = None+ self._app_token_expiry: float = 0++ def get_headers(self) -> Dict[str, str]:+ token = self._resolve_token()+ headers = {"Accept": "application/vnd.github.v3+json"}+ if token:+ headers["Authorization"] = f"token {token}"+ return headers++ def is_authenticated(self) -> bool:+ return self._resolve_token() is not None++ def auth_method(self) -> str:+ """'pat', 'gh-cli', 'github-app', or 'anonymous'."""+ self._resolve_token()+ return self._cached_method or "anonymous"++ def _resolve_token(self) -> Optional[str]:+ if self._cached_token and (+ self._cached_method != "github-app" or time.time() < self._app_token_expiry+ ):+ return self._cached_token++ # Profile-scoped secret lookup (multiplexed gateway safe).+ from agent.secret_scope import get_secret+ token = get_secret("GITHUB_TOKEN") or get_secret("GH_TOKEN")+ if token:+ self._cached_token, self._cached_method = token, "pat"+ return token++ token = self._try_gh_cli()+ if token:+ self._cached_token, self._cached_method = token, "gh-cli"+ return token++ token = self._try_github_app()+ if token:+ self._cached_token, self._cached_method = token, "github-app"+ self._app_token_expiry = time.time() + 3500 # ~58 min (tokens last 1 hour)+ return token++ self._cached_method = "anonymous"+ return None++ def _try_gh_cli(self) -> Optional[str]:+ try:+ result = subprocess.run(+ ["gh", "auth", "token"],+ capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,+ stdin=subprocess.DEVNULL,+ creationflags=windows_hide_flags(),+ )+ if result.returncode == 0 and result.stdout.strip():+ return result.stdout.strip()+ except (FileNotFoundError, subprocess.TimeoutExpired) as e:+ logger.debug("gh CLI token lookup failed: %s", e)+ return None++ def _try_github_app(self) -> Optional[str]:+ from agent.secret_scope import get_secret+ app_id = get_secret("GITHUB_APP_ID")+ key_path = get_secret("GITHUB_APP_PRIVATE_KEY_PATH")+ installation_id = get_secret("GITHUB_APP_INSTALLATION_ID")++ if not all([app_id, key_path, installation_id]):+ return None++ try:+ import jwt # PyJWT+ except ImportError:+ logger.debug("PyJWT not installed, skipping GitHub App auth")+ return None++ try:+ key_file = Path(key_path)+ if not key_file.exists():+ return None+ private_key = key_file.read_text(encoding="utf-8")++ now = int(time.time())+ payload = {"iat": now - 60, "exp": now + (10 * 60), "iss": app_id}+ encoded_jwt = jwt.encode(payload, private_key, algorithm="RS256")++ resp = httpx.post(+ f"https://api.github.com/app/installations/{installation_id}/access_tokens",+ headers={+ "Authorization": f"Bearer {encoded_jwt}",+ "Accept": "application/vnd.github.v3+json",+ },+ timeout=10,+ )+ if resp.status_code == 201:+ return resp.json().get("token")+ except Exception as e:+ logger.debug("GitHub App auth failed: %s", e)++ return None+++# ---------------------------------------------------------------------------+# GitHub source adapter+# ---------------------------------------------------------------------------++def _skip_bundle_file(rel_path: str) -> bool:+ """Dotfiles, bytecode and __pycache__ never ship in a bundle."""+ base = rel_path.rsplit("/", 1)[-1]+ return base.startswith(".") or base.endswith(".pyc") or "__pycache__" in rel_path.split("/")+++class GitHubSource(SkillSource):+ """Fetch skills from GitHub repos via the Contents API."""++ DEFAULT_TAPS = [+ # openai/skills keeps its content under skills/.curated/ and+ # skills/.system/; _list_skills_in_repo skips "."/"_" directories,+ # so both entries point at the inner paths directly.+ {"repo": "openai/skills", "path": "skills/.curated/"},+ {"repo": "openai/skills", "path": "skills/.system/"},+ {"repo": "anthropics/skills", "path": "skills/"},+ {"repo": "huggingface/skills", "path": "skills/"},+ # NVIDIA-verified skills (CUDA-X, NeMo, cuOpt, ...), each with a+ # signed skill.oms.sig + governance card; `trusted` via+ # tools/skills_guard.py::TRUSTED_REPOS.+ {"repo": "NVIDIA/skills", "path": "skills/"},+ {"repo": "garrytan/gstack", "path": ""},+ ]++ _parse_frontmatter_quick = staticmethod(_parse_frontmatter)++ def __init__(self, auth: GitHubAuth, extra_taps: Optional[List[Dict]] = None):+ self.auth = auth+ self.taps = list(self.DEFAULT_TAPS)+ if extra_taps:+ self.taps.extend(extra_taps)+ # Per-instance repo -> (default_branch, tree_entries); lives for one+ # search/install flow so repeated tree lookups cost no API calls.+ self._tree_cache: Dict[str, Tuple[str, List[dict]]] = {}+ self._tree_revisions: Dict[str, str] = {}+ # repo -> skills.sh.json grouping map; None = fetched, no sidecar.+ self._skillsh_groupings: Dict[str, Optional[Dict[str, str]]] = {}+ self._rate_limited: bool = False++ def source_id(self) -> str:+ return "github"++ @property+ def is_rate_limited(self) -> bool:+ """Whether GitHub API rate limit was hit during operations."""+ return self._rate_limited++ def trust_level_for(self, identifier: str) -> str:+ # identifier format: "owner/repo/path/to/skill"+ parts = identifier.split("/", 2)+ if len(parts) >= 2 and f"{parts[0]}/{parts[1]}" in TRUSTED_REPOS:+ return "trusted"+ return "community"++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ """Substring-match all taps; dedupe by identifier preferring higher trust."""+ results: List[SkillMeta] = []+ query_lower = query.lower()++ for tap in self.taps:+ try:+ for skill in self._list_skills_in_repo(tap["repo"], tap.get("path", "")):+ if _matches_query(query_lower, skill.name, skill.description, skill.tags):+ results.append(skill)+ except Exception as e:+ logger.debug("Failed to search %s: %s", tap['repo'], e)+ continue++ return _dedupe_by_trust(results)[:limit]++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ """Download a skill; identifier format: "owner/repo/path/to/skill-dir"."""+ parts = identifier.split("/", 2)+ if len(parts) < 3:+ return None++ repo = f"{parts[0]}/{parts[1]}"+ skill_path = parts[2]+ skill_dir = skill_path.rstrip("/")++ # Resolve the tree FIRST so every byte fetch — SKILL.md included — is+ # pinned to the same revision; an unpinned /contents fetch floats to+ # HEAD and can serve bytes newer than the tree the paths were+ # validated against (TOCTOU). Idempotent + cached.+ tree = self._get_repo_tree(repo)+ pinned_ref = self._tree_revisions.get(repo)+ skill_md = self._fetch_file_content(repo, f"{skill_dir}/SKILL.md", ref=pinned_ref)+ if skill_md is None:+ return None+ referenced = _referenced_support_paths(skill_md)+ if referenced is None:+ return None++ files: Dict[str, Union[str, bytes]] = {"SKILL.md": skill_md}+ if tree is not None:+ branch, entries = tree+ if not self._collect_tree_files(repo, skill_dir, entries, pinned_ref, referenced, files):+ return None+ revision = pinned_ref or branch+ else:+ for rel_path in referenced:+ content = self._fetch_file_bytes(repo, f"{skill_dir}/{rel_path}")+ if content is None:+ logger.warning("Failed to fetch referenced skill support "+ "file; continuing without it: %s", rel_path)+ continue+ files[rel_path] = content+ revision = ""++ return SkillBundle(+ name=skill_dir.split("/")[-1],+ files=files,+ source="github",+ identifier=identifier,+ trust_level=self.trust_level_for(identifier),+ metadata={+ "source_url": (+ f"https://github.com/{repo}/tree/{revision}/{skill_path}"+ if revision else f"https://github.com/{repo}/{skill_path}"+ ),+ "source_revision": revision,+ },+ )++ def _collect_tree_files(+ self,+ repo: str,+ skill_path: str,+ entries: List[dict],+ ref: Optional[str],+ referenced: set,+ files: Dict[str, Union[str, bytes]],+ ) -> bool:+ """Download the FULL skill directory from the pinned tree into ``files``.++ Link-driven fetching silently dropped support files under non-canonical+ dirs (``reference/``, ``agents/``, root LICENSE); everything still goes+ through quarantine + scan, and the scanner sees MORE this way.+ Returns False (bundle rejected) on an unsafe path or a SKILL.md-linked+ path that exists in the tree as a symlink/non-blob — that shape is an+ escape attempt. A linked path that is simply absent is a dangling link+ (repo-only dev tool, prose over-match): warn and install without it.+ """+ prefix = f"{skill_path}/"+ symlinked: set = set()+ for item in entries:+ item_path = item.get("path", "")+ if not item_path.startswith(prefix):+ continue+ rel_path = item_path[len(prefix):]+ if item.get("type") != "blob" or item.get("mode") == "120000":+ symlinked.add(rel_path)+ continue+ if rel_path == "SKILL.md" or _skip_bundle_file(rel_path):+ continue+ try:+ rel_path = _validate_bundle_rel_path(rel_path)+ except ValueError:+ logger.warning("Rejected unsafe file path in skill bundle: %s", item_path)+ return False+ content = self._fetch_file_bytes(repo, item_path, ref=ref)+ if content is None:+ logger.warning("Failed to fetch referenced skill support "+ "file; continuing without it: %s", item_path)+ continue+ files[rel_path] = content+ for rel_path in sorted(referenced):+ if rel_path in symlinked:+ logger.warning(+ "Rejected non-regular referenced file in skill "+ "bundle: %s%s", prefix, rel_path,+ )+ return False+ if rel_path not in files:+ logger.warning(+ "Referenced skill support file is missing; "+ "continuing without it: %s%s",+ prefix, rel_path,+ )+ return True++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ """Fetch just the SKILL.md metadata for preview."""+ parts = identifier.split("/", 2)+ if len(parts) < 3:+ return None++ repo = f"{parts[0]}/{parts[1]}"+ skill_path = parts[2].rstrip("/")++ content = self._fetch_file_content(repo, f"{skill_path}/SKILL.md")+ if not content:+ return None++ fm = _parse_frontmatter(content)+ tags = _hermes_tags(fm)+ if not tags:+ raw_tags = fm.get("tags", [])+ tags = raw_tags if isinstance(raw_tags, list) else []++ provider = github_provider_for(repo)+ return SkillMeta(+ name=fm.get("name", skill_path.split("/")[-1]),+ description=str(fm.get("description", "")),+ source="github",+ identifier=identifier,+ trust_level=self.trust_level_for(identifier),+ repo=repo,+ path=skill_path,+ tags=[str(t) for t in tags],+ extra={"provider": provider} if provider else {},+ )++ # -- Internal helpers --++ def _list_skills_in_repo(self, repo: str, path: str) -> List[SkillMeta]:+ """List skill directories in a GitHub repo path, using cached index."""+ cache_key = f"{repo}_{path}".replace("/", "_").replace(" ", "_")+ cached = self._read_cache(cache_key)+ if cached is not None:+ return [SkillMeta(**s) for s in cached]++ url = f"https://api.github.com/repos/{repo}/contents/{path.rstrip('/')}"+ resp = self._github_get(url)+ if resp is None or resp.status_code != 200:+ return []++ entries = resp.json()+ if not isinstance(entries, list):+ return []++ skills: List[SkillMeta] = []+ groupings = self._get_skillsh_groupings(repo)+ prefix = path.rstrip("/")+ for entry in entries:+ if entry.get("type") != "dir":+ continue+ dir_name = entry["name"]+ if dir_name.startswith((".", "_")):+ continue+ meta = self.inspect(f"{repo}/{prefix}/{dir_name}" if prefix else f"{repo}/{dir_name}")+ if meta:+ if groupings:+ category = groupings.get(meta.name) or groupings.get(dir_name)+ if category:+ meta.extra["category"] = category+ skills.append(meta)++ self._write_cache(cache_key, [_skill_meta_to_dict(s) for s in skills])+ return skills++ def _get_repo_tree(self, repo: str) -> Optional[Tuple[str, List[dict]]]:+ """Cached ``(default_branch, tree_entries)`` for a repo, or None.++ One install may need the tree several times; caching saves the+ ``GET /repos/{repo}`` + ``GET .../git/trees/{branch}`` pair each time+ (~12 of the 60/hr unauthenticated budget before).+ """+ if repo in self._tree_cache:+ return self._tree_cache[repo]++ headers = self.auth.get_headers()++ try:+ resp = httpx.get(+ f"https://api.github.com/repos/{repo}",+ headers=headers, timeout=15, follow_redirects=True,+ )+ if resp.status_code != 200:+ self._check_rate_limit_response(resp)+ return None+ default_branch = resp.json().get("default_branch", "main")+ except (httpx.HTTPError, ValueError):+ return None++ try:+ resp = httpx.get(+ f"https://api.github.com/repos/{repo}/git/trees/{default_branch}",+ params={"recursive": "1"},+ headers=headers, timeout=30, follow_redirects=True,+ )+ if resp.status_code != 200:+ self._check_rate_limit_response(resp)+ return None+ tree_data = resp.json()+ if tree_data.get("truncated"):+ logger.debug("Git tree truncated for %s, cannot cache", repo)+ return None+ except (httpx.HTTPError, ValueError):+ return None++ entries = tree_data.get("tree", [])+ revision = tree_data.get("sha")+ if isinstance(revision, str) and revision:+ self._tree_revisions[repo] = revision+ self._tree_cache[repo] = (default_branch, entries)+ return (default_branch, entries)++ def _check_rate_limit_response(self, resp: httpx.Response) -> None:+ """Flag the instance as rate-limited when GitHub returns 403 + exhausted quota."""+ if _is_rate_limit_response(resp):+ self._rate_limited = True+ logger.warning(+ "GitHub API rate limit exhausted (unauthenticated: 60 req/hr). "+ "Set GITHUB_TOKEN or install the gh CLI to raise the limit to 5,000/hr."+ )++ def _github_get(+ self,+ url: str,+ *,+ params: Optional[Dict] = None,+ headers: Optional[Dict] = None,+ timeout: float = 15.0,+ max_retries: int = 3,+ ) -> Optional[httpx.Response]:+ """GET against the GitHub API with retry/backoff on transient failures.++ Returns the final response (caller inspects status) or None when every+ attempt raised a transport error. Retries rate-limit 403/429 (waiting+ until ``Retry-After``/``X-RateLimit-Reset`` when present, capped 60s —+ one shared limit zeroes every GitHub tap at once during an index build),+ 5xx, and transport errors with exponential backoff. Terminal rate-limit+ exhaustion flags the instance so an index build fails loud instead of+ silently shipping zero GitHub skills.+ """+ hdrs = headers if headers is not None else self.auth.get_headers()+ backoff = 1.0+ last_resp: Optional[httpx.Response] = None+ for attempt in range(max_retries):+ last_attempt = attempt >= max_retries - 1+ try:+ resp = httpx.get(+ url, params=params, headers=hdrs,+ timeout=timeout, follow_redirects=True,+ )+ except httpx.HTTPError as e:+ logger.debug("GitHub GET %s failed (attempt %d/%d): %s",+ url, attempt + 1, max_retries, e)+ if last_attempt:+ return None+ time.sleep(backoff)+ backoff = min(backoff * 2, 30.0)+ continue++ last_resp = resp+ if resp.status_code == 200:+ return resp++ if resp.status_code in (403, 429):+ if not _is_rate_limit_response(resp) or last_attempt:+ self._check_rate_limit_response(resp)+ return resp+ wait = backoff+ reset = resp.headers.get("X-RateLimit-Reset", "")+ retry_after = resp.headers.get("Retry-After", "")+ if retry_after.isdigit():+ wait = min(float(retry_after), 60.0)+ elif reset.isdigit():+ delta = float(reset) - time.time()+ if 0 < delta <= 60.0:+ wait = delta+ logger.debug(+ "GitHub rate limited on %s, waiting %.1fs (attempt %d/%d)",+ url, wait, attempt + 1, max_retries,+ )+ time.sleep(wait)+ backoff = min(backoff * 2, 30.0)+ continue++ if 500 <= resp.status_code < 600 and not last_attempt:+ time.sleep(backoff)+ backoff = min(backoff * 2, 30.0)+ continue+ return resp++ return last_resp++ def _find_skill_in_repo_tree(self, repo: str, skill_name: str) -> Optional[str]:+ """Locate ``<skill_name>/SKILL.md`` anywhere in the repo tree (one API call).++ Returns the full identifier (``repo/path/to/skill``) or None.+ """+ cached = self._get_repo_tree(repo)+ if cached is None:+ return None+ _default_branch, tree_entries = cached++ skill_md_suffix = f"/{skill_name}/SKILL.md"+ for entry in tree_entries:+ if entry.get("type") != "blob":+ continue+ path = entry.get("path", "")+ if path.endswith(skill_md_suffix) or path == f"{skill_name}/SKILL.md":+ return f"{repo}/{path[: -len('/SKILL.md')]}"++ return None++ def _fetch_file_content(+ self, repo: str, path: str, ref: Optional[str] = None+ ) -> Optional[str]:+ """Fetch a single text file from GitHub (None on miss or non-UTF-8)."""+ content = self._fetch_file_bytes(repo, path, ref=ref)+ if content is None:+ return None+ try:+ return content.decode("utf-8")+ except UnicodeDecodeError:+ return None++ def _fetch_file_bytes(+ self, repo: str, path: str, ref: Optional[str] = None+ ) -> Optional[bytes]:+ """Fetch exact file bytes. ``ref`` pins to a tree SHA (see ``fetch`` on+ the TOCTOU); None keeps the legacy unpinned behavior."""+ encoded_path = quote(path, safe="/")+ url = f"https://api.github.com/repos/{repo}/contents/{encoded_path}"+ resp = self._github_get(+ url,+ params={"ref": ref} if ref else None,+ headers={**self.auth.get_headers(), "Accept": "application/vnd.github.v3.raw"},+ )+ if resp is not None and resp.status_code == 200:+ return resp.content+ return None++ def _get_skillsh_groupings(self, repo: str) -> Optional[Dict[str, str]]:+ """Repo-root ``skills.sh.json`` groupings flattened to ``{skill_name: title}``.++ ``skills.sh.json`` is a cross-ecosystem standard+ (``$schema: https://skills.sh/schemas/skills.sh.schema.json``); any tap+ shipping it gets category pills for free. None when absent/unparsable.+ Cached per repo on the instance.+ """+ if repo in self._skillsh_groupings:+ return self._skillsh_groupings[repo]++ content = self._fetch_file_content(repo, "skills.sh.json")+ groupings = self._parse_skillsh_groupings(content) if content else None+ self._skillsh_groupings[repo] = groupings+ return groupings++ @staticmethod+ def _parse_skillsh_groupings(content: str) -> Optional[Dict[str, str]]:+ """Flatten ``{"groupings": [{"title", "skills": [...]}]}``; None if not usable."""+ try:+ data = json.loads(content)+ except (json.JSONDecodeError, TypeError):+ return None+ if not isinstance(data, dict):+ return None+ groupings = data.get("groupings")+ if not isinstance(groupings, list):+ return None++ mapping: Dict[str, str] = {}+ for group in groupings:+ if not isinstance(group, dict):+ continue+ title = group.get("title")+ members = group.get("skills")+ if not isinstance(title, str) or not isinstance(members, list):+ continue+ for member in members:+ if isinstance(member, str) and member:+ mapping.setdefault(member, title) # first grouping wins+ return mapping++ def _read_cache(self, key: str) -> Optional[list]:+ return hub()._read_index_cache(key)++ def _write_cache(self, key: str, data: list) -> None:+ hub()._write_index_cache(key, data)diff --git a/tools/skills_hub_models.py b/tools/skills_hub_models.pynew file mode 100644index 00000000000..aa418105539--- /dev/null+++ b/tools/skills_hub_models.py@@ -0,0 +1,329 @@+"""Skills Hub data models, path validators, and SKILL.md helpers.++Leaf module (no imports from tools.skills_hub) so every source adapter module+can import it at top level without cycles.+"""++import re+from abc import ABC, abstractmethod+from dataclasses import dataclass, field+from pathlib import PurePosixPath+from typing import Any, Dict, Iterable, List, Optional, Union+from urllib.parse import unquote, urlsplit++import yaml+++def hub():+ """``tools.skills_hub`` resolved at call time.++ Its cache / HTTP / index helpers are the test-patch targets+ (``patch("tools.skills_hub._read_index_cache")`` ...), so adapters look+ them up through the module on every call instead of binding at import.+ """+ import tools.skills_hub as mod+ return mod+++@dataclass+class SkillMeta:+ """Minimal metadata returned by search results."""+ name: str+ description: str+ source: str # "official", "github", "clawhub", "lobehub"+ identifier: str # source-specific ID (e.g. "openai/skills/skill-creator")+ trust_level: str # "builtin" | "trusted" | "community"+ repo: Optional[str] = None+ path: Optional[str] = None+ tags: List[str] = field(default_factory=list)+ extra: Dict[str, Any] = field(default_factory=dict)+++@dataclass+class SkillBundle:+ """A downloaded skill ready for quarantine/scanning/installation."""+ name: str+ files: Dict[str, Union[str, bytes]] # relative_path -> file content+ source: str+ identifier: str+ trust_level: str+ metadata: Dict[str, Any] = field(default_factory=dict)+++def _skill_meta_to_dict(meta: SkillMeta) -> dict:+ """Convert a SkillMeta to a dict for caching."""+ return dict(vars(meta))+++def _cached_metas(key: str) -> Optional[List[SkillMeta]]:+ """SkillMeta list from the shared index cache, or None on miss/expiry."""+ cached = hub()._read_index_cache(key)+ return None if cached is None else [SkillMeta(**item) for item in cached]+++def _cache_metas(key: str, metas: List[SkillMeta]) -> None:+ hub()._write_index_cache(key, [_skill_meta_to_dict(m) for m in metas])+++def _matches_query(query_lower: str, *fields: Any) -> bool:+ """Case-insensitive substring match of ``query_lower`` against joined fields+ (lists are space-joined; an empty query matches everything)."""+ parts = [" ".join(str(t) for t in f) if isinstance(f, list) else str(f) for f in fields]+ return query_lower in " ".join(parts).lower()+++TRUST_RANK = {"builtin": 2, "trusted": 1, "community": 0}+++def _dedupe_by_trust(results: Iterable[SkillMeta]) -> List[SkillMeta]:+ """Dedupe by identifier, keeping the higher-trust copy (first wins on ties).++ identifier is unique per skill; name is not — two taps can publish+ same-named skills, and browse-sh reuses task names across sites.+ """+ seen: Dict[str, SkillMeta] = {}+ for r in results:+ kept = seen.get(r.identifier)+ if kept is None or TRUST_RANK.get(r.trust_level, 0) > TRUST_RANK.get(kept.trust_level, 0):+ seen[r.identifier] = r+ return list(seen.values())+++class SkillSource(ABC):+ """Abstract base for all skill registry adapters."""++ @abstractmethod+ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ """Search for skills matching a query string."""++ @abstractmethod+ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ """Download a skill bundle by identifier."""++ @abstractmethod+ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ """Fetch metadata for a skill without downloading all files."""++ @abstractmethod+ def source_id(self) -> str:+ """Unique identifier for this source (e.g. 'github', 'clawhub')."""++ def trust_level_for(self, identifier: str) -> str:+ return "community"+++class GuardedFetchMixin:+ """SSRF/policy-guarded GETs, routed through ``tools.skills_hub`` (test-patchable)."""++ @staticmethod+ def _fetch_text(url: str) -> Optional[str]:+ resp = hub()._guarded_http_get(url, timeout=20)+ return resp.text if resp is not None and resp.status_code == 200 else None++ @staticmethod+ def _fetch_bytes(url: str) -> Optional[bytes]:+ resp = hub()._guarded_http_get(url, timeout=20)+ return resp.content if resp is not None and resp.status_code == 200 else None+++# ---------------------------------------------------------------------------+# SKILL.md frontmatter+# ---------------------------------------------------------------------------++def _parse_frontmatter(content: str) -> dict:+ """Parse YAML frontmatter from SKILL.md content ({} when absent/invalid)."""+ content = content.lstrip("\ufeff") # tolerate UTF-8 BOM (Windows editors)+ if not content.startswith("---"):+ return {}+ match = re.search(r'\n---\s*\n', content[3:])+ if not match:+ return {}+ yaml_text = content[3:match.start() + 3]+ try:+ parsed = yaml.safe_load(yaml_text)+ return parsed if isinstance(parsed, dict) else {}+ except yaml.YAMLError:+ return {}+++def _hermes_tags(fm: dict) -> Any:+ """``metadata.hermes.tags`` from parsed frontmatter, or ``[]`` (unvalidated type)."""+ metadata = fm.get("metadata", {})+ if isinstance(metadata, dict):+ hermes_meta = metadata.get("hermes", {})+ if isinstance(hermes_meta, dict):+ return hermes_meta.get("tags", [])+ return []+++def source_url_for_bundle(bundle: SkillBundle) -> str:+ """Best available human-facing immutable-source provenance URL."""+ explicit = bundle.metadata.get("source_url") or bundle.metadata.get("url")+ if explicit:+ return str(explicit)+ if bundle.source == "github":+ parts = bundle.identifier.split("/", 2)+ if len(parts) >= 2:+ suffix = f"/tree/main/{parts[2]}" if len(parts) == 3 else ""+ return f"https://github.com/{parts[0]}/{parts[1]}{suffix}"+ return bundle.identifier+++# ---------------------------------------------------------------------------+# Bundle path validation+# ---------------------------------------------------------------------------++def _normalize_bundle_path(path_value: str, *, field_name: str, allow_nested: bool) -> str:+ """Normalize and validate bundle-controlled paths before touching disk."""+ if not isinstance(path_value, str):+ raise ValueError(f"Unsafe {field_name}: expected a string")++ raw = path_value.strip()+ if not raw:+ raise ValueError(f"Unsafe {field_name}: empty path")++ normalized = raw.replace("\\", "/")+ path = PurePosixPath(normalized)+ parts = [part for part in path.parts if part not in {"", "."}]++ # A colon in any component is rejected: on Windows it marks a drive+ # (``C:foo``) or an NTFS Alternate Data Stream (``file.py:payload`` writes+ # scanner-invisible bytes); ``/`` is the only legal separator once normalized.+ if (+ normalized.startswith("/") or path.is_absolute()+ or not parts or any(part == ".." for part in parts)+ or any(":" in part for part in parts)+ or (not allow_nested and len(parts) != 1)+ ):+ raise ValueError(f"Unsafe {field_name}: {path_value}")++ return "/".join(parts)+++def _validate_skill_name(name: str) -> str:+ return _normalize_bundle_path(name, field_name="skill name", allow_nested=False)+++def _validate_install_parent_path(category: str) -> str:+ return _normalize_bundle_path(category, field_name="install parent path", allow_nested=True)+++def _validate_bundle_rel_path(rel_path: str) -> str:+ return _normalize_bundle_path(rel_path, field_name="bundle file path", allow_nested=True)+++def _normalize_lock_install_path(install_path: str, skill_name: str) -> str:+ """Validate a lock-file ``install_path`` (the ``uninstall_skill`` rmtree target).++ Must be relative, traversal-free, and end with ``<skill_name>`` — nested+ official skills legitimately live at ``mlops/training/<skill_name>``; an+ empty/``"."``/absolute/mismatched entry could point rmtree at the whole+ ``skills/`` tree or outside it.+ """+ safe_skill_name = _validate_skill_name(skill_name)+ normalized = _normalize_bundle_path(install_path, field_name="install path", allow_nested=True)+ if normalized.split("/")[-1] != safe_skill_name:+ raise ValueError(f"Unsafe install path: {install_path}")+ return normalized+++# ---------------------------------------------------------------------------+# Referenced support-file extraction from SKILL.md+# ---------------------------------------------------------------------------++_ALLOWED_SUPPORT_DIRS = frozenset({"references", "templates", "scripts", "assets", "examples"})+_LOCAL_LINK_RE = re.compile(+ r"(?:\]\(|`|(?:^|[\s\"']))((?:references|templates|scripts|assets|examples)/[^\s)`\"'<>]+)",+ re.MULTILINE,+)+_SUSPICIOUS_LOCAL_REF_RE = re.compile(+ r"(?:references|templates|scripts|assets|examples)/(?:[^\s)`\"'<>]*/)?\.\.(?:/|$)"+)+_VALUELESS_QUERY_FLAG_RE = re.compile(r"(?:[A-Za-z0-9_~-]|%[0-9A-Fa-f]{2})+\Z")+# Same-directory links (``](./FILE.ext)`` / ``](FILE.ext)``): siblings of SKILL.md+# the document links explicitly (e.g. ./CONTEXT-FORMAT.md). Dropping them made the+# install "succeed" with unresolved links. The extension requirement keeps prose+# words out; support-dir links stay on _LOCAL_LINK_RE.+_SAMEDIR_LINK_RE = re.compile(r"\]\(([^)\s\"'<>]+)")+_SAMEDIR_NAME_RE = re.compile(r"^(?:\./)?[A-Za-z0-9][A-Za-z0-9._-]*$")+++def _query_is_concrete(query: str) -> bool:+ """Whether a URL query is real URL syntax rather than glob prose.++ A non-empty ``key=value`` part is always concrete. Valueless flags are+ accepted only when RFC 3986 unreserved-token shaped (percent escapes ok);+ ``.``, brackets and extra ``?`` are excluded because ``?x.md`` / ``?.md``+ is indistinguishable from a single-char glob finishing a filename in prose.+ """+ return all(+ ("=" in part and bool(part.split("=", 1)[0]))+ or bool(_VALUELESS_QUERY_FLAG_RE.fullmatch(part))+ for part in query.split("&")+ )+++def _referenced_support_paths(skill_md: str) -> Optional[set[str]]:+ """Extract safe referenced paths; return None on a traversal attempt (fail closed)."""+ normalized = skill_md.replace("\\", "/")+ if _SUSPICIOUS_LOCAL_REF_RE.search(normalized):+ return None+ paths: set[str] = set()+ for match in _LOCAL_LINK_RE.finditer(normalized):+ candidate = match.group(1).rstrip(".,;:")+ if candidate.endswith("?"):+ continue+ parsed = urlsplit(candidate)+ raw = unquote(parsed.path)+ if any(char in raw for char in "*?[]"):+ continue+ if parsed.query and not _query_is_concrete(parsed.query):+ continue+ try:+ safe = _validate_bundle_rel_path(raw)+ except ValueError:+ return None+ if safe.split("/", 1)[0] in _ALLOWED_SUPPORT_DIRS:+ # Prose placeholders (``references/type-<name>.md``, truncated at+ # ``<`` to ``references/type-``) are instructions, not files: a+ # basename ending in a separator is skipped. No extension+ # requirement — ``references/LICENSE`` is legitimate.+ base = safe.rsplit("/", 1)[-1]+ if re.search(r"[*?<>]", safe) or not re.search(r"[A-Za-z0-9]$", base):+ continue+ paths.add(safe)+ for match in _SAMEDIR_LINK_RE.finditer(normalized):+ raw = match.group(1).rstrip(".,;:")+ # Canonicalize like the support-dir branch (drop query/fragment,+ # percent-decode), then strip a leading ``./``.+ name = unquote(urlsplit(raw).path)+ name = name[2:] if name.startswith("./") else name+ # External URLs, anchors, mailto and site-absolute targets are not+ # same-directory file links.+ if not name or "://" in raw or raw.startswith(("mailto:", "#", "/")):+ continue+ if name.startswith(".."):+ return None+ # Only unambiguous file links: an extension, no internal slash, never+ # SKILL.md itself (casefolded — a ``skill.md`` entry would collide with+ # the bundle root on macOS/Windows; skipped, not merged).+ if "/" in name or name.casefold() == "skill.md" or "." not in name.lstrip("."):+ continue+ if not _SAMEDIR_NAME_RE.match(name):+ continue+ try:+ safe = _validate_bundle_rel_path(name)+ except ValueError:+ return None+ paths.add(safe)+ # Case-folded collisions among accepted same-dir names (``A.md`` + ``a.md``)+ # would collide on install — drop the pair rather than guess.+ folded: dict[str, str] = {}+ for p in sorted(paths):+ key = p.casefold()+ if key in folded:+ paths.discard(folded[key])+ paths.discard(p)+ else:+ folded[key] = p+ return pathsdiff --git a/tools/skills_hub_official.py b/tools/skills_hub_official.pynew file mode 100644index 00000000000..d6cd9ccc1a6--- /dev/null+++ b/tools/skills_hub_official.py@@ -0,0 +1,541 @@+"""Skills Hub official sources: repo-shipped optional skills and the centralized Hermes index."""++import logging+from pathlib import Path, PurePosixPath+from typing import Dict, List, Optional, Tuple, Union++from agent.skill_utils import is_excluded_skill_path+from tools.skills_hub_github import GitHubAuth, GitHubSource, _skip_bundle_file+from tools.skills_hub_models import (+ SkillBundle, SkillMeta, SkillSource, _hermes_tags, _matches_query, _parse_frontmatter, hub,+)++logger = logging.getLogger("tools.skills_hub")++# Identifier prefixes stripped when matching index entries loosely.+_INDEX_ID_PREFIXES = ("skills-sh/", "skills.sh/", "official/", "github/", "clawhub/")+++def _strip_prefix(value: str, prefixes) -> str:+ for prefix in prefixes:+ if value.startswith(prefix):+ return value[len(prefix):]+ return value+++def _clean_rel_parts(path: str) -> Optional[List[str]]:+ """Split a relative path, dropping ``.``/empty parts; None on traversal or empty."""+ parts = [p for p in path.split("/") if p not in ("", ".")]+ if not parts or any(p == ".." for p in parts):+ return None+ return parts+++# ---------------------------------------------------------------------------+# Official optional skills source adapter+# ---------------------------------------------------------------------------++class OptionalSkillSource(SkillSource):+ """Skills from the repo's ``optional-skills/`` directory.++ Official (Nous-maintained) but not activated by default — absent from the+ system prompt and not copied to ~/.hermes/skills/ at setup. Discoverable+ via the Skills Hub as source "official" with "builtin" trust.+ """++ OFFICIAL_REPO = "NousResearch/hermes-agent"+ OPTIONAL_SKILLS_PREFIX = "optional-skills"++ _parse_frontmatter = staticmethod(_parse_frontmatter)++ def __init__(self, auth: Optional[GitHubAuth] = None):+ from hermes_constants import get_optional_skills_dir++ self._optional_dir = get_optional_skills_dir(+ Path(__file__).parent.parent / "optional-skills"+ )+ self._auth = auth+ # GitHubSource for the live-repo fallback, created only when a skill is+ # missing from the local checkout.+ self._github: Optional[GitHubSource] = None+ # "category/skill" -> True from the live repo tree; None = not fetched yet.+ self._remote_dirs: Optional[Dict[str, bool]] = None++ def source_id(self) -> str:+ return "official"++ def trust_level_for(self, identifier: str) -> str:+ return "builtin"++ @staticmethod+ def _rel(identifier: str) -> str:+ return identifier.split("/", 1)[-1] if identifier.startswith("official/") else identifier++ def _remote_meta(self, rel_dir: str) -> SkillMeta:+ """Placeholder meta for a skill that exists on live main but not locally."""+ return SkillMeta(+ name=rel_dir.rsplit("/", 1)[-1],+ description="Official optional skill (from live repo; run install to fetch)",+ source="official",+ identifier=f"official/{rel_dir}",+ trust_level="builtin",+ repo=self.OFFICIAL_REPO,+ path=f"{self.OPTIONAL_SKILLS_PREFIX}/{rel_dir}",+ tags=[],+ )++ # -- search -----------------------------------------------------------++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ results: List[SkillMeta] = []+ query_lower = query.lower()++ local_rels: set = set()+ for meta in self._scan_all():+ local_rels.add(meta.identifier.split("/", 1)[-1] if meta.identifier else "")+ if _matches_query(query_lower, meta.name, meta.description, meta.tags):+ results.append(meta)+ if len(results) >= limit:+ break++ # Also surface skills that landed on live main after this install was cut.+ if len(results) < limit:+ for rel_dir in sorted(self._list_remote_skill_dirs()):+ if rel_dir in local_rels or (query_lower and query_lower not in rel_dir.lower()):+ continue+ results.append(self._remote_meta(rel_dir))+ if len(results) >= limit:+ break++ return results++ # -- fetch ------------------------------------------------------------++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ # identifier format: "official/category/skill" or "official/skill"+ rel = self._rel(identifier)+ skill_dir = self._optional_dir / rel++ # Guard against path traversal (e.g. "official/../../etc")+ try:+ resolved = skill_dir.resolve()+ optional_root = self._optional_dir.resolve()+ if not resolved.is_relative_to(optional_root):+ return None+ except (OSError, ValueError):+ return None++ if resolved.is_dir():+ skill_dir = resolved+ else:+ # Try by bare skill name; if still absent, the skill may have+ # landed on main after this install was cut — use the live repo.+ skill_dir = self._find_skill_dir(rel.rsplit("/", 1)[-1])+ if not skill_dir:+ return self._fetch_from_live_repo(rel)++ rel_id = skill_dir.resolve().relative_to(optional_root).as_posix()++ # Catalog stubs point at the real skill in an upstream-maintained repo+ # (metadata.hermes.upstream); install pulls the live content from there.+ upstream = self._upstream_pointer(skill_dir)+ if upstream is not None:+ return self._fetch_from_upstream(upstream, rel_id)++ files: Dict[str, Union[str, bytes]] = {}+ for f in skill_dir.rglob("*"):+ if f.is_file() and not _skip_bundle_file(f.relative_to(skill_dir).as_posix()):+ try:+ files[str(f.relative_to(skill_dir))] = f.read_bytes()+ except OSError:+ continue++ if not files:+ return None++ return SkillBundle(+ name=skill_dir.name,+ files=files,+ source="official",+ identifier=f"official/{rel_id}",+ trust_level="builtin",+ )++ # -- inspect ----------------------------------------------------------++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ skill_name = self._rel(identifier).rsplit("/", 1)[-1]++ for meta in self._scan_all():+ if meta.name == skill_name:+ return meta++ # Not in the local checkout — check live main.+ matches = self._remote_matches(skill_name)+ if len(matches) == 1:+ return self._remote_meta(matches[0])+ return None++ # -- catalog ----------------------------------------------------------++ def list_local(self) -> List[SkillMeta]:+ """Every optional skill in the local checkout, with frontmatter metadata+ (backs the dashboard/desktop "built-in optional skills" catalog)."""+ return self._scan_all()++ # -- internal helpers -------------------------------------------------++ def _get_github(self) -> GitHubSource:+ if self._github is None:+ self._github = GitHubSource(auth=self._auth or GitHubAuth())+ return self._github++ def _remote_matches(self, name: str) -> List[str]:+ return [d for d in self._list_remote_skill_dirs() if d.rsplit("/", 1)[-1] == name]++ def _fetch_from_live_repo(self, rel: str) -> Optional[SkillBundle]:+ """Fetch an optional skill straight from the live default branch.++ Local installs lag ``main``; rather than demanding ``hermes update``+ first, resolve against the live repo. ``rel`` is ``category/skill``+ (used verbatim) or a bare skill name (located via the repo tree).+ """+ parts = _clean_rel_parts(rel.strip("/"))+ if parts is None:+ return None+ rel = "/".join(parts)++ github = self._get_github()+ if rel not in self._list_remote_skill_dirs():+ # Bare name (or stale category) — locate by final path segment.+ matches = self._remote_matches(parts[-1])+ if len(matches) != 1:+ return None+ rel = matches[0]+ repo_path = f"{self.OPTIONAL_SKILLS_PREFIX}/{rel}"++ # Download the FULL directory byte-exact (root-level install scripts,+ # LICENSE, tests/). GitHubSource.fetch() would only pull SKILL.md ++ # referenced support dirs.+ tree = github._get_repo_tree(self.OFFICIAL_REPO)+ if tree is None:+ return None+ _branch, entries = tree+ prefix = f"{repo_path}/"+ files: Dict[str, Union[str, bytes]] = {}+ for item in entries:+ item_path = item.get("path", "")+ if (+ item.get("type") != "blob" or item.get("mode") == "120000"+ or not item_path.startswith(prefix)+ ):+ continue+ rel_file = item_path[len(prefix):]+ if _skip_bundle_file(rel_file):+ continue+ content = github._fetch_file_bytes(self.OFFICIAL_REPO, item_path)+ if content is None:+ logger.warning("Live-repo optional skill fetch failed for %s", item_path)+ return None+ files[rel_file] = content++ if "SKILL.md" not in files:+ return None++ # Live-fetched catalog stubs redirect the same way local ones do.+ upstream = self._upstream_pointer_from_content(files["SKILL.md"])+ if upstream is not None:+ return self._fetch_from_upstream(upstream, rel)++ logger.info("Optional skill '%s' fetched from live repo (not in local checkout)", rel)+ return SkillBundle(+ name=rel.rsplit("/", 1)[-1],+ files=files,+ source="official",+ identifier=f"official/{rel}",+ trust_level="builtin",+ )++ def _list_remote_skill_dirs(self) -> Dict[str, bool]:+ """``category/skill`` dirs under optional-skills/ on live main.++ One repo-tree call (cached per-process by GitHubSource + the on-disk+ index cache). {} when the network/API is unavailable — callers degrade+ to local-only.+ """+ if self._remote_dirs is not None:+ return self._remote_dirs++ cache_key = "official_optional_dirs"+ cached = hub()._read_index_cache(cache_key)+ if isinstance(cached, dict) and cached:+ self._remote_dirs = cached+ return cached++ dirs: Dict[str, bool] = {}+ tree = self._get_github()._get_repo_tree(self.OFFICIAL_REPO)+ if tree is not None:+ _branch, entries = tree+ prefix = f"{self.OPTIONAL_SKILLS_PREFIX}/"+ suffix = "/SKILL.md"+ for item in entries:+ path = item.get("path", "")+ if item.get("type") == "blob" and path.startswith(prefix) and path.endswith(suffix):+ rel_dir = path[len(prefix):-len(suffix)]+ if rel_dir and not is_excluded_skill_path(PurePosixPath(rel_dir + suffix)):+ dirs[rel_dir] = True+ if dirs:+ hub()._write_index_cache(cache_key, dirs)++ self._remote_dirs = dirs+ return dirs++ def _upstream_pointer(self, skill_dir: Path) -> Optional[Dict[str, str]]:+ """Upstream pointer for a catalog-stub skill dir, or None for vendored skills.++ A stub declares ``metadata.hermes.upstream: {repo: owner/name, path: ...}``+ in its SKILL.md frontmatter.+ """+ try:+ content = (skill_dir / "SKILL.md").read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError):+ return None+ return self._upstream_pointer_from_content(content)++ def _upstream_pointer_from_content(self, content: Union[str, bytes]) -> Optional[Dict[str, str]]:+ """Parse ``metadata.hermes.upstream`` out of SKILL.md content."""+ if isinstance(content, bytes):+ try:+ content = content.decode("utf-8")+ except UnicodeDecodeError:+ return None+ meta_block = _parse_frontmatter(content).get("metadata")+ hermes_meta = meta_block.get("hermes") if isinstance(meta_block, dict) else None+ upstream = hermes_meta.get("upstream") if isinstance(hermes_meta, dict) else None+ if not isinstance(upstream, dict):+ return None+ repo = str(upstream.get("repo", "")).strip().strip("/")+ path = str(upstream.get("path", "")).strip().strip("/")+ # repo must be exactly owner/name; path must be a clean relative path.+ if not repo or repo.count("/") != 1 or not path:+ return None+ parts = _clean_rel_parts(path)+ if parts is None:+ return None+ return {"repo": repo, "path": "/".join(parts)}++ def _fetch_from_upstream(self, upstream: Dict[str, str], rel_id: str) -> Optional[SkillBundle]:+ """Fetch an upstream-maintained optional skill via GitHubSource.fetch()+ (full-tree download, symlink/unsafe-path rejection, quarantine + scan+ downstream) and re-label it as an official catalog entry."""+ bundle = self._get_github().fetch(f"{upstream['repo']}/{upstream['path']}")+ if bundle is None:+ logger.warning(+ "Upstream fetch failed for optional skill %s (%s:%s)",+ rel_id, upstream["repo"], upstream["path"],+ )+ return None+ return SkillBundle(+ name=bundle.name,+ files=bundle.files,+ source="official",+ identifier=f"official/{rel_id}",+ # Curated endorsement, but the content is live third-party:+ # "trusted", not "builtin", so a dangerous scan verdict still blocks.+ trust_level="trusted",+ metadata={+ **bundle.metadata,+ "upstream_repo": upstream["repo"],+ "upstream_path": upstream["path"],+ },+ )++ def _local_skill_mds(self):+ if not self._optional_dir.is_dir():+ return+ for skill_md in sorted(self._optional_dir.rglob("SKILL.md")):+ if not is_excluded_skill_path(+ skill_md.relative_to(self._optional_dir), root=self._optional_dir+ ):+ yield skill_md++ def _find_skill_dir(self, name: str) -> Optional[Path]:+ """Find a skill directory by name anywhere in optional-skills/."""+ for skill_md in self._local_skill_mds():+ if skill_md.parent.name == name:+ return skill_md.parent+ return None++ def _scan_all(self) -> List[SkillMeta]:+ """Enumerate all optional skills with metadata."""+ results: List[SkillMeta] = []+ for skill_md in self._local_skill_mds():+ parent = skill_md.parent+ try:+ content = skill_md.read_text(encoding="utf-8")+ except (OSError, UnicodeDecodeError):+ continue++ fm = _parse_frontmatter(content)+ tags = _hermes_tags(fm)+ rel_path = parent.relative_to(self._optional_dir).as_posix()+ results.append(SkillMeta(+ name=fm.get("name", parent.name),+ description=fm.get("description", "")[:200],+ source="official",+ identifier=f"official/{rel_path}",+ trust_level="builtin",+ repo=self.OFFICIAL_REPO,+ # The centralized skills index consumes repo-root-relative paths.+ path=f"optional-skills/{rel_path}",+ tags=tags if isinstance(tags, list) else [],+ ))++ return results+++# ---------------------------------------------------------------------------+# Hermes centralized index source+# ---------------------------------------------------------------------------++class HermesIndexSource(SkillSource):+ """Skill source backed by the centralized Hermes Skills Index.++ A JSON catalog on the docs site, rebuilt daily by CI, with metadata ++ resolved GitHub paths for every skill — search and path discovery cost+ zero GitHub API calls. When unavailable every method returns empty/None+ so downstream sources take over transparently.+ """++ def __init__(self, auth: GitHubAuth):+ self._index: Optional[dict] = None+ self._loaded = False+ self.auth = auth+ self._github: Optional[GitHubSource] = None # only needed for fetch++ def _ensure_loaded(self) -> dict:+ if not self._loaded:+ self._index = hub()._load_hermes_index()+ self._loaded = True+ return self._index or {}++ def _skills(self) -> list:+ return self._ensure_loaded().get("skills", [])++ def _get_github(self) -> GitHubSource:+ if self._github is None:+ self._github = GitHubSource(auth=self.auth)+ return self._github++ def source_id(self) -> str:+ return "hermes-index"++ @property+ def is_available(self) -> bool:+ """Whether the index is loaded and has skills."""+ return bool(self._skills())++ def trust_level_for(self, identifier: str) -> str:+ for skill in self._skills():+ if skill.get("identifier") == identifier:+ return skill.get("trust_level", "community")+ return "community"++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ """Search the cached index (zero API calls).++ Matches name, description, tags, identifier and ``extra.provider`` (so+ ``nvidia`` finds ``NVIDIA/skills/...`` entries stored as source+ "github"). Ranked exact name > name prefix > provider > whole-word >+ name substring > other, index order as tiebreaker — a raw+ break-at-limit slice buried the most relevant skills.+ """+ skills = self._skills()+ if not skills:+ return []++ if not query.strip():+ return [self._to_meta(s) for s in skills[:limit]] # featured / index order++ query_lower = query.lower()+ scored: List[Tuple[int, int, dict]] = []+ for i, s in enumerate(skills):+ name = str(s.get("name", "")).lower()+ provider = str((s.get("extra") or {}).get("provider", "")).lower()+ haystack = " ".join([+ name,+ str(s.get("description", "")).lower(),+ " ".join(str(t).lower() for t in s.get("tags", [])),+ str(s.get("identifier", "")).lower(),+ provider,+ ])+ if query_lower not in haystack:+ continue+ if name == query_lower:+ score = 0+ elif name.startswith(query_lower):+ score = 1+ elif provider == query_lower:+ score = 2+ elif query_lower in name.split() or query_lower in provider.split():+ score = 3+ elif query_lower in name:+ score = 4+ else:+ score = 5+ scored.append((score, i, s))++ scored.sort(key=lambda x: (x[0], x[1]))+ return [self._to_meta(s) for _, _, s in scored[:limit]]++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ """Fetch via the index's ``resolved_github_id`` (skipping the whole+ candidate/discovery chain), falling back to ``repo/path``."""+ entry = self._find_entry(identifier, self._ensure_loaded())+ if not entry:+ return None++ candidates = [entry.get("resolved_github_id")]+ repo, path = entry.get("repo", ""), entry.get("path", "")+ if repo and path:+ candidates.append(f"{repo}/{path}")+ for github_id in candidates:+ if not github_id:+ continue+ bundle = self._get_github().fetch(github_id)+ if bundle:+ bundle.source = entry.get("source", "hermes-index")+ bundle.identifier = identifier+ return bundle+ return None++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ """Return metadata from the index (zero API calls)."""+ entry = self._find_entry(identifier, self._ensure_loaded())+ return self._to_meta(entry) if entry else None++ def _find_entry(self, identifier: str, index: dict) -> Optional[dict]:+ """Exact identifier match first, then match with source prefixes stripped."""+ skills = index.get("skills", [])+ for s in skills:+ if s.get("identifier") == identifier:+ return s+ normalized = _strip_prefix(identifier, _INDEX_ID_PREFIXES)+ for s in skills:+ if _strip_prefix(s.get("identifier", ""), _INDEX_ID_PREFIXES) == normalized:+ return s+ return None++ @staticmethod+ def _to_meta(entry: dict) -> SkillMeta:+ return SkillMeta(+ name=entry.get("name", ""),+ description=entry.get("description", ""),+ source=entry.get("source", "hermes-index"),+ identifier=entry.get("identifier", ""),+ trust_level=entry.get("trust_level", "community"),+ repo=entry.get("repo"),+ path=entry.get("path"),+ tags=entry.get("tags", []),+ extra=entry.get("extra", {}),+ )diff --git a/tools/skills_hub_skillssh.py b/tools/skills_hub_skillssh.pynew file mode 100644index 00000000000..e874f93fccc--- /dev/null+++ b/tools/skills_hub_skillssh.py@@ -0,0 +1,506 @@+"""Skills Hub skills.sh adapter: catalog discovery via skills.sh, content via GitHub."""++import hashlib+import json+import logging+import re+from typing import Any, Dict, List, Optional++import httpx++from tools.skills_hub_github import GitHubAuth, GitHubSource+from tools.skills_hub_models import (+ SkillBundle, SkillMeta, SkillSource, _cache_metas, _cached_metas, hub,+)++logger = logging.getLogger("tools.skills_hub")+++def _strip_html(value: str) -> str:+ return re.sub(r'<[^>]+>', '', value)+++def _dedupe_keep_order(items: List[str]) -> List[str]:+ return list(dict.fromkeys(items))+++class SkillsShSource(SkillSource):+ """Discover skills via skills.sh and fetch content from the underlying GitHub repo."""++ BASE_URL = "https://skills.sh"+ SEARCH_URL = f"{BASE_URL}/api/search"+ # The sitemap is the real catalog source: the homepage only exposes a+ # ~200-entry featured strip; sitemap.xml points at sitemap-skills-N.xml+ # files (10k URLs each) covering the full ~20k+ catalog.+ SITEMAP_INDEX_URL = "https://www.skills.sh/sitemap.xml"+ # skills.sh serves per-skill sitemaps brotli-compressed and httpx's optional+ # brotlicffi backend has a streaming-decode bug on them; asking for gzip+ # only makes the server fall back to gzip/identity on every httpx install.+ _SITEMAP_HEADERS = {"Accept-Encoding": "gzip"}+ _SITEMAP_LOC_RE = re.compile(r"<loc>([^<]+)</loc>", re.IGNORECASE)+ _SITEMAP_SKILL_RE = re.compile(+ r"^https?://(?:www\.)?skills\.sh/(?P<owner>[^/]+)/(?P<repo>[^/]+)/(?P<skill>[^/]+)/?$",+ re.IGNORECASE,+ )+ _SKILL_LINK_RE = re.compile(r'href=["\']/(?P<id>(?!agents/|_next/|api/)[^"\'/]+/[^"\'/]+/[^"\'/]+)["\']')+ _INSTALL_CMD_RE = re.compile(+ r'npx\s+skills\s+add\s+(?P<repo>https?://github\.com/[^\s<]+|[^\s<]+)'+ r'(?:\s+--skill\s+(?P<skill>[^\s<]+))?',+ re.IGNORECASE,+ )+ _PAGE_H1_RE = re.compile(r'<h1[^>]*>(?P<title>.*?)</h1>', re.IGNORECASE | re.DOTALL)+ _PROSE_H1_RE = re.compile(+ r'<div[^>]*class=["\'][^"\']*prose[^"\']*["\'][^>]*>.*?<h1[^>]*>(?P<title>.*?)</h1>',+ re.IGNORECASE | re.DOTALL,+ )+ _PROSE_P_RE = re.compile(+ r'<div[^>]*class=["\'][^"\']*prose[^"\']*["\'][^>]*>.*?<p[^>]*>(?P<body>.*?)</p>',+ re.IGNORECASE | re.DOTALL,+ )+ _WEEKLY_INSTALLS_RE = re.compile(r'Weekly Installs.*?children\\":\\"(?P<count>[0-9.,Kk]+)\\"', re.DOTALL)+ _ID_PREFIX_ALIASES = ("skills-sh/", "skills.sh/", "skils-sh/", "skils.sh/")+ # Standard skill sub-paths tried before any tree/discovery walk.+ _STANDARD_BASE_PATHS = ("skills/", ".agents/skills/", ".claude/skills/")++ _strip_html = staticmethod(_strip_html)++ def __init__(self, auth: GitHubAuth):+ self.auth = auth+ self.github = GitHubSource(auth=auth)++ def source_id(self) -> str:+ return "skills-sh"++ def trust_level_for(self, identifier: str) -> str:+ return self.github.trust_level_for(self._normalize_identifier(identifier))++ def _meta(self, canonical: str, *, name: str, description: str, path: str,+ extra: Optional[Dict[str, Any]] = None) -> SkillMeta:+ repo = "/".join(canonical.split("/", 2)[:2])+ return SkillMeta(+ name=name,+ description=description,+ source="skills.sh",+ identifier=self._wrap_identifier(canonical),+ trust_level=self.github.trust_level_for(canonical),+ repo=repo,+ path=path,+ extra=extra if extra is not None else {},+ )++ def _urls_for(self, canonical: str, repo: str) -> Dict[str, str]:+ return {"detail_url": f"{self.BASE_URL}/{canonical}", "repo_url": f"https://github.com/{repo}"}++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ if not query.strip():+ # Empty query = bulk catalog dump (build_skills_index.py) — walk the sitemap.+ return self._sitemap_catalog(limit)++ cache_key = f"skills_sh_search_{hashlib.md5(f'{query}|{limit}'.encode()).hexdigest()}"+ cached = _cached_metas(cache_key)+ if cached is not None:+ return cached[:limit]++ try:+ resp = httpx.get(self.SEARCH_URL, params={"q": query, "limit": limit}, timeout=20)+ if resp.status_code != 200:+ return []+ data = resp.json()+ except (httpx.HTTPError, json.JSONDecodeError):+ return []++ items = data.get("skills", []) if isinstance(data, dict) else []+ if not isinstance(items, list):+ return []++ results = [m for m in (self._meta_from_search_item(i) for i in items[:limit]) if m]+ _cache_metas(cache_key, results)+ return results++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ canonical = self._normalize_identifier(identifier)+ detail = self._fetch_detail_page(canonical)++ def _relabel(github_id: Optional[str]) -> Optional[SkillBundle]:+ bundle = self.github.fetch(github_id) if github_id else None+ if bundle:+ bundle.source = "skills.sh"+ bundle.identifier = self._wrap_identifier(canonical)+ bundle.metadata.update(self._detail_to_metadata(canonical, detail))+ return bundle or None++ for candidate in self._candidate_identifiers(canonical):+ bundle = _relabel(candidate)+ if bundle:+ return bundle+ return _relabel(self._discover_identifier(canonical, detail=detail))++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ canonical = self._normalize_identifier(identifier)+ detail = self._fetch_detail_page(canonical)+ meta = self._resolve_github_meta(canonical, detail=detail)+ if meta:+ return self._finalize_inspect_meta(meta, canonical, detail)+ return None++ def _sitemap_catalog(self, limit: int) -> List[SkillMeta]:+ """Enumerate the full catalog via the sitemap (cached for the index TTL —+ ~2 MB of XML). Falls back to ``_featured_skills`` when unreachable/empty."""+ cache_key = "skills_sh_sitemap_v1"+ cached = _cached_metas(cache_key)+ if cached is not None:+ return cached[:limit] if limit > 0 else cached++ # Step 1: sitemap index -> per-skill sitemap URLs.+ try:+ resp = httpx.get(self.SITEMAP_INDEX_URL, timeout=20, follow_redirects=True,+ headers=self._SITEMAP_HEADERS)+ if resp.status_code != 200:+ return self._featured_skills(limit)+ skill_sitemap_urls = [+ m.group(1).strip() for m in self._SITEMAP_LOC_RE.finditer(resp.text)+ if "sitemap-skills" in m.group(1)+ ]+ except httpx.HTTPError:+ return self._featured_skills(limit)++ if not skill_sitemap_urls:+ return self._featured_skills(limit)++ # Step 2: collect canonical "owner/repo/skill" IDs from each sitemap.+ seen: set[str] = set()+ results: List[SkillMeta] = []+ for sitemap_url in skill_sitemap_urls:+ try:+ resp = httpx.get(sitemap_url, timeout=30, follow_redirects=True,+ headers=self._SITEMAP_HEADERS)+ if resp.status_code != 200:+ continue+ except httpx.HTTPError:+ continue+ for loc_match in self._SITEMAP_LOC_RE.finditer(resp.text):+ m = self._SITEMAP_SKILL_RE.match(loc_match.group(1).strip())+ if not m:+ continue+ repo = f"{m.group('owner')}/{m.group('repo')}"+ skill_name = m.group("skill")+ canonical = f"{repo}/{skill_name}"+ if canonical in seen:+ continue+ seen.add(canonical)+ results.append(self._meta(+ canonical, name=skill_name,+ description=f"Indexed by skills.sh from {repo}",+ path=skill_name, extra=self._urls_for(canonical, repo),+ ))++ if not results:+ return self._featured_skills(limit)++ _cache_metas(cache_key, results)+ return results[:limit] if limit > 0 else results++ def _featured_skills(self, limit: int) -> List[SkillMeta]:+ cache_key = "skills_sh_featured"+ cached = _cached_metas(cache_key)+ if cached is not None:+ return cached[:limit]++ try:+ resp = httpx.get(self.BASE_URL, timeout=20)+ if resp.status_code != 200:+ return []+ except httpx.HTTPError:+ return []++ seen: set[str] = set()+ results: List[SkillMeta] = []+ for match in self._SKILL_LINK_RE.finditer(resp.text):+ canonical = match.group("id")+ if canonical in seen:+ continue+ seen.add(canonical)+ parts = canonical.split("/", 2)+ if len(parts) < 3:+ continue+ results.append(self._meta(+ canonical, name=parts[2].split("/")[-1],+ description=f"Featured on skills.sh from {parts[0]}/{parts[1]}",+ path=parts[2],+ ))+ if len(results) >= limit:+ break++ _cache_metas(cache_key, results)+ return results++ def _meta_from_search_item(self, item: dict) -> Optional[SkillMeta]:+ if not isinstance(item, dict):+ return None++ canonical = item.get("id")+ repo = item.get("source")+ skill_path = item.get("skillId")+ if not isinstance(canonical, str) or canonical.count("/") < 2:+ if not (isinstance(repo, str) and isinstance(skill_path, str)):+ return None+ canonical = f"{repo}/{skill_path}"++ parts = canonical.split("/", 2)+ if len(parts) < 3:+ return None++ repo = f"{parts[0]}/{parts[1]}"+ skill_path = parts[2]+ installs = item.get("installs")+ installs_label = f" · {int(installs):,} installs" if isinstance(installs, int) else ""++ return self._meta(+ canonical,+ name=str(item.get("name") or skill_path.split("/")[-1]),+ description=f"Indexed by skills.sh from {repo}{installs_label}",+ path=skill_path,+ extra={"installs": installs, **self._urls_for(canonical, repo)},+ )++ def _fetch_detail_page(self, identifier: str) -> Optional[dict]:+ cache_key = f"skills_sh_detail_{hashlib.md5(identifier.encode()).hexdigest()}"+ cached = hub()._read_index_cache(cache_key)+ if isinstance(cached, dict):+ return cached++ try:+ resp = httpx.get(f"{self.BASE_URL}/{identifier}", timeout=20)+ if resp.status_code != 200:+ return None+ except httpx.HTTPError:+ return None++ detail = self._parse_detail_page(identifier, resp.text)+ if detail:+ hub()._write_index_cache(cache_key, detail)+ return detail++ def _parse_detail_page(self, identifier: str, html: str) -> Optional[dict]:+ parts = identifier.split("/", 2)+ if len(parts) < 3:+ return None++ repo = f"{parts[0]}/{parts[1]}"+ install_skill = parts[2]++ install_command = None+ install_match = self._INSTALL_CMD_RE.search(html)+ if install_match:+ install_command = install_match.group(0).strip()+ install_skill = (install_match.group("skill") or install_skill).strip()+ repo = self._extract_repo_slug((install_match.group("repo") or "").strip()) or repo++ return {+ "repo": repo,+ "install_skill": install_skill,+ "page_title": self._extract_first_match(self._PAGE_H1_RE, html),+ "body_title": self._extract_first_match(self._PROSE_H1_RE, html),+ "body_summary": self._extract_first_match(self._PROSE_P_RE, html),+ "weekly_installs": self._extract_weekly_installs(html),+ "install_command": install_command,+ **self._urls_for(identifier, repo),+ "security_audits": self._extract_security_audits(html, identifier),+ }++ def _discover_identifier(self, identifier: str, detail: Optional[dict] = None) -> Optional[str]:+ parts = identifier.split("/", 2)+ if len(parts) < 3:+ return None++ default_repo = f"{parts[0]}/{parts[1]}"+ repo = detail.get("repo", default_repo) if isinstance(detail, dict) else default_repo+ skill_token = parts[2].split("/")[-1]+ tokens = [skill_token]+ if isinstance(detail, dict):+ tokens.extend([+ detail.get("install_skill", ""),+ detail.get("page_title", ""),+ detail.get("body_title", ""),+ ])++ def _match_in(base_path: str) -> Optional[str]:+ try:+ skills = self.github._list_skills_in_repo(repo, base_path)+ except Exception:+ return None+ for meta in skills:+ if self._matches_skill_tokens(meta, tokens):+ return meta.identifier+ return None++ for base_path in self._STANDARD_BASE_PATHS:+ found = _match_in(base_path)+ if found:+ return found++ # One recursive tree lookup before brute-forcing every top-level dir+ # (avoids request bursts on categorized repos like borghei/claude-skills).+ tree_result = self.github._find_skill_in_repo_tree(repo, skill_token)+ if tree_result:+ return tree_result++ # Fallback: scan repo root for directories that might contain skills.+ try:+ resp = httpx.get(f"https://api.github.com/repos/{repo}/contents/",+ headers=self.github.auth.get_headers(),+ timeout=15, follow_redirects=True)+ if resp.status_code == 200:+ entries = resp.json()+ if isinstance(entries, list):+ for entry in entries:+ if entry.get("type") != "dir":+ continue+ dir_name = entry["name"]+ if dir_name.startswith((".", "_")) or dir_name in {"skills", ".agents", ".claude"}:+ continue+ meta = self.github.inspect(f"{repo}/{dir_name}/{skill_token}")+ if meta:+ return meta.identifier+ found = _match_in(dir_name + "/")+ if found:+ return found+ except Exception:+ pass++ return None++ def _resolve_github_meta(self, identifier: str, detail: Optional[dict] = None) -> Optional[SkillMeta]:+ for candidate in self._candidate_identifiers(identifier):+ meta = self.github.inspect(candidate)+ if meta:+ return meta++ resolved = self._discover_identifier(identifier, detail=detail)+ if resolved:+ return self.github.inspect(resolved)+ return None++ def _finalize_inspect_meta(self, meta: SkillMeta, canonical: str, detail: Optional[dict]) -> SkillMeta:+ meta.source = "skills.sh"+ meta.identifier = self._wrap_identifier(canonical)+ meta.trust_level = self.trust_level_for(canonical)+ meta.extra = {**meta.extra, **self._detail_to_metadata(canonical, detail)}++ if isinstance(detail, dict):+ body_summary = detail.get("body_summary")+ weekly_installs = detail.get("weekly_installs")+ if body_summary:+ meta.description = body_summary+ elif meta.description and weekly_installs:+ meta.description = f"{meta.description} · {weekly_installs} weekly installs on skills.sh"+ return meta++ @classmethod+ def _matches_skill_tokens(cls, meta: SkillMeta, skill_tokens: List[str]) -> bool:+ candidates = set()+ candidates.update(cls._token_variants(meta.name))+ candidates.update(cls._token_variants(meta.path))+ candidates.update(cls._token_variants(meta.identifier.split("/", 2)[-1] if meta.identifier else None))+ return any(cls._token_variants(token) & candidates for token in skill_tokens)++ @staticmethod+ def _token_variants(value: Optional[str]) -> set[str]:+ if not value:+ return set()++ plain = _strip_html(str(value)).strip().strip("/").lower()+ if not plain:+ return set()++ base = plain.split("/")[-1]+ sanitized = re.sub(r'[^a-z0-9/_-]+', '-', plain).strip('-')+ sanitized_base = sanitized.split("/")[-1] if sanitized else ""+ slash_tail_clean = base.lstrip('@').split('/')[-1]++ variants = {+ plain,+ plain.replace("_", "-"),+ plain.replace("/", "-"),+ base,+ base.replace("_", "-"),+ sanitized,+ sanitized.replace("/", "-") if sanitized else "",+ sanitized_base,+ slash_tail_clean,+ slash_tail_clean.replace("_", "-"),+ }+ return {v for v in variants if v}++ @staticmethod+ def _extract_repo_slug(repo_value: str) -> Optional[str]:+ repo_value = repo_value.strip()+ if repo_value.startswith("https://github.com/"):+ repo_value = repo_value[len("https://github.com/"):]+ parts = repo_value.strip("/").split("/")+ if len(parts) >= 2:+ return f"{parts[0]}/{parts[1]}"+ return None++ @staticmethod+ def _extract_first_match(pattern: re.Pattern, text: str) -> Optional[str]:+ match = pattern.search(text)+ if not match:+ return None+ value = next((group for group in match.groups() if group), None)+ if value is None:+ return None+ return _strip_html(value).strip() or None++ def _detail_to_metadata(self, canonical: str, detail: Optional[dict]) -> Dict[str, Any]:+ parts = canonical.split("/", 2)+ repo = f"{parts[0]}/{parts[1]}" if len(parts) >= 2 else ""+ metadata = {"detail_url": f"{self.BASE_URL}/{canonical}"}+ if repo:+ metadata["repo_url"] = f"https://github.com/{repo}"+ if isinstance(detail, dict):+ for key in ("weekly_installs", "install_command", "repo_url", "detail_url", "security_audits"):+ value = detail.get(key)+ if value:+ metadata[key] = value+ return metadata++ @classmethod+ def _extract_weekly_installs(cls, html: str) -> Optional[str]:+ match = cls._WEEKLY_INSTALLS_RE.search(html)+ return match.group("count") if match else None++ @staticmethod+ def _extract_security_audits(html: str, identifier: str) -> Dict[str, str]:+ audits: Dict[str, str] = {}+ for audit in ("agent-trust-hub", "socket", "snyk"):+ idx = html.find(f"/security/{audit}")+ if idx == -1:+ continue+ match = re.search(r'(Pass|Warn|Fail)', html[idx:idx + 500], re.IGNORECASE)+ if match:+ audits[audit] = match.group(1).title()+ return audits++ @classmethod+ def _normalize_identifier(cls, identifier: str) -> str:+ for prefix in cls._ID_PREFIX_ALIASES:+ if identifier.startswith(prefix):+ return identifier[len(prefix):]+ return identifier++ @classmethod+ def _candidate_identifiers(cls, identifier: str) -> List[str]:+ parts = identifier.split("/", 2)+ if len(parts) < 3:+ return [identifier]++ repo = f"{parts[0]}/{parts[1]}"+ skill_path = parts[2].lstrip("/")+ return _dedupe_keep_order(+ [f"{repo}/{skill_path}"] + [f"{repo}/{base}{skill_path}" for base in cls._STANDARD_BASE_PATHS]+ )++ @staticmethod+ def _wrap_identifier(identifier: str) -> str:+ return f"skills-sh/{identifier}"diff --git a/tools/skills_hub_sources.py b/tools/skills_hub_sources.pynew file mode 100644index 00000000000..d3d55f4fc55--- /dev/null+++ b/tools/skills_hub_sources.py@@ -0,0 +1,674 @@+"""Skills Hub adapters for well-known endpoints, direct URLs, LobeHub, and browse.sh."""++import hashlib+import json+import logging+import re+from typing import Any, Dict, List, Optional, Union+from urllib.parse import quote, urljoin, urlparse, urlunparse++import httpx++from tools.skills_hub_models import (+ GuardedFetchMixin, SkillBundle, SkillMeta, SkillSource, _hermes_tags, _matches_query,+ _parse_frontmatter, _referenced_support_paths, _validate_bundle_rel_path,+ _validate_skill_name, hub,+)++logger = logging.getLogger("tools.skills_hub")+++def _get_json(url: str, *, timeout: int = 20, **kwargs) -> Optional[Any]:+ """Plain (unguarded) GET + JSON decode; None on non-200 or transport/decode error."""+ try:+ resp = httpx.get(url, timeout=timeout, **kwargs)+ if resp.status_code != 200:+ return None+ return resp.json()+ except (httpx.HTTPError, json.JSONDecodeError):+ return None+++# ---------------------------------------------------------------------------+# Well-known Agent Skills endpoint source adapter+# ---------------------------------------------------------------------------++class WellKnownSkillSource(GuardedFetchMixin, SkillSource):+ """Read skills from a domain exposing /.well-known/skills/index.json."""++ BASE_PATH = "/.well-known/skills"++ def source_id(self) -> str:+ return "well-known"++ def trust_level_for(self, identifier: str) -> str:+ return "community"++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ index_url = self._query_to_index_url(query)+ if not index_url:+ return []++ parsed = self._parse_index(index_url)+ if not parsed:+ return []++ results: List[SkillMeta] = []+ for entry in parsed["skills"][:limit]:+ name = entry.get("name")+ if not isinstance(name, str) or not name:+ continue+ files = entry.get("files", ["SKILL.md"])+ results.append(SkillMeta(+ name=name,+ description=str(entry.get("description", "")),+ source="well-known",+ identifier=self._wrap_identifier(parsed["base_url"], name),+ trust_level="community",+ path=name,+ extra={+ "index_url": parsed["index_url"],+ "base_url": parsed["base_url"],+ "files": files if isinstance(files, list) else ["SKILL.md"],+ },+ ))+ return results++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ parsed = self._parse_identifier(identifier)+ if not parsed:+ return None++ entry = self._index_entry(parsed["index_url"], parsed["skill_name"])+ if not entry:+ return None++ skill_md = self._fetch_text(f"{parsed['skill_url']}/SKILL.md")+ if skill_md is None:+ return None++ fm = _parse_frontmatter(skill_md)+ return SkillMeta(+ name=str(fm.get("name") or parsed["skill_name"]),+ description=str(fm.get("description") or entry.get("description") or ""),+ source="well-known",+ identifier=self._wrap_identifier(parsed["base_url"], parsed["skill_name"]),+ trust_level="community",+ path=parsed["skill_name"],+ extra={+ "index_url": parsed["index_url"],+ "base_url": parsed["base_url"],+ "files": entry.get("files", ["SKILL.md"]),+ "endpoint": parsed["skill_url"],+ },+ )++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ parsed = self._parse_identifier(identifier)+ if not parsed:+ return None++ try:+ skill_name = _validate_skill_name(parsed["skill_name"])+ except ValueError:+ logger.warning("Well-known skill identifier contained unsafe skill name: %s", identifier)+ return None++ entry = self._index_entry(parsed["index_url"], parsed["skill_name"])+ if not entry:+ return None++ files = entry.get("files", ["SKILL.md"])+ if not isinstance(files, list) or not files:+ files = ["SKILL.md"]++ downloaded: Dict[str, str] = {}+ for rel_path in files:+ if not isinstance(rel_path, str) or not rel_path:+ continue+ try:+ safe_rel_path = _validate_bundle_rel_path(rel_path)+ except ValueError:+ logger.warning(+ "Well-known skill %s advertised unsafe file path: %r",+ identifier,+ rel_path,+ )+ return None+ text = self._fetch_text(f"{parsed['skill_url']}/{safe_rel_path}")+ if text is None:+ return None+ downloaded[safe_rel_path] = text++ if "SKILL.md" not in downloaded:+ return None++ return SkillBundle(+ name=skill_name,+ files=downloaded,+ source="well-known",+ identifier=self._wrap_identifier(parsed["base_url"], skill_name),+ trust_level="community",+ metadata={+ "index_url": parsed["index_url"],+ "base_url": parsed["base_url"],+ "endpoint": parsed["skill_url"],+ "files": files,+ },+ )++ def _query_to_index_url(self, query: str) -> Optional[str]:+ query = query.strip()+ if not query.startswith(("http://", "https://")):+ return None+ if query.endswith("/index.json"):+ return query+ if f"{self.BASE_PATH}/" in query:+ base_url = query.split(f"{self.BASE_PATH}/", 1)[0] + self.BASE_PATH+ return f"{base_url}/index.json"+ return query.rstrip("/") + f"{self.BASE_PATH}/index.json"++ def _parse_identifier(self, identifier: str) -> Optional[dict]:+ raw = identifier[len("well-known:"):] if identifier.startswith("well-known:") else identifier+ if not raw.startswith(("http://", "https://")):+ return None++ parsed_url = urlparse(raw)+ clean_url = urlunparse(parsed_url._replace(fragment=""))+ fragment = parsed_url.fragment++ if clean_url.endswith("/index.json"):+ if not fragment:+ return None+ base_url = clean_url[:-len("/index.json")]+ skill_name = fragment+ skill_url = f"{base_url}/{skill_name}"+ else:+ skill_url = clean_url[:-len("/SKILL.md")] if clean_url.endswith("/SKILL.md") else clean_url.rstrip("/")+ if f"{self.BASE_PATH}/" not in skill_url:+ return None+ base_url, skill_name = skill_url.rsplit("/", 1)+ return {+ "index_url": f"{base_url}/index.json",+ "base_url": base_url,+ "skill_name": skill_name,+ "skill_url": skill_url,+ }++ def _parse_index(self, index_url: str) -> Optional[dict]:+ cache_key = f"well_known_index_{hashlib.md5(index_url.encode()).hexdigest()}"+ cached = hub()._read_index_cache(cache_key)+ if isinstance(cached, dict) and isinstance(cached.get("skills"), list):+ return cached++ resp = hub()._guarded_http_get(index_url, timeout=20)+ if resp is None or resp.status_code != 200:+ return None+ try:+ data = resp.json()+ except json.JSONDecodeError:+ return None++ skills = data.get("skills", []) if isinstance(data, dict) else []+ if not isinstance(skills, list):+ return None++ parsed = {+ "index_url": index_url,+ "base_url": index_url[:-len("/index.json")],+ "skills": skills,+ }+ hub()._write_index_cache(cache_key, parsed)+ return parsed++ def _index_entry(self, index_url: str, skill_name: str) -> Optional[dict]:+ parsed = self._parse_index(index_url)+ if not parsed:+ return None+ for entry in parsed["skills"]:+ if isinstance(entry, dict) and entry.get("name") == skill_name:+ return entry+ return None++ @staticmethod+ def _wrap_identifier(base_url: str, skill_name: str) -> str:+ return f"well-known:{base_url.rstrip('/')}/{skill_name}"+++# ---------------------------------------------------------------------------+# Direct URL source adapter+# ---------------------------------------------------------------------------++class UrlSource(GuardedFetchMixin, SkillSource):+ """Fetch SKILL.md plus explicitly referenced, allowlisted support files.++ The identifier IS the URL (``https://example.com/path/SKILL.md``). Bare URLs+ cannot enumerate a repository, so only exact references below+ references/templates/scripts/assets are fetched. The skill name comes from+ frontmatter ``name:`` (URL-slug fallback); trust is always ``community``.+ """++ # Skill names must look like identifiers: lowercase letters/digits with+ # optional hyphens/underscores. Blocks dangerous (``../evil``) AND useless+ # (``SKILL``, ``README``, empty) candidates before they hit the disk.+ _VALID_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")++ def source_id(self) -> str:+ return "url"++ def trust_level_for(self, identifier: str) -> str:+ return "community"++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ return [] # search is meaningless for a direct URL++ def _matches(self, identifier: str) -> bool:+ """Claim bare HTTP(S) URLs ending in ``.md``; leave wrapped identifiers+ and ``/.well-known/skills/`` URLs to their own adapters."""+ if not isinstance(identifier, str):+ return False+ ident = identifier.strip()+ if not ident.lower().startswith(("http://", "https://")):+ return False+ if "/.well-known/skills/" in ident or ident.rstrip("/").endswith("/index.json"):+ return False+ try:+ path = urlparse(ident).path+ except ValueError:+ return False+ return path.lower().endswith(".md")++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ if not self._matches(identifier):+ return None+ url = identifier.strip()+ text = self._fetch_text(url)+ if text is None:+ return None+ fm = _parse_frontmatter(text)+ name = self._resolve_skill_name(fm, url)+ raw_tags = _hermes_tags(fm)+ return SkillMeta(+ name=name or "",+ description=str(fm.get("description") or ""),+ source="url",+ identifier=url,+ trust_level="community",+ path=name or "",+ tags=[str(t) for t in raw_tags] if isinstance(raw_tags, list) else [],+ extra={"url": url, "awaiting_name": name is None},+ )++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ if not self._matches(identifier):+ return None+ url = identifier.strip()+ text = self._fetch_text(url)+ if text is None:+ return None++ fm = _parse_frontmatter(text)+ name = self._resolve_skill_name(fm, url)+ referenced = _referenced_support_paths(text)+ if referenced is None:+ return None+ files: Dict[str, Union[str, bytes]] = {"SKILL.md": text}+ base_url = url.rsplit("/", 1)[0] + "/"+ for rel_path in sorted(referenced):+ support_url = urljoin(base_url, quote(rel_path, safe="/"))+ if urlparse(support_url).netloc != urlparse(url).netloc:+ return None+ content = self._fetch_bytes(support_url)+ if content is None:+ # A 404ing support file shouldn't sink the whole install.+ logger.warning(+ "URL skill %s: referenced support file %r could not be "+ "fetched from %s; skipping it",+ url, rel_path, support_url,+ )+ continue+ files[rel_path] = content++ # When no name resolves, return the bundle with an empty name and+ # ``awaiting_name=True``: ``do_install`` prompts on a TTY or refuses+ # non-interactively, without re-downloading after the user picks a name.+ skill_name = ""+ if name is not None:+ try:+ skill_name = _validate_skill_name(name)+ except ValueError:+ logger.warning("URL skill %s produced unsafe skill name: %r", url, name)+ return None++ return SkillBundle(+ name=skill_name,+ files=files,+ source="url",+ identifier=url,+ trust_level="community",+ metadata={"url": url, "source_url": url, "awaiting_name": not skill_name},+ )++ @classmethod+ def _is_valid_skill_name(cls, name: Optional[str]) -> bool:+ if not isinstance(name, str):+ return False+ candidate = name.strip().lower()+ if not candidate or candidate in {"skill", "readme", "index", "unnamed-skill"}:+ return False+ return bool(cls._VALID_NAME_RE.match(candidate))++ @classmethod+ def _resolve_skill_name(cls, fm: dict, url: str) -> Optional[str]:+ """Frontmatter ``name:`` when valid, else a URL-slug candidate+ (``.../<name>/SKILL.md`` -> ``<name>``, ``.../<name>.md`` -> ``<name>``).++ None when nothing usable — the CLI then prompts or refuses rather than+ auto-naming something like ``SKILL``.+ """+ fm_name = fm.get("name") if isinstance(fm, dict) else None+ if isinstance(fm_name, str) and cls._is_valid_skill_name(fm_name):+ return fm_name.strip()++ try:+ path = urlparse(url).path+ except ValueError:+ return None+ parts = [p for p in path.split("/") if p]+ if len(parts) >= 2 and parts[-1].lower() == "skill.md" and cls._is_valid_skill_name(parts[-2]):+ return parts[-2]+ if parts:+ candidate = re.sub(r"\.md$", "", parts[-1], flags=re.IGNORECASE)+ if cls._is_valid_skill_name(candidate):+ return candidate+ return None+++# ---------------------------------------------------------------------------+# LobeHub source adapter+# ---------------------------------------------------------------------------++class LobeHubSource(SkillSource):+ """LobeHub agent marketplace (14,500+ system-prompt agents, converted to+ SKILL.md on fetch). Data lives in GitHub: lobehub/lobe-chat-agents."""++ INDEX_URL = "https://chat-agents.lobehub.com/index.json"++ def source_id(self) -> str:+ return "lobehub"++ def trust_level_for(self, identifier: str) -> str:+ return "community"++ def _agents(self) -> Optional[list]:+ index = self._fetch_index()+ if not index:+ return None+ agents = index.get("agents", index) if isinstance(index, dict) else index+ return agents if isinstance(agents, list) else None++ @staticmethod+ def _agent_id(identifier: str) -> str:+ return identifier.split("/", 1)[-1] if identifier.startswith("lobehub/") else identifier++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ agents = self._agents()+ if agents is None:+ return []++ query_lower = query.lower()+ results: List[SkillMeta] = []+ for agent in agents:+ meta = agent.get("meta", agent)+ title = meta.get("title", agent.get("identifier", ""))+ desc = meta.get("description", "")+ tags = meta.get("tags", [])++ if _matches_query(query_lower, title, desc, tags if isinstance(tags, list) else ""):+ identifier = agent.get("identifier", title.lower().replace(" ", "-"))+ results.append(SkillMeta(+ name=identifier,+ description=desc[:200],+ source="lobehub",+ identifier=f"lobehub/{identifier}",+ trust_level="community",+ tags=tags if isinstance(tags, list) else [],+ ))++ if len(results) >= limit:+ break++ return results++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ agent_id = self._agent_id(identifier)+ agent_data = self._fetch_agent(agent_id)+ if not agent_data:+ return None++ return SkillBundle(+ name=agent_id,+ files={"SKILL.md": self._convert_to_skill_md(agent_data)},+ source="lobehub",+ identifier=f"lobehub/{agent_id}",+ trust_level="community",+ )++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ agent_id = self._agent_id(identifier)+ agents = self._agents()+ if agents is None:+ return None++ for agent in agents:+ if agent.get("identifier") == agent_id:+ meta = agent.get("meta", agent)+ return SkillMeta(+ name=agent_id,+ description=meta.get("description", ""),+ source="lobehub",+ identifier=f"lobehub/{agent_id}",+ trust_level="community",+ tags=meta.get("tags", []) if isinstance(meta.get("tags"), list) else [],+ )+ return None++ def _fetch_index(self) -> Optional[Any]:+ """Fetch the LobeHub agent index (cached for 1 hour)."""+ cache_key = "lobehub_index"+ cached = hub()._read_index_cache(cache_key)+ if cached is not None:+ return cached++ data = _get_json(self.INDEX_URL, timeout=30)+ if data is None:+ return None+ hub()._write_index_cache(cache_key, data)+ return data++ def _fetch_agent(self, agent_id: str) -> Optional[dict]:+ """Fetch a single agent's JSON file."""+ url = f"https://chat-agents.lobehub.com/{agent_id}.json"+ try:+ resp = httpx.get(url, timeout=15)+ if resp.status_code == 200:+ return resp.json()+ except (httpx.HTTPError, json.JSONDecodeError) as e:+ logger.debug("LobeHub agent fetch failed: %s", e)+ return None++ @staticmethod+ def _convert_to_skill_md(agent_data: dict) -> str:+ """Convert a LobeHub agent JSON into SKILL.md format."""+ meta = agent_data.get("meta", agent_data)+ identifier = agent_data.get("identifier", "lobehub-agent")+ title = meta.get("title", identifier)+ description = meta.get("description", "")+ tags = meta.get("tags", [])+ system_role = agent_data.get("config", {}).get("systemRole", "")++ tag_list = tags if isinstance(tags, list) else []+ fm_lines = [+ "---",+ f"name: {identifier}",+ f"description: {description[:500]}",+ "metadata:",+ " hermes:",+ f" tags: [{', '.join(str(t) for t in tag_list)}]",+ " lobehub:",+ " source: lobehub",+ "---",+ ]++ body_lines = [+ f"# {title}",+ "",+ description,+ "",+ "## Instructions",+ "",+ system_role if system_role else "(No system role defined)",+ ]++ return "\n".join(fm_lines) + "\n\n" + "\n".join(body_lines) + "\n"+++# ---------------------------------------------------------------------------+# browse.sh source adapter+# ---------------------------------------------------------------------------++class BrowseShSource(SkillSource):+ """Browserbase's browse.sh catalog of site-specific browser-automation SKILL.md files.++ The catalog is ``/api/skills``; content comes from ``/api/skills/{slug}``'s+ ``skillMdUrl`` (CDN blob). The catalog's ``sourceUrl`` is a GitHub HTML URL+ whose repo is not always public, so it is not used for content.+ """++ CATALOG_URL = "https://browse.sh/api/skills"+ SKILL_DETAIL_URL = "https://browse.sh/api/skills/{slug}"+ _CACHE_KEY = "browse_sh_catalog"++ def source_id(self) -> str:+ return "browse-sh"++ def trust_level_for(self, identifier: str) -> str:+ return "community"++ def _fetch_catalog(self) -> List[Dict]:+ cached = hub()._read_index_cache(self._CACHE_KEY)+ if cached is not None:+ return cached+ data = _get_json(self.CATALOG_URL)+ if data is None:+ return []+ skills = data.get("skills", []) if isinstance(data, dict) else []+ if not isinstance(skills, list):+ return []+ hub()._write_index_cache(self._CACHE_KEY, skills)+ return skills++ def _item_to_meta(self, item: Dict) -> Optional[SkillMeta]:+ slug = item.get("slug", "")+ name = item.get("name", "")+ title = item.get("title", name)+ description = item.get("description", title)+ if not slug or not name:+ return None+ if len(description) > 1024:+ description = description[:1021] + "..."+ return SkillMeta(+ name=name,+ description=description,+ source="browse-sh",+ identifier=f"browse-sh/{slug}",+ trust_level="community",+ tags=item.get("tags", []),+ extra={+ "slug": slug,+ "hostname": item.get("hostname", ""),+ "category": item.get("category", ""),+ "source_url": item.get("sourceUrl", ""),+ "recommended_method": item.get("recommendedMethod", ""),+ "proxies": item.get("proxies", False),+ "install_count": item.get("installCount", 0),+ },+ )++ def search(self, query: str, limit: int = 10) -> List[SkillMeta]:+ query_lower = query.lower()+ results = []+ for item in self._fetch_catalog():+ if _matches_query(+ query_lower, item.get("name", ""), item.get("title", ""), item.get("description", ""),+ item.get("hostname", ""), item.get("category", ""), item.get("tags", []),+ ):+ meta = self._item_to_meta(item)+ if meta:+ results.append(meta)+ if len(results) >= limit:+ break+ return results++ def _catalog_item(self, identifier: str) -> Optional[Dict]:+ slug = self._slug_from_identifier(identifier)+ if not slug:+ return None+ return next((i for i in self._fetch_catalog() if i.get("slug") == slug), None)++ def inspect(self, identifier: str) -> Optional[SkillMeta]:+ item = self._catalog_item(identifier)+ return self._item_to_meta(item) if item else None++ def fetch(self, identifier: str) -> Optional[SkillBundle]:+ item = self._catalog_item(identifier)+ if not item:+ return None+ slug = item["slug"]++ md_url = self._resolve_skill_md_url(slug, item)+ if not md_url:+ return None+ try:+ resp = httpx.get(md_url, timeout=20, follow_redirects=True)+ if resp.status_code != 200:+ return None+ content = resp.text+ except httpx.HTTPError:+ return None++ meta = self._item_to_meta(item)+ return SkillBundle(+ name=meta.name if meta else slug.split("/")[-1],+ files={"SKILL.md": content},+ source="browse-sh",+ identifier=identifier,+ trust_level="community",+ metadata={+ "slug": slug,+ "hostname": item.get("hostname", ""),+ "source_url": item.get("sourceUrl", ""),+ "skill_md_url": md_url,+ },+ )++ def _resolve_skill_md_url(self, slug: str, item: Dict) -> Optional[str]:+ """``skillMdUrl`` from ``/api/skills/{slug}``; fallback to a+ ``raw.githubusercontent.com`` catalog ``sourceUrl`` when present."""+ data = _get_json(self.SKILL_DETAIL_URL.format(slug=slug), follow_redirects=True)+ if isinstance(data, dict):+ md_url = data.get("skillMdUrl")+ if isinstance(md_url, str) and md_url.startswith("http"):+ return md_url++ source_url = item.get("sourceUrl", "") if isinstance(item, dict) else ""+ from utils import base_url_host_matches+ if source_url and base_url_host_matches(source_url, "raw.githubusercontent.com"):+ return source_url+ return None++ def _slug_from_identifier(self, identifier: str) -> str:+ """'browse-sh/airbnb.com/search-listings-abc' -> 'airbnb.com/search-listings-abc'."""+ if identifier.startswith("browse-sh/"):+ return identifier[len("browse-sh/"):]+ return identifierdiff --git a/tools/skills_tool.py b/tools/skills_tool.pyindex 53d7947aa8e..dded25917ee 100644--- a/tools/skills_tool.py+++ b/tools/skills_tool.py@@ -1,102 +1,66 @@#!/usr/bin/env python3-"""-Skills Tool Module--This module provides tools for listing and viewing skill documents.-Skills are organized as directories containing a SKILL.md file (the main instructions)-and optional supporting files like references, templates, and examples.--Inspired by Anthropic's Claude Skills system with progressive disclosure architecture:-- Metadata (name ≤64 chars, description ≤1024 chars) - shown in skills_list-- Full Instructions - loaded via skill_view when needed-- Linked Files (references, templates) - loaded on demand--Directory Structure:- skills/- ├── my-skill/- │ ├── SKILL.md # Main instructions (required)- │ ├── references/ # Supporting documentation- │ │ ├── api.md- │ │ └── examples.md- │ ├── templates/ # Templates for output- │ │ └── template.md- │ └── assets/ # Supplementary files (agentskills.io standard)- └── category/ # Category folder for organization- └── another-skill/- └── SKILL.md--SKILL.md Format (YAML Frontmatter, agentskills.io compatible):- ---- name: skill-name # Required, max 64 chars- description: Brief description # Required, max 1024 chars- version: 1.0.0 # Optional- license: MIT # Optional (agentskills.io)- platforms: [macos] # Optional — restrict to specific OS platforms- # Valid: macos, linux, windows- # Omit to load on all platforms (default)- prerequisites: # Optional — legacy runtime requirements- env_vars: [API_KEY] # Legacy env var names are normalized into- # required_environment_variables on load.- commands: [curl, jq] # Command checks remain advisory only.- compatibility: Requires X # Optional (agentskills.io)- metadata: # Optional, arbitrary key-value (agentskills.io)- hermes:- tags: [fine-tuning, llm]- related_skills: [peft, lora]- ----- # Skill Title-- Full instructions and content here...--Available tools:-- skills_list: List skills with metadata (progressive disclosure tier 1)-- skill_view: Load full skill content (progressive disclosure tier 2-3)--Usage:- from tools.skills_tool import skills_list, skill_view, check_skills_requirements-- # List all skills (returns metadata only - token efficient)- result = skills_list()-- # View a skill's main content (loads full instructions)- content = skill_view("axolotl")-- # View a reference file within a skill (loads linked file)- content = skill_view("axolotl", "references/dataset-formats.md")+"""Skills Tool Module — list and view skill documents (progressive disclosure).++Skills are directories holding a SKILL.md (YAML frontmatter + instructions) plus+optional references/, templates/, assets/, scripts/ (agentskills.io layout).+Tier 1 (`skills_list`) returns name/description only; tier 2-3 (`skill_view`)+returns full content and linked files on demand.++Frontmatter: name (≤64), description (≤1024) required; optional version,+license, platforms [macos|linux|windows], prerequisites.env_vars (legacy —+normalized into required_environment_variables), prerequisites.commands+(advisory only), compatibility, metadata.hermes.{tags,related_skills}.++Sibling modules (every name re-exported here so ``from tools.skills_tool import X``+and ``patch("tools.skills_tool.X")`` keep working):+- tools.skills_tool_setup: required env vars / secret capture / setup notes+- tools.skills_tool_plugin: plugin-skill serving + shared file/JSON helpers+- tools.skills_tool_dedup: repeat-view dedup registry"""import jsonimport logging-import time-import threading--from hermes_constants import get_hermes_home, display_hermes_homeimport os-import re-from enum import Enum+import timefrom pathlib import Path, PurePosixPath, PureWindowsPath-from typing import Dict, Any, List, Optional, Set, Tuple+from typing import Any, Dict, List, Optional, Set, Tuple+from hermes_constants import get_hermes_homefrom tools.registry import registry, tool_errorfrom hermes_cli.config import cfg_get-from utils import env_var_enabledfrom agent.skill_utils import (EXCLUDED_SKILL_DIRS as _EXCLUDED_SKILL_DIRS,is_skill_support_path as _is_skill_support_path,)+from tools.skills_tool_setup import ( # noqa: F401+ SkillReadinessStatus, _ENV_VAR_NAME_RE, _REMOTE_ENV_BACKENDS, _build_setup_note,+ _capture_required_environment_variables, _collect_prerequisite_values,+ _gateway_setup_hint, _get_required_environment_variables, _get_terminal_backend_name,+ _is_env_var_persisted, _is_gateway_surface, _is_remote_env_backend,+ _normalize_prerequisite_values, _normalize_setup_metadata,+ _remaining_required_environment_names,+)+from tools.skills_tool_plugin import ( # noqa: F401+ MAX_DESCRIPTION_LENGTH, MAX_NAME_LENGTH, _INJECTION_PATTERNS, _available_skill_files,+ _fail, _json, _mark_background_review_read, _plugin_skill_linked_files,+ _preprocess_skill, _read_skill_text, _serve_plugin_skill, _serve_skill_file,+ _truncate_description,+)+from tools.skills_tool_dedup import ( # noqa: F401+ _SKILL_VIEW_DEDUP_CAP, _SKILL_VIEW_DEDUP_MESSAGE, _check_skill_view_dedup,+ _record_skill_view, _skill_view_fingerprint, _skill_view_tracker,+ _skill_view_tracker_lock, reset_skill_view_dedup,+)logger = logging.getLogger(__name__)-# Per-session skill discovery cache. _find_all_skills() re-reads every-# SKILL.md on every call; with hundreds of skills this is wasteful.-# Cache validation (mirrors hermes_cli/profiles.py::_count_skills, d5eee133e):-# - signature = per-dir max mtime of the dir AND its immediate children-# (one scandir per dir; catches skill add/remove inside categories,-# which does NOT bump the root dir's mtime), plus the disabled-set-# (config-driven — changes with no filesystem mtime bump at all)-# - a short TTL bounds staleness from in-place SKILL.md edits, which-# bump only the file's mtime, invisible to any directory signature.+# Per-session skill discovery cache (re-reading every SKILL.md per call is+# wasteful with hundreds of skills). Validation mirrors+# hermes_cli/profiles.py::_count_skills (d5eee133e): the signature is the+# per-dir max mtime of the dir AND its immediate children (catches add/remove+# inside categories, which does NOT bump the root mtime) plus the disabled-set+# (config-driven, no mtime bump at all); a short TTL bounds staleness from+# in-place SKILL.md edits, invisible to any directory signature.# skip_disabled True/False are cached separately._SKILLS_CACHE: dict = {} # {cache_key: (signature, timestamp, skills_list)}_SKILLS_CACHE_TTL_SECONDS = 30.0@@ -105,13 +69,10 @@ _SKILLS_CACHE_KEY_FILTERED = "filtered"def _skills_scan_signature(dirs_to_scan, disabled) -> tuple:- """Cheap change-signature for the skill scan inputs.-- O(#dirs + #categories) stat calls, not a recursive walk. Includes the- platform the scan's ``skill_matches_platform`` filter will use (read- from ``agent.skill_utils``'s ``sys`` so test patches of that module- are honored) — the scan result is platform-dependent.- """+ """Cheap change-signature for the skill scan inputs: O(#dirs + #categories)+ stat calls, not a recursive walk. Includes the platform the scan's+ ``skill_matches_platform`` filter will use (read from ``agent.skill_utils``'s+ ``sys`` so test patches are honored) — the scan result is platform-dependent."""from agent import skill_utils as _skill_utilsplatform = getattr(getattr(_skill_utils, "sys", None), "platform", "")@@ -126,9 +87,7 @@ def _skills_scan_signature(dirs_to_scan, disabled) -> tuple:for entry in it:try:if entry.is_dir(follow_symlinks=False):- em = entry.stat(follow_symlinks=False).st_mtime- if em > m:- m = em+ m = max(m, entry.stat(follow_symlinks=False).st_mtime)except OSError:continueexcept OSError:@@ -137,81 +96,46 @@ def _skills_scan_signature(dirs_to_scan, disabled) -> tuple:return (tuple(sig), frozenset(disabled), platform)-# All skills live in ~/.hermes/skills/ (seeded from bundled skills/ on install).-# This is the single source of truth -- agent edits, hub installs, and bundled-# skills all coexist here without polluting the git repo.+# All skills live in ~/.hermes/skills/ (seeded from bundled skills/ on install):+# agent edits, hub installs, and bundled skills coexist here without polluting+# the git repo.HERMES_HOME = get_hermes_home()SKILLS_DIR = HERMES_HOME / "skills"_SKILLS_DIR_AT_IMPORT = SKILLS_DIRdef _skills_dir() -> Path:- """Return the active profile's skills directory at call time.+ """Active profile's skills directory at call time.- Some long-lived runtimes import this module before the active profile has- set HERMES_HOME. Keep the legacy SKILLS_DIR module attribute for tests and- external patchers, but when it has not been patched, resolve from the live- profile-scoped HERMES_HOME on every call.- """+ Long-lived runtimes may import this module before the active profile has set+ HERMES_HOME. Keep the legacy SKILLS_DIR attribute for tests and external+ patchers, but when it has not been patched, resolve from the live+ profile-scoped HERMES_HOME on every call."""configured = Path(SKILLS_DIR)if configured != _SKILLS_DIR_AT_IMPORT:return configuredreturn get_hermes_home() / "skills"-# Anthropic-recommended limits for progressive disclosure efficiency-MAX_NAME_LENGTH = 64-MAX_DESCRIPTION_LENGTH = 1024--# Platform identifiers for the 'platforms' frontmatter field.-# Maps user-friendly names to sys.platform prefixes.-_PLATFORM_MAP = {- "macos": "darwin",- "linux": "linux",- "windows": "win32",-}-_ENV_VAR_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")-_REMOTE_ENV_BACKENDS = frozenset(- {"docker", "singularity", "modal", "ssh", "daytona", "vercel_sandbox"}-)---def _is_remote_env_backend(backend: str) -> bool:- """Built-in remote backends plus plugin backends declaring is_remote."""- if backend in _REMOTE_ENV_BACKENDS:- return True- if not backend or backend == "local":- return False- try:- from agent.terminal_env_registry import provider_flag-- return bool(provider_flag(backend, "is_remote", False))- except Exception:- return False_secret_capture_callback = None+_LOOKUP_HINT = "Use a skill name or relative path within the skills directory."def _skill_lookup_path_error(name: str) -> Optional[str]:- """Return an error if a local skill lookup *name* can escape search roots.-- The skill ``name`` is joined onto each trusted search dir to build the- on-disk lookup path, so it must stay relative and free of ``..`` segments —- otherwise ``name="../outside"`` or an absolute path could select a skill- (and read files) outside the skills directory. Mirrors the ``file_path``- validation done later via ``tools.path_security``. We also reject Windows- drive paths (e.g. ``C:\\skills``), whose ``:`` would otherwise be misread as- a plugin namespace separator.- """+ """Error if a local skill lookup *name* can escape the search roots.++ ``name`` is joined onto each trusted search dir, so it must stay relative and+ free of ``..`` — otherwise ``"../outside"`` or an absolute path could select a+ skill (and read files) outside the skills directory. Mirrors the ``file_path``+ validation in ``tools.path_security``. Windows drive paths (``C:\\skills``) are+ rejected too: their ``:`` would be misread as a plugin namespace separator."""from tools.path_security import has_traversal_componentif not isinstance(name, str):return "Skill name must be a string."candidate = name.strip()- if (- PurePosixPath(candidate).is_absolute()- or PureWindowsPath(candidate).is_absolute()- or PureWindowsPath(candidate).drive- ):+ win = PureWindowsPath(candidate)+ if PurePosixPath(candidate).is_absolute() or win.is_absolute() or win.drive:return "Skill name must be a relative path within the skills directory."if has_traversal_component(candidate):return "Skill name cannot contain '..' path traversal components."@@ -224,10 +148,8 @@ def load_env() -> Dict[str, str]:env_vars: Dict[str, str] = {}if not env_path.exists():return env_vars-- # utf-8-sig: users hand-edit .env in Notepad, which prepends a BOM that- # would otherwise glue U+FEFF onto the first key name (same dialect as- # the canonical readers in hermes_cli/config.py).+ # utf-8-sig: users hand-edit .env in Notepad, whose BOM would otherwise glue+ # U+FEFF onto the first key (same dialect as hermes_cli/config.py readers).with env_path.open(encoding="utf-8-sig", errors="replace") as f:for line in f:line = line.strip()@@ -239,327 +161,36 @@ def load_env() -> Dict[str, str]:return env_vars-class SkillReadinessStatus(str, Enum):- AVAILABLE = "available"- SETUP_NEEDED = "setup_needed"- UNSUPPORTED = "unsupported"---# Prompt injection detection — shared by local-skill and plugin-skill paths.-_INJECTION_PATTERNS: list = [- "ignore previous instructions",- "ignore all previous",- "you are now",- "disregard your",- "forget your instructions",- "new instructions:",- "system prompt:",- "<system>",- "]]>",-]--def set_secret_capture_callback(callback) -> None:global _secret_capture_callback_secret_capture_callback = callback+# Lazy delegates to ``agent.skill_utils`` — public re-exports so existing+# callers (and tests patching either module) don't need updating.def skill_matches_platform(frontmatter: Dict[str, Any]) -> bool:- """Check if a skill is compatible with the current OS platform.-- Delegates to ``agent.skill_utils.skill_matches_platform`` — kept here- as a public re-export so existing callers don't need updating.- """+ """Check if a skill is compatible with the current OS platform."""from agent.skill_utils import skill_matches_platform as _implreturn _impl(frontmatter)def skill_matches_environment(frontmatter: Dict[str, Any]) -> bool:- """Check if a skill is relevant to the current runtime environment.-- Delegates to ``agent.skill_utils.skill_matches_environment`` — kept here- as a public re-export so existing callers don't need updating. This is an- offer-time relevance gate (kanban/docker/s6), NOT a hard-compatibility gate;- explicit skill loads bypass it.- """+ """Offer-time relevance gate (kanban/docker/s6), NOT a hard-compatibility+ gate; explicit skill loads bypass it."""from agent.skill_utils import skill_matches_environment as _implreturn _impl(frontmatter)-def _normalize_prerequisite_values(value: Any) -> List[str]:- if not value:- return []- if isinstance(value, str):- value = [value]- return [str(item) for item in value if str(item).strip()]---def _collect_prerequisite_values(- frontmatter: Dict[str, Any],-) -> Tuple[List[str], List[str]]:- prereqs = frontmatter.get("prerequisites")- if not prereqs or not isinstance(prereqs, dict):- return [], []- return (- _normalize_prerequisite_values(prereqs.get("env_vars")),- _normalize_prerequisite_values(prereqs.get("commands")),- )---def _normalize_setup_metadata(frontmatter: Dict[str, Any]) -> Dict[str, Any]:- setup = frontmatter.get("setup")- if not isinstance(setup, dict):- return {"help": None, "collect_secrets": []}-- help_text = setup.get("help")- normalized_help = (- str(help_text).strip()- if isinstance(help_text, str) and help_text.strip()- else None- )-- collect_secrets_raw = setup.get("collect_secrets")- if isinstance(collect_secrets_raw, dict):- collect_secrets_raw = [collect_secrets_raw]- if not isinstance(collect_secrets_raw, list):- collect_secrets_raw = []-- collect_secrets: List[Dict[str, Any]] = []- for item in collect_secrets_raw:- if not isinstance(item, dict):- continue-- env_var = str(item.get("env_var") or "").strip()- if not env_var:- continue-- prompt = str(item.get("prompt") or f"Enter value for {env_var}").strip()- provider_url = str(item.get("provider_url") or item.get("url") or "").strip()-- entry: Dict[str, Any] = {- "env_var": env_var,- "prompt": prompt,- "secret": bool(item.get("secret", True)),- }- if provider_url:- entry["provider_url"] = provider_url- collect_secrets.append(entry)-- return {- "help": normalized_help,- "collect_secrets": collect_secrets,- }---def _get_required_environment_variables(- frontmatter: Dict[str, Any],- legacy_env_vars: List[str] | None = None,-) -> List[Dict[str, Any]]:- setup = _normalize_setup_metadata(frontmatter)- required_raw = frontmatter.get("required_environment_variables")- if isinstance(required_raw, dict):- required_raw = [required_raw]- if not isinstance(required_raw, list):- required_raw = []-- required: List[Dict[str, Any]] = []- seen: set[str] = set()-- def _append_required(entry: Dict[str, Any]) -> None:- env_name = str(entry.get("name") or entry.get("env_var") or "").strip()- if not env_name or env_name in seen:- return- if not _ENV_VAR_NAME_RE.match(env_name):- return-- normalized: Dict[str, Any] = {- "name": env_name,- "prompt": str(entry.get("prompt") or f"Enter value for {env_name}").strip(),- }-- help_text = (- entry.get("help")- or entry.get("provider_url")- or entry.get("url")- or setup.get("help")- )- if isinstance(help_text, str) and help_text.strip():- normalized["help"] = help_text.strip()-- required_for = entry.get("required_for")- if isinstance(required_for, str) and required_for.strip():- normalized["required_for"] = required_for.strip()-- if entry.get("optional"):- normalized["optional"] = True-- seen.add(env_name)- required.append(normalized)-- for item in required_raw:- if isinstance(item, str):- _append_required({"name": item})- continue- if isinstance(item, dict):- _append_required(item)-- for item in setup["collect_secrets"]:- _append_required(- {- "name": item.get("env_var"),- "prompt": item.get("prompt"),- "help": item.get("provider_url") or setup.get("help"),- }- )-- if legacy_env_vars is None:- legacy_env_vars, _ = _collect_prerequisite_values(frontmatter)- for env_var in legacy_env_vars:- _append_required({"name": env_var})-- return required---def _capture_required_environment_variables(- skill_name: str,- missing_entries: List[Dict[str, Any]],-) -> Dict[str, Any]:- if not missing_entries:- return {- "missing_names": [],- "setup_skipped": False,- "gateway_setup_hint": None,- }-- missing_names = [entry["name"] for entry in missing_entries]- # Most gateway surfaces (messaging platforms) can't prompt for a secret, so- # they short-circuit to the "unsupported" hint. Interactive gateway surfaces- # — the desktop app / TUI — set HERMES_INTERACTIVE and register a- # secret-capture callback that routes to a secure secret.request overlay, so- # they fall through and actually prompt. (HERMES_INTERACTIVE is the same flag- # tools/approval.py uses to tell an interactive surface from a messaging one.)- if _is_gateway_surface() and not env_var_enabled("HERMES_INTERACTIVE"):- return {- "missing_names": missing_names,- "setup_skipped": False,- "gateway_setup_hint": _gateway_setup_hint(),- }-- if _secret_capture_callback is None:- return {- "missing_names": missing_names,- "setup_skipped": False,- "gateway_setup_hint": None,- }-- setup_skipped = False- remaining_names: List[str] = []-- for entry in missing_entries:- metadata = {"skill_name": skill_name}- if entry.get("help"):- metadata["help"] = entry["help"]- if entry.get("required_for"):- metadata["required_for"] = entry["required_for"]-- try:- callback_result = _secret_capture_callback(- entry["name"],- entry["prompt"],- metadata,- )- except Exception:- logger.warning(- f"Secret capture callback failed for {entry['name']}", exc_info=True- )- callback_result = {- "success": False,- "stored_as": entry["name"],- "validated": False,- "skipped": True,- }-- success = isinstance(callback_result, dict) and bool(- callback_result.get("success")- )- skipped = isinstance(callback_result, dict) and bool(- callback_result.get("skipped")- )- if success and not skipped:- continue-- setup_skipped = True- remaining_names.append(entry["name"])-- return {- "missing_names": remaining_names,- "setup_skipped": setup_skipped,- "gateway_setup_hint": None,- }---def _is_gateway_surface() -> bool:- if env_var_enabled("HERMES_GATEWAY_SESSION"):- return True- from gateway.session_context import get_session_env- return bool(get_session_env("HERMES_SESSION_PLATFORM"))---def _get_terminal_backend_name() -> str:- return str(os.getenv("TERMINAL_ENV", "local")).strip().lower() or "local"---def _is_env_var_persisted(- var_name: str, env_snapshot: Dict[str, str] | None = None-) -> bool:- if env_snapshot is None:- env_snapshot = load_env()- if var_name in env_snapshot:- return bool(env_snapshot.get(var_name))- return bool(os.getenv(var_name))---def _remaining_required_environment_names(- required_env_vars: List[Dict[str, Any]],- capture_result: Dict[str, Any],- *,- env_snapshot: Dict[str, str] | None = None,-) -> List[str]:- missing_names = set(capture_result["missing_names"])-- if env_snapshot is None:- env_snapshot = load_env()- remaining = []- for entry in required_env_vars:- name = entry["name"]- if entry.get("optional"):- continue- if name in missing_names or not _is_env_var_persisted(name, env_snapshot):- remaining.append(name)- return remaining-+def _parse_frontmatter(content: str) -> Tuple[Dict[str, Any], str]:+ """Parse YAML frontmatter from markdown content."""+ from agent.skill_utils import parse_frontmatter+ return parse_frontmatter(content)-def _gateway_setup_hint() -> str:- try:- from gateway.platforms.base import GATEWAY_SECRET_CAPTURE_UNSUPPORTED_MESSAGE- return GATEWAY_SECRET_CAPTURE_UNSUPPORTED_MESSAGE- except Exception:- return f"Secure secret entry is not available. Load this skill in the local CLI to be prompted, or add the key to {display_hermes_home()}/.env manually."---def _build_setup_note(- readiness_status: SkillReadinessStatus,- missing: List[str],- setup_help: str | None = None,-) -> str | None:- if readiness_status == SkillReadinessStatus.SETUP_NEEDED:- missing_str = ", ".join(missing) if missing else "required prerequisites"- note = f"Setup needed before using this skill: missing {missing_str}."- if setup_help:- return f"{note} {setup_help}"- return note- return None+def _get_disabled_skill_names() -> Set[str]:+ """Load disabled skill names from config."""+ from agent.skill_utils import get_disabled_skill_names+ return get_disabled_skill_names()def check_skills_requirements() -> bool:@@ -567,25 +198,10 @@ def check_skills_requirements() -> bool:return True-def _parse_frontmatter(content: str) -> Tuple[Dict[str, Any], str]:- """Parse YAML frontmatter from markdown content.-- Delegates to ``agent.skill_utils.parse_frontmatter`` — kept here- as a public re-export so existing callers don't need updating.- """- from agent.skill_utils import parse_frontmatter- return parse_frontmatter(content)--def _get_category_from_path(skill_path: Path) -> Optional[str]:- """- Extract category from skill path based on directory structure.-- For paths like: ~/.hermes/skills/mlops/axolotl/SKILL.md -> "mlops"- Also works for external skill dirs configured via skills.external_dirs.- """- # Try the active profile skills dir first (respects monkeypatching in tests),- # then fall back to external dirs from config.+ """``~/.hermes/skills/mlops/axolotl/SKILL.md`` -> ``"mlops"`` (also for+ skills.external_dirs). Tries the active profile dir first (respects test+ monkeypatching), then external dirs from config."""dirs_to_check = [_skills_dir()]try:from agent.skill_utils import get_external_skills_dirs@@ -594,63 +210,31 @@ def _get_category_from_path(skill_path: Path) -> Optional[str]:passfor skills_dir in dirs_to_check:try:- rel_path = skill_path.relative_to(skills_dir)- parts = rel_path.parts- if len(parts) >= 3:- return parts[0]+ parts = skill_path.relative_to(skills_dir).partsexcept ValueError:continue+ if len(parts) >= 3:+ return parts[0]return Nonedef _parse_tags(tags_value) -> List[str]:- """- Parse tags from frontmatter value.-- Handles:- - Already-parsed list (from yaml.safe_load): [tag1, tag2]- - String with brackets: "[tag1, tag2]"- - Comma-separated string: "tag1, tag2"-- Args:- tags_value: Raw tags value — may be a list or string-- Returns:- List of tag strings- """+ """Tags from frontmatter: a parsed list (yaml.safe_load), a bracket-wrapped+ string "[a, b]", or a comma-separated string "a, b"."""if not tags_value:return []-- # yaml.safe_load already returns a list for [tag1, tag2]if isinstance(tags_value, list):return [str(t).strip() for t in tags_value if t]-- # String fallback — handle bracket-wrapped or comma-separatedtags_value = str(tags_value).strip()if tags_value.startswith("[") and tags_value.endswith("]"):tags_value = tags_value[1:-1]-return [t.strip().strip("\"'") for t in tags_value.split(",") if t.strip()]--def _get_disabled_skill_names() -> Set[str]:- """Load disabled skill names from config.-- Delegates to ``agent.skill_utils.get_disabled_skill_names`` — kept here- as a public re-export so existing callers don't need updating.- """- from agent.skill_utils import get_disabled_skill_names- return get_disabled_skill_names()--def _get_session_platform() -> str:- """Resolve the current platform from gateway session context.-- Mirrors the platform-resolution logic in- ``agent.skill_utils.get_disabled_skill_names`` so that- ``_is_skill_disabled`` respects ``HERMES_SESSION_PLATFORM``.- """+ """Platform from gateway session context. Mirrors+ ``agent.skill_utils.get_disabled_skill_names`` so ``_is_skill_disabled``+ respects ``HERMES_SESSION_PLATFORM``."""try:from gateway.session_context import get_session_envreturn get_session_env("HERMES_SESSION_PLATFORM") or ""@@ -659,120 +243,83 @@ def _get_session_platform() -> str:def _is_skill_disabled(name: str, platform: str = None) -> bool:- """Check if a skill is disabled in config.-- Resolves the active platform from (in order of precedence):- 1. Explicit ``platform`` argument- 2. ``HERMES_PLATFORM`` environment variable- 3. ``HERMES_SESSION_PLATFORM`` from gateway session context- """+ """Is the skill disabled in config? Platform precedence: explicit arg,+ ``HERMES_PLATFORM`` env, ``HERMES_SESSION_PLATFORM`` from session context."""try:from hermes_cli.config import load_config- config = load_config()- skills_cfg = config.get("skills", {})+ skills_cfg = load_config().get("skills", {})resolved_platform = platform or os.getenv("HERMES_PLATFORM") or _get_session_platform()global_disabled = skills_cfg.get("disabled", [])if resolved_platform:platform_disabled = cfg_get(skills_cfg, "platform_disabled", resolved_platform)if platform_disabled is not None:- # A globally-disabled skill stays disabled on every platform;- # the platform list adds to it rather than replacing it. Keep- # in sync with agent.skill_utils.get_disabled_skill_names.+ # A globally-disabled skill stays disabled on every platform; the+ # platform list adds to it. Keep in sync with+ # agent.skill_utils.get_disabled_skill_names.return name in platform_disabled or name in global_disabledreturn name in global_disabledexcept Exception:return False-def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:- """Recursively find all skills in ~/.hermes/skills/ and external dirs.-- Args:- skip_disabled: If True, return ALL skills regardless of disabled- state (used by ``hermes skills`` config UI). Default False- filters out disabled skills.-- Returns:- List of skill metadata dicts (name, description, category).-- Results are cached per-session; the cache is invalidated when the scan- signature changes (dir/category mtimes or the disabled-set) and expires- after a short TTL to bound staleness from in-place SKILL.md edits.- """- from agent.skill_utils import (- get_external_skills_dirs,- get_project_skills_dirs,- iter_project_skill_files,- iter_skill_index_files,- )+def _skill_search_dirs() -> Tuple[list, list, Path]:+ """(project_dirs, all_dirs, active_skills_dir) in precedence order.- cache_key = _SKILLS_CACHE_KEY_DISABLED if skip_disabled else _SKILLS_CACHE_KEY_FILTERED+ Trusted project-local dirs come FIRST: first-wins dedup / the collision+ resolver give them precedence over same-named local/external skills.+ ``_skills_dir()`` resolves the LIVE profile HERMES_HOME; module-level+ SKILLS_DIR can be stale in long-lived runtimes."""+ from agent.skill_utils import get_external_skills_dirs, get_project_skills_dirs- # Load disabled set once (not per-skill). Part of the cache signature:- # disabling a skill is a config change with no filesystem mtime bump.- disabled = set() if skip_disabled else _get_disabled_skill_names()-- # Collect directories to scan — same resolution as the scan loop below- # (_skills_dir() resolves the LIVE profile HERMES_HOME; the module-level- # SKILLS_DIR can be stale in long-lived runtimes). Trusted project-local- # dirs come FIRST: first-wins dedup below gives them precedence over- # same-named local/external skills.project_dirs = list(get_project_skills_dirs())- dirs_to_scan: list = list(project_dirs)+ all_dirs: list = list(project_dirs)active_skills_dir = _skills_dir()if active_skills_dir.exists():- dirs_to_scan.append(active_skills_dir)- dirs_to_scan.extend(get_external_skills_dirs())+ all_dirs.append(active_skills_dir)+ all_dirs.extend(get_external_skills_dirs())+ return project_dirs, all_dirs, active_skills_dir+++def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:+ """All skills (name, description, category) in ~/.hermes/skills/ and+ project/external dirs. ``skip_disabled=True`` returns ALL skills regardless+ of disabled state (used by the ``hermes skills`` config UI).++ Cached per-session; invalidated when the scan signature changes (dir/category+ mtimes or the disabled-set) and after a short TTL (in-place SKILL.md edits)."""+ from agent.skill_utils import iter_project_skill_files, iter_skill_index_files+ cache_key = _SKILLS_CACHE_KEY_DISABLED if skip_disabled else _SKILLS_CACHE_KEY_FILTERED+ # Disabled set loaded once (not per-skill); part of the cache signature since+ # disabling a skill is a config change with no filesystem mtime bump.+ disabled = set() if skip_disabled else _get_disabled_skill_names()+ project_dirs, dirs_to_scan, _ = _skill_search_dirs()signature = _skills_scan_signature(dirs_to_scan, disabled)now = time.monotonic()cached = _SKILLS_CACHE.get(cache_key)- if (- cached is not None- and cached[0] == signature- and (now - cached[1]) < _SKILLS_CACHE_TTL_SECONDS- ):- # Per-call shallow copies: callers mutate the returned dicts- # (e.g. web_server annotates s["enabled"]/s["usage"]) — handing- # out the cached objects would poison the cache for everyone else.+ if cached is not None and cached[0] == signature and (now - cached[1]) < _SKILLS_CACHE_TTL_SECONDS:+ # Per-call shallow copies: callers mutate the returned dicts (web_server+ # annotates s["enabled"]/s["usage"]); handing out cached objects would+ # poison the cache for everyone else.return [dict(s) for s in cached[2]]skills = []seen_names: set = set()-- # Scan project dirs first, then local, then external (first-wins) —- # dirs_to_scan already resolved above for the signature. Project dirs+ # Project dirs first, then local, then external (first-wins). Project dirs# iterate through the quarantine chokepoint (scan-time injection gate).for scan_dir in dirs_to_scan:- _is_project = scan_dir in project_dirs- _iter = (- iter_project_skill_files(scan_dir)- if _is_project- else iter_skill_index_files(scan_dir, "SKILL.md")- )- for skill_md in _iter:+ _iter = iter_project_skill_files if scan_dir in project_dirs else lambda d: iter_skill_index_files(d, "SKILL.md")+ for skill_md in _iter(scan_dir):if any(part in _EXCLUDED_SKILL_DIRS for part in skill_md.parts):continue-- skill_dir = skill_md.parent-try:- content = skill_md.read_text(encoding="utf-8-sig", errors="replace")[:4000]- frontmatter, body = _parse_frontmatter(content)-- if not skill_matches_platform(frontmatter):- continue-- if not skill_matches_environment(frontmatter):- continue-- name = frontmatter.get("name", skill_dir.name)[:MAX_NAME_LENGTH]- if name in seen_names:+ frontmatter, body = _parse_frontmatter(_read_skill_text(skill_md)[:4000])+ if not skill_matches_platform(frontmatter) or not skill_matches_environment(frontmatter):continue- if name in disabled:+ name = frontmatter.get("name", skill_md.parent.name)[:MAX_NAME_LENGTH]+ if name in seen_names or name in disabled:continue-description = frontmatter.get("description", "")if not description:for line in body.strip().split("\n"):@@ -780,32 +327,20 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:if line and not line.startswith("#"):description = linebreak-- if len(description) > MAX_DESCRIPTION_LENGTH:- description = description[:MAX_DESCRIPTION_LENGTH - 3] + "..."-- category = _get_category_from_path(skill_md)-seen_names.add(name)skills.append({"name": name,- "description": description,- "category": category,+ "description": _truncate_description(description),+ "category": _get_category_from_path(skill_md),})-except (UnicodeDecodeError, PermissionError) as e:logger.debug("Failed to read skill file %s: %s", skill_md, e)- continueexcept Exception as e:- logger.debug(- "Skipping skill at %s: failed to parse: %s", skill_md, e, exc_info=True- )- continue+ logger.debug("Skipping skill at %s: failed to parse: %s", skill_md, e, exc_info=True)- # Store in cache keyed by the scan signature computed BEFORE the scan- # (a write racing the scan changes the signature, so the next call- # re-scans rather than serving the torn result past the TTL). Same- # shallow-copy contract as the hit path — the caller may mutate.+ # Keyed by the signature computed BEFORE the scan: a write racing the scan+ # changes the signature, so the next call re-scans instead of serving the+ # torn result past the TTL. Same shallow-copy contract as the hit path._SKILLS_CACHE[cache_key] = (signature, now, skills)return [dict(s) for s in skills]@@ -816,25 +351,13 @@ def _sort_skills(skills: List[Dict[str, Any]]) -> List[Dict[str, Any]]:def skills_list(category: str = None, task_id: str = None) -> str:- """- List all available skills (progressive disclosure tier 1 - minimal metadata).-- Returns only name + description to minimize token usage. Use skill_view() to- load full content, tags, related files, etc.-- Args:- category: Optional category filter (e.g., "mlops")- task_id: Optional task identifier used to probe the active backend-- Returns:- JSON string with minimal skill info: name, description, category- """+ """Tier 1 listing: name + description (+ category) only, to minimize tokens.+ ``category`` filters; ``task_id`` is accepted for handler parity."""try:active_skills_dir = _skills_dir()if not active_skills_dir.exists():active_skills_dir.mkdir(parents=True, exist_ok=True)- # Find all skillsall_skills = _find_all_skills()try:from hermes_cli.plugins import discover_plugins, get_plugin_manager@@ -842,245 +365,311 @@ def skills_list(category: str = None, task_id: str = None) -> str:discover_plugins()for plugin_skill in get_plugin_manager().list_plugin_skill_metadata():frontmatter = plugin_skill.pop("frontmatter", {})- if not skill_matches_platform(frontmatter):- continue- if _is_skill_disabled(plugin_skill["name"]):+ if not skill_matches_platform(frontmatter) or _is_skill_disabled(plugin_skill["name"]):continueall_skills.append(plugin_skill)except Exception:logger.debug("Plugin skill listing failed", exc_info=True)if not all_skills:- return json.dumps(- {- "success": True,- "skills": [],- "categories": [],- "message": "No skills found in skills/ directory.",- },- ensure_ascii=False,- )-- # Filter by category if specified+ return _json({+ "success": True, "skills": [], "categories": [],+ "message": "No skills found in skills/ directory.",+ })if category:all_skills = [s for s in all_skills if s.get("category") == category]-- # Sort by category then nameall_skills = _sort_skills(all_skills)-- # Extract unique categories- categories = sorted(- {s.get("category") for s in all_skills if s.get("category")}- )-- return json.dumps(- {- "success": True,- "skills": all_skills,- "categories": categories,- "count": len(all_skills),- "hint": "Use skill_view(name) to see full content, tags, and linked files",- },- ensure_ascii=False,- )-+ categories = sorted({s.get("category") for s in all_skills if s.get("category")})+ return _json({+ "success": True,+ "skills": all_skills,+ "categories": categories,+ "count": len(all_skills),+ "hint": "Use skill_view(name) to see full content, tags, and linked files",+ })except Exception as e:return tool_error(str(e), success=False)-# ── Plugin skill serving ──────────────────────────────────────────────────+# ── skill_view helpers ─────────────────────────────────────────────────────+def _resolve_plugin_skill(name, file_path, task_id, preprocess):+ """Qualified-name dispatch for ``plugin:skill`` names.-def _serve_plugin_skill(- skill_md: Path,- namespace: str,- bare: str,- file_path: str | None = None,- *,- preprocess: bool = True,- session_id: str | None = None,-) -> str:- """Read a plugin-provided skill, apply guards, return JSON."""- from hermes_cli.plugins import _get_disabled_plugins, get_plugin_manager-- if namespace in _get_disabled_plugins():- return json.dumps(- {- "success": False,- "error": (- f"Plugin '{namespace}' is disabled. "- f"Re-enable with: hermes plugins enable {namespace}"- ),- },- ensure_ascii=False,- )+ Returns ``(result_json, None)`` when answered, or ``(None, local_category_name)``+ to fall through to the flat-tree scan: categorized local skills also use+ ``category:skill`` in config and gateway prompts, so the on-disk+ ``category/skill`` translation is returned (None when there's no bare part)."""+ from agent.skill_utils import is_valid_namespace, parse_qualified_name+ from hermes_cli.plugins import discover_plugins, get_plugin_manager+ namespace, bare = parse_qualified_name(name)+ if not is_valid_namespace(namespace):+ return _fail(f"Invalid namespace '{namespace}' in '{name}'. Namespaces must match [a-zA-Z0-9_-]+."), None++ discover_plugins() # idempotent+ pm = get_plugin_manager()+ active_memory_provider = Nonetry:- # utf-8-sig + errors="replace": SKILL.md files are user-authored and- # sometimes carry a Notepad BOM or stray non-UTF-8 bytes. Pinning- # UTF-8 with replacement keeps skill_view deterministic across- # platforms — falling back to the machine locale (cp1252/GBK) would- # make the same skill render differently per host (see PR #51701).- content = skill_md.read_text(encoding="utf-8-sig", errors="replace")- except Exception as e:- return json.dumps(- {"success": False, "error": f"Failed to read skill '{namespace}:{bare}': {e}"},- ensure_ascii=False,- )+ from plugins.memory import _get_active_memory_provider, _prune_inactive_memory_provider_skills+ active_memory_provider = _get_active_memory_provider()+ _prune_inactive_memory_provider_skills(active_memory_provider)+ except Exception as exc:+ logger.debug("Failed pruning inactive memory-provider skills: %s", exc)++ plugin_skill_md = pm.find_plugin_skill(name)+ # Memory provider plugins load through plugins.memory rather than the general+ # PluginManager. If a memory provider shim also registers skills, load the+ # namespaced provider once so its collector can forward those skills into the+ # plugin skill registry before declaring the qualified skill missing.+ if plugin_skill_md is None:+ try:+ if namespace == active_memory_provider:+ from plugins.memory import load_memory_provider- parsed_frontmatter: Dict[str, Any] = {}+ load_memory_provider(namespace)+ plugin_skill_md = pm.find_plugin_skill(name)+ except Exception as exc:+ logger.debug("Failed lazy memory-provider skill load for %s: %s", namespace, exc)++ if plugin_skill_md is not None:+ if not plugin_skill_md.exists():+ pm.remove_plugin_skill(name) # stale registry entry — file deleted out of band+ return _fail(+ f"Skill '{name}' file no longer exists at {plugin_skill_md}. The registry entry "+ f"has been cleaned up — try again after the plugin is reloaded."+ ), None+ return _serve_plugin_skill(+ plugin_skill_md, namespace, bare,+ file_path=file_path, preprocess=preprocess, session_id=task_id,+ ), None++ available = pm.list_plugin_skills(namespace)+ if available: # plugin exists but this specific skill is missing+ return _fail(+ f"Skill '{bare}' not found in plugin '{namespace}'.",+ available_skills=[f"{namespace}:{s}" for s in available],+ hint=f"The '{namespace}' plugin provides {len(available)} skill(s).",+ ), None+ return None, (f"{namespace}/{bare}" if bare else None) # plugin not found → local scan+++def _under_any(path: Path, dirs) -> bool:+ """True when ``path`` (resolved where possible) lives under one of ``dirs``."""try:- parsed_frontmatter, _ = _parse_frontmatter(content)+ resolved = path.resolve()except Exception:- pass+ resolved = path+ for d in dirs:+ try:+ resolved.relative_to(d)+ return True+ except ValueError:+ continue+ return False- qualified_name = f"{namespace}:{bare}"- if _is_skill_disabled(qualified_name):- return json.dumps(- {- "success": False,- "error": f"Skill '{qualified_name}' is disabled.",- },- ensure_ascii=False,- )-- if not skill_matches_platform(parsed_frontmatter):- return json.dumps(- {- "success": False,- "error": f"Skill '{qualified_name}' is not supported on this platform.",- "readiness_status": SkillReadinessStatus.UNSUPPORTED.value,- },- ensure_ascii=False,- )- if file_path:- from tools.path_security import has_traversal_component, validate_within_dir+def _collect_skill_candidates(name, local_category_name, all_dirs):+ """ALL (skill_dir, skill_md) candidates across every dir using every lookup+ strategy (direct path, recursive by parent dir / frontmatter name, legacy flat+ <name>.md), deduped by resolved path.- skill_root = skill_md.parent- if has_traversal_component(file_path):- return json.dumps(- {"success": False, "error": "Path traversal ('..') is not allowed."},- ensure_ascii=False,- )- target = skill_root / file_path- path_error = validate_within_dir(target, skill_root)- if path_error:- return json.dumps(- {"success": False, "error": path_error}, ensure_ascii=False- )- if not target.is_file():- return json.dumps(- {- "success": False,- "error": f"File '{file_path}' not found in skill '{namespace}:{bare}'.",- },- ensure_ascii=False,- )+ Collision detection is the point: silent shadowing of a local skill by a+ same-named external skill is a real bug class (`/skills` shows one, agent+ loaded the other), so the caller refuses when more than one matches."""+ from agent.skill_utils import iter_skill_index_files++ candidates: List[Tuple[Optional[Path], Path]] = []+ seen_md: set = set()++ def _record(sd: Optional[Path], smd: Path) -> None:try:- content = target.read_text(encoding="utf-8-sig", errors="replace")- except UnicodeDecodeError:- return json.dumps(- {- "success": True,- "name": f"{namespace}:{bare}",- "file": file_path,- "content": f"[Binary file: {target.name}, size: {target.stat().st_size} bytes]",- "is_binary": True,- },- ensure_ascii=False,- )- except Exception as exc:- return json.dumps(- {"success": False, "error": f"Failed to read '{file_path}': {exc}"},- ensure_ascii=False,- )- return json.dumps(- {- "success": True,- "name": f"{namespace}:{bare}",- "file": file_path,- "content": content,- "file_type": target.suffix,- "_source_path": str(target),- },- ensure_ascii=False,- )+ key = smd.resolve()+ except Exception:+ key = smd+ if key not in seen_md:+ seen_md.add(key)+ candidates.append((sd, smd))- # Injection scan — log but still serve (matches local-skill behaviour)- if any(p in content.lower() for p in _INJECTION_PATTERNS):- logger.warning(- "Plugin skill '%s:%s' contains patterns that may indicate prompt injection",- namespace, bare,- )+ def _record_direct(direct_path: Path) -> None:+ # Direct path ("mlops/axolotl" or bare "axolotl") or its legacy flat .md sibling.+ flat = direct_path.with_suffix(".md")+ if not _is_skill_support_path(direct_path) and direct_path.is_dir() and (direct_path / "SKILL.md").exists():+ _record(direct_path, direct_path / "SKILL.md")+ elif flat.exists() and not _is_skill_support_path(flat):+ _record(None, flat)++ for search_dir in all_dirs:+ _record_direct(search_dir / name)+ # Categorized form for plugin-namespace fall-through ("myplugin:explore"+ # with no such plugin also tries the on-disk path "myplugin/explore").+ if local_category_name:+ _record_direct(search_dir / local_category_name)+ # Recursive by directory name (nested skills called by bare name) plus+ # frontmatter `name:` — skills_list() exposes the frontmatter name, so+ # skill_view(name) must accept it even when the directory is an alias.+ for found_skill_md in iter_skill_index_files(search_dir, "SKILL.md"):+ if found_skill_md.parent.name == name:+ _record(found_skill_md.parent, found_skill_md)+ continue+ try:+ fm, _ = _parse_frontmatter(_read_skill_text(found_skill_md))+ except Exception:+ fm = {}+ if fm.get("name") == name:+ _record(found_skill_md.parent, found_skill_md)+ # Legacy flat <name>.md anywhere under the dir. Skill support docs+ # (references/templates/assets/scripts) are excluded: they load via+ # file_path and must not shadow real skills sharing the basename.+ for found_md in search_dir.rglob(f"{name}.md"):+ if found_md.name != "SKILL.md" and not _is_skill_support_path(found_md):+ _record(None, found_md)+ return candidates+++_TEMPLATE_GLOBS = ["*.md", "*.py", "*.yaml", "*.yml", "*.json", "*.tex", "*.sh"]+_SCRIPT_GLOBS = ["*.py", "*.sh", "*.bash", "*.js", "*.ts", "*.rb"]+++def _skill_linked_files(skill_dir: Optional[Path]) -> dict:+ """references/templates/assets/scripts of a directory skill (empty groups dropped)."""+ if not skill_dir:+ return {}++ def _rel(paths):+ return [str(f.relative_to(skill_dir)) for f in paths]+ def _multi(sub: Path, globs, rglob: bool):+ out: list = []+ for ext in globs:+ out.extend(_rel(sub.rglob(ext) if rglob else sub.glob(ext)))+ return out++ refs, tmpl, assets, scripts = (skill_dir / n for n in ("references", "templates", "assets", "scripts"))+ files = {+ "references": _rel(refs.glob("*.md")) if refs.exists() else [],+ "templates": _multi(tmpl, _TEMPLATE_GLOBS, True) if tmpl.exists() else [],+ "assets": _rel(f for f in assets.rglob("*") if f.is_file()) if assets.exists() else [],+ "scripts": _multi(scripts, _SCRIPT_GLOBS, False) if scripts.exists() else [],+ }+ return {k: v for k, v in files.items() if v}- description = str(parsed_frontmatter.get("description", ""))- if len(description) > MAX_DESCRIPTION_LENGTH:- description = description[: MAX_DESCRIPTION_LENGTH - 3] + "..."- # Bundle context banner — tells the agent about sibling skills- try:- siblings = [- s for s in get_plugin_manager().list_plugin_skills(namespace)- if s != bare- ]- if siblings:- sib_list = ", ".join(siblings)- banner = (- f"[Bundle context: This skill is part of the '{namespace}' plugin.\n"- f"Sibling skills: {sib_list}.\n"- f"Use qualified form to invoke siblings (e.g. {namespace}:{siblings[0]}).]\n\n"- )- else:- banner = f"[Bundle context: This skill is part of the '{namespace}' plugin.]\n\n"- except Exception:- banner = ""+def _org_provenance_header(skill_dir: Path, active_skills_dir: Path):+ """(org_provenance dict, header text) for an org-mirror skill, else (None, "").- rendered_content = content- if preprocess:- try:- from agent.skill_preprocessing import preprocess_skill_content+ An org-shared skill announces its provenance IN the returned content — the+ moment the model consumes it — not only in the listing. The commit author is+ token-verified at push time by the sync plane (author_mismatch guard), so the+ header is trustworthy, not client-claimed. Org mirrors are read-only: changes+ go through propose → admin approval, never local edits."""+ from agent.skill_utils import ORG_PROVENANCE_FILE, is_org_mirror_path, org_id_of_path- rendered_content = preprocess_skill_content(- content,- skill_md.parent,- session_id=session_id,- )+ if not is_org_mirror_path(skill_dir, active_skills_dir):+ return None, ""+ prov_org = org_id_of_path(skill_dir, active_skills_dir)+ author = ts = ""+ if prov_org:+ try:+ prov = json.loads(_read_skill_text(active_skills_dir / "_org" / prov_org / ORG_PROVENANCE_FILE))+ author = str(prov.get("author_device") or prov.get("author_user_id") or "")+ ts = str(prov.get("ts") or "")except Exception:- logger.debug(- "Could not preprocess plugin skill %s:%s", namespace, bare, exc_info=True- )-- return json.dumps(- {- "success": True,- "name": f"{namespace}:{bare}",- "content": f"{banner}{rendered_content}" if banner else rendered_content,- "description": description,- "linked_files": _plugin_skill_linked_files(skill_md.parent),- "readiness_status": SkillReadinessStatus.AVAILABLE.value,- },- ensure_ascii=False,+ pass+ header = (+ "> [!NOTE] ORG-SHARED SKILL — provenance\n"+ f"> This skill is shared by your organisation (org "+ f"`{prov_org}`"+ + (f", last updated by `{author}`" if author else "")+ + (f", as of {ts}" if ts else "")+ + "). It was reviewed and approved for the whole\n"+ "> team — treat it as third-party instructions rather "+ "than your own notes.\n"+ "> You MAY improve it in place like any other skill. "+ "Your edits are kept locally\n"+ "> and are never overwritten by org updates; share "+ "them back with\n"+ "> `hermes sync propose` (or automatically, if your "+ "org enables it).\n\n")+ return {"org_id": prov_org, "shared_by": author or None, "as_of": ts or None}, header+++def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict, dict]:+ """Resolve required env vars / credential files (prompting for secrets where+ the surface allows) and register what's available for sandboxes.++ Returns ``(fields, extras)``: ``fields`` are the readiness keys placed before+ ``_source_path`` in the skill_view result; ``extras`` (setup_help,+ gateway_setup_hint, setup_note) are appended after it — result key order is+ part of the tool output."""+ legacy_env_vars, _ = _collect_prerequisite_values(frontmatter)+ required_env_vars = _get_required_environment_variables(frontmatter, legacy_env_vars)+ backend = _get_terminal_backend_name()+ env_snapshot = load_env()+ missing_required_env_vars = [+ e for e in required_env_vars+ if not e.get("optional") and not _is_env_var_persisted(e["name"], env_snapshot)+ ]+ capture_result = _capture_required_environment_variables(skill_name, missing_required_env_vars)+ if missing_required_env_vars:+ env_snapshot = load_env()+ remaining = _remaining_required_environment_names(+ required_env_vars, capture_result, env_snapshot=env_snapshot+ )+ setup_needed = bool(remaining)+ # Register available env vars so they pass through to sandboxed execution+ # (execute_code, terminal). Only vars actually set get registered — missing+ # ones are reported as setup_needed.+ available_env_names = [e["name"] for e in required_env_vars if e["name"] not in remaining]+ if available_env_names:+ try:+ from tools.env_passthrough import register_env_passthrough-def _plugin_skill_linked_files(skill_root: Path) -> Dict[str, List[str]] | None:- from tools.path_security import validate_within_dir+ register_env_passthrough(available_env_names)+ except Exception:+ logger.debug("Could not register env passthrough for skill %s", skill_name, exc_info=True)- linked: Dict[str, List[str]] = {}- for category in ("references", "templates", "assets", "scripts"):- base = skill_root / category- if not base.is_dir():- continue- files = [- str(path.relative_to(skill_root))- for path in sorted(base.rglob("*"))- if path.is_file()- and validate_within_dir(path, skill_root) is None- ]- if files:- linked[category] = files- return linked or None+ # Credential files for mounting into remote sandboxes (Modal, Docker):+ # existing host files are registered, missing ones flag setup_needed.+ required_cred_files_raw = frontmatter.get("required_credential_files", [])+ missing_cred_files: list = []+ if isinstance(required_cred_files_raw, list) and required_cred_files_raw:+ try:+ from tools.credential_files import register_credential_files++ missing_cred_files = register_credential_files(required_cred_files_raw)+ if missing_cred_files:+ setup_needed = True+ except Exception:+ logger.debug("Could not register credential files for skill %s", skill_name, exc_info=True)++ fields = {+ "required_environment_variables": required_env_vars,+ "required_commands": [],+ "missing_required_environment_variables": remaining,+ "missing_credential_files": missing_cred_files,+ "missing_required_commands": [],+ "setup_needed": setup_needed,+ "setup_skipped": capture_result["setup_skipped"],+ "readiness_status": (+ SkillReadinessStatus.SETUP_NEEDED if setup_needed else SkillReadinessStatus.AVAILABLE+ ).value,+ }+ extras: dict = {}+ setup_help = next((e["help"] for e in required_env_vars if e.get("help")), None)+ if setup_help:+ extras["setup_help"] = setup_help+ if capture_result["gateway_setup_hint"]:+ extras["gateway_setup_hint"] = capture_result["gateway_setup_hint"]+ if setup_needed:+ missing_items = [f"env ${n}" for n in remaining] + [f"file {p}" for p in missing_cred_files]+ setup_note = _build_setup_note(SkillReadinessStatus.SETUP_NEEDED, missing_items, setup_help)+ if _is_remote_env_backend(backend) and setup_note:+ setup_note = f"{setup_note} {backend.upper()}-backed skills need these requirements available inside the remote environment as well."+ if setup_note:+ extras["setup_note"] = setup_note+ return fields, extrasdef skill_view(@@ -1089,776 +678,141 @@ def skill_view(task_id: str = None,preprocess: bool = True,) -> str:- """- View the content of a skill or a specific file within a skill directory.-- Args:- name: Name or path of the skill (e.g., "axolotl" or "03-fine-tuning/axolotl").- Qualified names like "plugin:skill" resolve to plugin-provided skills.- file_path: Optional path to a specific file within the skill (e.g., "references/api.md")- task_id: Optional task identifier used to probe the active backend- preprocess: Apply configured SKILL.md template and inline shell rendering- to main skill content. Internal slash/preload callers disable this- because they render the skill message themselves.-- Returns:- JSON string with skill content or error message- """+ """View a skill (SKILL.md) or a specific file within its directory, as JSON.++ ``name`` is a skill name or path ("axolotl", "03-fine-tuning/axolotl"); the+ qualified form "plugin:skill" resolves plugin-provided skills. ``preprocess``+ applies the configured SKILL.md template / inline shell rendering to main+ content; internal slash/preload callers disable it because they render the+ skill message themselves."""try:- # Validate before the ':' qualified-name dispatch so a Windows drive- # path (e.g. C:\skills\foo) can't be reinterpreted as a plugin- # namespace, and so a traversal/absolute name never reaches the- # search-dir join that builds direct_path below.+ # Validate before the ':' dispatch so a Windows drive path (C:\skills\foo)+ # can't be reinterpreted as a plugin namespace, and so a traversal /+ # absolute name never reaches the search-dir join.lookup_error = _skill_lookup_path_error(name)if lookup_error:- return json.dumps(- {- "success": False,- "error": lookup_error,- "hint": "Use a skill name or relative path within the skills directory.",- },- ensure_ascii=False,- )+ return _fail(lookup_error, hint=_LOOKUP_HINT)local_category_name: str | None = None- # ── Qualified name dispatch (plugin skills) ──────────────────- # Names containing ':' are routed to the plugin skill registry.- # Bare names fall through to the existing flat-tree scan below.- if ":" in name:- from agent.skill_utils import is_valid_namespace, parse_qualified_name- from hermes_cli.plugins import discover_plugins, get_plugin_manager-- namespace, bare = parse_qualified_name(name)- if not is_valid_namespace(namespace):- return json.dumps(- {- "success": False,- "error": (- f"Invalid namespace '{namespace}' in '{name}'. "- f"Namespaces must match [a-zA-Z0-9_-]+."- ),- },- ensure_ascii=False,- )-- discover_plugins() # idempotent- pm = get_plugin_manager()- active_memory_provider = None- try:- from plugins.memory import (- _get_active_memory_provider,- _prune_inactive_memory_provider_skills,- )-- active_memory_provider = _get_active_memory_provider()- _prune_inactive_memory_provider_skills(active_memory_provider)- except Exception as exc:- logger.debug(- "Failed pruning inactive memory-provider skills: %s",- exc,- )-- plugin_skill_md = pm.find_plugin_skill(name)-- # Memory provider plugins are loaded through plugins.memory rather- # than the general PluginManager. If a memory provider shim also- # registers skills, load the namespaced provider once so its- # collector can forward those skills into the plugin skill registry- # before declaring the qualified skill missing.- if plugin_skill_md is None:- try:- from plugins.memory import load_memory_provider-- if namespace == active_memory_provider:- load_memory_provider(namespace)- plugin_skill_md = pm.find_plugin_skill(name)- except Exception as exc:- logger.debug(- "Failed lazy memory-provider skill load for %s: %s",- namespace,- exc,- )-- if plugin_skill_md is not None:- if not plugin_skill_md.exists():- # Stale registry entry — file deleted out of band- pm.remove_plugin_skill(name)- return json.dumps(- {- "success": False,- "error": (- f"Skill '{name}' file no longer exists at "- f"{plugin_skill_md}. The registry entry has "- f"been cleaned up — try again after the "- f"plugin is reloaded."- ),- },- ensure_ascii=False,- )- return _serve_plugin_skill(- plugin_skill_md,- namespace,- bare,- file_path=file_path,- preprocess=preprocess,- session_id=task_id,- )-- # Plugin exists but this specific skill is missing?- available = pm.list_plugin_skills(namespace)- if available:- return json.dumps(- {- "success": False,- "error": f"Skill '{bare}' not found in plugin '{namespace}'.",- "available_skills": [f"{namespace}:{s}" for s in available],- "hint": f"The '{namespace}' plugin provides {len(available)} skill(s).",- },- ensure_ascii=False,- )- # Plugin itself not found — fall through to flat-tree scan.- # Categorized local skills also use `category:skill` in config and- # gateway prompts, so preserve that form and translate it to the- # on-disk `category/skill` path during the local scan below.- if bare:- local_category_name = f"{namespace}/{bare}"-- from agent.skill_utils import get_external_skills_dirs, get_project_skills_dirs-+ if ":" in name: # plugin registry; bare names use the flat-tree scan below+ served, local_category_name = _resolve_plugin_skill(name, file_path, task_id, preprocess)+ if served is not None:+ return served# The categorized fall-through form (namespace/bare) joins onto each# search dir too; re-validate it since `bare` is not namespace-checked.if local_category_name:lookup_error = _skill_lookup_path_error(local_category_name)if lookup_error:- return json.dumps(- {- "success": False,- "error": lookup_error,- "hint": "Use a skill name or relative path within the skills directory.",- },- ensure_ascii=False,- )-- # Build list of all skill directories to search. Project dirs first —- # they're the highest-precedence tier and the collision resolver- # below uses this ordering.- project_dirs = get_project_skills_dirs()- all_dirs = list(project_dirs)- active_skills_dir = _skills_dir()- if active_skills_dir.exists():- all_dirs.append(active_skills_dir)- all_dirs.extend(get_external_skills_dirs())+ return _fail(lookup_error, hint=_LOOKUP_HINT)+ project_dirs, all_dirs, active_skills_dir = _skill_search_dirs()if not all_dirs:- return json.dumps(- {- "success": False,- "error": "Skills directory does not exist yet. It will be created on first install.",- },- ensure_ascii=False,- )-- skill_dir = None- skill_md = None-- # Collision detection: collect ALL candidates across every dir using- # every lookup strategy (direct path, recursive by parent dir name,- # legacy flat <name>.md). If more than one matches, refuse and tell- # the caller — silent shadowing of a local skill by a same-named- # external skill is a real bug class (`/skills` shows one, agent- # loaded the other) so we surface it loudly instead of guessing.- from agent.skill_utils import iter_skill_index_files-- candidates: List[Tuple[Optional[Path], Path]] = [] # (skill_dir, skill_md)- seen_md: set = set()-- def _record(sd: Optional[Path], smd: Path) -> None:- try:- key = smd.resolve()- except Exception:- key = smd- if key in seen_md:- return- seen_md.add(key)- candidates.append((sd, smd))-- for search_dir in all_dirs:- # Strategy 1: direct path (e.g., "mlops/axolotl" or bare "axolotl"- # at the top of the dir).- direct_path = search_dir / name- if (- not _is_skill_support_path(direct_path)- and direct_path.is_dir()- and (direct_path / "SKILL.md").exists()- ):- _record(direct_path, direct_path / "SKILL.md")- elif direct_path.with_suffix(".md").exists() and not _is_skill_support_path(- direct_path.with_suffix(".md")- ):- _record(None, direct_path.with_suffix(".md"))-- # Strategy 1b: categorized form for plugin namespace fall-through- # (e.g., a "myplugin:explore" name with no plugin registered also- # tries the on-disk path "myplugin/explore").- if local_category_name:- categorized_path = search_dir / local_category_name- if (- not _is_skill_support_path(categorized_path)- and categorized_path.is_dir()- and (categorized_path / "SKILL.md").exists()- ):- _record(categorized_path, categorized_path / "SKILL.md")- elif categorized_path.with_suffix(- ".md"- ).exists() and not _is_skill_support_path(- categorized_path.with_suffix(".md")- ):- _record(None, categorized_path.with_suffix(".md"))-- # Strategy 2: recursive by directory name (catches nested skills- # like "foundations/runtime/explore-codebase" called by bare name),- # plus frontmatter `name:` lookup. `skills_list()` exposes the- # frontmatter name, so `skill_view(name)` must accept it too even- # when the on-disk directory is a shorter category/alias.- for found_skill_md in iter_skill_index_files(search_dir, "SKILL.md"):- if found_skill_md.parent.name == name:- _record(found_skill_md.parent, found_skill_md)- continue- try:- fm_content = found_skill_md.read_text(encoding="utf-8-sig", errors="replace")- fm, _ = _parse_frontmatter(fm_content)- except Exception:- fm = {}- if fm.get("name") == name:- _record(found_skill_md.parent, found_skill_md)-- # Strategy 3: legacy flat <name>.md files anywhere under the dir.- # Exclude skill support docs: references/templates/assets/scripts- # are loaded through skill_view(skill, file_path=...) and must not- # shadow or collide with real skills that share the same basename.- for found_md in search_dir.rglob(f"{name}.md"):- if found_md.name != "SKILL.md" and not _is_skill_support_path(- found_md- ):- _record(None, found_md)+ return _fail("Skills directory does not exist yet. It will be created on first install.")+ skill_dir = skill_md = None+ candidates = _collect_skill_candidates(name, local_category_name, all_dirs)if len(candidates) > 1 and project_dirs:# Cross-tier collision resolution: a project skill intentionally- # overrides a same-named local/external skill, so when at least- # one candidate lives under a trusted project dir, narrow to- # those. Ambiguity WITHIN the project tier still refuses below.- def _in_project(smd: Path) -> bool:- try:- resolved = smd.resolve()- except Exception:- resolved = smd- for pd in project_dirs:- try:- resolved.relative_to(pd)- return True- except ValueError:- continue- return False-- project_candidates = [- (sd, smd) for sd, smd in candidates if _in_project(smd)- ]+ # overrides a same-named local/external skill, so narrow to project+ # candidates when any exist. Ambiguity WITHIN that tier still refuses.+ project_candidates = [(sd, smd) for sd, smd in candidates if _under_any(smd, project_dirs)]if project_candidates:candidates = project_candidates-if len(candidates) > 1:paths = [str(smd) for _, smd in candidates]- logging.getLogger(__name__).warning(- "Skill name collision for '%s': %d candidates — %s",- name, len(candidates), "; ".join(paths),+ logger.warning("Skill name collision for '%s': %d candidates — %s", name, len(candidates), "; ".join(paths))+ return _fail(+ f"Ambiguous skill name '{name}': {len(candidates)} skills match across your local skills dir "+ "and external_dirs. Refusing to guess — load one explicitly by its categorized path.",+ matches=paths,+ hint="Pass the full relative path instead of the bare name (e.g., 'category/skill-name'), "+ "or rename one of the colliding skills so each name is unique.",)- return json.dumps(- {- "success": False,- "error": (- f"Ambiguous skill name '{name}': {len(candidates)} skills "- "match across your local skills dir and external_dirs. "- "Refusing to guess — load one explicitly by its categorized path."- ),- "matches": paths,- "hint": (- "Pass the full relative path instead of the bare name "- "(e.g., 'category/skill-name'), or rename one of the "- "colliding skills so each name is unique."- ),- },- ensure_ascii=False,- )-if candidates:skill_dir, skill_md = candidates[0]- # Quarantine gate: a project-tier skill with a dangerous scan verdict- # must not load even by explicit name (same chokepoint the index and+ # Quarantine gate: a project-tier skill with a dangerous scan verdict must+ # not load even by explicit name (same chokepoint the index and# skills_list use — see agent.skill_utils.iter_project_skill_files).if skill_md is not None and project_dirs:from agent.skill_utils import is_quarantined_project_skill- def _under_project(p: Path) -> bool:- try:- rp = p.resolve()- except Exception:- rp = p- for pd in project_dirs:- try:- rp.relative_to(pd)- return True- except ValueError:- continue- return False-- if _under_project(skill_md) and is_quarantined_project_skill(skill_md):- return json.dumps(- {- "success": False,- "error": (- f"Project skill '{name}' is quarantined: the security "- "scan flagged its content as dangerous. It will not "- "load until the repo's skill content changes and "- "passes a re-scan."- ),- "hint": (- "Inspect the skill in the repo checkout, or untrust "- "the repo with `hermes skills untrust`."- ),- },- ensure_ascii=False,+ if _under_any(skill_md, project_dirs) and is_quarantined_project_skill(skill_md):+ return _fail(+ f"Project skill '{name}' is quarantined: the security scan flagged its content as "+ "dangerous. It will not load until the repo's skill content changes and passes a re-scan.",+ hint="Inspect the skill in the repo checkout, or untrust the repo with `hermes skills untrust`.",)if not skill_md or not skill_md.exists():available = [s["name"] for s in _sort_skills(_find_all_skills())[:20]]- return json.dumps(- {- "success": False,- "error": f"Skill '{name}' not found.",- "available_skills": available,- "hint": "Use skills_list to see all available skills",- },- ensure_ascii=False,- )+ return _fail(f"Skill '{name}' not found.", available_skills=available, hint="Use skills_list to see all available skills")- # Read the file once — reused for platform check and main content below- try:- content = skill_md.read_text(encoding="utf-8-sig", errors="replace")+ try: # read once — reused for platform check and main content+ content = _read_skill_text(skill_md)except Exception as e:- return json.dumps(- {- "success": False,- "error": f"Failed to read skill '{name}': {e}",- },- ensure_ascii=False,- )+ return _fail(f"Failed to read skill '{name}': {e}")- # Security: warn if skill is loaded from outside trusted directories- # (project dirs + local skills dir + configured external_dirs — i.e.- # everything in all_dirs — are trusted)- _outside_skills_dir = True+ # Security warnings: loaded from outside the trusted dirs (project ++ # local + external = all_dirs), and/or common prompt-injection patterns._trusted_dirs = [active_skills_dir.resolve()]try:_trusted_dirs.extend(d.resolve() for d in all_dirs)except Exception:pass- for _td in _trusted_dirs:- try:- skill_md.resolve().relative_to(_td)- _outside_skills_dir = False- break- except ValueError:- continue-- # Security: detect common prompt injection patterns- # (pattern list at module level as _INJECTION_PATTERNS)+ _warnings = []+ if not _under_any(skill_md, _trusted_dirs):+ _warnings.append(f"skill file is outside the trusted skills directory (~/.hermes/skills/): {skill_md}")_content_lower = content.lower()- _injection_detected = any(p in _content_lower for p in _INJECTION_PATTERNS)+ if any(p in _content_lower for p in _INJECTION_PATTERNS):+ _warnings.append("skill content contains patterns that may indicate prompt injection")+ if _warnings:+ logger.warning("Skill security warning for '%s': %s", name, "; ".join(_warnings))- if _outside_skills_dir or _injection_detected:- _warnings = []- if _outside_skills_dir:- _warnings.append(f"skill file is outside the trusted skills directory (~/.hermes/skills/): {skill_md}")- if _injection_detected:- _warnings.append("skill content contains patterns that may indicate prompt injection")- logging.getLogger(__name__).warning("Skill security warning for '%s': %s", name, "; ".join(_warnings))-- parsed_frontmatter: Dict[str, Any] = {}try:- parsed_frontmatter, _ = _parse_frontmatter(content)+ frontmatter, _ = _parse_frontmatter(content)except Exception:- parsed_frontmatter = {}-- if not skill_matches_platform(parsed_frontmatter):- return json.dumps(- {- "success": False,- "error": f"Skill '{name}' is not supported on this platform.",- "readiness_status": SkillReadinessStatus.UNSUPPORTED.value,- },- ensure_ascii=False,- )+ frontmatter = {}- # Check if the skill is disabled by the user- resolved_name = parsed_frontmatter.get("name", skill_md.parent.name)+ if not skill_matches_platform(frontmatter):+ return _fail(f"Skill '{name}' is not supported on this platform.", readiness_status=SkillReadinessStatus.UNSUPPORTED.value)+ resolved_name = frontmatter.get("name", skill_md.parent.name)if _is_skill_disabled(resolved_name):- return json.dumps(- {- "success": False,- "error": (- f"Skill '{resolved_name}' is disabled. "- "Enable it with `hermes skills` or inspect the files directly on disk."- ),- },- ensure_ascii=False,- )+ return _fail(f"Skill '{resolved_name}' is disabled. Enable it with `hermes skills` or inspect the files directly on disk.")- # If a specific file path is requested, read that insteadif file_path and skill_dir:- from tools.path_security import validate_within_dir, has_traversal_component-- # Security: Prevent path traversal attacks- if has_traversal_component(file_path):- return json.dumps(- {- "success": False,- "error": "Path traversal ('..') is not allowed.",- "hint": "Use a relative path within the skill directory",- },- ensure_ascii=False,- )-- target_file = skill_dir / file_path-- # Security: Verify resolved path is still within skill directory- traversal_error = validate_within_dir(target_file, skill_dir)- if traversal_error:- return json.dumps(- {- "success": False,- "error": traversal_error,- "hint": "Use a relative path within the skill directory",- },- ensure_ascii=False,- )- # Gate on is_file(), not exists(): a directory (e.g. requesting- # 'references' bare) must take the not-found listing branch, not- # fall through to read_text() and surface a raw [Errno 21]- # "Is a directory" OS error. Matches the plugin-skill branch above.- if not target_file.is_file():- # List available files in the skill directory, organized by type- available_files = {- "references": [],- "templates": [],- "assets": [],- "scripts": [],- "other": [],- }-- # Scan for all readable files- for f in skill_dir.rglob("*"):- if f.is_file() and f.name != "SKILL.md":- rel = str(f.relative_to(skill_dir))- if rel.startswith("references/"):- available_files["references"].append(rel)- elif rel.startswith("templates/"):- available_files["templates"].append(rel)- elif rel.startswith("assets/"):- available_files["assets"].append(rel)- elif rel.startswith("scripts/"):- available_files["scripts"].append(rel)- elif f.suffix in {- ".md",- ".py",- ".yaml",- ".yml",- ".json",- ".tex",- ".sh",- }:- available_files["other"].append(rel)-- # Remove empty categories- available_files = {k: v for k, v in available_files.items() if v}-- return json.dumps(- {- "success": False,- "error": f"File '{file_path}' not found in skill '{name}'.",- "available_files": available_files,- "hint": "Use one of the available file paths listed above",- },- ensure_ascii=False,- )-- # Read the file content- try:- content = target_file.read_text(encoding="utf-8-sig", errors="replace")- except UnicodeDecodeError:- # Binary file - return info about it instead- return json.dumps(- {- "success": True,- "name": name,- "file": file_path,- "content": f"[Binary file: {target_file.name}, size: {target_file.stat().st_size} bytes]",- "is_binary": True,- },- ensure_ascii=False,- )-- try:- from tools.skill_manager_tool import mark_background_review_skill_read-- mark_background_review_skill_read(target_file)- except Exception:- logger.debug(- "Could not record background-review skill read for %s",- target_file,- exc_info=True,- )-- return json.dumps(- {- "success": True,- "name": name,- "file": file_path,- "content": content,- "file_type": target_file.suffix,- # Internal: absolute source path for the repeat-view dedup- # fingerprint (mtime+size change detection).- "_source_path": str(target_file),- },- ensure_ascii=False,+ return _serve_skill_file(+ skill_dir, file_path, name,+ hint="Use a relative path within the skill directory",+ list_available=True, mark_read=True,)- # Reuse the parse from the platform check above- frontmatter = parsed_frontmatter-- # Get reference, template, asset, and script files if this is a directory-based skill- reference_files = []- template_files = []- asset_files = []- script_files = []-- if skill_dir:- references_dir = skill_dir / "references"- if references_dir.exists():- reference_files = [- str(f.relative_to(skill_dir)) for f in references_dir.glob("*.md")- ]-- templates_dir = skill_dir / "templates"- if templates_dir.exists():- for ext in [- "*.md",- "*.py",- "*.yaml",- "*.yml",- "*.json",- "*.tex",- "*.sh",- ]:- template_files.extend(- [- str(f.relative_to(skill_dir))- for f in templates_dir.rglob(ext)- ]- )-- # assets/ — agentskills.io standard directory for supplementary files- assets_dir = skill_dir / "assets"- if assets_dir.exists():- for f in assets_dir.rglob("*"):- if f.is_file():- asset_files.append(str(f.relative_to(skill_dir)))-- scripts_dir = skill_dir / "scripts"- if scripts_dir.exists():- for ext in ["*.py", "*.sh", "*.bash", "*.js", "*.ts", "*.rb"]:- script_files.extend(- [str(f.relative_to(skill_dir)) for f in scripts_dir.glob(ext)]- )-- # Read tags/related_skills with backward compat:- # Check metadata.hermes.* first (agentskills.io convention), fall back to top-level- hermes_meta = {}+ # tags/related_skills: metadata.hermes.* (agentskills.io) first, then top-level.metadata = frontmatter.get("metadata")- if isinstance(metadata, dict):- hermes_meta = metadata.get("hermes", {}) or {}-+ hermes_meta = (metadata.get("hermes", {}) or {}) if isinstance(metadata, dict) else {}tags = _parse_tags(hermes_meta.get("tags") or frontmatter.get("tags", ""))- related_skills = _parse_tags(- hermes_meta.get("related_skills") or frontmatter.get("related_skills", "")- )-- # Build linked files structure for clear discovery- linked_files = {}- if reference_files:- linked_files["references"] = reference_files- if template_files:- linked_files["templates"] = template_files- if asset_files:- linked_files["assets"] = asset_files- if script_files:- linked_files["scripts"] = script_files+ related_skills = _parse_tags(hermes_meta.get("related_skills") or frontmatter.get("related_skills", ""))+ linked_files = _skill_linked_files(skill_dir)try:rel_path = str(skill_md.relative_to(active_skills_dir))- except ValueError:- # External skill — use path relative to the skill's own parent dir+ except ValueError: # external skill — relative to its own parent dirrel_path = str(skill_md.relative_to(skill_md.parent.parent)) if skill_md.parent.parent else skill_md.name- skill_name = frontmatter.get(- "name", skill_md.stem if not skill_dir else skill_dir.name- )- legacy_env_vars, _ = _collect_prerequisite_values(frontmatter)- required_env_vars = _get_required_environment_variables(- frontmatter, legacy_env_vars- )- backend = _get_terminal_backend_name()- env_snapshot = load_env()- missing_required_env_vars = [- e- for e in required_env_vars- if not e.get("optional")- and not _is_env_var_persisted(e["name"], env_snapshot)- ]- capture_result = _capture_required_environment_variables(- skill_name,- missing_required_env_vars,- )- if missing_required_env_vars:- env_snapshot = load_env()- remaining_missing_required_envs = _remaining_required_environment_names(- required_env_vars,- capture_result,- env_snapshot=env_snapshot,- )- setup_needed = bool(remaining_missing_required_envs)-- # Register available skill env vars so they pass through to sandboxed- # execution environments (execute_code, terminal). Only vars that are- # actually set get registered — missing ones are reported as setup_needed.- available_env_names = [- e["name"]- for e in required_env_vars- if e["name"] not in remaining_missing_required_envs- ]- if available_env_names:- try:- from tools.env_passthrough import register_env_passthrough-- register_env_passthrough(available_env_names)- except Exception:- logger.debug(- "Could not register env passthrough for skill %s",- skill_name,- exc_info=True,- )-- # Register credential files for mounting into remote sandboxes- # (Modal, Docker). Files that exist on the host are registered;- # missing ones are added to the setup_needed indicators.- required_cred_files_raw = frontmatter.get("required_credential_files", [])- if not isinstance(required_cred_files_raw, list):- required_cred_files_raw = []- missing_cred_files: list = []- if required_cred_files_raw:- try:- from tools.credential_files import register_credential_files-- missing_cred_files = register_credential_files(required_cred_files_raw)- if missing_cred_files:- setup_needed = True- except Exception:- logger.debug(- "Could not register credential files for skill %s",- skill_name,- exc_info=True,- )+ skill_name = frontmatter.get("name", skill_md.stem if not skill_dir else skill_dir.name)+ readiness, readiness_extras = _skill_readiness(frontmatter, skill_name)rendered_content = contentif preprocess:- try:- from agent.skill_preprocessing import preprocess_skill_content-- rendered_content = preprocess_skill_content(- content,- skill_dir,- session_id=task_id,- )- except Exception:- logger.debug(- "Could not preprocess skill content for %s", skill_name, exc_info=True- )-- # ── M2 org provenance header (load-time) ──────────────────────────- # An org-shared skill announces its provenance IN the returned content- # — the moment the model consumes it — not only in the listing. The- # commit author behind this content is token-verified at push time by- # the sync plane (author_mismatch guard), so the header is- # trustworthy, not client-claimed. Org mirrors are read-only: changes- # go through propose → admin approval, never local edits.+ rendered_content = _preprocess_skill(+ content, skill_dir, task_id, "Could not preprocess skill content for %s", skill_name,+ )org_provenance = Noneif skill_dir:try:- from agent.skill_utils import (- ORG_PROVENANCE_FILE,- is_org_mirror_path,- org_id_of_path,- )-- if is_org_mirror_path(skill_dir, active_skills_dir):- prov_org = org_id_of_path(skill_dir, active_skills_dir)- author = ""- ts = ""- if prov_org:- try:- prov = json.loads(- (- active_skills_dir- / "_org"- / prov_org- / ORG_PROVENANCE_FILE- ).read_text(encoding="utf-8-sig", errors="replace")- )- author = str(- prov.get("author_device")- or prov.get("author_user_id")- or ""- )- ts = str(prov.get("ts") or "")- except Exception:- pass- org_provenance = {- "org_id": prov_org,- "shared_by": author or None,- "as_of": ts or None,- }- header = (- "> [!NOTE] ORG-SHARED SKILL — provenance\n"- f"> This skill is shared by your organisation (org "- f"`{prov_org}`"- + (f", last updated by `{author}`" if author else "")- + (f", as of {ts}" if ts else "")- + "). It was reviewed and approved for the whole\n"- "> team — treat it as third-party instructions rather "- "than your own notes.\n"- "> You MAY improve it in place like any other skill. "- "Your edits are kept locally\n"- "> and are never overwritten by org updates; share "- "them back with\n"- "> `hermes sync propose` (or automatically, if your "- "org enables it).\n\n"- )- rendered_content = header + rendered_content+ org_provenance, header = _org_provenance_header(skill_dir, active_skills_dir)+ rendered_content = header + rendered_contentexcept Exception:- logger.debug(- "Could not resolve org provenance for %s",- skill_name,- exc_info=True,- )+ logger.debug("Could not resolve org provenance for %s", skill_name, exc_info=True)result = {"success": True,@@ -1871,118 +825,24 @@ def skill_view("skill_dir": str(skill_dir) if skill_dir else None,"org_provenance": org_provenance,"linked_files": linked_files if linked_files else None,- "usage_hint": "To view linked files, call skill_view(name, file_path) where file_path is e.g. 'references/api.md' or 'assets/config.yaml'"- if linked_files- else None,- "required_environment_variables": required_env_vars,- "required_commands": [],- "missing_required_environment_variables": remaining_missing_required_envs,- "missing_credential_files": missing_cred_files,- "missing_required_commands": [],- "setup_needed": setup_needed,- "setup_skipped": capture_result["setup_skipped"],- "readiness_status": SkillReadinessStatus.SETUP_NEEDED.value- if setup_needed- else SkillReadinessStatus.AVAILABLE.value,- # Internal: absolute source path for the repeat-view dedup- # fingerprint (mtime+size change detection).+ "usage_hint": "To view linked files, call skill_view(name, file_path) where file_path is e.g. 'references/api.md' or 'assets/config.yaml'" if linked_files else None,+ **readiness,+ # Internal: absolute source path for the repeat-view dedup fingerprint."_source_path": str(skill_md),+ **readiness_extras,}-- setup_help = next((e["help"] for e in required_env_vars if e.get("help")), None)- if setup_help:- result["setup_help"] = setup_help-- if capture_result["gateway_setup_hint"]:- result["gateway_setup_hint"] = capture_result["gateway_setup_hint"]-- try:- from tools.skill_manager_tool import mark_background_review_skill_read-- mark_background_review_skill_read(skill_md)- except Exception:- logger.debug(- "Could not record background-review skill read for %s",- skill_md,- exc_info=True,- )-- if setup_needed:- missing_items = [- f"env ${env_name}" for env_name in remaining_missing_required_envs- ] + [- f"file {path}" for path in missing_cred_files- ]- setup_note = _build_setup_note(- SkillReadinessStatus.SETUP_NEEDED,- missing_items,- setup_help,- )- if _is_remote_env_backend(backend) and setup_note:- setup_note = f"{setup_note} {backend.upper()}-backed skills need these requirements available inside the remote environment as well."- if setup_note:- result["setup_note"] = setup_note-- # Surface agentskills.io optional fields when present+ _mark_background_review_read(skill_md)+ # agentskills.io optional fieldsif frontmatter.get("compatibility"):result["compatibility"] = frontmatter["compatibility"]if isinstance(metadata, dict):result["metadata"] = metadata-- return json.dumps(result, ensure_ascii=False)-+ return _json(result)except Exception as e:return tool_error(str(e), success=False)---if __name__ == "__main__":- """Test the skills tool"""- print("🎯 Skills Tool Test")- print("=" * 60)-- # Test listing skills- print("\n📋 Listing all skills:")- result = json.loads(skills_list())- if result["success"]:- print(- f"Found {result['count']} skills in {len(result.get('categories', []))} categories"- )- print(f"Categories: {result.get('categories', [])}")- print("\nFirst 10 skills:")- for skill in result["skills"][:10]:- cat = f"[{skill['category']}] " if skill.get("category") else ""- print(f" • {cat}{skill['name']}: {skill['description'][:60]}...")- else:- print(f"Error: {result['error']}")-- # Test viewing a skill- print("\n📖 Viewing skill 'axolotl':")- result = json.loads(skill_view("axolotl"))- if result["success"]:- print(f"Name: {result['name']}")- print(f"Description: {result.get('description', 'N/A')[:100]}...")- print(f"Content length: {len(result['content'])} chars")- if result.get("linked_files"):- print(f"Linked files: {result['linked_files']}")- else:- print(f"Error: {result['error']}")-- # Test viewing a reference file- print("\n📄 Viewing reference file 'axolotl/references/dataset-formats.md':")- result = json.loads(skill_view("axolotl", "references/dataset-formats.md"))- if result["success"]:- print(f"File: {result['file']}")- print(f"Content length: {len(result['content'])} chars")- print(f"Preview: {result['content'][:150]}...")- else:- print(f"Error: {result['error']}")---# ----------------------------------------------------------------------------# Registry-# ---------------------------------------------------------------------------+# ── Registry ────────────────────────────────────────────────────────────────SKILLS_LIST_SCHEMA = {"name": "skills_list",@@ -2022,160 +882,43 @@ registry.register(name="skills_list",toolset="skills",schema=SKILLS_LIST_SCHEMA,- handler=lambda args, **kw: skills_list(- category=args.get("category"), task_id=kw.get("task_id")- ),+ handler=lambda args, **kw: skills_list(category=args.get("category"), task_id=kw.get("task_id")),check_fn=check_skills_requirements,emoji="📚",)-# ── skill_view repeat-view dedup ────────────────────────────────────────-# Per-task cache of (skill name, file_path) -> (skill file mtime+size).-# On a repeat view of an UNCHANGED skill file, return a short stub instead-# of re-sending the full content — the earlier tool result in this-# conversation already carries it verbatim. Cleared on context compression-# via reset_skill_view_dedup() (wired next to read_file's reset_file_dedup)-# because after compression the original content is summarized away.-_skill_view_tracker: Dict[str, Dict[tuple, tuple]] = {}-_skill_view_tracker_lock = threading.Lock()-_SKILL_VIEW_DEDUP_CAP = 200--_SKILL_VIEW_DEDUP_MESSAGE = (- "Skill content unchanged since it was loaded earlier in this "- "conversation — refer to the earlier skill_view result; it is still "- "current and complete. (Re-issued after context compression, this "- "returns the full content again.)"-)---def _skill_view_fingerprint(payload: dict) -> tuple | None:- """Stat the skill file a successful skill_view served, for change detection."""- src = payload.get("_source_path")- if not src:- return None- try:- st = os.stat(src)- return (src, st.st_mtime_ns, st.st_size)- except OSError:- return None---def _record_skill_view(task_id, name, file_path, payload: dict) -> None:- """Record a served skill_view so an identical repeat can be deduped."""- if not task_id:- return- # Never dedup setup-needed views: readiness depends on config/env state- # that can change without the skill file changing, and the model must- # see the refreshed setup status on a re-view.- if payload.get("setup_needed") or payload.get("readiness_status") == "setup_needed":- return- fp = _skill_view_fingerprint(payload)- if fp is None:- return- key = (str(payload.get("name") or name), file_path or "")- with _skill_view_tracker_lock:- cache = _skill_view_tracker.setdefault(str(task_id), {})- cache[key] = fp- while len(cache) > _SKILL_VIEW_DEDUP_CAP:- try:- cache.pop(next(iter(cache)))- except (StopIteration, KeyError):- break---def _check_skill_view_dedup(task_id, name, file_path) -> str | None:- """Return a dedup stub when this exact skill file was already served- to this task and is unchanged on disk; None otherwise."""- if not task_id:- return None- with _skill_view_tracker_lock:- cache = _skill_view_tracker.get(str(task_id))- if not cache:- return None- # The record key uses the RESOLVED name; check both the raw arg and- # resolved forms so 'category/skill' and bare-name views coalesce.- for key, (src, mtime_ns, size) in list(cache.items()):- rec_name, rec_fp = key- if rec_fp != (file_path or ""):- continue- if rec_name != str(name) and not str(name).endswith("/" + rec_name) \- and not rec_name.endswith("/" + str(name)) \- and str(name).split(":")[-1] != rec_name:- continue- try:- st = os.stat(src)- if (st.st_mtime_ns, st.st_size) != (mtime_ns, size):- cache.pop(key, None)- return None- except OSError:- cache.pop(key, None)- return None- return json.dumps(- {- "success": True,- "status": "unchanged",- "name": rec_name,- "file": file_path or "SKILL.md",- "dedup": True,- "content_returned": False,- "message": _SKILL_VIEW_DEDUP_MESSAGE,- },- ensure_ascii=False,- )- return None---def reset_skill_view_dedup(task_id: str | None = None) -> None:- """Clear the skill_view dedup cache (all tasks when task_id is None).-- Called on context compression: the original skill content is- summarized away, so a re-view must return full content again.- """- with _skill_view_tracker_lock:- if task_id is None:- _skill_view_tracker.clear()- else:- _skill_view_tracker.pop(str(task_id), None)def _skill_view_with_bump(args, **kw):"""Invoke skill_view, then bump view_count on success. Best-effort: a- telemetry failure never breaks the tool call."""+ telemetry failure never breaks the tool call.++ Repeat-view dedup mirrors read_file's unchanged-stub: when this session+ already loaded the SAME skill file and it hasn't changed on disk, return a+ short stub instead of the full content (production mining: ~286k tokens of+ verbatim repeat skill_view content in one 400k-message window). The stub only+ replaces content already fully present earlier in this conversation, so the+ "skills must be loaded fully" rule holds — and the cache is cleared on+ context compression so a post-compression re-view returns full content."""name = args.get("name", "")task_id = kw.get("task_id")- # ── Repeat-view dedup ────────────────────────────────────────────- # Mirrors read_file's unchanged-stub: when this session already- # loaded the SAME skill file and it hasn't changed on disk, return a- # short stub instead of re-sending the full content (production- # mining: ~286k tokens of verbatim repeat skill_view content in one- # 400k-message window). The stub only ever replaces content that is- # already fully present earlier in this conversation, so the- # "skills must be loaded fully" rule is preserved — and the cache is- # cleared on context compression (same hook as read_file's dedup)- # so a post-compression re-view returns full content again.stub = _check_skill_view_dedup(task_id, name, args.get("file_path"))if stub is not None:return stub- result = skill_view(- name, file_path=args.get("file_path"), task_id=task_id- )+ result = skill_view(name, file_path=args.get("file_path"), task_id=task_id)try:parsed = json.loads(result)if isinstance(parsed, dict) and parsed.get("success"):_record_skill_view(task_id, name, args.get("file_path"), parsed)- # Use the resolved skill name from the payload when present —- # qualified forms ("plugin:skill") return with the canonical name.+ # Resolved name from the payload when present — qualified forms+ # ("plugin:skill") return with the canonical name.resolved = parsed.get("name") or nameif resolved:from tools.skill_usage import bump_use, bump_viewbump_view(str(resolved))- # A skill_view tool call is the agent actively loading the skill- # to act on it — that counts as use, not just a browse/view.- # Curator's stale timer keys off last_used_at (see agent/curator.py).- bump_use(- str(resolved),- task_id=kw.get("task_id"),- session_id=kw.get("session_id"),- )+ # A skill_view call is the agent actively loading the skill to act+ # on it — that counts as use, not just a browse. Curator's stale+ # timer keys off last_used_at (see agent/curator.py).+ bump_use(str(resolved), task_id=kw.get("task_id"), session_id=kw.get("session_id"))except Exception:passreturn resultdiff --git a/tools/skills_tool_dedup.py b/tools/skills_tool_dedup.pynew file mode 100644index 00000000000..dfd4a03e11e--- /dev/null+++ b/tools/skills_tool_dedup.py@@ -0,0 +1,109 @@+"""skill_view repeat-view dedup registry.++Per-task cache of (skill name, file_path) -> (skill file mtime+size). On a+repeat view of an UNCHANGED skill file, ``tools.skills_tool`` returns a short+stub instead of re-sending the full content — the earlier tool result in this+conversation already carries it verbatim. Cleared on context compression via+``reset_skill_view_dedup()`` (wired next to read_file's reset_file_dedup)+because after compression the original content is summarized away.++Every name is re-imported into ``tools.skills_tool``; the tracker state lives+here and only here.+"""++import json+import os+import threading+from typing import Dict++_skill_view_tracker: Dict[str, Dict[tuple, tuple]] = {}+_skill_view_tracker_lock = threading.Lock()+_SKILL_VIEW_DEDUP_CAP = 200++_SKILL_VIEW_DEDUP_MESSAGE = (+ "Skill content unchanged since it was loaded earlier in this "+ "conversation — refer to the earlier skill_view result; it is still "+ "current and complete. (Re-issued after context compression, this "+ "returns the full content again.)"+)+++def _skill_view_fingerprint(payload: dict) -> tuple | None:+ """Stat the skill file a successful skill_view served, for change detection."""+ src = payload.get("_source_path")+ if not src:+ return None+ try:+ st = os.stat(src)+ return (src, st.st_mtime_ns, st.st_size)+ except OSError:+ return None+++def _record_skill_view(task_id, name, file_path, payload: dict) -> None:+ """Record a served skill_view so an identical repeat can be deduped."""+ if not task_id:+ return+ # Never dedup setup-needed views: readiness depends on config/env state+ # that can change without the skill file changing, and the model must+ # see the refreshed setup status on a re-view.+ if payload.get("setup_needed") or payload.get("readiness_status") == "setup_needed":+ return+ fp = _skill_view_fingerprint(payload)+ if fp is None:+ return+ key = (str(payload.get("name") or name), file_path or "")+ with _skill_view_tracker_lock:+ cache = _skill_view_tracker.setdefault(str(task_id), {})+ cache[key] = fp+ while len(cache) > _SKILL_VIEW_DEDUP_CAP:+ try:+ cache.pop(next(iter(cache)))+ except (StopIteration, KeyError):+ break+++def _check_skill_view_dedup(task_id, name, file_path) -> str | None:+ """Return a dedup stub when this exact skill file was already served+ to this task and is unchanged on disk; None otherwise."""+ if not task_id:+ return None+ with _skill_view_tracker_lock:+ cache = _skill_view_tracker.get(str(task_id))+ if not cache:+ return None+ # The record key uses the RESOLVED name; check both the raw arg and+ # resolved forms so 'category/skill' and bare-name views coalesce.+ for key, (src, mtime_ns, size) in list(cache.items()):+ rec_name, rec_fp = key+ if rec_fp != (file_path or ""):+ continue+ n = str(name)+ if rec_name != n and not n.endswith("/" + rec_name) \+ and not rec_name.endswith("/" + n) and n.split(":")[-1] != rec_name:+ continue+ try:+ st = os.stat(src)+ if (st.st_mtime_ns, st.st_size) != (mtime_ns, size):+ cache.pop(key, None)+ return None+ except OSError:+ cache.pop(key, None)+ return None+ return json.dumps({+ "success": True, "status": "unchanged", "name": rec_name,+ "file": file_path or "SKILL.md", "dedup": True,+ "content_returned": False, "message": _SKILL_VIEW_DEDUP_MESSAGE,+ }, ensure_ascii=False)+ return None+++def reset_skill_view_dedup(task_id: str | None = None) -> None:+ """Clear the skill_view dedup cache (all tasks when task_id is None). Called on+ context compression: the original content is summarized away, so a re-view+ must return full content again."""+ with _skill_view_tracker_lock:+ if task_id is None:+ _skill_view_tracker.clear()+ else:+ _skill_view_tracker.pop(str(task_id), None)diff --git a/tools/skills_tool_plugin.py b/tools/skills_tool_plugin.pynew file mode 100644index 00000000000..73e619ec57d--- /dev/null+++ b/tools/skills_tool_plugin.py@@ -0,0 +1,231 @@+"""Plugin-provided skill serving for ``skill_view`` (``plugin:skill`` names) plus+the JSON / file-serving helpers shared with the local-skill path.++Split out of ``tools.skills_tool``; every name is re-imported there. Helpers+that tests patch on the origin module (``_is_skill_disabled``,+``_parse_frontmatter``, ``skill_matches_platform``) are looked up lazily via+``tools.skills_tool`` at call time so those patches keep working.+"""++import json+import logging+from pathlib import Path+from typing import Any, Dict, List++from tools.skills_tool_setup import SkillReadinessStatus++logger = logging.getLogger("tools.skills_tool")++# Anthropic-recommended limits for progressive disclosure efficiency+MAX_NAME_LENGTH = 64+MAX_DESCRIPTION_LENGTH = 1024++# Prompt injection detection — shared by local-skill and plugin-skill paths.+_INJECTION_PATTERNS: list = [+ "ignore previous instructions", "ignore all previous", "you are now",+ "disregard your", "forget your instructions", "new instructions:",+ "system prompt:", "<system>", "]]>",+]+_SUPPORT_DIRS = ("references", "templates", "assets", "scripts")+_SKILL_FILE_EXTS = {".md", ".py", ".yaml", ".yml", ".json", ".tex", ".sh"}+++def _json(payload: dict) -> str:+ return json.dumps(payload, ensure_ascii=False)+++def _fail(error: str, **extra) -> str:+ return _json({"success": False, "error": error, **extra})+++def _read_skill_text(path: Path) -> str:+ """utf-8-sig + errors="replace": SKILL.md files are user-authored and may carry+ a Notepad BOM or stray non-UTF-8 bytes. Pinning UTF-8 with replacement keeps+ skill_view deterministic across platforms — falling back to the machine locale+ (cp1252/GBK) would render the same skill differently per host (PR #51701)."""+ return path.read_text(encoding="utf-8-sig", errors="replace")+++def _truncate_description(description: str) -> str:+ if len(description) > MAX_DESCRIPTION_LENGTH:+ return description[: MAX_DESCRIPTION_LENGTH - 3] + "..."+ return description+++def _available_skill_files(skill_dir: Path) -> Dict[str, List[str]]:+ """Non-SKILL.md files grouped by support dir (+ "other" for known source+ extensions at other locations); empty groups dropped."""+ groups: Dict[str, List[str]] = {k: [] for k in (*_SUPPORT_DIRS, "other")}+ for f in skill_dir.rglob("*"):+ if not f.is_file() or f.name == "SKILL.md":+ continue+ rel = str(f.relative_to(skill_dir))+ top = rel.split("/", 1)[0] if "/" in rel else None+ if top in _SUPPORT_DIRS:+ groups[top].append(rel)+ elif f.suffix in _SKILL_FILE_EXTS:+ groups["other"].append(rel)+ return {k: v for k, v in groups.items() if v}+++def _serve_skill_file(+ skill_root: Path,+ file_path: str,+ label: str,+ *,+ hint: str | None = None,+ list_available: bool = False,+ read_error_prefix: bool = False,+ mark_read: bool = False,+) -> str:+ """Serve one linked file from a skill directory as a skill_view JSON result.++ ``hint`` is attached to traversal/containment errors (local skills only);+ ``list_available`` adds the available-files listing on not-found (local);+ ``read_error_prefix`` wraps non-decode read errors (plugin) instead of letting+ them propagate to the caller's generic handler (local)."""+ from tools.path_security import has_traversal_component, validate_within_dir++ extra = {"hint": hint} if hint else {}+ if has_traversal_component(file_path):+ return _fail("Path traversal ('..') is not allowed.", **extra)+ target = skill_root / file_path+ path_error = validate_within_dir(target, skill_root)+ if path_error:+ return _fail(path_error, **extra)+ # is_file(), not exists(): a directory (e.g. requesting 'references' bare)+ # must take the not-found branch, not surface a raw [Errno 21] from read_text().+ if not target.is_file():+ not_found = f"File '{file_path}' not found in skill '{label}'."+ if list_available:+ return _fail(+ not_found,+ available_files=_available_skill_files(skill_root),+ hint="Use one of the available file paths listed above",+ )+ return _fail(not_found)+ try:+ content = _read_skill_text(target)+ except UnicodeDecodeError:+ return _json({+ "success": True, "name": label, "file": file_path,+ "content": f"[Binary file: {target.name}, size: {target.stat().st_size} bytes]",+ "is_binary": True,+ })+ except Exception as exc:+ if not read_error_prefix:+ raise+ return _fail(f"Failed to read '{file_path}': {exc}")+ if mark_read:+ _mark_background_review_read(target)+ return _json({+ "success": True, "name": label, "file": file_path, "content": content,+ "file_type": target.suffix,+ # Internal: absolute source path for the repeat-view dedup fingerprint.+ "_source_path": str(target),+ })+++def _mark_background_review_read(path: Path) -> None:+ try:+ from tools.skill_manager_tool import mark_background_review_skill_read+ mark_background_review_skill_read(path)+ except Exception:+ logger.debug("Could not record background-review skill read for %s", path, exc_info=True)+++def _preprocess_skill(content: str, skill_dir, session_id, debug_msg: str, *args) -> str:+ """Apply the configured SKILL.md preprocessing; on failure log and serve raw."""+ try:+ from agent.skill_preprocessing import preprocess_skill_content+ return preprocess_skill_content(content, skill_dir, session_id=session_id)+ except Exception:+ logger.debug(debug_msg, *args, exc_info=True)+ return content+++def _serve_plugin_skill(+ skill_md: Path,+ namespace: str,+ bare: str,+ file_path: str | None = None,+ *,+ preprocess: bool = True,+ session_id: str | None = None,+) -> str:+ """Read a plugin-provided skill, apply guards, return JSON."""+ from hermes_cli.plugins import _get_disabled_plugins, get_plugin_manager+ from tools import skills_tool as _st++ if namespace in _get_disabled_plugins():+ return _fail(f"Plugin '{namespace}' is disabled. Re-enable with: hermes plugins enable {namespace}")+ qualified_name = f"{namespace}:{bare}"+ try:+ content = _read_skill_text(skill_md)+ except Exception as e:+ return _fail(f"Failed to read skill '{qualified_name}': {e}")+ parsed_frontmatter: Dict[str, Any] = {}+ try:+ parsed_frontmatter, _ = _st._parse_frontmatter(content)+ except Exception:+ pass+ if _st._is_skill_disabled(qualified_name):+ return _fail(f"Skill '{qualified_name}' is disabled.")+ if not _st.skill_matches_platform(parsed_frontmatter):+ return _fail(+ f"Skill '{qualified_name}' is not supported on this platform.",+ readiness_status=SkillReadinessStatus.UNSUPPORTED.value,+ )+ if file_path:+ return _serve_skill_file(skill_md.parent, file_path, qualified_name, read_error_prefix=True)++ # Injection scan — log but still serve (matches local-skill behaviour)+ if any(p in content.lower() for p in _INJECTION_PATTERNS):+ logger.warning(+ "Plugin skill '%s:%s' contains patterns that may indicate prompt injection",+ namespace, bare,+ )+ # Bundle context banner — tells the agent about sibling skills+ try:+ siblings = [s for s in get_plugin_manager().list_plugin_skills(namespace) if s != bare]+ banner = f"[Bundle context: This skill is part of the '{namespace}' plugin."+ if siblings:+ banner += (+ f"\nSibling skills: {', '.join(siblings)}.\n"+ f"Use qualified form to invoke siblings (e.g. {namespace}:{siblings[0]})."+ )+ banner += "]\n\n"+ except Exception:+ banner = ""+ rendered_content = content+ if preprocess:+ rendered_content = _preprocess_skill(+ content, skill_md.parent, session_id,+ "Could not preprocess plugin skill %s:%s", namespace, bare,+ )+ return _json({+ "success": True,+ "name": qualified_name,+ "content": f"{banner}{rendered_content}" if banner else rendered_content,+ "description": _truncate_description(str(parsed_frontmatter.get("description", ""))),+ "linked_files": _plugin_skill_linked_files(skill_md.parent),+ "readiness_status": SkillReadinessStatus.AVAILABLE.value,+ })+++def _plugin_skill_linked_files(skill_root: Path) -> Dict[str, List[str]] | None:+ from tools.path_security import validate_within_dir++ linked: Dict[str, List[str]] = {}+ for category in _SUPPORT_DIRS:+ base = skill_root / category+ if not base.is_dir():+ continue+ files = [+ str(path.relative_to(skill_root))+ for path in sorted(base.rglob("*"))+ if path.is_file() and validate_within_dir(path, skill_root) is None+ ]+ if files:+ linked[category] = files+ return linked or Nonediff --git a/tools/skills_tool_setup.py b/tools/skills_tool_setup.pynew file mode 100644index 00000000000..d00f19eaed4--- /dev/null+++ b/tools/skills_tool_setup.py@@ -0,0 +1,255 @@+"""Skill readiness: required env vars, secret capture, and setup notes.++Split out of ``tools.skills_tool``; every name is re-imported there so+``from tools.skills_tool import X`` / ``patch("tools.skills_tool.X")`` keep+working. Module state (``_secret_capture_callback``, ``load_env``) stays in+``tools.skills_tool`` and is read lazily at call time so test patches on the+origin module are honored.+"""++import logging+import os+import re+from enum import Enum+from typing import Any, Dict, List, Tuple++from hermes_constants import display_hermes_home+from utils import env_var_enabled++logger = logging.getLogger("tools.skills_tool")++_ENV_VAR_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")+_REMOTE_ENV_BACKENDS = frozenset({"docker", "singularity", "modal", "ssh", "daytona", "vercel_sandbox"})+++class SkillReadinessStatus(str, Enum):+ AVAILABLE = "available"+ SETUP_NEEDED = "setup_needed"+ UNSUPPORTED = "unsupported"+++def _is_remote_env_backend(backend: str) -> bool:+ """Built-in remote backends plus plugin backends declaring is_remote."""+ if backend in _REMOTE_ENV_BACKENDS:+ return True+ if not backend or backend == "local":+ return False+ try:+ from agent.terminal_env_registry import provider_flag++ return bool(provider_flag(backend, "is_remote", False))+ except Exception:+ return False+++def _normalize_prerequisite_values(value: Any) -> List[str]:+ if not value:+ return []+ if isinstance(value, str):+ value = [value]+ return [str(item) for item in value if str(item).strip()]+++def _collect_prerequisite_values(frontmatter: Dict[str, Any]) -> Tuple[List[str], List[str]]:+ prereqs = frontmatter.get("prerequisites")+ if not prereqs or not isinstance(prereqs, dict):+ return [], []+ return (+ _normalize_prerequisite_values(prereqs.get("env_vars")),+ _normalize_prerequisite_values(prereqs.get("commands")),+ )+++def _as_dict_list(raw: Any) -> list:+ """Accept a single mapping or a list; anything else is treated as empty."""+ if isinstance(raw, dict):+ return [raw]+ return raw if isinstance(raw, list) else []+++def _clean_str(value: Any) -> str | None:+ """Stripped string when *value* is a non-blank str, else None."""+ return value.strip() if isinstance(value, str) and value.strip() else None+++def _normalize_setup_metadata(frontmatter: Dict[str, Any]) -> Dict[str, Any]:+ setup = frontmatter.get("setup")+ if not isinstance(setup, dict):+ return {"help": None, "collect_secrets": []}+ collect_secrets: List[Dict[str, Any]] = []+ for item in _as_dict_list(setup.get("collect_secrets")):+ if not isinstance(item, dict):+ continue+ env_var = str(item.get("env_var") or "").strip()+ if not env_var:+ continue+ entry: Dict[str, Any] = {+ "env_var": env_var,+ "prompt": str(item.get("prompt") or f"Enter value for {env_var}").strip(),+ "secret": bool(item.get("secret", True)),+ }+ provider_url = str(item.get("provider_url") or item.get("url") or "").strip()+ if provider_url:+ entry["provider_url"] = provider_url+ collect_secrets.append(entry)+ return {"help": _clean_str(setup.get("help")), "collect_secrets": collect_secrets}+++def _get_required_environment_variables(+ frontmatter: Dict[str, Any],+ legacy_env_vars: List[str] | None = None,+) -> List[Dict[str, Any]]:+ """Merge required_environment_variables, setup.collect_secrets and legacy+ prerequisites.env_vars into one deduped, validated list (first entry wins)."""+ setup = _normalize_setup_metadata(frontmatter)+ required: List[Dict[str, Any]] = []+ seen: set[str] = set()++ def _append_required(entry: Dict[str, Any]) -> None:+ env_name = str(entry.get("name") or entry.get("env_var") or "").strip()+ if not env_name or env_name in seen or not _ENV_VAR_NAME_RE.match(env_name):+ return+ normalized: Dict[str, Any] = {+ "name": env_name,+ "prompt": str(entry.get("prompt") or f"Enter value for {env_name}").strip(),+ }+ help_text = _clean_str(+ entry.get("help") or entry.get("provider_url") or entry.get("url") or setup.get("help")+ )+ if help_text:+ normalized["help"] = help_text+ required_for = _clean_str(entry.get("required_for"))+ if required_for:+ normalized["required_for"] = required_for+ if entry.get("optional"):+ normalized["optional"] = True+ seen.add(env_name)+ required.append(normalized)++ for item in _as_dict_list(frontmatter.get("required_environment_variables")):+ if isinstance(item, str):+ _append_required({"name": item})+ elif isinstance(item, dict):+ _append_required(item)+ for item in setup["collect_secrets"]:+ _append_required({+ "name": item.get("env_var"),+ "prompt": item.get("prompt"),+ "help": item.get("provider_url") or setup.get("help"),+ })+ if legacy_env_vars is None:+ legacy_env_vars, _ = _collect_prerequisite_values(frontmatter)+ for env_var in legacy_env_vars:+ _append_required({"name": env_var})+ return required+++def _capture_result(missing_names, setup_skipped=False, gateway_setup_hint=None):+ return {+ "missing_names": missing_names,+ "setup_skipped": setup_skipped,+ "gateway_setup_hint": gateway_setup_hint,+ }+++def _capture_required_environment_variables(+ skill_name: str,+ missing_entries: List[Dict[str, Any]],+) -> Dict[str, Any]:+ """Prompt for missing secrets via the registered capture callback (if any)."""+ from tools import skills_tool as _st++ if not missing_entries:+ return _capture_result([])+ missing_names = [entry["name"] for entry in missing_entries]+ # Most gateway surfaces (messaging platforms) can't prompt for a secret, so+ # they short-circuit to the "unsupported" hint. Interactive gateway surfaces+ # (desktop app / TUI) set HERMES_INTERACTIVE — the same flag tools/approval.py+ # uses — and register a callback routing to a secure secret.request overlay,+ # so they fall through and actually prompt.+ if _is_gateway_surface() and not env_var_enabled("HERMES_INTERACTIVE"):+ return _capture_result(missing_names, gateway_setup_hint=_gateway_setup_hint())+ callback = _st._secret_capture_callback+ if callback is None:+ return _capture_result(missing_names)++ setup_skipped = False+ remaining_names: List[str] = []+ for entry in missing_entries:+ metadata = {"skill_name": skill_name}+ for k in ("help", "required_for"):+ if entry.get(k):+ metadata[k] = entry[k]+ try:+ callback_result = callback(entry["name"], entry["prompt"], metadata)+ except Exception:+ logger.warning(f"Secret capture callback failed for {entry['name']}", exc_info=True)+ callback_result = {"success": False, "stored_as": entry["name"], "validated": False, "skipped": True}+ ok = isinstance(callback_result, dict)+ if ok and callback_result.get("success") and not callback_result.get("skipped"):+ continue+ setup_skipped = True+ remaining_names.append(entry["name"])+ return _capture_result(remaining_names, setup_skipped)+++def _is_gateway_surface() -> bool:+ if env_var_enabled("HERMES_GATEWAY_SESSION"):+ return True+ from gateway.session_context import get_session_env+ return bool(get_session_env("HERMES_SESSION_PLATFORM"))+++def _get_terminal_backend_name() -> str:+ return str(os.getenv("TERMINAL_ENV", "local")).strip().lower() or "local"+++def _env_snapshot_or_load(env_snapshot):+ if env_snapshot is None:+ from tools import skills_tool as _st++ return _st.load_env()+ return env_snapshot+++def _is_env_var_persisted(var_name: str, env_snapshot: Dict[str, str] | None = None) -> bool:+ env_snapshot = _env_snapshot_or_load(env_snapshot)+ if var_name in env_snapshot:+ return bool(env_snapshot.get(var_name))+ return bool(os.getenv(var_name))+++def _remaining_required_environment_names(+ required_env_vars: List[Dict[str, Any]],+ capture_result: Dict[str, Any],+ *,+ env_snapshot: Dict[str, str] | None = None,+) -> List[str]:+ missing_names = set(capture_result["missing_names"])+ env_snapshot = _env_snapshot_or_load(env_snapshot)+ return [+ e["name"]+ for e in required_env_vars+ if not e.get("optional")+ and (e["name"] in missing_names or not _is_env_var_persisted(e["name"], env_snapshot))+ ]+++def _gateway_setup_hint() -> str:+ try:+ from gateway.platforms.base import GATEWAY_SECRET_CAPTURE_UNSUPPORTED_MESSAGE++ return GATEWAY_SECRET_CAPTURE_UNSUPPORTED_MESSAGE+ except Exception:+ return f"Secure secret entry is not available. Load this skill in the local CLI to be prompted, or add the key to {display_hermes_home()}/.env manually."+++def _build_setup_note(+ readiness_status: SkillReadinessStatus,+ missing: List[str],+ setup_help: str | None = None,+) -> str | None:+ if readiness_status != SkillReadinessStatus.SETUP_NEEDED:+ return None+ note = f"Setup needed before using this skill: missing {', '.join(missing) if missing else 'required prerequisites'}."+ return f"{note} {setup_help}" if setup_help else note