The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): capability declarations + install/update consent flow (#64228)
Tekniumb088535c7811
diff --git a/hermes_cli/plugin_capabilities.py b/hermes_cli/plugin_capabilities.pynew file mode 100644index 00000000000..77b94329f8b--- /dev/null+++ b/hermes_cli/plugin_capabilities.py@@ -0,0 +1,384 @@+"""Plugin capability declarations + consent state (#64228).++Unifies the scattered per-plugin trust gates (``plugins.entries.<id>.allow_*``)+into one declared, diffable **capability model** with install/update-time+consent.++**This is NOT a sandbox.** In-process Python plugins remain trusted code — a+malicious plugin can import anything, monkey-patch core, and ignore all of+this. Capabilities govern the *host API surfaces* Hermes hands out (which+registrations succeed, which ``ctx`` methods are live) and give the user an+honest consent + audit trail. Actual isolation is a separate research track.++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:++=========================== ==================================================+Capability id Legacy config gate (``plugins.entries.<id>.…``)+=========================== ==================================================+``tools.override`` ``allow_tool_override``+``llm.provider_override`` ``llm.allow_provider_override``+``llm.model_override`` ``llm.allow_model_override``+``llm.agent_id_override`` ``llm.allow_agent_id_override``+``llm.profile_override`` ``llm.allow_profile_override``+``llm.task_override`` ``llm.allow_task_override``+=========================== ==================================================++The legacy ``allow_*`` keys keep working verbatim (deprecated but honored):+a gate is open when the legacy key is true **or** the capability is granted.++Consent state+-------------+Stored under the plugin's config entry::++ plugins:+ entries:+ <plugin_id>:+ granted_capabilities: [tools.override]+ capabilities_consent:+ hash: "<sha256 of the declared capability set at consent time>"+ granted_at: "2026-08-12T00:00:00+00:00"++The hash records *what the user saw* when they consented. When an update+declares capabilities whose set hash differs, the additions stay ungranted+until the user re-consents (``hermes plugins update`` surfaces the diff).++Ground rule: everything defaults OFF. Any failure to read consent state+(missing config, corrupt YAML, wrong types) means **not granted**.+"""++from __future__ import annotations++import hashlib+import logging+from dataclasses import dataclass+from datetime import datetime, timezone+from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple++logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+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+++# Canonical registry — ONLY capabilities with an existing enforcing surface.+CAPABILITY_REGISTRY: Dict[str, CapabilitySpec] = {+ spec.id: spec+ for spec in (+ CapabilitySpec(+ id="tools.override",+ legacy_path=("allow_tool_override",),+ description=(+ "Replace built-in tools (e.g. shell_exec, write_file) — an "+ "override can intercept everything routed through that tool"+ ),+ ),+ CapabilitySpec(+ id="llm.provider_override",+ legacy_path=("llm", "allow_provider_override"),+ description=(+ "Run host-owned LLM calls against a provider other than your "+ "active one (uses your credentials)"+ ),+ ),+ CapabilitySpec(+ id="llm.model_override",+ legacy_path=("llm", "allow_model_override"),+ description=(+ "Choose which model host-owned LLM calls use (spend follows "+ "the chosen model)"+ ),+ ),+ CapabilitySpec(+ id="llm.agent_id_override",+ legacy_path=("llm", "allow_agent_id_override"),+ description="Attribute its LLM calls to a different agent id",+ ),+ CapabilitySpec(+ id="llm.profile_override",+ legacy_path=("llm", "allow_profile_override"),+ description="Run LLM calls under a different auth profile",+ ),+ CapabilitySpec(+ id="llm.task_override",+ legacy_path=("llm", "allow_task_override"),+ description=(+ "Route its LLM calls through the host's built-in auxiliary "+ "task lanes"+ ),+ ),+ )+}++VALID_CAPABILITY_IDS = frozenset(CAPABILITY_REGISTRY)++# Config keys under ``plugins.entries.<plugin_id>``.+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).+ """+ if not raw:+ return []+ if not isinstance(raw, (list, tuple)):+ logger.warning(+ "Plugin %s: manifest 'capabilities' must be a list, got %s — ignoring",+ plugin_name, type(raw).__name__,+ )+ return []+ out: List[str] = []+ for item in raw:+ if not isinstance(item, str):+ logger.warning(+ "Plugin %s: ignoring non-string capability entry %r",+ plugin_name, item,+ )+ continue+ cap = item.strip()+ if cap in VALID_CAPABILITY_IDS:+ if cap not in out:+ out.append(cap)+ else:+ logger.warning(+ "Plugin %s: unknown capability %r (known: %s) — ignoring",+ plugin_name, cap, ", ".join(sorted(VALID_CAPABILITY_IDS)),+ )+ return out+++def capability_set_hash(capabilities: Iterable[str]) -> str:+ """Deterministic sha256 over a capability set (order-insensitive)."""+ canon = "\n".join(sorted(set(capabilities)))+ return hashlib.sha256(canon.encode("utf-8")).hexdigest()+++# ---------------------------------------------------------------------------+# Consent state (read side — fail closed on ANY error)+# ---------------------------------------------------------------------------++def _plugin_entry(plugin_id: str, config: Optional[Mapping[str, Any]] = None) -> dict:+ """Return ``plugins.entries.<plugin_id>`` or ``{}`` — never raises."""+ 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 {}+ 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.++ Fail-closed: missing/corrupt state yields the empty set.+ """+ entry = _plugin_entry(plugin_id, config)+ raw = entry.get(GRANTED_KEY)+ if not isinstance(raw, list):+ return frozenset()+ return frozenset(+ c.strip() for c in raw+ if isinstance(c, str) and c.strip() in VALID_CAPABILITY_IDS+ )+++def _legacy_gate_set(entry: Mapping[str, Any], spec: CapabilitySpec) -> bool:+ """True when the deprecated ``allow_*`` key for *spec* is truthy."""+ node: Any = entry+ for part in spec.legacy_path:+ if not isinstance(node, Mapping):+ return False+ node = node.get(part)+ return bool(node) and node is not None+++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 EITHER:++ * the capability appears in ``granted_capabilities`` (consent flow), OR+ * the legacy ``allow_*`` config key is set (deprecated, still honored so+ existing configs keep working).++ Unknown capability ids and any failure to read state return ``False``+ (ground rule 4: fail closed).+ """+ spec = CAPABILITY_REGISTRY.get(capability)+ if spec is None:+ logger.debug(+ "capability check for unknown id %r (plugin %s) — denied",+ capability, plugin_id,+ )+ return False+ entry = _plugin_entry(plugin_id, config)+ if capability in granted_capabilities(plugin_id, config={"plugins": {"entries": {plugin_id: entry}}}):+ _log_capability_decision(plugin_id, capability, True, "granted_capabilities")+ return True+ if _legacy_gate_set(entry, spec):+ _log_capability_decision(+ plugin_id, capability, True,+ f"legacy key plugins.entries.{plugin_id}.{'.'.join(spec.legacy_path)} (deprecated)",+ )+ return True+ _log_capability_decision(plugin_id, capability, False, "not granted")+ return False+++def _log_capability_decision(+ plugin_id: str, capability: str, allowed: bool, evidence: str+) -> None:+ """Audit line for capability gate decisions (the ``checked_by`` trail)."""+ logger.info(+ "capability_check plugin=%s capability=%s decision=%s checked_by=plugin_capability_granted evidence=%s",+ plugin_id, capability, "allow" if allowed else "deny", evidence,+ )+++# ---------------------------------------------------------------------------+# Consent state (write side)+# ---------------------------------------------------------------------------++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 any previously granted set),+ the consent record (hash of the *declared* set the user saw + UTC+ timestamp), and — so every existing enforcement site keeps working+ without changes — the corresponding legacy ``allow_*`` keys for each+ newly granted capability.+ """+ from hermes_cli.config import load_config, save_config++ granted_list = [c for c in dict.fromkeys(granted) if c in VALID_CAPABILITY_IDS]+ declared_list = [c for c in dict.fromkeys(declared) if c in VALID_CAPABILITY_IDS]++ config = load_config()+ plugins_cfg = config.setdefault("plugins", {})+ if not isinstance(plugins_cfg, dict):+ plugins_cfg = {}+ config["plugins"] = plugins_cfg+ entries = plugins_cfg.setdefault("entries", {})+ if not isinstance(entries, dict):+ entries = {}+ plugins_cfg["entries"] = entries+ entry = entries.setdefault(plugin_id, {})+ if not isinstance(entry, dict):+ entry = {}+ entries[plugin_id] = entry++ previous = entry.get(GRANTED_KEY)+ merged = list(previous) if isinstance(previous, list) else []+ for cap in granted_list:+ if cap not in merged:+ merged.append(cap)+ entry[GRANTED_KEY] = sorted(+ c for c in dict.fromkeys(merged)+ if isinstance(c, str) and c in VALID_CAPABILITY_IDS+ )+ entry[CONSENT_KEY] = {+ "hash": capability_set_hash(declared_list),+ "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.+ for cap in entry[GRANTED_KEY]:+ spec = CAPABILITY_REGISTRY[cap]+ node = entry+ for part in spec.legacy_path[:-1]:+ child = node.setdefault(part, {})+ if not isinstance(child, dict):+ child = {}+ node[part] = child+ node = child+ node[spec.legacy_path[-1]] = True++ save_config(config)+ logger.info(+ "capability_consent plugin=%s granted=%s declared_hash=%s",+ plugin_id, ",".join(entry[GRANTED_KEY]) or "(none)",+ entry[CONSENT_KEY]["hash"][:12],+ )+++def consent_hash(plugin_id: str, config: Optional[Mapping[str, Any]] = None) -> Optional[str]:+ """Return the stored consent hash, or None when absent/corrupt."""+ entry = _plugin_entry(plugin_id, config)+ consent = entry.get(CONSENT_KEY)+ if not isinstance(consent, dict):+ return None+ h = consent.get("hash")+ return h if isinstance(h, str) and h else 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_list = [c for c in dict.fromkeys(declared) if c in VALID_CAPABILITY_IDS]+ granted = granted_capabilities(plugin_id, config)+ return [c for c in declared_list if c not in granted]+++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).+ """+ stored = consent_hash(plugin_id, config)+ if stored is None:+ return True+ return stored != capability_set_hash(+ c for c in declared if c in VALID_CAPABILITY_IDS+ )diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 9459dda9ce1..2c0bc429421 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -55,6 +55,13 @@ from hermes_constants import get_hermes_homefrom utils import env_var_enabled, fast_safe_loadfrom hermes_cli.config import cfg_getfrom hermes_cli.middleware import OBSERVER_SCHEMA_VERSION, VALID_MIDDLEWARE+from hermes_cli.plugin_capabilities import ( # noqa: F401 — re-exported+ CAPABILITY_REGISTRY,+ plugin_capability_granted,+)+from hermes_cli.plugin_capabilities import (+ parse_declared_capabilities as _parse_declared_capabilities,+)def get_bundled_plugins_dir() -> Path:@@ -391,6 +398,13 @@ class PluginManifest:key: str = ""portable: bool = Falseskill_namespace: str = ""+ # Declared capability ids from the manifest ``capabilities:`` list+ # (#64228). Normalized to KNOWN ids only — see+ # ``hermes_cli.plugin_capabilities.CAPABILITY_REGISTRY``. Declaration is+ # consent metadata, not a grant: a capability is live only when the user+ # granted it (``plugins.entries.<id>.granted_capabilities``) or the+ # deprecated legacy ``allow_*`` key is set.+ capabilities: List[str] = field(default_factory=list)@dataclass(frozen=True)@@ -861,6 +875,24 @@ class PluginContext:self.manifest.name, name, " (override)" if override else "",)+ # -- capability probing (#64228) -----------------------------------------++ def has_capability(self, capability: str) -> bool:+ """Return True when *capability* is live for this plugin.++ Plugins should probe with this and degrade gracefully instead of+ crashing when a gated host surface refuses them. Bundled plugins are+ trusted for ``tools.override`` (mirrors the registration gate); for+ everything else the answer comes from the granted-capability set or+ the deprecated legacy ``allow_*`` config key. Unknown capability ids+ and unreadable consent state return False (fail closed).+ """+ source = getattr(self.manifest, "source", "") or ""+ if source == "bundled" and capability == "tools.override":+ return True+ plugin_id = self.manifest.key or self.manifest.name+ return plugin_capability_granted(plugin_id, capability)+# -- override trust gate ------------------------------------------------def _tool_override_allowed(self, tool_name: str) -> bool:@@ -868,24 +900,20 @@ class PluginContext:Bundled plugins (shipped with Hermes core) are trusted by default —an override there is a deliberate maintainer choice, not a third-party- plugin trying to elevate privilege. For every other source, require- ``allow_tool_override: true`` under- ``plugins.entries.<plugin_id>`` in config.yaml.+ plugin trying to elevate privilege. For every other source, the+ canonical check is :func:`plugin_capability_granted` with the+ ``tools.override`` capability — satisfied by EITHER the consent-flow+ grant (``plugins.entries.<plugin_id>.granted_capabilities``) OR the+ deprecated legacy key ``allow_tool_override: true`` (still honored+ for backward compatibility; #64228 reference migration)."""source = getattr(self.manifest, "source", "") or ""if source == "bundled":return True- try:- from hermes_cli.config import load_config- cfg = load_config() or {}- except Exception:- # If we can't load config, fail closed — better to break the- # override than silently grant it.- return Falseplugin_id = self.manifest.key or self.manifest.name- entries = (cfg.get("plugins") or {}).get("entries") or {}- entry = entries.get(plugin_id) or {}- return bool(entry.get("allow_tool_override", False))+ # Fail-closed by construction: any failure to read consent state+ # inside plugin_capability_granted returns False.+ return plugin_capability_granted(plugin_id, "tools.override")# -- message injection --------------------------------------------------@@ -2335,6 +2363,9 @@ class PluginManager:path=str(plugin_dir),kind=kind,key=key,+ capabilities=_parse_declared_capabilities(+ data.get("capabilities"), name+ ),)except Exception as exc:logger.warning(diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex 873fb5118a3..7ddd23a098b 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -866,6 +866,17 @@ def cmd_install(f"Run `hermes plugins enable {installed_name}` to activate.[/dim]",)+ # Capability consent (#64228): if the manifest declares capabilities,+ # show the list once and record consent. Non-interactive installs (and+ # declines) proceed with capabilities ungranted — fail closed.+ declared_caps = _declared_capabilities_from_manifest(+ installed_manifest, installed_name+ )+ if declared_caps:+ _run_capability_consent(+ console, installed_name, declared_caps, context="install"+ )+console.print("[dim]Restart the gateway for the plugin to take effect:[/dim]")console.print("[dim] hermes gateway restart[/dim]")console.print()@@ -930,6 +941,28 @@ def cmd_update(name: str) -> None:# Copy any new .example files_copy_example_files(target, console)+ # Update-time re-consent (#64228): if the new version declares+ # capabilities the granted set lacks, surface the diff and require+ # re-consent for the additions. The stored consent hash detects a+ # changed declaration; additions stay ungranted until the user says yes+ # (non-interactive updates leave them ungranted — fail closed).+ updated_manifest = _read_manifest(target)+ plugin_id = updated_manifest.get("name") or target.name+ declared_caps = _declared_capabilities_from_manifest(+ updated_manifest, plugin_id+ )+ if declared_caps:+ from hermes_cli.plugin_capabilities import (+ declared_set_changed,+ pending_capabilities,+ )+ if pending_capabilities(plugin_id, declared_caps) or declared_set_changed(+ plugin_id, declared_caps+ ):+ _run_capability_consent(+ console, plugin_id, declared_caps, context="update"+ )+out = output.strip()if "Already up to date" in out:console.print(@@ -1196,9 +1229,188 @@ def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:if source == "bundled":return+ # Capability consent (#64228): when the manifest declares capabilities,+ # the consent screen is the canonical grant path — it covers+ # tools.override too, so skip the legacy standalone prompt unless the+ # operator explicitly passed --allow-tool-override/--no-allow-tool-override.+ declared_caps = _declared_capabilities_for_key(key)+ if declared_caps:+ _run_capability_consent(console, key, declared_caps, context="enable")+ if allow_tool_override is not None:+ _resolve_tool_override_grant(console, key, allow_tool_override)+ return+_resolve_tool_override_grant(console, key, allow_tool_override)+# ── Capability consent flow (#64228) ─────────────────────────────────────────+++def _declared_capabilities_from_manifest(manifest: dict, plugin_name: str = "?") -> list:+ """Extract + normalize the ``capabilities:`` declaration from a manifest."""+ from hermes_cli.plugin_capabilities import parse_declared_capabilities++ return parse_declared_capabilities(+ (manifest or {}).get("capabilities"), plugin_name+ )+++def _declared_capabilities_for_key(key: str) -> list:+ """Read the declared capabilities for an installed/bundled plugin by key."""+ for entry in _discover_all_plugins():+ # entry = (name, version, description, source, dir_path, key)+ if entry[5] == key or entry[0] == key:+ dir_path = entry[4]+ if not dir_path:+ return []+ manifest = _read_manifest(Path(dir_path))+ return _declared_capabilities_from_manifest(manifest, entry[0])+ return []+++def _print_capability_list(console, capabilities: list) -> None:+ """Render the consent screen body: one line per capability."""+ from hermes_cli.plugin_capabilities import CAPABILITY_REGISTRY++ for cap in capabilities:+ spec = CAPABILITY_REGISTRY.get(cap)+ desc = spec.description if spec else ""+ console.print(f" [bold]{cap}[/bold] — {desc}")+++def _run_capability_consent(+ console,+ plugin_id: str,+ declared: list,+ *,+ context: str = "install",+) -> bool:+ """Show the capability consent screen and record the decision.++ Prints the declared capability list with one-line risk descriptions and+ asks a single Y/n. On consent, the *pending* capabilities are granted+ (recorded under ``plugins.entries.<plugin_id>.granted_capabilities`` with+ a consent hash of the declared set). On decline — or in ANY+ non-interactive context — capabilities stay ungranted (fail closed) and+ the plugin must degrade gracefully via ``ctx.has_capability()``.++ The consent wording deliberately does not imply a code audit: granting a+ capability trusts the plugin author. This is consent + audit, NOT a+ sandbox — an in-process plugin can run arbitrary Python regardless.++ Returns True when consent was granted.+ """+ from hermes_cli.plugin_capabilities import (+ pending_capabilities,+ record_consent,+ )++ pending = pending_capabilities(plugin_id, declared)+ if not pending:+ # Everything declared is already granted — refresh the consent hash+ # so a later declaration change is detected against the current set.+ if declared:+ record_consent(plugin_id, [], declared)+ return True++ verb = "requests" if context == "install" else "now requests"+ console.print(+ f"\n [yellow]Plugin [bold]{plugin_id}[/bold] {verb} the following "+ "capabilities:[/yellow]"+ )+ _print_capability_list(console, pending)+ console.print(+ " [dim]Granting trusts the plugin author with these host surfaces. "+ "This is consent, not a sandbox — plugins run as regular Python "+ "in-process.[/dim]"+ )++ if not (sys.stdin.isatty() and sys.stdout.isatty()):+ console.print(+ " [yellow]Non-interactive session: capabilities NOT granted "+ "(fail closed).[/yellow] Run "+ f"`hermes plugins capabilities {plugin_id}` to review and "+ f"`hermes plugins enable {plugin_id}` to grant interactively."+ )+ return False++ try:+ answer = console.input(" Grant these capabilities? [y/N] ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ answer = ""+ if answer in {"y", "yes"}:+ record_consent(plugin_id, pending, declared)+ console.print(+ f" [green]✓[/green] Granted: {', '.join(pending)} "+ f"([dim]plugins.entries.{plugin_id}.granted_capabilities[/dim])"+ )+ return True++ console.print(+ f" [dim]Declined. {plugin_id} stays enabled with these capabilities "+ "off; it should degrade gracefully (ctx.has_capability()). Re-run "+ f"`hermes plugins enable {plugin_id}` to grant later.[/dim]"+ )+ return False+++def cmd_capabilities(name: Optional[str] = None) -> None:+ """``hermes plugins capabilities [<id>]`` — declared vs granted."""+ from rich.console import Console++ from hermes_cli.plugin_capabilities import granted_capabilities++ console = Console()++ rows = []+ for entry in _discover_all_plugins():+ # entry = (name, version, description, source, dir_path, key)+ key = entry[5] or entry[0]+ if name is not None and name not in (key, entry[0]):+ continue+ declared = _declared_capabilities_for_key(key)+ granted = granted_capabilities(key)+ # Legacy grants surface too: report capabilities live via deprecated+ # allow_* keys so `capabilities` shows the true effective state.+ from hermes_cli.plugin_capabilities import (+ CAPABILITY_REGISTRY,+ plugin_capability_granted,+ )+ effective = {+ cap for cap in CAPABILITY_REGISTRY+ if plugin_capability_granted(key, cap)+ }+ if not declared and not effective and name is None:+ continue+ rows.append((key, entry[3], declared, granted, effective))++ if name is not None and not rows:+ console.print(f"[red]Plugin '{name}' is not installed or bundled.[/red]")+ sys.exit(1)++ if not rows:+ console.print("[dim]No plugins declare or hold capabilities.[/dim]")+ return++ for key, source, declared, granted, effective in sorted(rows):+ console.print(f"[bold]{key}[/bold] [dim]({source})[/dim]")+ if not declared:+ console.print(" declared: [dim](none)[/dim]")+ for cap in declared:+ if cap in effective:+ mark = "[green]granted[/green]"+ if cap not in granted:+ mark += " [dim](via legacy allow_* key — deprecated)[/dim]"+ else:+ mark = "[yellow]not granted[/yellow]"+ console.print(f" {cap}: {mark}")+ for cap in sorted(effective - set(declared)):+ console.print(+ f" {cap}: [green]granted[/green] "+ "[dim](not declared in manifest)[/dim]"+ )++def _resolve_tool_override_grant(console, key: str, allow_tool_override: Optional[bool]) -> None:@@ -2459,6 +2671,8 @@ def plugins_command(args) -> None:cmd_enable(args.name, allow_tool_override=allow_override)elif action == "disable":cmd_disable(args.name)+ elif action == "capabilities":+ cmd_capabilities(getattr(args, "name", None))elif action in {"list", "ls"}:cmd_list(args)elif action == "doctor":diff --git a/hermes_cli/subcommands/plugins.py b/hermes_cli/subcommands/plugins.pyindex ffc25fd0dc4..87c3bb0b14e 100644--- a/hermes_cli/subcommands/plugins.py+++ b/hermes_cli/subcommands/plugins.py@@ -112,6 +112,22 @@ def build_plugins_parser(subparsers, *, cmd_plugins: Callable) -> None:)plugins_disable.add_argument("name", help="Plugin name to disable")+ plugins_capabilities = plugins_subparsers.add_parser(+ "capabilities",+ help="Show declared vs granted capabilities per plugin",+ description=(+ "Show each plugin's declared capabilities (from plugin.yaml) "+ "against what the user has granted. Capabilities are a consent "+ "and audit layer over host API surfaces — NOT a sandbox."+ ),+ )+ plugins_capabilities.add_argument(+ "name",+ nargs="?",+ default=None,+ help="Plugin id to inspect (omit to list all plugins with capabilities)",+ )+plugins_doctor = plugins_subparsers.add_parser("doctor", help="Validate a plugin with the real runtime contracts")diff --git a/tests/hermes_cli/test_plugin_capabilities.py b/tests/hermes_cli/test_plugin_capabilities.pynew file mode 100644index 00000000000..059dd8ba4ee--- /dev/null+++ b/tests/hermes_cli/test_plugin_capabilities.py@@ -0,0 +1,394 @@+"""Tests for the plugin capability model + consent flow (#64228).++Covers: declaration parsing, consent grant/persist, update re-consent on+added capabilities, fail-closed behavior on missing/corrupt consent state,+and backward compatibility with the legacy ``allow_*`` gates.+"""++from __future__ import annotations++from unittest.mock import MagicMock, patch++import pytest+import yaml++from hermes_cli.plugin_capabilities import (+ CAPABILITY_REGISTRY,+ VALID_CAPABILITY_IDS,+ capability_set_hash,+ consent_hash,+ declared_set_changed,+ granted_capabilities,+ parse_declared_capabilities,+ pending_capabilities,+ plugin_capability_granted,+ record_consent,+)+++def hermes_home(tmp_path, monkeypatch):+ """Point HERMES_HOME at a tmp dir with an empty config.yaml."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "config.yaml").write_text("{}\n", encoding="utf-8")+ return tmp_path+++def _read_cfg(home):+ return yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8")) or {}+++# ── Registry sanity ──────────────────────────────────────────────────────────+++class TestRegistry:+ def test_every_capability_has_legacy_gate(self):+ for spec in CAPABILITY_REGISTRY.values():+ assert spec.legacy_path, spec.id+ assert spec.description++ def test_known_ids(self):+ assert "tools.override" in VALID_CAPABILITY_IDS+ assert "llm.model_override" in VALID_CAPABILITY_IDS+++# ── Declaration parsing ──────────────────────────────────────────────────────+++class TestDeclarationParsing:+ def test_parses_known_ids(self):+ got = parse_declared_capabilities(["tools.override", "llm.model_override"])+ assert got == ["tools.override", "llm.model_override"]++ def test_drops_unknown_ids(self):+ got = parse_declared_capabilities(["tools.override", "root.everything"])+ assert got == ["tools.override"]++ def test_non_list_ignored(self):+ assert parse_declared_capabilities("tools.override") == []+ assert parse_declared_capabilities({"a": 1}) == []+ assert parse_declared_capabilities(None) == []++ def test_non_string_entries_ignored(self):+ assert parse_declared_capabilities([1, None, "tools.override"]) == [+ "tools.override"+ ]++ def test_dedup_preserves_order(self):+ got = parse_declared_capabilities(+ ["llm.model_override", "tools.override", "llm.model_override"]+ )+ assert got == ["llm.model_override", "tools.override"]++ def test_manifest_field_lands_on_parsed_manifest(self, tmp_path):+ """PluginManifest picks up ``capabilities:`` from plugin.yaml."""+ from hermes_cli.plugins import PluginManager++ plugin_dir = tmp_path / "capplug"+ plugin_dir.mkdir()+ (plugin_dir / "plugin.yaml").write_text(+ "name: capplug\nversion: '1.0'\n"+ "capabilities:\n - tools.override\n - bogus.capability\n",+ encoding="utf-8",+ )+ mgr = PluginManager()+ manifest = mgr._parse_manifest(+ plugin_dir / "plugin.yaml", plugin_dir, "user", ""+ )+ assert manifest is not None+ assert manifest.capabilities == ["tools.override"]++ def test_manifest_without_capabilities_field(self, tmp_path):+ from hermes_cli.plugins import PluginManager++ plugin_dir = tmp_path / "plainplug"+ plugin_dir.mkdir()+ (plugin_dir / "plugin.yaml").write_text(+ "name: plainplug\n", encoding="utf-8"+ )+ mgr = PluginManager()+ manifest = mgr._parse_manifest(+ plugin_dir / "plugin.yaml", plugin_dir, "user", ""+ )+ assert manifest is not None+ assert manifest.capabilities == []+++# ── Consent grant + persistence ──────────────────────────────────────────────+++class TestConsentPersistence:+ def test_record_consent_persists_grant(self, hermes_home):+ record_consent("capplug", ["tools.override"], ["tools.override"])+ cfg = _read_cfg(hermes_home)+ entry = cfg["plugins"]["entries"]["capplug"]+ assert entry["granted_capabilities"] == ["tools.override"]+ assert entry["capabilities_consent"]["hash"] == capability_set_hash(+ ["tools.override"]+ )+ assert entry["capabilities_consent"]["granted_at"]+ # Bridge: legacy key mirrored so existing enforcement sites work.+ assert entry["allow_tool_override"] is True++ def test_record_consent_mirrors_nested_legacy_key(self, hermes_home):+ record_consent(+ "capplug", ["llm.model_override"], ["llm.model_override"]+ )+ entry = _read_cfg(hermes_home)["plugins"]["entries"]["capplug"]+ assert entry["llm"]["allow_model_override"] is True++ def test_granted_capabilities_roundtrip(self, hermes_home):+ record_consent("capplug", ["tools.override"], ["tools.override"])+ assert granted_capabilities("capplug") == frozenset({"tools.override"})++ def test_grant_is_union_with_previous(self, hermes_home):+ record_consent("capplug", ["tools.override"], ["tools.override"])+ record_consent(+ "capplug",+ ["llm.model_override"],+ ["tools.override", "llm.model_override"],+ )+ assert granted_capabilities("capplug") == frozenset(+ {"tools.override", "llm.model_override"}+ )++ def test_capability_granted_after_consent(self, hermes_home):+ record_consent("capplug", ["tools.override"], ["tools.override"])+ assert plugin_capability_granted("capplug", "tools.override") is True++ def test_declined_stays_off(self, hermes_home):+ # No record_consent call — nothing granted.+ assert plugin_capability_granted("capplug", "tools.override") is False+ assert pending_capabilities("capplug", ["tools.override"]) == [+ "tools.override"+ ]+++# ── Update re-consent ────────────────────────────────────────────────────────+++class TestUpdateReconsent:+ def test_added_capability_is_pending(self, hermes_home):+ # v1 declared + granted tools.override.+ record_consent("capplug", ["tools.override"], ["tools.override"])+ # v2 adds llm.model_override.+ declared_v2 = ["tools.override", "llm.model_override"]+ assert pending_capabilities("capplug", declared_v2) == [+ "llm.model_override"+ ]+ assert declared_set_changed("capplug", declared_v2) is True+ # The added capability stays ungranted until re-consent.+ assert plugin_capability_granted("capplug", "llm.model_override") is False+ # The previously granted one keeps working.+ assert plugin_capability_granted("capplug", "tools.override") is True++ def test_unchanged_set_needs_no_reconsent(self, hermes_home):+ record_consent("capplug", ["tools.override"], ["tools.override"])+ assert pending_capabilities("capplug", ["tools.override"]) == []+ assert declared_set_changed("capplug", ["tools.override"]) is False++ def test_hash_order_insensitive(self):+ a = capability_set_hash(["tools.override", "llm.model_override"])+ b = capability_set_hash(["llm.model_override", "tools.override"])+ assert a == b++ def test_no_consent_record_counts_as_changed(self, hermes_home):+ assert declared_set_changed("capplug", ["tools.override"]) is True++ def test_reconsent_grants_addition(self, hermes_home):+ record_consent("capplug", ["tools.override"], ["tools.override"])+ declared_v2 = ["tools.override", "llm.model_override"]+ record_consent(+ "capplug", pending_capabilities("capplug", declared_v2), declared_v2+ )+ assert plugin_capability_granted("capplug", "llm.model_override") is True+ assert declared_set_changed("capplug", declared_v2) is False+++# ── Fail closed ──────────────────────────────────────────────────────────────+++class TestFailClosed:+ def test_missing_config_not_granted(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "nonexistent"))+ assert plugin_capability_granted("capplug", "tools.override") is False+ assert granted_capabilities("capplug") == frozenset()++ def test_corrupt_granted_list_not_granted(self, hermes_home):+ (hermes_home / "config.yaml").write_text(+ "plugins:\n entries:\n capplug:\n"+ " granted_capabilities: not-a-list\n",+ encoding="utf-8",+ )+ assert plugin_capability_granted("capplug", "tools.override") is False++ def test_corrupt_entry_types_not_granted(self, hermes_home):+ (hermes_home / "config.yaml").write_text(+ "plugins:\n entries:\n capplug: 42\n", encoding="utf-8"+ )+ assert plugin_capability_granted("capplug", "tools.override") is False++ def test_unknown_capability_denied(self, hermes_home):+ record_consent("capplug", ["tools.override"], ["tools.override"])+ assert plugin_capability_granted("capplug", "root.everything") is False++ def test_unknown_ids_in_granted_list_ignored(self, hermes_home):+ (hermes_home / "config.yaml").write_text(+ "plugins:\n entries:\n capplug:\n"+ " granted_capabilities: [root.everything, 42]\n",+ encoding="utf-8",+ )+ assert granted_capabilities("capplug") == frozenset()+ assert plugin_capability_granted("capplug", "tools.override") is False++ def test_corrupt_consent_hash_counts_as_changed(self, hermes_home):+ (hermes_home / "config.yaml").write_text(+ "plugins:\n entries:\n capplug:\n"+ " capabilities_consent: broken\n",+ encoding="utf-8",+ )+ assert consent_hash("capplug") is None+ assert declared_set_changed("capplug", ["tools.override"]) is True+++# ── Legacy gate backward compat ──────────────────────────────────────────────+++class TestLegacyGateCompat:+ def test_legacy_allow_tool_override_still_works(self, hermes_home):+ (hermes_home / "config.yaml").write_text(+ "plugins:\n entries:\n oldplug:\n"+ " allow_tool_override: true\n",+ encoding="utf-8",+ )+ assert plugin_capability_granted("oldplug", "tools.override") is True++ def test_legacy_nested_llm_key_still_works(self, hermes_home):+ (hermes_home / "config.yaml").write_text(+ "plugins:\n entries:\n oldplug:\n"+ " llm:\n allow_model_override: true\n",+ encoding="utf-8",+ )+ assert plugin_capability_granted("oldplug", "llm.model_override") is True++ def test_legacy_false_stays_denied(self, hermes_home):+ (hermes_home / "config.yaml").write_text(+ "plugins:\n entries:\n oldplug:\n"+ " allow_tool_override: false\n",+ encoding="utf-8",+ )+ assert plugin_capability_granted("oldplug", "tools.override") is False++ def test_tool_override_gate_uses_canonical_path(self, hermes_home):+ """PluginContext._tool_override_allowed honors capability grant."""+ from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager++ record_consent("capplug", ["tools.override"], ["tools.override"])+ manifest = PluginManifest(name="capplug", source="user", key="capplug")+ ctx = PluginContext(manifest, PluginManager())+ assert ctx._tool_override_allowed("write_file") is True++ def test_tool_override_gate_denies_without_grant(self, hermes_home):+ from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager++ manifest = PluginManifest(name="capplug", source="user", key="capplug")+ ctx = PluginContext(manifest, PluginManager())+ assert ctx._tool_override_allowed("write_file") is False++ def test_tool_override_gate_legacy_key(self, hermes_home):+ from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager++ (hermes_home / "config.yaml").write_text(+ "plugins:\n entries:\n oldplug:\n"+ " allow_tool_override: true\n",+ encoding="utf-8",+ )+ manifest = PluginManifest(name="oldplug", source="user", key="oldplug")+ ctx = PluginContext(manifest, PluginManager())+ assert ctx._tool_override_allowed("write_file") is True++ def test_bundled_plugin_trusted(self, hermes_home):+ from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager++ manifest = PluginManifest(name="bplug", source="bundled", key="bplug")+ ctx = PluginContext(manifest, PluginManager())+ assert ctx._tool_override_allowed("write_file") is True+ assert ctx.has_capability("tools.override") is True+++# ── ctx.has_capability probing ───────────────────────────────────────────────+++class TestHasCapability:+ def test_probe_granted(self, hermes_home):+ from hermes_cli.plugins import PluginContext, PluginManifest, PluginManager++ record_consent("capplug", ["llm.model_override"], ["llm.model_override"])+ manifest = PluginManifest(name="capplug", source="user", key="capplug")+ ctx = PluginContext(manifest, PluginManager())+ assert ctx.has_capability("llm.model_override") is True+ assert ctx.has_capability("tools.override") is False+ assert ctx.has_capability("nonsense.capability") is False+++# ── Consent CLI flow ─────────────────────────────────────────────────────────+++class TestConsentFlow:+ def _console(self, answers=None, interactive=True):+ console = MagicMock()+ it = iter(answers or [])+ console.input.side_effect = lambda *a, **k: next(it, "")+ return console++ def test_consent_yes_records_grant(self, hermes_home, monkeypatch):+ from hermes_cli.plugins_cmd import _run_capability_consent++ console = self._console(["y"])+ with patch("sys.stdin") as stdin, patch("sys.stdout") as stdout:+ stdin.isatty.return_value = True+ stdout.isatty.return_value = True+ granted = _run_capability_consent(+ console, "capplug", ["tools.override"], context="install"+ )+ assert granted is True+ assert plugin_capability_granted("capplug", "tools.override") is True++ def test_consent_decline_leaves_ungranted(self, hermes_home):+ from hermes_cli.plugins_cmd import _run_capability_consent++ console = self._console(["n"])+ with patch("sys.stdin") as stdin, patch("sys.stdout") as stdout:+ stdin.isatty.return_value = True+ stdout.isatty.return_value = True+ granted = _run_capability_consent(+ console, "capplug", ["tools.override"], context="install"+ )+ assert granted is False+ assert plugin_capability_granted("capplug", "tools.override") is False++ def test_non_interactive_fails_closed(self, hermes_home):+ from hermes_cli.plugins_cmd import _run_capability_consent++ console = self._console()+ with patch("sys.stdin") as stdin, patch("sys.stdout") as stdout:+ stdin.isatty.return_value = False+ stdout.isatty.return_value = False+ granted = _run_capability_consent(+ console, "capplug", ["tools.override"], context="install"+ )+ assert granted is False+ assert plugin_capability_granted("capplug", "tools.override") is False+ # No prompt was shown.+ console.input.assert_not_called()++ def test_already_granted_skips_prompt(self, hermes_home):+ from hermes_cli.plugins_cmd import _run_capability_consent++ record_consent("capplug", ["tools.override"], ["tools.override"])+ console = self._console()+ granted = _run_capability_consent(+ console, "capplug", ["tools.override"], context="enable"+ )+ assert granted is True+ console.input.assert_not_called()diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex b86eeece4c7..ec963db1881 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -223,8 +223,37 @@ requires_env: # gate loading on env vars; prompted during installdescription: "Key for the Other service"url: "https://other.com/keys"secret: true+capabilities: # privileged host surfaces you request (consent flow)+ - tools.override # replace built-in tools (needs user consent)+ - llm.model_override # choose the model for host-owned LLM calls```+### Declaring capabilities++If your plugin needs a privileged host surface — overriding a built-in tool,+picking the model for `ctx.llm` calls, etc. — declare it in `capabilities:`.+At install/enable time the user sees the list and consents once; if a later+version adds a capability, the update flow asks again for just the addition.+Undeclared or unconsented capabilities are simply off (fail closed), so+**probe before using them and degrade gracefully**:++```python+def register(ctx):+ if ctx.has_capability("tools.override"):+ ctx.register_tool(..., override=True)+ else:+ ctx.register_tool(...) # register under a non-conflicting name+```++Known capability ids: `tools.override`, `llm.provider_override`,+`llm.model_override`, `llm.agent_id_override`, `llm.profile_override`,+`llm.task_override` (see `hermes_cli/plugin_capabilities.py` for the+canonical registry). Unknown ids are ignored. The older per-capability+config keys (`plugins.entries.<id>.allow_tool_override`, …) still work but+are deprecated — declare capabilities instead so users get a single,+auditable consent screen. Capabilities are consent + audit, **not a+sandbox**: they gate host API surfaces, nothing more.+## Step 3: Write the tool schemasCreate `schemas.py` — this is what the LLM reads to decide when to call your tools:diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 0a98bd60652..bdb790cb2a0 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -338,8 +338,68 @@ hermes plugins update my-plugin # pull latesthermes plugins remove my-plugin # uninstallhermes plugins enable my-plugin # add to allow-listhermes plugins disable my-plugin # remove from allow-list + add to disabled+hermes plugins capabilities [my-plugin] # declared vs granted capabilities```+### Plugin capabilities and consent++Plugins can declare the privileged host surfaces they want in their+`plugin.yaml`:++```yaml+name: my-plugin+capabilities:+ - tools.override # replace built-in tools+ - llm.model_override # pick the model for host-owned LLM calls+```++When a plugin declares capabilities, `hermes plugins install` (and+`hermes plugins enable`) shows the list with one-line risk descriptions and+asks once. Consenting records the grant under+`plugins.entries.<id>.granted_capabilities` together with a consent hash and+timestamp. Declining leaves the plugin enabled with those capabilities off —+a well-behaved plugin probes with `ctx.has_capability()` and degrades+gracefully.++**Update re-consent:** if a plugin update declares capabilities you haven't+granted, `hermes plugins update` surfaces the additions and asks again. New+capabilities stay off until you consent — a plugin update can never silently+widen its access.++**Non-interactive sessions fail closed:** installing or updating without a+TTY completes the install, but declared capabilities are *not* granted. Run+`hermes plugins enable <id>` interactively to grant them later.++Inspect the state at any time:++```bash+hermes plugins capabilities # all plugins with declared/granted capabilities+hermes plugins capabilities my-plugin # one plugin, declared vs granted+```++Capability ids map 1:1 to the older per-feature config gates, which keep+working but are **deprecated** in favor of the consent flow:++| Capability | Legacy key (`plugins.entries.<id>.…`) |+|---|---|+| `tools.override` | `allow_tool_override` |+| `llm.provider_override` | `llm.allow_provider_override` |+| `llm.model_override` | `llm.allow_model_override` |+| `llm.agent_id_override` | `llm.allow_agent_id_override` |+| `llm.profile_override` | `llm.allow_profile_override` |+| `llm.task_override` | `llm.allow_task_override` |++A gate is open when *either* the capability is granted *or* the legacy key is+set — existing configs keep working unchanged.++:::warning Not a sandbox+Capabilities are a **consent and audit layer**, not isolation. Plugins run as+regular in-process Python: a malicious plugin can ignore every gate here.+Granting a capability is a statement of trust in the plugin author — it is+not a code audit, and Hermes has not reviewed the plugin's code. Only install+plugins from sources you trust.+:::+### Interactive UIRunning `hermes plugins` with no arguments opens a composite interactive screen: