refactor(tools): skills_tool drops _Located dataclass, shares _safe_frontmatter, flattens env-var merge; squeeze body blanks
This commit is contained in:
+17
-30
@@ -63,6 +63,10 @@ def _manifest_file() -> Path:
|
||||
return _live(MANIFEST_FILE, _MANIFEST_FILE_AT_IMPORT, lambda: _skills_dir() / ".bundled_manifest")
|
||||
|
||||
|
||||
def _rel_skills_posix(path: Path) -> str:
|
||||
return path.relative_to(_skills_dir()).as_posix()
|
||||
|
||||
|
||||
# Written by `hermes profile create --no-skills` / installer `--no-skills`: sync seeds
|
||||
# only essential skills. Mirrors hermes_cli.profiles.NO_BUNDLED_SKILLS_MARKER (no CLI import here).
|
||||
NO_BUNDLED_SKILLS_MARKER = ".no-bundled-skills"
|
||||
@@ -89,7 +93,6 @@ def _build_external_skill_index() -> Set[str]:
|
||||
"""Names (directory and frontmatter) of every skill provided by external_dirs,
|
||||
so sync_skills never shadows an externally-delegated skill."""
|
||||
from agent.skill_utils import get_external_skills_dirs, _external_dirs_cache_clear
|
||||
|
||||
_external_dirs_cache_clear() # so a config edit (or a test patch) is seen
|
||||
external_names: Set[str] = set()
|
||||
for ext_dir in get_external_skills_dirs():
|
||||
@@ -155,18 +158,6 @@ def _dir_hash(directory: Path) -> str:
|
||||
return hasher.hexdigest()
|
||||
|
||||
|
||||
def _index_active_skills() -> Dict[str, List[Path]]:
|
||||
"""Index every skill in the user's tree by frontmatter name (for rename recovery)."""
|
||||
index: Dict[str, List[Path]] = {}
|
||||
for md in _iter_active_skill_mds():
|
||||
index.setdefault(_read_skill_name(md, md.parent.name), []).append(md.parent)
|
||||
return index
|
||||
|
||||
|
||||
def _rel_skills_posix(path: Path) -> str:
|
||||
return path.relative_to(_skills_dir()).as_posix()
|
||||
|
||||
|
||||
def _move_dir(src: Path, dest: Path) -> None:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(src), str(dest))
|
||||
@@ -185,10 +176,11 @@ def _recover_renamed_skill(st: "_SyncState", skill_name: str, dest: Path) -> Opt
|
||||
origin_hash = st.manifest.get(skill_name, "")
|
||||
if not origin_hash:
|
||||
return None
|
||||
if st.active_index is None:
|
||||
st.active_index = _index_active_skills()
|
||||
if st.active_index is None: # by frontmatter name
|
||||
st.active_index = {}
|
||||
for md in _iter_active_skill_mds():
|
||||
st.active_index.setdefault(_read_skill_name(md, md.parent.name), []).append(md.parent)
|
||||
st.hub_paths = _read_hub_install_paths()
|
||||
|
||||
for candidate in st.active_index.get(skill_name, []):
|
||||
if candidate == dest or not candidate.is_dir():
|
||||
continue
|
||||
@@ -277,8 +269,7 @@ def _install_new_skill(st: _SyncState, skill_name: str, skill_src: Path, dest: P
|
||||
else:
|
||||
st.say(
|
||||
f" ⚠ {skill_name}: bundled version shipped but you already have a local skill by this name — "
|
||||
f"yours was kept. Run `hermes skills reset {skill_name}` to replace it with the bundled version."
|
||||
)
|
||||
f"yours was kept. Run `hermes skills reset {skill_name}` to replace it with the bundled version.")
|
||||
else:
|
||||
_copy_dir(skill_src, dest)
|
||||
st.copied.append(skill_name)
|
||||
@@ -299,13 +290,14 @@ def _replace_skill_dir(skill_src: Path, dest: Path) -> None:
|
||||
shutil.copytree(skill_src, dest)
|
||||
except OSError:
|
||||
# Clear a partially-written dest so it can't shadow or block the restore.
|
||||
if backup.exists() and dest.exists():
|
||||
try:
|
||||
_rmtree_writable(dest)
|
||||
except OSError:
|
||||
logger.warning("Could not clear partial copy %s during restore", dest, exc_info=True)
|
||||
if backup.exists() and not dest.exists():
|
||||
shutil.move(str(backup), str(dest))
|
||||
if backup.exists():
|
||||
if dest.exists():
|
||||
try:
|
||||
_rmtree_writable(dest)
|
||||
except OSError:
|
||||
logger.warning("Could not clear partial copy %s during restore", dest, exc_info=True)
|
||||
if not dest.exists():
|
||||
shutil.move(str(backup), str(dest))
|
||||
raise
|
||||
try:
|
||||
_rmtree_writable(backup)
|
||||
@@ -379,15 +371,12 @@ def sync_skills(quiet: bool = False) -> dict:
|
||||
if skill_name in suppressed and skill_name not in ESSENTIAL_SKILLS:
|
||||
st.suppressed.append(skill_name)
|
||||
continue
|
||||
|
||||
dest = _compute_relative_dest(skill_src, bundled_dir)
|
||||
bundled_hash = _dir_hash(skill_src)
|
||||
|
||||
# Recoveries run BEFORE classification so a missing dest isn't misread as user-deleted.
|
||||
_recover_orphan_backup(dest)
|
||||
if not dest.exists() and skill_name in st.manifest and _recover_renamed_skill(st, skill_name, dest):
|
||||
st.relocated.append(skill_name)
|
||||
|
||||
if skill_name in external_index:
|
||||
_defer_to_external(st, skill_name, dest, bundled_hash)
|
||||
elif skill_name not in st.manifest:
|
||||
@@ -396,7 +385,6 @@ def sync_skills(quiet: bool = False) -> dict:
|
||||
_update_existing_skill(st, skill_name, skill_src, dest, bundled_hash)
|
||||
else:
|
||||
st.skipped += 1 # in manifest but not on disk — user deleted it
|
||||
|
||||
# Clean manifest entries for skills removed upstream. Skipped when opted out: bundled_skills
|
||||
# is only the essential set there, so cleaning would drop tracking for everything else.
|
||||
cleaned = [] if essential_only else sorted(set(st.manifest) - {name for name, _ in bundled_skills})
|
||||
@@ -405,7 +393,6 @@ def sync_skills(quiet: bool = False) -> dict:
|
||||
_seed_category_descriptions(
|
||||
bundled_dir,
|
||||
{_compute_relative_dest(src, bundled_dir).parent for _, src in bundled_skills} if essential_only else None)
|
||||
|
||||
_write_manifest(st.manifest)
|
||||
return {
|
||||
"copied": st.copied, "updated": st.updated, "skipped": st.skipped, "user_modified": st.user_modified,
|
||||
|
||||
@@ -42,7 +42,6 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:
|
||||
if not in_manifest and not is_bundled:
|
||||
return _fail("not_in_manifest", f"'{name}' is not a tracked bundled skill. Nothing to reset. "
|
||||
f"(Hub-installed skills use `hermes skills uninstall`.)")
|
||||
|
||||
# Delete the user's copy BEFORE touching the manifest so a failed rmtree can't
|
||||
# leave the skill in a manifest-less limbo.
|
||||
deleted_user_copy = False
|
||||
@@ -51,19 +50,16 @@ def reset_bundled_skill(name: str, restore: bool = False) -> dict:
|
||||
return _fail("bundled_missing", f"'{name}' has no bundled source — manifest entry preserved "
|
||||
f"but cannot restore from bundled (skill was removed upstream).")
|
||||
dest = ss._compute_relative_dest(bundled_by_name[name], bundled_dir)
|
||||
if dest.exists():
|
||||
if deleted_user_copy := dest.exists():
|
||||
try:
|
||||
ss._rmtree_writable(dest)
|
||||
except OSError as e:
|
||||
return _fail("not_reset", f"Could not delete user copy at {dest}: {e}. "
|
||||
f"Manifest entry preserved — nothing was changed.")
|
||||
deleted_user_copy = True
|
||||
|
||||
if in_manifest:
|
||||
del manifest[name]
|
||||
ss._write_manifest(manifest)
|
||||
synced = ss.sync_skills(quiet=True)
|
||||
|
||||
if not restore:
|
||||
action, message = "manifest_cleared", (f"Cleared manifest entry for '{name}'. Future `hermes update` runs "
|
||||
f"will re-baseline against your current copy and accept upstream changes.")
|
||||
@@ -78,8 +74,7 @@ def list_user_modified_bundled_skills() -> List[dict]:
|
||||
"""Bundled skills ``hermes update`` keeps because the user edited them (same test
|
||||
the sync loop uses). Name-sorted ``{"name", "dest", "bundled_src"}`` dicts."""
|
||||
ss = _ss()
|
||||
manifest = ss._read_manifest()
|
||||
if not manifest:
|
||||
if not (manifest := ss._read_manifest()):
|
||||
return []
|
||||
bundled_dir = ss._get_bundled_dir()
|
||||
modified: List[dict] = []
|
||||
@@ -107,20 +102,17 @@ def diff_bundled_skill(name: str) -> dict:
|
||||
modified, message, diffs}``; each diff is ``{"path", "status", "diff"}`` with status
|
||||
modified / added (only in user copy) / removed (only in bundled) / binary."""
|
||||
import difflib
|
||||
|
||||
ss, _, bundled_dir, bundled_by_name = _bundled_state()
|
||||
|
||||
def _fail(found: bool, message: str) -> dict:
|
||||
return {"ok": False, "name": name, "found": found, "modified": False, "diffs": [], "message": message}
|
||||
|
||||
bundled_src = bundled_by_name.get(name)
|
||||
if bundled_src is None:
|
||||
if (bundled_src := bundled_by_name.get(name)) is None:
|
||||
return _fail(False, f"'{name}' is not a tracked bundled skill (no stock version to "
|
||||
f"diff against). Hub-installed skills use `hermes skills inspect`.")
|
||||
dest = ss._compute_relative_dest(bundled_src, bundled_dir)
|
||||
if not dest.exists():
|
||||
return _fail(True, f"No local copy of '{name}' found at {dest}.")
|
||||
|
||||
user_files = set(_skill_file_list(dest))
|
||||
stock_files = set(_skill_file_list(bundled_src))
|
||||
diffs: List[dict] = []
|
||||
@@ -140,7 +132,6 @@ def diff_bundled_skill(name: str) -> dict:
|
||||
stock_text.splitlines(keepends=True), user_text.splitlines(keepends=True),
|
||||
fromfile=f"stock/{rel}", tofile=f"yours/{rel}"))
|
||||
diffs.append({"path": rel, "status": "modified", "diff": text})
|
||||
|
||||
message = (f"'{name}' differs from the stock version in {len(diffs)} file(s)." if diffs
|
||||
else f"'{name}' matches the stock version.")
|
||||
return {"ok": True, "name": name, "found": True, "modified": bool(diffs), "diffs": diffs, "message": message}
|
||||
@@ -205,10 +196,8 @@ def remove_pristine_bundled_skills(dry_run: bool = False) -> dict:
|
||||
continue
|
||||
manifest.pop(name, None)
|
||||
removed.append(name)
|
||||
|
||||
if not dry_run and removed:
|
||||
ss._write_manifest(manifest)
|
||||
|
||||
verb = "Would remove" if dry_run else "Removed"
|
||||
return {
|
||||
"ok": True, "removed": removed, "skipped": skipped, "dry_run": dry_run,
|
||||
|
||||
@@ -19,7 +19,6 @@ logger = logging.getLogger("tools.skills_sync")
|
||||
def _ss():
|
||||
"""Live ``tools.skills_sync`` module (imported lazily: it re-exports this module)."""
|
||||
from tools import skills_sync
|
||||
|
||||
return skills_sync
|
||||
|
||||
|
||||
@@ -28,7 +27,6 @@ def _content_hash(directory: Path) -> str:
|
||||
if guard deps are unavailable."""
|
||||
try:
|
||||
from tools.skills_guard import content_hash
|
||||
|
||||
return content_hash(directory)
|
||||
except Exception:
|
||||
return _ss()._dir_hash(directory)
|
||||
@@ -36,8 +34,7 @@ def _content_hash(directory: Path) -> str:
|
||||
|
||||
def _safe_rel_install_path(path: Path, base: Path) -> str:
|
||||
"""Normalized relative POSIX path; rejects traversal/absolute paths."""
|
||||
posix = path.relative_to(base).as_posix()
|
||||
pure = PurePosixPath(posix)
|
||||
pure = PurePosixPath(posix := path.relative_to(base).as_posix())
|
||||
parts = [part for part in pure.parts if part not in {"", "."}]
|
||||
if pure.is_absolute() or not parts or ".." in parts:
|
||||
raise ValueError(f"Unsafe optional skill path: {posix}")
|
||||
@@ -96,12 +93,9 @@ def _optional_skill_index() -> Dict[str, Tuple[str, str, Path]]:
|
||||
ss = _ss()
|
||||
optional_dir = ss._get_optional_dir()
|
||||
index: Dict[str, Tuple[str, str, Path]] = {}
|
||||
if not optional_dir.exists():
|
||||
return index
|
||||
for skill_md, src, install_path in _iter_optional_skills(optional_dir, root_relative=True):
|
||||
value = (src.name, install_path, src)
|
||||
index[src.name] = value
|
||||
index[ss._read_skill_name(skill_md, src.name)] = value
|
||||
if optional_dir.exists():
|
||||
for skill_md, src, install_path in _iter_optional_skills(optional_dir, root_relative=True):
|
||||
index[src.name] = index[ss._read_skill_name(skill_md, src.name)] = (src.name, install_path, src)
|
||||
return index
|
||||
|
||||
|
||||
@@ -124,10 +118,8 @@ def _find_active_copies(folder_name: str, src_frontmatter: str, dest: Path) -> L
|
||||
ss = _ss()
|
||||
names = {folder_name, src_frontmatter}
|
||||
return [
|
||||
md.parent
|
||||
for md in ss._iter_active_skill_mds(sort=True)
|
||||
if md.parent != dest and (md.parent.name == folder_name or ss._read_skill_name(md, md.parent.name) in names)
|
||||
]
|
||||
md.parent for md in ss._iter_active_skill_mds(sort=True)
|
||||
if md.parent != dest and (md.parent.name == folder_name or ss._read_skill_name(md, md.parent.name) in names)]
|
||||
|
||||
|
||||
def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict:
|
||||
@@ -143,12 +135,10 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict
|
||||
else:
|
||||
message = f"Official optional skill not found: {name}" if index else "No official optional skills directory found."
|
||||
return {"ok": False, "message": message, "restored": [], "backfilled": [], "backed_up": []}
|
||||
|
||||
restored: List[str] = []
|
||||
backed_up: List[str] = []
|
||||
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
|
||||
backup_root = ss._skills_dir() / ".restore-backups" / f"official-optional-{timestamp}"
|
||||
|
||||
for folder_name, install_path, src in targets if restore else []:
|
||||
dest = ss._skills_dir() / Path(*install_path.split("/"))
|
||||
canonical_ok = dest.exists() and ss._dir_hash(dest) == ss._dir_hash(src)
|
||||
@@ -161,7 +151,6 @@ def restore_official_optional_skill(name: str, *, restore: bool = False) -> dict
|
||||
if not dest.exists():
|
||||
ss._copy_dir(src, dest)
|
||||
restored.append(folder_name)
|
||||
|
||||
return {
|
||||
"ok": True, "message": "Official optional skill repair complete.", "restored": restored,
|
||||
"backfilled": _backfill_optional_provenance(quiet=True), "backed_up": backed_up,
|
||||
@@ -187,8 +176,7 @@ def _relocated_dest(src_name: str, index: Dict[str, List[Path]]) -> Optional[Tup
|
||||
"""The active tree may hold a skill under a DIFFERENT category path than the repo
|
||||
(upstream reorganized; the installed copy kept its location). Fall back to a UNIQUE
|
||||
same-directory-name match; ambiguity gives no basis to pick. ``(dest, install_path)`` or None."""
|
||||
candidates = index.get(src_name, [])
|
||||
if len(candidates) != 1:
|
||||
if len(candidates := index.get(src_name, [])) != 1:
|
||||
return None
|
||||
dest = candidates[0]
|
||||
try:
|
||||
@@ -206,13 +194,11 @@ def _backfill_optional_provenance(quiet: bool = False) -> List[str]:
|
||||
optional_dir = ss._get_optional_dir()
|
||||
if not optional_dir.exists():
|
||||
return []
|
||||
|
||||
data = _load_hub_lock()
|
||||
if data is None:
|
||||
data = {"version": 1, "installed": {}}
|
||||
installed = data.setdefault("installed", {})
|
||||
existing_paths = {entry.get("install_path") for entry in _hub_lock_entries(data)}
|
||||
|
||||
backfilled: List[str] = []
|
||||
installed_dir_index: Optional[Dict[str, List[Path]]] = None
|
||||
for _skill_md, src, install_path in _iter_optional_skills(optional_dir, root_relative=False):
|
||||
@@ -223,13 +209,11 @@ def _backfill_optional_provenance(quiet: bool = False) -> List[str]:
|
||||
if not dest.is_dir():
|
||||
if installed_dir_index is None:
|
||||
installed_dir_index = _index_installed_skill_dirs_by_name()
|
||||
found = _relocated_dest(src.name, installed_dir_index)
|
||||
if found is None:
|
||||
if (found := _relocated_dest(src.name, installed_dir_index)) is None:
|
||||
continue
|
||||
dest, install_path = found # still requires a byte-identical hash below
|
||||
if install_path in existing_paths or ss._dir_hash(dest) != ss._dir_hash(src):
|
||||
continue
|
||||
|
||||
timestamp = datetime.now(timezone.utc).isoformat()
|
||||
installed[lock_name] = {
|
||||
"source": "official",
|
||||
@@ -246,7 +230,6 @@ def _backfill_optional_provenance(quiet: bool = False) -> List[str]:
|
||||
backfilled.append(lock_name)
|
||||
if not quiet:
|
||||
print(f" = {lock_name} (official optional provenance backfilled)")
|
||||
|
||||
if backfilled:
|
||||
_write_hub_lock(_hub_lock_path(), data)
|
||||
return backfilled
|
||||
|
||||
+43
-109
@@ -13,7 +13,6 @@ import logging
|
||||
import os
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path, PurePosixPath, PureWindowsPath
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
@@ -32,8 +31,8 @@ from tools.skills_tool_setup import ( # noqa: F401
|
||||
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)
|
||||
_preprocess_skill, _read_skill_text, _safe_frontmatter, _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,
|
||||
@@ -54,8 +53,6 @@ def _skills_scan_signature(dirs_to_scan, disabled) -> tuple:
|
||||
"""O(#dirs + #categories) stat-based change signature. The platform is read via
|
||||
``agent.skill_utils.sys`` so test patches are honored."""
|
||||
from agent import skill_utils as _skill_utils
|
||||
|
||||
platform = getattr(getattr(_skill_utils, "sys", None), "platform", "")
|
||||
sig = []
|
||||
for d in dirs_to_scan:
|
||||
try:
|
||||
@@ -68,7 +65,7 @@ def _skills_scan_signature(dirs_to_scan, disabled) -> tuple:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
m = max(m, entry.stat(follow_symlinks=False).st_mtime)
|
||||
sig.append((str(d), m))
|
||||
return (tuple(sig), frozenset(disabled), platform)
|
||||
return (tuple(sig), frozenset(disabled), getattr(getattr(_skill_utils, "sys", None), "platform", ""))
|
||||
|
||||
|
||||
# All skills live in ~/.hermes/skills/ (seeded from bundled skills/ on install).
|
||||
@@ -94,7 +91,6 @@ def _skill_lookup_path_error(name: str) -> Optional[str]:
|
||||
Windows drive paths are rejected too: their ``:`` would be misread as a
|
||||
plugin namespace separator."""
|
||||
from tools.path_security import has_traversal_component
|
||||
|
||||
if not isinstance(name, str):
|
||||
return "Skill name must be a string."
|
||||
candidate = name.strip()
|
||||
@@ -110,14 +106,13 @@ def load_env() -> Dict[str, str]:
|
||||
"""Load profile-scoped environment variables from HERMES_HOME/.env."""
|
||||
env_path = get_hermes_home() / ".env"
|
||||
env_vars: Dict[str, str] = {}
|
||||
if not env_path.exists():
|
||||
return env_vars
|
||||
# utf-8-sig: a Notepad BOM would otherwise glue U+FEFF onto the first key.
|
||||
with env_path.open(encoding="utf-8-sig", errors="replace") as f:
|
||||
for line in map(str.strip, f):
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
key, _, value = line.removeprefix("export ").partition("=")
|
||||
env_vars[key.strip()] = value.strip().strip("\"'")
|
||||
if env_path.exists():
|
||||
# utf-8-sig: a Notepad BOM would otherwise glue U+FEFF onto the first key.
|
||||
with env_path.open(encoding="utf-8-sig", errors="replace") as f:
|
||||
for line in map(str.strip, f):
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
key, _, value = line.removeprefix("export ").partition("=")
|
||||
env_vars[key.strip()] = value.strip().strip("\"'")
|
||||
return env_vars
|
||||
|
||||
|
||||
@@ -158,8 +153,7 @@ def _get_category_from_path(skill_path: Path) -> Optional[str]:
|
||||
dirs_to_check.extend(get_external_skills_dirs())
|
||||
for skills_dir in dirs_to_check:
|
||||
with suppress(ValueError):
|
||||
parts = skill_path.relative_to(skills_dir).parts
|
||||
if len(parts) >= 3:
|
||||
if len(parts := skill_path.relative_to(skills_dir).parts) >= 3:
|
||||
return parts[0]
|
||||
return None
|
||||
|
||||
@@ -194,10 +188,10 @@ def _is_skill_disabled(name: str, platform: str = None) -> bool:
|
||||
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:
|
||||
return name in platform_disabled or name in global_disabled
|
||||
platform_disabled = (
|
||||
cfg_get(skills_cfg, "platform_disabled", resolved_platform) if resolved_platform else None)
|
||||
if platform_disabled is not None:
|
||||
return name in platform_disabled or name in global_disabled
|
||||
return name in global_disabled
|
||||
except Exception:
|
||||
return False
|
||||
@@ -207,12 +201,9 @@ def _skill_search_dirs() -> Tuple[list, list, Path]:
|
||||
"""(project_dirs, all_dirs, active_skills_dir); trusted project-local dirs come
|
||||
FIRST so first-wins dedup / the collision resolver prefer them."""
|
||||
from agent.skill_utils import get_external_skills_dirs, get_project_skills_dirs
|
||||
|
||||
project_dirs = list(get_project_skills_dirs())
|
||||
all_dirs: list = list(project_dirs)
|
||||
active_skills_dir = _skills_dir()
|
||||
if active_skills_dir.exists():
|
||||
all_dirs.append(active_skills_dir)
|
||||
all_dirs = project_dirs + ([active_skills_dir] if active_skills_dir.exists() else [])
|
||||
all_dirs.extend(get_external_skills_dirs())
|
||||
return project_dirs, all_dirs, active_skills_dir
|
||||
|
||||
@@ -222,19 +213,16 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:
|
||||
first-wins by name; cached per session. ``skip_disabled=True`` returns ALL skills
|
||||
regardless of disabled state (``hermes skills`` config UI)."""
|
||||
from agent.skill_utils import iter_project_skill_files, iter_skill_index_files
|
||||
|
||||
cache_key = "with_disabled" if skip_disabled else "filtered"
|
||||
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:
|
||||
# Shallow copies: callers mutate the returned dicts (web_server annotates
|
||||
# s["enabled"]/s["usage"]); handing out cached objects would poison the cache.
|
||||
return [dict(s) for s in cached[2]]
|
||||
|
||||
skills = []
|
||||
seen_names: set = set()
|
||||
# Project dirs iterate through the quarantine chokepoint (scan-time injection gate).
|
||||
@@ -264,7 +252,6 @@ def _find_all_skills(*, skip_disabled: bool = False) -> List[Dict[str, Any]]:
|
||||
logger.debug("Failed to read skill file %s: %s", skill_md, e)
|
||||
except Exception as e:
|
||||
logger.debug("Skipping skill at %s: failed to parse: %s", skill_md, e, exc_info=True)
|
||||
|
||||
# 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 a torn result.
|
||||
_SKILLS_CACHE[cache_key] = (signature, now, skills)
|
||||
@@ -283,7 +270,6 @@ def skills_list(category: str = None, task_id: str = None) -> str:
|
||||
all_skills = _find_all_skills()
|
||||
try:
|
||||
from hermes_cli.plugins import discover_plugins, get_plugin_manager
|
||||
|
||||
discover_plugins()
|
||||
for plugin_skill in get_plugin_manager().list_plugin_skill_metadata():
|
||||
frontmatter = plugin_skill.pop("frontmatter", {})
|
||||
@@ -292,7 +278,6 @@ def skills_list(category: str = None, task_id: str = None) -> str:
|
||||
all_skills.append(plugin_skill)
|
||||
except Exception:
|
||||
logger.debug("Plugin skill listing failed", exc_info=True)
|
||||
|
||||
if not all_skills:
|
||||
return _json({
|
||||
"success": True, "skills": [], "categories": [],
|
||||
@@ -320,34 +305,28 @@ def _resolve_plugin_skill(name, file_path, task_id, preprocess):
|
||||
prompts, so the on-disk ``category/skill`` form is returned (None without a 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 = 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 providers load through plugins.memory, not the general PluginManager: load
|
||||
# the namespaced provider once so its collector can forward its skills into the registry.
|
||||
if plugin_skill_md is None and namespace == active_memory_provider:
|
||||
try:
|
||||
from plugins.memory import load_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():
|
||||
pm.remove_plugin_skill(name) # stale registry entry — file deleted out of band
|
||||
@@ -356,7 +335,6 @@ def _resolve_plugin_skill(name, file_path, task_id, preprocess):
|
||||
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
|
||||
|
||||
if available := pm.list_plugin_skills(namespace): # plugin exists but this specific skill is missing
|
||||
return _fail(
|
||||
f"Skill '{bare}' not found in plugin '{namespace}'.",
|
||||
@@ -380,7 +358,6 @@ def _collect_skill_candidates(name, local_category_name, all_dirs):
|
||||
by resolved path. Collision detection is the point: silent shadowing of a local
|
||||
skill by a same-named external one is a real bug class, so the caller refuses >1."""
|
||||
from agent.skill_utils import iter_skill_index_files
|
||||
|
||||
candidates: List[Tuple[Optional[Path], Path]] = []
|
||||
seen_md: set = set()
|
||||
|
||||
@@ -405,13 +382,7 @@ def _collect_skill_candidates(name, local_category_name, all_dirs):
|
||||
# Recursive by directory name plus frontmatter `name:` — skills_list()
|
||||
# exposes the frontmatter name, so skill_view(name) must accept it too.
|
||||
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
|
||||
fm: dict = {}
|
||||
with suppress(Exception):
|
||||
fm, _ = _parse_frontmatter(_read_skill_text(found_skill_md))
|
||||
if fm.get("name") == name:
|
||||
if found_skill_md.parent.name == name or _safe_frontmatter(found_skill_md).get("name") == name:
|
||||
_record(found_skill_md.parent, found_skill_md)
|
||||
# Legacy flat <name>.md anywhere under the dir; support docs are excluded
|
||||
# (they load via file_path and must not shadow real skills sharing the basename).
|
||||
@@ -451,7 +422,6 @@ def _org_provenance_header(skill_dir: Path, active_skills_dir: Path):
|
||||
Announced IN the content the model consumes; the author is token-verified at push
|
||||
time by the sync plane, so the header is trustworthy."""
|
||||
from agent.skill_utils import ORG_PROVENANCE_FILE, is_org_mirror_path, org_id_of_path
|
||||
|
||||
if not is_org_mirror_path(skill_dir, active_skills_dir):
|
||||
return None, ""
|
||||
prov_org = org_id_of_path(skill_dir, active_skills_dir)
|
||||
@@ -491,16 +461,13 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict
|
||||
env_snapshot = load_env()
|
||||
remaining = _remaining_required_environment_names(required_env_vars, capture_result, env_snapshot=env_snapshot)
|
||||
setup_needed = bool(remaining)
|
||||
|
||||
# Only vars actually set pass through to sandboxed execution (execute_code, terminal).
|
||||
if available_env_names := [e["name"] for e in required_env_vars if e["name"] not in remaining]:
|
||||
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)
|
||||
|
||||
# Credential files for remote sandboxes: existing host files are registered,
|
||||
# missing ones flag setup_needed.
|
||||
required_cred_files_raw = frontmatter.get("required_credential_files", [])
|
||||
@@ -508,12 +475,10 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict
|
||||
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)
|
||||
setup_needed = setup_needed or bool(missing_cred_files)
|
||||
except Exception:
|
||||
logger.debug("Could not register credential files for skill %s", skill_name, exc_info=True)
|
||||
|
||||
status = SkillReadinessStatus.SETUP_NEEDED if setup_needed else SkillReadinessStatus.AVAILABLE
|
||||
fields = {
|
||||
"required_environment_variables": required_env_vars,
|
||||
@@ -539,27 +504,12 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict
|
||||
return fields, extras
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Located:
|
||||
"""Outcome of the local skill lookup phase of ``skill_view``."""
|
||||
|
||||
project_dirs: list
|
||||
all_dirs: list
|
||||
active_skills_dir: Path
|
||||
skill_dir: Optional[Path] = None
|
||||
skill_md: Any = None # set whenever error is None
|
||||
error: Optional[str] = None # JSON failure payload to return as-is
|
||||
|
||||
|
||||
def _locate_skill(name: str, local_category_name: Optional[str]) -> _Located:
|
||||
def _locate_skill(name: str, local_category_name: Optional[str], project_dirs: list, all_dirs: list):
|
||||
"""Unique on-disk skill for *name*: collision refusal, project-tier precedence,
|
||||
quarantine gate, not-found listing."""
|
||||
project_dirs, all_dirs, active_skills_dir = _skill_search_dirs()
|
||||
loc = _Located(project_dirs, all_dirs, active_skills_dir)
|
||||
quarantine gate, not-found listing. Returns ``(error_json, skill_dir, skill_md)``;
|
||||
``skill_md`` is set whenever ``error_json`` is None."""
|
||||
if not all_dirs:
|
||||
loc.error = _fail("Skills directory does not exist yet. It will be created on first install.")
|
||||
return loc
|
||||
|
||||
return _fail("Skills directory does not exist yet. It will be created on first install."), None, None
|
||||
candidates = _collect_skill_candidates(name, local_category_name, all_dirs)
|
||||
if len(candidates) > 1 and project_dirs:
|
||||
# A project skill intentionally overrides a same-named local/external skill;
|
||||
@@ -568,40 +518,36 @@ def _locate_skill(name: str, local_category_name: Optional[str]) -> _Located:
|
||||
if len(candidates) > 1:
|
||||
paths = [str(smd) for _, smd in candidates]
|
||||
logger.warning("Skill name collision for '%s': %d candidates — %s", name, len(candidates), "; ".join(paths))
|
||||
loc.error = _fail(
|
||||
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 loc
|
||||
if candidates:
|
||||
loc.skill_dir, loc.skill_md = candidates[0]
|
||||
|
||||
"or rename one of the colliding skills so each name is unique."), None, None
|
||||
skill_dir, skill_md = candidates[0] if candidates else (None, None)
|
||||
# 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).
|
||||
if loc.skill_md is not None and project_dirs:
|
||||
if skill_md is not None and project_dirs:
|
||||
from agent.skill_utils import is_quarantined_project_skill
|
||||
|
||||
if _under_any(loc.skill_md, project_dirs) and is_quarantined_project_skill(loc.skill_md):
|
||||
loc.error = _fail(
|
||||
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`.")
|
||||
return loc
|
||||
|
||||
if not loc.skill_md or not loc.skill_md.exists():
|
||||
hint="Inspect the skill in the repo checkout, or untrust the repo with `hermes skills untrust`."
|
||||
), None, None
|
||||
if not skill_md or not skill_md.exists():
|
||||
available = [s["name"] for s in _sort_skills(_find_all_skills())[:20]]
|
||||
loc.error = _fail(f"Skill '{name}' not found.", available_skills=available, hint="Use skills_list to see all available skills")
|
||||
return loc
|
||||
return _fail(f"Skill '{name}' not found.", available_skills=available,
|
||||
hint="Use skills_list to see all available skills"), None, None
|
||||
return None, skill_dir, skill_md
|
||||
|
||||
|
||||
def _log_security_warnings(name: str, skill_md: Path, content: str, loc: _Located) -> None:
|
||||
def _log_security_warnings(name: str, skill_md: Path, content: str, all_dirs: list, active_skills_dir: Path):
|
||||
"""Warn (never block) when loaded from outside the trusted dirs (project + local +
|
||||
external) and/or when common prompt-injection patterns appear."""
|
||||
trusted_dirs = [loc.active_skills_dir.resolve()]
|
||||
trusted_dirs = [active_skills_dir.resolve()]
|
||||
with suppress(Exception):
|
||||
trusted_dirs.extend(d.resolve() for d in loc.all_dirs)
|
||||
trusted_dirs.extend(d.resolve() for d in all_dirs)
|
||||
warnings = []
|
||||
if not _under_any(skill_md, trusted_dirs):
|
||||
warnings.append(f"skill file is outside the trusted skills directory (~/.hermes/skills/): {skill_md}")
|
||||
@@ -623,7 +569,6 @@ def skill_view(
|
||||
# can't be reinterpreted as a plugin namespace.
|
||||
if lookup_error := _skill_lookup_path_error(name):
|
||||
return _fail(lookup_error, hint=_LOOKUP_HINT)
|
||||
|
||||
local_category_name: str | None = None
|
||||
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)
|
||||
@@ -633,28 +578,21 @@ def skill_view(
|
||||
# re-validate it since `bare` is not namespace-checked.
|
||||
if local_category_name and (lookup_error := _skill_lookup_path_error(local_category_name)):
|
||||
return _fail(lookup_error, hint=_LOOKUP_HINT)
|
||||
|
||||
loc = _locate_skill(name, local_category_name)
|
||||
if loc.error is not None:
|
||||
return loc.error
|
||||
skill_dir, skill_md, active_skills_dir = loc.skill_dir, loc.skill_md, loc.active_skills_dir
|
||||
|
||||
project_dirs, all_dirs, active_skills_dir = _skill_search_dirs()
|
||||
error, skill_dir, skill_md = _locate_skill(name, local_category_name, project_dirs, all_dirs)
|
||||
if error is not None:
|
||||
return error
|
||||
try: # read once — reused for platform check and main content
|
||||
content = _read_skill_text(skill_md)
|
||||
except Exception as e:
|
||||
return _fail(f"Failed to read skill '{name}': {e}")
|
||||
_log_security_warnings(name, skill_md, content, loc)
|
||||
|
||||
frontmatter: Dict[str, Any] = {}
|
||||
with suppress(Exception):
|
||||
frontmatter, _ = _parse_frontmatter(content)
|
||||
|
||||
_log_security_warnings(name, skill_md, content, all_dirs, active_skills_dir)
|
||||
frontmatter = _safe_frontmatter(content=content)
|
||||
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 _fail(f"Skill '{resolved_name}' is disabled. Enable it with `hermes skills` or inspect the files directly on disk.")
|
||||
|
||||
if file_path and skill_dir:
|
||||
return _serve_skill_file(
|
||||
skill_dir, file_path, name,
|
||||
@@ -667,14 +605,12 @@ def skill_view(
|
||||
tags, related_skills = (
|
||||
_parse_tags(hermes_meta.get(k) or frontmatter.get(k, "")) for k in ("tags", "related_skills"))
|
||||
linked_files = _skill_linked_files(skill_dir)
|
||||
|
||||
try:
|
||||
rel_path = str(skill_md.relative_to(active_skills_dir))
|
||||
except ValueError: # external skill — relative to its own parent dir
|
||||
rel_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)
|
||||
readiness, readiness_extras = _skill_readiness(frontmatter, skill_name)
|
||||
|
||||
rendered_content = content if not preprocess else _preprocess_skill(
|
||||
content, skill_dir, task_id, "Could not preprocess skill content for %s", skill_name)
|
||||
org_provenance = None
|
||||
@@ -684,7 +620,6 @@ def skill_view(
|
||||
rendered_content = header + rendered_content
|
||||
except Exception:
|
||||
logger.debug("Could not resolve org provenance for %s", skill_name, exc_info=True)
|
||||
|
||||
result = {
|
||||
"success": True,
|
||||
"name": skill_name,
|
||||
@@ -763,8 +698,7 @@ def _skill_view_with_bump(args, **kw):
|
||||
in this session returns a short stub (cache cleared on context compression)."""
|
||||
name = args.get("name", "")
|
||||
task_id = kw.get("task_id")
|
||||
stub = _check_skill_view_dedup(task_id, name, args.get("file_path"))
|
||||
if stub is not None:
|
||||
if (stub := _check_skill_view_dedup(task_id, name, args.get("file_path"))) is not None:
|
||||
return stub
|
||||
result = skill_view(name, file_path=args.get("file_path"), task_id=task_id)
|
||||
try:
|
||||
|
||||
@@ -25,8 +25,7 @@ _SKILL_VIEW_DEDUP_MESSAGE = (
|
||||
|
||||
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:
|
||||
if not (src := payload.get("_source_path")):
|
||||
return None
|
||||
try:
|
||||
st = os.stat(src)
|
||||
@@ -37,14 +36,11 @@ def _skill_view_fingerprint(payload: dict) -> tuple | 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
|
||||
# changes without the file changing; the model must see the refreshed status.
|
||||
if payload.get("setup_needed") or payload.get("readiness_status") == "setup_needed":
|
||||
if not task_id or payload.get("setup_needed") or payload.get("readiness_status") == "setup_needed":
|
||||
return
|
||||
fp = _skill_view_fingerprint(payload)
|
||||
if fp is None:
|
||||
if (fp := _skill_view_fingerprint(payload)) is None:
|
||||
return
|
||||
key = (str(payload.get("name") or name), file_path or "")
|
||||
with _skill_view_tracker_lock:
|
||||
@@ -59,19 +55,17 @@ def _check_skill_view_dedup(task_id, name, file_path) -> str | None:
|
||||
is unchanged on disk; None otherwise."""
|
||||
if not task_id:
|
||||
return None
|
||||
n = str(name)
|
||||
with _skill_view_tracker_lock:
|
||||
cache = _skill_view_tracker.get(str(task_id))
|
||||
if not cache:
|
||||
if not (cache := _skill_view_tracker.get(str(task_id))):
|
||||
return None
|
||||
# Record key is the RESOLVED name; match raw 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:
|
||||
if rec_fp != (file_path or "") or (
|
||||
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)
|
||||
|
||||
+16
-15
@@ -49,20 +49,29 @@ def _truncate_description(description: str) -> str:
|
||||
return description
|
||||
|
||||
|
||||
def _safe_frontmatter(path: Path | None = None, *, content: str | None = None) -> Dict[str, Any]:
|
||||
"""Frontmatter of *path* (or of *content*), ``{}`` on any read/parse failure.
|
||||
Parses via ``tools.skills_tool._parse_frontmatter`` so test patches are honored."""
|
||||
from tools import skills_tool as _st
|
||||
with suppress(Exception):
|
||||
return _st._parse_frontmatter(_read_skill_text(path) if content is None else content)[0]
|
||||
return {}
|
||||
|
||||
|
||||
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")}
|
||||
groups: Dict[str, List[str]] = {}
|
||||
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)
|
||||
groups.setdefault(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}
|
||||
groups.setdefault("other", []).append(rel)
|
||||
return {k: groups[k] for k in (*_SUPPORT_DIRS, "other") if k in groups}
|
||||
|
||||
|
||||
def _serve_skill_file(
|
||||
@@ -74,7 +83,6 @@ def _serve_skill_file(
|
||||
available-files listing on not-found (local skills); ``read_error_prefix`` wraps
|
||||
non-decode read errors (plugin) instead of propagating to the caller's handler."""
|
||||
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)
|
||||
@@ -133,7 +141,6 @@ def _serve_plugin_skill(
|
||||
"""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}"
|
||||
@@ -141,9 +148,7 @@ def _serve_plugin_skill(
|
||||
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] = {}
|
||||
with suppress(Exception):
|
||||
parsed_frontmatter, _ = _st._parse_frontmatter(content)
|
||||
parsed_frontmatter = _safe_frontmatter(content=content)
|
||||
if _st._is_skill_disabled(qualified_name):
|
||||
return _fail(f"Skill '{qualified_name}' is disabled.")
|
||||
if not _st.skill_matches_platform(parsed_frontmatter):
|
||||
@@ -152,7 +157,6 @@ def _serve_plugin_skill(
|
||||
readiness_status=SkillReadinessStatus.UNSUPPORTED.value)
|
||||
if file_path:
|
||||
return _serve_skill_file(skill_md.parent, file_path, qualified_name, read_error_prefix=True)
|
||||
|
||||
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)
|
||||
@@ -166,10 +170,8 @@ def _serve_plugin_skill(
|
||||
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)
|
||||
rendered_content = content if not preprocess else _preprocess_skill(
|
||||
content, skill_md.parent, session_id, "Could not preprocess plugin skill %s:%s", namespace, bare)
|
||||
return _json({
|
||||
"success": True,
|
||||
"name": qualified_name,
|
||||
@@ -181,7 +183,6 @@ def _serve_plugin_skill(
|
||||
|
||||
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
|
||||
|
||||
+23
-50
@@ -34,7 +34,6 @@ def _is_remote_env_backend(backend: str) -> bool:
|
||||
return False
|
||||
try:
|
||||
from agent.terminal_env_registry import provider_flag
|
||||
|
||||
return bool(provider_flag(backend, "is_remote", False))
|
||||
except Exception:
|
||||
return False
|
||||
@@ -48,7 +47,7 @@ def _normalize_prerequisite_values(value: Any) -> List[str]:
|
||||
|
||||
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):
|
||||
if not isinstance(prereqs, dict) or not prereqs:
|
||||
return [], []
|
||||
return (
|
||||
_normalize_prerequisite_values(prereqs.get("env_vars")),
|
||||
@@ -73,10 +72,7 @@ def _normalize_setup_metadata(frontmatter: Dict[str, Any]) -> Dict[str, Any]:
|
||||
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:
|
||||
if not isinstance(item, dict) or not (env_var := str(item.get("env_var") or "").strip()):
|
||||
continue
|
||||
entry: Dict[str, Any] = {
|
||||
"env_var": env_var,
|
||||
@@ -93,13 +89,19 @@ def _get_required_environment_variables(
|
||||
"""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:
|
||||
required: Dict[str, Dict[str, Any]] = {} # env name -> entry, insertion-ordered, first wins
|
||||
declared = _as_dict_list(frontmatter.get("required_environment_variables"))
|
||||
entries = [{"name": i} if isinstance(i, str) else i for i in declared if isinstance(i, (str, dict))]
|
||||
entries += [
|
||||
{"name": i.get("env_var"), "prompt": i.get("prompt"), "help": i.get("provider_url") or setup.get("help")}
|
||||
for i in setup["collect_secrets"]]
|
||||
if legacy_env_vars is None:
|
||||
legacy_env_vars, _ = _collect_prerequisite_values(frontmatter)
|
||||
entries += [{"name": v} for v in legacy_env_vars]
|
||||
for entry in entries:
|
||||
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
|
||||
if not env_name or env_name in required or not _ENV_VAR_NAME_RE.match(env_name):
|
||||
continue
|
||||
normalized: Dict[str, Any] = {
|
||||
"name": env_name,
|
||||
"prompt": str(entry.get("prompt") or f"Enter value for {env_name}").strip()}
|
||||
@@ -110,24 +112,8 @@ def _get_required_environment_variables(
|
||||
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
|
||||
required[env_name] = normalized
|
||||
return list(required.values())
|
||||
|
||||
|
||||
def _capture_result(missing_names, setup_skipped=False, gateway_setup_hint=None):
|
||||
@@ -138,7 +124,6 @@ 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]
|
||||
@@ -151,8 +136,6 @@ def _capture_required_environment_variables(
|
||||
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, **{k: entry[k] for k in ("help", "required_for") if entry.get(k)}}
|
||||
@@ -162,11 +145,9 @@ def _capture_required_environment_variables(
|
||||
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) and callback_result.get("success")
|
||||
if ok and not callback_result.get("skipped"):
|
||||
continue
|
||||
setup_skipped = True
|
||||
remaining_names.append(entry["name"])
|
||||
return _capture_result(remaining_names, setup_skipped)
|
||||
if not (ok and not callback_result.get("skipped")):
|
||||
remaining_names.append(entry["name"])
|
||||
return _capture_result(remaining_names, bool(remaining_names))
|
||||
|
||||
|
||||
def _is_gateway_surface() -> bool:
|
||||
@@ -189,37 +170,29 @@ def _env_snapshot_or_load(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))
|
||||
return bool(env_snapshot[var_name] if var_name in env_snapshot else os.getenv(var_name))
|
||||
|
||||
|
||||
def _remaining_required_environment_names(
|
||||
required_env_vars: List[Dict[str, Any]],
|
||||
capture_result: Dict[str, Any],
|
||||
*,
|
||||
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")
|
||||
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:
|
||||
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'}."
|
||||
|
||||
Reference in New Issue
Block a user