Skip to content

The agent that grows with you

refactor(hermes_cli): compact plugin_dev, plugin_index, plugin_capabilities

Teknium7f457609b3d7
diff --git a/hermes_cli/plugin_capabilities.py b/hermes_cli/plugin_capabilities.py
index cb655d5d222..143121b9ebc 100644
--- a/hermes_cli/plugin_capabilities.py
+++ b/hermes_cli/plugin_capabilities.py
@@ -1,8 +1,7 @@
-"""Plugin capability declarations + consent state (#64228).
+"""Plugin capability declarations + consent state.
-Canonical registry ------------------ Every capability id maps 1:1 to a trust gate that **already
-exists** on the enforcing surface. We deliberately do not mint capability ids without an enforcing
-gate:
+Every capability id maps 1:1 to a trust gate that already exists on the enforcing surface; ids
+without an enforcing gate are deliberately never minted.
"""
from __future__ import annotations
@@ -21,15 +20,11 @@ class CapabilitySpec:
"""One declarable capability and the legacy gate it maps to."""
id: str
- # Path of the deprecated boolean under ``plugins.entries.<plugin_id>``,
- # e.g. ("allow_tool_override",) or ("llm", "allow_model_override").
- legacy_path: Tuple[str, ...]
- # One-line risk description shown on the consent screen.
- description: str
+ legacy_path: Tuple[str, ...] # deprecated boolean under plugins.entries.<id>, e.g. ("llm", "allow_model_override")
+ description: str # one-line risk description shown on the consent screen
-# Canonical registry — ONLY capabilities with an existing enforcing surface.
-# (id, legacy_path, description)
+# (id, legacy_path, description) — ONLY capabilities with an existing enforcing surface.
_CAPABILITY_ROWS = (
("tools.override", ("allow_tool_override",),
"Replace built-in tools (e.g. shell_exec, write_file) — an "
@@ -52,9 +47,8 @@ _CAPABILITY_ROWS = (
"(add reactions, rename threads) via ctx.platform_actions"),
)
CAPABILITY_REGISTRY: Dict[str, CapabilitySpec] = {
- cid: CapabilitySpec(id=cid, legacy_path=path, description=desc) for cid, path, desc in _CAPABILITY_ROWS
+ cid: CapabilitySpec(cid, path, desc) for cid, path, desc in _CAPABILITY_ROWS
}
-
VALID_CAPABILITY_IDS = frozenset(CAPABILITY_REGISTRY)
# Config keys under ``plugins.entries.<plugin_id>``.
@@ -62,16 +56,11 @@ GRANTED_KEY = "granted_capabilities"
CONSENT_KEY = "capabilities_consent"
-# ---------------------------------------------------------------------------
-# Declaration parsing
-# ---------------------------------------------------------------------------
-
def parse_declared_capabilities(raw: Any, plugin_name: str = "?") -> List[str]:
"""Normalize a manifest ``capabilities:`` value into known capability ids.
- Unknown ids are dropped with a warning (forward compat: a plugin built for a newer Hermes may
- declare ids this build doesn't know; they can never be granted here, so hiding them from the
- consent screen is the fail-closed choice — the plugin must degrade gracefully).
+ Unknown ids are dropped with a warning: they can never be granted by this build, so hiding
+ them from the consent screen is the fail-closed choice (the plugin must degrade gracefully).
"""
if not raw:
return []
@@ -113,24 +102,24 @@ def capability_set_hash(capabilities: Iterable[str]) -> str:
# ---------------------------------------------------------------------------
def _plugin_entry(plugin_id: str, config: Optional[Mapping[str, Any]] = None) -> dict:
- """Return ``plugins.entries.<plugin_id>`` or ``{}`` — never raises."""
+ """``plugins.entries.<plugin_id>`` or ``{}`` — never raises (unreadable state = not granted)."""
try:
cfg: Any = config
if cfg is None:
from hermes_cli.config import load_config
cfg = load_config() or {}
- entries = (cfg.get("plugins") or {}).get("entries") or {}
- entry = entries.get(plugin_id) or {}
+ entry = ((cfg.get("plugins") or {}).get("entries") or {}).get(plugin_id) or {}
return entry if isinstance(entry, dict) else {}
except Exception:
- # Ground rule: failure to read consent state = not granted.
return {}
def granted_capabilities(plugin_id: str, config: Optional[Mapping[str, Any]] = None) -> frozenset:
- """Return the set of capabilities the user has granted this plugin."""
+ """The set of capabilities the user has granted this plugin."""
raw = _plugin_entry(plugin_id, config).get(GRANTED_KEY)
- return frozenset(_known(c.strip() for c in raw if isinstance(c, str))) if isinstance(raw, list) else frozenset()
+ if not isinstance(raw, list):
+ return frozenset()
+ return frozenset(_known(c.strip() for c in raw if isinstance(c, str)))
def _legacy_gate_set(entry: Mapping[str, Any], spec: CapabilitySpec) -> bool:
@@ -144,12 +133,8 @@ def _legacy_gate_set(entry: Mapping[str, Any], spec: CapabilitySpec) -> bool:
def plugin_capability_granted(plugin_id: str, capability: str, config: Optional[Mapping[str, Any]] = None) -> bool:
- """Canonical check: is *capability* live for *plugin_id*?
-
- True when the capability is in ``granted_capabilities`` (consent flow) OR the legacy
- ``allow_*`` key is set (deprecated, still honored so existing configs keep working). Unknown
- ids and any failure to read state return ``False`` (fail closed).
- """
+ """Canonical check: is *capability* live for *plugin_id*? True via ``granted_capabilities`` OR
+ the deprecated-but-honored legacy ``allow_*`` key. Unknown ids / unreadable state -> False."""
spec = CAPABILITY_REGISTRY.get(capability)
if spec is None:
logger.debug("capability check for unknown id %r (plugin %s) — denied", capability, plugin_id)
@@ -161,8 +146,7 @@ def plugin_capability_granted(plugin_id: str, capability: str, config: Optional[
allowed, evidence = True, f"legacy key plugins.entries.{plugin_id}.{'.'.join(spec.legacy_path)} (deprecated)"
else:
allowed, evidence = False, "not granted"
- # Audit line for capability gate decisions (the ``checked_by`` trail).
- logger.info(
+ logger.info( # audit trail for capability gate decisions
"capability_check plugin=%s capability=%s decision=%s checked_by=plugin_capability_granted evidence=%s",
plugin_id, capability, "allow" if allowed else "deny", evidence,
)
@@ -183,17 +167,13 @@ def _child_dict(parent: dict, key: str) -> dict:
def record_consent(plugin_id: str, granted: Iterable[str], declared: Iterable[str]) -> None:
- """Persist a consent decision for *plugin_id*.
-
- Writes ``granted_capabilities`` (union with prior grants), the consent record (hash of the
- declared set the user saw + UTC timestamp), and the legacy ``allow_*`` keys for each new grant
- so every existing enforcement site keeps working unchanged.
- """
+ """Persist a consent decision: ``granted_capabilities`` (union with prior grants), the consent
+ record (hash of the declared set the user saw + UTC timestamp), and the legacy ``allow_*`` key
+ for each grant so existing enforcement sites keep working unchanged."""
from hermes_cli.config import load_config, save_config
config = load_config()
entry = _child_dict(_child_dict(_child_dict(config, "plugins"), "entries"), plugin_id)
-
previous = entry.get(GRANTED_KEY)
merged = (list(previous) if isinstance(previous, list) else []) + _known(granted)
entry[GRANTED_KEY] = sorted(_known(c for c in merged if isinstance(c, str)))
@@ -201,9 +181,7 @@ def record_consent(plugin_id: str, granted: Iterable[str], declared: Iterable[st
"hash": capability_set_hash(_known(declared)),
"granted_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
-
- # Bridge: mirror each granted capability into its legacy gate so the
- # existing enforcement sites (which still read allow_*) honor the grant.
+ # Bridge: mirror each grant into its legacy gate (enforcement sites still read allow_*).
for cap in entry[GRANTED_KEY]:
*parents, leaf = CAPABILITY_REGISTRY[cap].legacy_path
node = entry
@@ -229,13 +207,8 @@ def consent_hash(plugin_id: str, config: Optional[Mapping[str, Any]] = None) ->
def pending_capabilities(
plugin_id: str, declared: Iterable[str], config: Optional[Mapping[str, Any]] = None
) -> List[str]:
- """Capabilities declared by the plugin but not yet granted.
-
- Used both at first consent (everything is pending) and on update re-consent: when a new version
- declares capabilities the granted set lacks, those additions are returned and must be re-
- consented before they go live. The stored consent hash tells whether the *declared* set changed
- since the user last saw it.
- """
+ """Declared-but-ungranted capabilities: everything at first consent, only the additions on an
+ update re-consent (they must be re-consented before going live)."""
granted = granted_capabilities(plugin_id, config)
return [c for c in _known(declared) if c not in granted]
@@ -243,9 +216,6 @@ def pending_capabilities(
def declared_set_changed(
plugin_id: str, declared: Iterable[str], config: Optional[Mapping[str, Any]] = None
) -> bool:
- """True when the declared set differs from what the user consented to.
-
- No stored consent at all counts as changed (never consented).
- """
+ """True when the declared set differs from what the user consented to (or never consented)."""
stored = consent_hash(plugin_id, config)
return stored is None or stored != capability_set_hash(_known(declared))
diff --git a/hermes_cli/plugin_dev.py b/hermes_cli/plugin_dev.py
index 3994ef9f040..87d6cf60ba3 100644
--- a/hermes_cli/plugin_dev.py
+++ b/hermes_cli/plugin_dev.py
@@ -1,8 +1,5 @@
-"""Runtime-backed validation behind ``hermes plugins doctor``.
-
-This core command keeps that contribution's manifest/import/ registration validation intent while
-routing every check through the current runtime contracts instead of maintaining a parallel scanner.
-"""
+"""Runtime-backed validation behind ``hermes plugins doctor``: every manifest/import/registration
+check routes through the real runtime contracts instead of a parallel scanner."""
from __future__ import annotations
@@ -32,43 +29,30 @@ def _deny_network(*_args: Any, **_kwargs: Any) -> None:
@contextmanager
def _doctor_runtime(plugin_path: Path):
- """Load one plugin through the real runtime and restore global state.
+ """Load one plugin through the real runtime and restore global state afterwards.
- Deliberately private Doctor machinery, not a plugin test framework. Registration code runs
- under a temporary HERMES_HOME with outbound socket connects blocked.
+ Private Doctor machinery, not a plugin test framework. Registration code runs under a temporary
+ HERMES_HOME with outbound socket connects blocked.
"""
stack = ExitStack()
try:
- # The temp dir enters the stack FIRST so any failure below — including
- # ENOSPC or KeyboardInterrupt inside copytree — deterministically
- # removes it instead of stranding a hermes-plugin-doctor-* directory
- # until interpreter GC (or never, on a hard exit).
- temporary_home = stack.enter_context(
- tempfile.TemporaryDirectory(prefix="hermes-plugin-doctor-")
- )
- home = Path(temporary_home)
+ # The temp dir enters the stack FIRST so any failure below (ENOSPC / KeyboardInterrupt in
+ # copytree) removes it instead of stranding a hermes-plugin-doctor-* directory.
+ home = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="hermes-plugin-doctor-")))
bundled = home / "bundled-plugins"
plugins_root = home / "plugins"
bundled.mkdir(parents=True)
plugins_root.mkdir(parents=True)
copied = plugins_root / plugin_path.name
shutil.copytree(
- plugin_path,
- copied,
+ plugin_path, copied,
ignore=shutil.ignore_patterns(".git", "__pycache__", ".pytest_cache", "*.pyc"),
)
-
- stack.enter_context(
- patch.dict(
- os.environ,
- {
- "HERMES_HOME": str(home),
- "HERMES_BUNDLED_PLUGINS": str(bundled),
- "HERMES_ENABLE_PROJECT_PLUGINS": "0",
- },
- clear=False,
- )
- )
+ stack.enter_context(patch.dict(os.environ, {
+ "HERMES_HOME": str(home),
+ "HERMES_BUNDLED_PLUGINS": str(bundled),
+ "HERMES_ENABLE_PROJECT_PLUGINS": "0",
+ }, clear=False))
stack.enter_context(patch.object(socket, "create_connection", _deny_network))
stack.enter_context(patch.object(socket.socket, "connect", _deny_network))
stack.enter_context(patch.object(socket.socket, "connect_ex", _deny_network))
@@ -81,18 +65,12 @@ def _doctor_runtime(plugin_path: Path):
entries_before = {entry.name: entry for entry in registry._snapshot_entries()}
policy_before = dict(registry._plugin_override_policy)
- modules_before = {
- name
- for name in sys.modules
- if name == "hermes_plugins" or name.startswith("hermes_plugins.")
- }
+ modules_before = {name for name in sys.modules if _is_plugin_module(name)}
manager = PluginManager()
try:
manifests = manager._scan_directory(plugins_root, source="user")
if not manifests:
- raise _DoctorLoadError(
- f"Hermes discovery found no valid plugin manifest under {copied}"
- )
+ raise _DoctorLoadError(f"Hermes discovery found no valid plugin manifest under {copied}")
if len(manifests) != 1:
raise _DoctorLoadError(
f"Expected one plugin manifest, discovered {len(manifests)} under {copied}"
@@ -131,14 +109,15 @@ def _doctor_runtime(plugin_path: Path):
if changed_names:
registry._generation += 1
for name in list(sys.modules):
- if (
- name not in modules_before
- and (name == "hermes_plugins" or name.startswith("hermes_plugins."))
- ):
+ if name not in modules_before and _is_plugin_module(name):
sys.modules.pop(name, None)
stack.close()
+def _is_plugin_module(name: str) -> bool:
+ return name == "hermes_plugins" or name.startswith("hermes_plugins.")
+
+
@dataclass(frozen=True)
class DoctorFinding:
level: Literal["error", "warning"]
@@ -171,12 +150,9 @@ class DoctorReport:
f"{self.manifest.version or '(no version)'} ({self.manifest.kind})"
)
for finding in self.findings:
- marker = "ERROR" if finding.level == "error" else "WARN"
- lines.append(f" {marker}: {finding.message}")
+ lines.append(f" {'ERROR' if finding.level == 'error' else 'WARN'}: {finding.message}")
if self.ok:
- lines.append(
- " OK: runtime discovery, manifest parsing, import, and registration passed"
- )
+ lines.append(" OK: runtime discovery, manifest parsing, import, and registration passed")
lines.append(
f" registrations: {len(self.registered_tools)} tool(s), "
f"{len(self.registered_hooks)} hook(s)"
@@ -188,20 +164,13 @@ _MANIFEST_NAMES = ("plugin.yaml", "plugin.yml", "plugin.json")
def _has_manifest(path: Path) -> bool:
- return any(
- (path / name).exists() or (path / name).is_symlink()
- for name in _MANIFEST_NAMES
- )
+ return any((path / name).exists() or (path / name).is_symlink() for name in _MANIFEST_NAMES)
def _holds_plugin(path: Path) -> bool:
- """True when plugin discovery would find a manifest under *path*.
-
- Mirrors ``PluginManager._scan_directory``: a manifest in *path* itself or in one immediate
- subdirectory (category layout). Doctor copies the resolved directory wholesale before the
- runtime can reject it, so an unvalidated resolve is a disk-usage bug: with no argument
- Doctor defaults to ``.``, and any directory used to satisfy that.
- """
+ """True when discovery would find a manifest in *path* or one immediate subdirectory (category
+ layout), mirroring ``PluginManager._scan_directory``. Doctor copies the resolved directory
+ wholesale, so resolving an arbitrary directory (e.g. the default ``.``) would be a disk bug."""
if not path.is_dir():
return False
if _has_manifest(path):
@@ -214,12 +183,8 @@ def _holds_plugin(path: Path) -> bool:
def _is_plugin_id(raw: str) -> bool:
- """True when *raw* can name an installed plugin rather than a path.
-
- Ids are relative and may carry one category segment (``image_gen/openai``). Dot components
- are excluded: joining ``.`` onto a plugins root yields the root itself, handing Doctor every
- installed plugin at once instead of one.
- """
+ """True when *raw* can name an installed plugin (relative, maybe ``category/name``). Dot
+ components are excluded: ``.`` joined onto a plugins root would hand Doctor every plugin."""
if not raw or PurePath(raw).is_absolute():
return False
parts = PurePath(raw).parts
@@ -236,19 +201,11 @@ def resolve_plugin_path(target: str | os.PathLike[str] | None = None) -> Path:
candidates: list[Path] = []
if _is_plugin_id(raw):
- user_root = get_hermes_home() / "plugins"
- candidates.append(user_root / raw)
+ candidates.append(get_hermes_home() / "plugins" / raw)
try:
from hermes_cli.plugins import get_bundled_plugins_dir
-
bundled = get_bundled_plugins_dir()
- candidates.extend(
- [
- bundled / raw,
- bundled / "platforms" / raw,
- bundled / "model-providers" / raw,
- ]
- )
+ candidates += [bundled / raw, bundled / "platforms" / raw, bundled / "model-providers" / raw]
except Exception:
pass
candidates.append(Path.cwd() / ".hermes" / "plugins" / raw)
@@ -261,9 +218,7 @@ def resolve_plugin_path(target: str | os.PathLike[str] | None = None) -> Path:
f"({', '.join(_MANIFEST_NAMES)}), and {raw!r} is not an installed "
"plugin id. Point Doctor at a plugin directory."
)
- raise FileNotFoundError(
- f"Plugin {raw!r} was not found as a path or installed plugin id"
- )
+ raise FileNotFoundError(f"Plugin {raw!r} was not found as a path or installed plugin id")
def _accepts_var_kwargs(callback: Any) -> bool:
@@ -275,7 +230,7 @@ def _accepts_var_kwargs(callback: Any) -> bool:
def _check_manifest_v2(report: "DoctorReport", manifest: Any) -> None:
- """Manifest v2 (#64165) checks: versions, deps, pip declarations, schema."""
+ """Manifest v2 checks: versions, deps, pip declarations, config schema."""
import importlib.metadata
import re as _re
@@ -326,25 +281,18 @@ def _check_manifest_v2(report: "DoctorReport", manifest: Any) -> None:
)
if missing:
report.warning(
- "declared python_dependencies not installed: "
- + ", ".join(missing)
- + " — Hermes never auto-installs plugin dependencies; "
- + "install manually: pip install "
+ "declared python_dependencies not installed: " + ", ".join(missing)
+ + " — Hermes never auto-installs plugin dependencies; install manually: pip install "
+ " ".join(f"'{m}'" for m in missing)
)
schema = getattr(manifest, "config_schema", {}) or {}
if schema:
from hermes_cli.plugins import _CONFIG_SCHEMA_TYPES
-
for skey, spec in schema.items():
- if not isinstance(spec, dict):
- continue
- stype = spec.get("type")
+ stype = spec.get("type") if isinstance(spec, dict) else None
if stype is not None and str(stype).lower() not in _CONFIG_SCHEMA_TYPES:
- report.warning(
- f"config_schema key {skey!r} declares unknown type {stype!r}"
- )
+ report.warning(f"config_schema key {skey!r} declares unknown type {stype!r}")
def doctor_plugin(target: str | os.PathLike[str] | None = None) -> DoctorReport:
@@ -391,19 +339,16 @@ def doctor_plugin(target: str | os.PathLike[str] | None = None) -> DoctorReport:
"must accept **kwargs for forward compatibility"
)
- declared_hook_names = {name for name in declared_hooks if isinstance(name, str)}
- registered_hook_names = set(host.registered_hooks)
- for name in sorted(declared_hook_names - registered_hook_names):
- report.warning(f"manifest declares hook {name!r} but registration did not add it")
- for name in sorted(registered_hook_names - declared_hook_names):
- report.warning(f"registration adds hook {name!r} not listed in provides_hooks")
-
- declared_tool_names = {name for name in declared_tools if isinstance(name, str)}
- registered_tool_names = set(host.registered_tools)
- for name in sorted(declared_tool_names - registered_tool_names):
- report.warning(f"manifest declares tool {name!r} but registration did not add it")
- for name in sorted(registered_tool_names - declared_tool_names):
- report.warning(f"registration adds tool {name!r} not listed in provides_tools")
+ for kind, declared, registered in (
+ ("hook", declared_hooks, host.registered_hooks),
+ ("tool", declared_tools, host.registered_tools),
+ ):
+ declared_names = {name for name in declared if isinstance(name, str)}
+ registered_names = set(registered)
+ for name in sorted(declared_names - registered_names):
+ report.warning(f"manifest declares {kind} {name!r} but registration did not add it")
+ for name in sorted(registered_names - declared_names):
+ report.warning(f"registration adds {kind} {name!r} not listed in provides_{kind}s")
_check_manifest_v2(report, host.manifest)
except _DoctorLoadError as exc:
diff --git a/hermes_cli/plugin_index.py b/hermes_cli/plugin_index.py
index de814abeea4..4b910eea985 100644
--- a/hermes_cli/plugin_index.py
+++ b/hermes_cli/plugin_index.py
@@ -1,10 +1,8 @@
"""Community plugin index — fetch, cache, search, and name resolution.
-Mirrors the Skills Hub catalog pattern (``tools/skills_hub.py``): a static machine-readable JSON
-index hosted at a canonical URL, cached locally under ``HERMES_HOME/cache/`` with a TTL, with a
-bundled seed file as the offline fallback and format reference.
-
-Fallback chain: remote index → cached copy (fresh or stale) → bundled seed.
+Mirrors the Skills Hub catalog (``tools/skills_hub.py``): a static JSON index at a canonical URL,
+cached under ``HERMES_HOME/cache/`` with a TTL, bundled seed as offline fallback / format reference.
+Fallback chain: fresh cache → remote → stale cache → bundled seed.
"""
from __future__ import annotations
@@ -21,17 +19,9 @@ from hermes_constants import get_hermes_home
logger = logging.getLogger(__name__)
# Canonical index location. Override via config key ``plugins.index_url``.
-DEFAULT_INDEX_URL = (
- "https://raw.githubusercontent.com/NousResearch/hermes-plugin-index/main/index.json"
-)
-
-# Cache the fetched index for 24 hours; a stale cache is still preferred over
-# the bundled seed when the remote is unreachable.
-INDEX_CACHE_TTL = 24 * 3600
-
-# Bundled seed — offline fallback and the machine-readable format reference.
+DEFAULT_INDEX_URL = "https://raw.githubusercontent.com/NousResearch/hermes-plugin-index/main/index.json"
+INDEX_CACHE_TTL = 24 * 3600 # a stale cache still beats the bundled seed when remote is unreachable
SEED_INDEX_PATH = Path(__file__).parent / "data" / "plugin_index.json"
-
_FETCH_TIMEOUT = 10.0
_MAX_INDEX_BYTES = 5 * 1024 * 1024 # refuse absurdly large index payloads
@@ -96,17 +86,16 @@ def get_index_url() -> str:
def _parse_entries(raw: Any) -> List[PluginIndexEntry]:
- """Parse a decoded index document into entries, skipping malformed items."""
+ """Parse a decoded index document (object with ``plugins`` or bare list), skipping malformed items."""
if isinstance(raw, dict):
raw = raw.get("plugins", [])
if not isinstance(raw, list):
raise ValueError("Plugin index 'plugins' field must be a list.")
- elif not isinstance(raw, list): # bare-list form also accepted
+ elif not isinstance(raw, list):
raise ValueError("Plugin index must be a JSON object or list.")
- items = raw
entries: List[PluginIndexEntry] = []
- for item in items:
+ for item in raw:
if not isinstance(item, dict):
continue
name = item.get("name")
@@ -118,21 +107,19 @@ def _parse_entries(raw: Any) -> List[PluginIndexEntry]:
continue
subdir = item.get("subdir")
api_version = item.get("api_version")
- entries.append(
- PluginIndexEntry(
- name=name.strip(),
- description=str(item.get("description") or ""),
- author=str(item.get("author") or ""),
- tags=[str(t) for t in item.get("tags") or [] if isinstance(t, (str, int))],
- repo=repo.strip(),
- ref=str(item.get("ref") or ""),
- subdir=str(subdir).strip("/") if isinstance(subdir, str) and subdir.strip("/") else None,
- homepage=str(item["homepage"]) if item.get("homepage") else None,
- capabilities=[str(c) for c in item.get("capabilities") or []],
- api_version=int(api_version) if isinstance(api_version, (int, str)) and str(api_version).isdigit() else None,
- added_at=str(item["added_at"]) if item.get("added_at") else None,
- )
- )
+ entries.append(PluginIndexEntry(
+ name=name.strip(),
+ description=str(item.get("description") or ""),
+ author=str(item.get("author") or ""),
+ tags=[str(t) for t in item.get("tags") or [] if isinstance(t, (str, int))],
+ repo=repo.strip(),
+ ref=str(item.get("ref") or ""),
+ subdir=subdir.strip("/") if isinstance(subdir, str) and subdir.strip("/") else None,
+ homepage=str(item["homepage"]) if item.get("homepage") else None,
+ capabilities=[str(c) for c in item.get("capabilities") or []],
+ api_version=int(api_version) if isinstance(api_version, (int, str)) and str(api_version).isdigit() else None,
+ added_at=str(item["added_at"]) if item.get("added_at") else None,
+ ))
return entries
@@ -163,7 +150,6 @@ def _write_cache(text: str) -> None:
cache = _cache_path()
cache.parent.mkdir(parents=True, exist_ok=True)
from utils import atomic_write_text
-
atomic_write_text(cache, text)
except OSError as exc: # pragma: no cover - best effort
logger.debug("plugin index: cache write failed: %s", exc)
@@ -189,43 +175,31 @@ def _fetch_remote() -> Optional[List[PluginIndexEntry]]:
def load_index(*, refresh: bool = False, offline: bool = False) -> tuple[List[PluginIndexEntry], str]:
- """Load the plugin index.
-
- Returns ``(entries, source)`` where *source* is one of ``"remote"``, ``"cache"``, or ``"seed"``.
-
- Order: fresh cache (unless *refresh*) → remote → stale cache → bundled seed. ``offline=True``
- skips the network entirely.
- """
+ """Load the plugin index as ``(entries, source)``; source is ``"remote"``/``"cache"``/``"seed"``.
+ Order: fresh cache (unless *refresh*) → remote (unless *offline*) → stale cache → seed."""
if not refresh:
cached = _read_cache(max_age=INDEX_CACHE_TTL)
if cached is not None:
return cached, "cache"
-
if not offline:
remote = _fetch_remote()
if remote is not None:
return remote, "remote"
-
stale = _read_cache(max_age=None)
if stale is not None:
return stale, "cache"
-
return _load_seed_entries(), "seed"
-# Search
-
def _score_entry(entry: PluginIndexEntry, term: str) -> float:
"""Fuzzy relevance score for *entry* against lowercase *term* (0 = no match)."""
import difflib
name = entry.name.lower()
tags = [t.lower() for t in entry.tags]
-
if term == name:
return 100.0
- # Fuzzy close-match on the name for typo tolerance.
- ratio = difflib.SequenceMatcher(None, term, name).ratio()
+ ratio = difflib.SequenceMatcher(None, term, name).ratio() # typo tolerance on the name
signals = (
(term in name, 80.0),
(term in tags, 70.0),
@@ -245,11 +219,9 @@ def search_index(
if capability:
cap = capability.lower()
pool = [e for e in entries if any(cap == c.lower() for c in e.capabilities)]
-
term = (term or "").strip().lower()
if not term:
return sorted(pool, key=lambda e: e.name)
-
matched = [(e, s) for e in pool if (s := _score_entry(e, term)) > 0]
matched.sort(key=lambda pair: (-pair[1], pair[0].name))
return [e for e, _s in matched]
@@ -258,12 +230,8 @@ def search_index(
def resolve_name(
entries: List[PluginIndexEntry], name: str
) -> tuple[Optional[PluginIndexEntry], List[PluginIndexEntry]]:
- """Resolve a bare plugin *name* against the index.
-
- Returns ``(entry, candidates)``: an exact (case-insensitive) unique match in ``entry``,
- otherwise ``entry is None`` and ``candidates`` holds any partial matches (empty = nothing
- similar, >1 on exact = ambiguous).
- """
+ """Resolve a bare *name*: ``(entry, candidates)`` — a unique case-insensitive match in
+ ``entry``, else ``None`` with the partial matches (empty = nothing similar, >1 = ambiguous)."""
lowered = name.strip().lower()
exact = [e for e in entries if e.name.lower() == lowered]
matches = exact or [e for e in entries if lowered in e.name.lower()]