The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): shell-hook consent and freshness under the one-gateway runtime (CLI-5)
kshitijk4poor6887c0edd103
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.pyindex 851f0bb9533..770b665edfe 100644--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@ -141,45 +141,120 @@ class ShellHookSpec(_ToolMatcherMixin):def register_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool = False) -> list[ShellHookSpec]:"""Register every configured shell hook (idempotent); returns the newly wired specs. Skippedentries (unknown, malformed, not allowlisted, already registered) are logged only."""- from agent.safe_worker_policy import safe_worker_enabled-- if safe_worker_enabled():- return []- if not isinstance(cfg, dict):- return []- from utils import env_var_enabled- if env_var_enabled("HERMES_SAFE_MODE"): # hooks are user customizations too — fire zero user-configured code- logger.info("HERMES_SAFE_MODE=1 — shell-hook registration skipped")- return []- effective_accept = _resolve_effective_accept(cfg, accept_hooks)- specs = _parse_hooks_block(cfg.get("hooks"))+ specs = _hook_specs(cfg)if not specs:return []+ accept, allowed = _resolve_effective_accept(cfg, accept_hooks), _allowlisted_pairs()from hermes_cli.plugins import get_plugin_manager # lazy: avoids import cycle- manager, home_key, registered = get_plugin_manager(), _home_key(), []- # Idempotence + allowlist read under the lock; TTY prompt outside it; mutation re-takes the lock and re-checks.+ manager, home_key = get_plugin_manager(), _home_key()+ # TTY prompt outside the lock; _wire takes the lock and re-checks.+ consented = []for spec in specs:- key = (home_key, spec.event, spec.matcher, spec.command)- with _registered_lock:- if key in _registered:- continue- already_allowlisted = _is_allowlisted(spec.event, spec.command)- if not already_allowlisted and not _prompt_and_record(spec.event, spec.command, accept_hooks=effective_accept):+ if _consented(spec, accept, allowed):+ consented.append(spec)+ else:logger.warning("shell hook for %s (%s) not allowlisted — skipped. Use --accept-hooks / ""HERMES_ACCEPT_HOOKS=1 / hooks_auto_accept: true, or approve at the TTY prompt next run.",spec.event, spec.command)+ with _registered_lock:+ return _wire(manager, home_key, consented)+++def sync_from_config(cfg: dict[str, Any]) -> None:+ """Bring this home's registered shell hooks in step with ``cfg`` and its consent, for a+ long-lived process (the gateway) that must behave as a new process would: hooks configured and+ consented since start register, hooks removed from ``cfg`` or revoked are unregistered. Consent+ is the allowlist, or an opt-in in force (``hooks_auto_accept`` / ``HERMES_ACCEPT_HOOKS``), which+ approves every configured hook as on main, even one whose allowlist write failed. Never prompts+ or writes. An empty ``cfg`` (a loader that failed open) or an unreadable allowlist must never+ disarm a ``fail_closed`` guard, so either adds but never removes."""+ specs = _hook_specs(cfg)+ if not specs and not cfg:+ return+ allowlist, readable = _read_allowlist()+ allowed = _approved_pairs(allowlist["approvals"])+ accept = _resolve_effective_accept(cfg, False)+ wanted = [spec for spec in specs or [] if accept or (spec.event, spec.command) in allowed]+ from hermes_cli.plugins import get_plugin_manager # lazy: avoids import cycle+ manager, home_key = get_plugin_manager(), _home_key()+ # One lock hold for add + remove: a concurrent sync on an older snapshot can never drop what a+ # newer one just added.+ with _registered_lock:+ _wire(manager, home_key, wanted)+ if specs is None or not readable:+ return+ keep = {(home_key, spec.event, spec.matcher, spec.command) for spec in wanted}+ stale = {k for k in _registered if k[0] == home_key and k not in keep}+ _registered.difference_update(stale)+ for event in {k[1] for k in stale}:+ # Replaced, never edited in place: a concurrent invoke_hook keeps iterating the old list.+ manager._hooks[event] = [cb for cb in manager._hooks.get(event, [])+ if getattr(cb, "shell_hook_key", None) not in stale]+ for _home, event, _matcher, command in stale:+ logger.info("shell hook unregistered (removed from config or allowlist): %s -> %s", event, command)+++def record_consent_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool = False) -> None:+ """First-use consent without registering anything, for a client whose turns run in a gateway that+ has no TTY: the prompt (or an opt-in) for each configured hook not yet allowlisted. The gateway+ registers from the same allowlist when the client opens its session."""+ specs = _hook_specs(cfg)+ if not specs:+ return+ accept, allowed = _resolve_effective_accept(cfg, accept_hooks), _allowlisted_pairs()+ for spec in specs:+ _consented(spec, accept, allowed)+++def _hook_specs(cfg: Optional[dict[str, Any]]) -> Optional[list[ShellHookSpec]]:+ """The configured hooks, or ``None`` when this process must run none (safe worker, safe mode,+ no config) — the one guard every registrar and the consent path share."""+ from agent.safe_worker_policy import safe_worker_enabled+ from utils import env_var_enabled+ if safe_worker_enabled() or not isinstance(cfg, dict):+ return None+ if env_var_enabled("HERMES_SAFE_MODE"): # hooks are user customizations too — fire zero user-configured code+ logger.debug("HERMES_SAFE_MODE=1 — shell-hook registration skipped")+ return None+ return _parse_hooks_block(cfg.get("hooks"))+++def _wire(manager: Any, home_key: str, specs: list[ShellHookSpec]) -> list[ShellHookSpec]:+ """Register ``specs`` not yet wired for this home; caller holds ``_registered_lock``."""+ registered = []+ for spec in specs:+ key = (home_key, spec.event, spec.matcher, spec.command)+ if key in _registered:continue- with _registered_lock:- if key in _registered:- continue- manager._hooks.setdefault(spec.event, []).append(_make_callback(spec))- _registered.add(key)- registered.append(spec)- logger.info("shell hook registered: %s -> %s (matcher=%s, timeout=%ds, fail_closed=%s)",- spec.event, spec.command, spec.matcher, spec.timeout, spec.fail_closed)+ callback = _make_callback(spec)+ callback.shell_hook_key = key # type: ignore[attr-defined] # identifies it for sync_from_config+ manager._hooks.setdefault(spec.event, []).append(callback)+ _registered.add(key)+ registered.append(spec)+ logger.info("shell hook registered: %s -> %s (matcher=%s, timeout=%ds, fail_closed=%s)",+ spec.event, spec.command, spec.matcher, spec.timeout, spec.fail_closed)return registered+def _approved_pairs(approvals: list[Any]) -> set[tuple[Any, Any]]:+ return {(e.get("event"), e.get("command")) for e in approvals if isinstance(e, dict)}+++def _allowlisted_pairs() -> set[tuple[Any, Any]]:+ return _approved_pairs(load_allowlist()["approvals"])+++def _consented(spec: ShellHookSpec, accept: bool, allowed: set[tuple[Any, Any]]) -> bool:+ """Allowlisted, or approved now (opt-in or TTY prompt, recorded); ``allowed`` caches one read."""+ pair = (spec.event, spec.command)+ if pair in allowed:+ return True+ if not _prompt_and_record(spec.event, spec.command, accept_hooks=accept):+ return False+ allowed.add(pair)+ return True++def iter_configured_hooks(cfg: Optional[dict[str, Any]]) -> list[ShellHookSpec]:"""Parse config hooks without registering (``hermes hooks list`` / doctor)."""return _parse_hooks_block(cfg.get("hooks")) if isinstance(cfg, dict) else []@@ -527,17 +602,27 @@ def allowlist_path() -> Path:return get_hermes_home() / ALLOWLIST_FILENAME-def load_allowlist() -> dict[str, Any]:- """Return the parsed allowlist, or an empty skeleton if absent."""+def _read_allowlist() -> tuple[dict[str, Any], bool]:+ """``(allowlist, readable)``: the parsed allowlist (an empty skeleton when absent or broken) and+ whether it could be trusted; a missing file is readable (nothing approved yet), an unreadable or+ malformed one is not."""try:raw = json.loads(allowlist_path().read_text(encoding="utf-8-sig"))- except (json.JSONDecodeError, OSError):- raw = None+ except FileNotFoundError:+ return {"approvals": []}, True+ except (json.JSONDecodeError, OSError, UnicodeDecodeError):+ return {"approvals": []}, Falseif not isinstance(raw, dict):- return {"approvals": []}- if not isinstance(raw.get("approvals"), list):+ return {"approvals": []}, False+ readable = isinstance(raw.get("approvals"), list)+ if not readable:raw["approvals"] = []- return raw+ return raw, readable+++def load_allowlist() -> dict[str, Any]:+ """Return the parsed allowlist, or an empty skeleton if absent."""+ return _read_allowlist()[0]def save_allowlist(data: dict[str, Any]) -> None:@@ -551,10 +636,6 @@ def save_allowlist(data: dict[str, Any]) -> None:"--accept-hooks / HERMES_ACCEPT_HOOKS).", p, exc)-def _is_allowlisted(event: str, command: str) -> bool:- return allowlist_entry_for(event, command) is not None--@contextmanagerdef _locked_update_approvals() -> Iterator[dict[str, Any]]:"""Serialise allowlist read-modify-write across processes via a sibling flock file."""@@ -607,7 +688,8 @@ def _record_approval(event: str, command: str) -> None:def revoke(command: str) -> int:- """Remove every allowlist entry for ``command``; returns the count. Live callbacks stay registered until restart."""+ """Remove every allowlist entry for ``command``; returns the count. A gateway unregisters it at its+ next local session open (``sync_from_config``); other live processes keep it until restart."""with _locked_update_approvals() as data:before = len(data.get("approvals", []))data["approvals"] = [e for e in data.get("approvals", []) if not _entry_matches(e, None, command)]diff --git a/gateway/AGENTS.md b/gateway/AGENTS.mdindex dcb1b17dca2..b8225a2d63a 100644--- a/gateway/AGENTS.md+++ b/gateway/AGENTS.md@@ -185,7 +185,9 @@ gateway under the backend, and do NOT "fix" update locks by widening the tree-ki- **Hooks and observers register per served profile.** `builtin_hooks/`, `agent/shell_hooks.py::register_from_config` and lifecycle observers are prepared under each profile's scope at startupand on profile add/remove; idempotence keys include the profile, and `hooks/` paths resolve at call- time (a module constant freezes to the first importer).+ time (a module constant freezes to the first importer). Shell hooks are also re-synced (added AND+ unregistered) on every local session create/resume via `session_policy.refresh_profile_hooks` ->+ `shell_hooks.sync_from_config`, the only caller that removes.- **Adapter YAML never reaches `os.environ` under multiplex.** `platforms/_shared.py::apply_yaml_bridge` seeds `PlatformConfig.extra` and skips the environ write under a secondaryprofile's scope; gate/allowlist reads go through `platform_gate_env`. A `if not os.getenv(X):diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex d3412405569..a81103a9a7b 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -373,6 +373,7 @@ class AuthorityConnection:await tracked_write(self.authority, partial(commit_local_session, self.authority.db, epoch=self.authority.epoch, receipt=receipt))ref = restore_local_session(self.authority, receipt['session_id'])+ # `--accept-hooks`: record this launch's consent; ``resume`` below registers the hooks.if params.get('accept_hooks') is True:from gateway.session_policy import accept_launch_hooks, restore_policyfrom hermes_state_local import local_receipt@@ -505,6 +506,8 @@ class AuthorityConnection:info = {'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL}source = self.authority.sessions[snapshot.handle.ref.session_id].sourceif source is not None and source.platform == Platform.LOCAL:+ from gateway.session_policy import policy_for_source, refresh_profile_hooks+ await asyncio.to_thread(refresh_profile_hooks, policy_for_source(self.authority.runner, source))info = await snapshot_info(self.authority, snapshot.handle.ref)display = {}if params.get('display_projection'):diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex e6a3d1c2234..fe204e0bcb0 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -527,13 +527,31 @@ def render_launch_skills(params, session_id):def accept_launch_hooks(policy):"""`--accept-hooks` / `HERMES_ACCEPT_HOOKS=1` on a launch: consent to the profile's configured- shell hooks (recorded in the per-user allowlist, as the in-process CLI/TUI did) and register- them on this owner. A bypass launch has no profile hooks to consent to (main's safe mode- registered none either), so the flag is a no-op there rather than a refusal. Allowlist file- lock + write: callers run it off the owner loop."""+ shell hooks in the per-user allowlist (no prompt). A bypass launch has no profile hooks to+ consent to, so the flag is a no-op there rather than a refusal. Allowlist I/O: off the loop."""if json.loads(policy.request_json).get('accept_hooks') and not policy.ignore_user_config:- from agent.shell_hooks import register_from_config- register_from_config(policy.config(), accept_hooks=True)+ from agent.shell_hooks import record_consent_from_config+ from gateway.run import _load_gateway_config+ record_consent_from_config(_load_gateway_config(), accept_hooks=True)+++def refresh_profile_hooks(policy):+ """Bring this owner's shell hooks in step with the profile on every local session open+ (create and resume): hooks added to ``config.yaml`` or approved since the gateway started+ register, removed or revoked ones stop firing, as each new CLI process did on main. Reads the+ owner home's LIVE config (as session creation does), never the session's frozen copy: the+ registry is shared by every session and surface of this profile. Consent comes from the+ allowlist only (the launching client's TTY prompt, or ``accept_launch_hooks``); this never+ prompts. A bypass launch registers nothing (main's safe mode registered none). Config read ++ allowlist I/O: run off the loop."""+ if policy is None or policy.ignore_user_config:+ return+ from agent.shell_hooks import sync_from_config+ from gateway.run import _load_gateway_config+ try:+ sync_from_config(_load_gateway_config()) # it never removes on an empty (failed-open) config+ except Exception: # health: allow BLE001 -- best effort; a hook re-sync never blocks opening a session+ logger.warning("shell-hook re-sync failed; keeping the registered hooks", exc_info=True)def register_worker_hooks(policy):diff --git a/hermes_cli/cli_init_mixin.py b/hermes_cli/cli_init_mixin.pyindex 30f8d4cee1f..8476c536c3e 100644--- a/hermes_cli/cli_init_mixin.py+++ b/hermes_cli/cli_init_mixin.py@@ -56,6 +56,24 @@ def _explicit_launch_skills(cli):return [name for name in requested if name not in auto] or None+def _record_shell_hook_consent():+ """Main's first-use shell-hook prompt, on this terminal. The gateway that registers the hooks+ has no TTY; it reads the allowlist this writes when the session opens (create or resume).+ ``--accept-hooks`` / ``HERMES_ACCEPT_HOOKS`` / ``hooks_auto_accept`` approve without asking.+ A remote gateway has its own home and allowlist, and a bypass launch reads no profile hooks,+ so nothing is asked for either."""+ from hermes_cli.gateway_chat import env_launch_flags+ flags = env_launch_flags()+ if os.environ.get("HERMES_TUI_GATEWAY_URL", "").strip() or flags.get("safe_mode") or flags.get("ignore_user_config"):+ return+ try:+ from agent.shell_hooks import record_consent_from_config+ from hermes_cli.config import load_config+ record_consent_from_config(load_config())+ except Exception: # health: allow BLE001 -- consent is best effort; the gateway skips unapproved hooks+ logger.warning("shell-hook consent check failed", exc_info=True)++class CLIInitMixin:"""HermesCLI constructor phases: display options, model/provider routing, turn limits, toolsets, checkpoints, prompt/reasoning, runtime state, session store and UI state."""@@ -416,6 +434,7 @@ class CLIInitMixin:# including this process's own, claimed before the first turn. Hand the slot over around the# attach, then re-claim it for the id the gateway returned (main's exclusivity is kept).held = getattr(self, "_resumed", False) and getattr(self, "_active_session_lease", None) is not None+ _record_shell_hook_consent()if held:self._release_active_session()sid = store.open_session(self, launch)diff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.pyindex b9fbe35ebc2..1318d3f53fa 100644--- a/hermes_cli/hooks.py+++ b/hermes_cli/hooks.py@@ -263,8 +263,8 @@ def _cmd_revoke(args) -> None:returnprint(f"Removed {removed} allowlist entry/entries for: {args.command}")print(- "Note: currently running CLI / gateway processes keep their "- "already-registered callbacks until they restart."+ "Note: a running gateway stops running it when the next local session opens; "+ "other running processes keep it until they restart.")diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 47aa9814a12..f282a4f00d1 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2947,9 +2947,10 @@ def _prepare_agent_startup(args) -> None:except Exception:logger.debug("MCP server filter setup failed", exc_info=True)- # TUI launches hand off to a startup path that backgrounds MCP discovery- # with a bounded join; acp/gateway/cron do their own on the runtime path.+ # TUI launches background MCP discovery with a bounded join; acp/gateway/cron do their own.if _chat_runs_at_gateway(args): # chat turns run in the gateway: it owns MCP, hooks, webhooks+ if _accept_hooks: # rides session.create (env_launch_flags) and the classic CLI's consent check+ os.environ["HERMES_ACCEPT_HOOKS"] = "1"return_run_inline_mcp_discovery = not (_is_tui_chat_launch(args) or _command_has_dedicated_mcp_startup(args))if _run_inline_mcp_discovery and _should_background_mcp_startup(args):@@ -3215,8 +3216,7 @@ def _try_termux_fast_cli_launch() -> bool:_promote_top_level_resume(args)if args.command in {None, "chat"}:_set_chat_arg_defaults(args)- interactive_prompt = not getattr(args, "query", None) and not getattr(args, "image", None)- if interactive_prompt:+ if not getattr(args, "query", None) and not getattr(args, "image", None): # interactive prompt# Reach the prompt first; agent-only discovery on the first turn.args.compact = Trueos.environ["HERMES_DEFER_AGENT_STARTUP"] = "1"diff --git a/hermes_cli/subcommands/hooks.py b/hermes_cli/subcommands/hooks.pyindex cc3afd9237f..0c29337c207 100644--- a/hermes_cli/subcommands/hooks.py+++ b/hermes_cli/subcommands/hooks.py@@ -33,7 +33,7 @@ def build_hooks_parser(subparsers, *, cmd_hooks: Callable) -> None:_hk_revoke = hooks_subparsers.add_parser("revoke", aliases=["remove", "rm"],- help="Remove a command's allowlist entries (takes effect on next restart)")+ help="Remove a command's allowlist entries (a running gateway drops it at the next local session open)")_hk_revoke.add_argument("command", help="The exact command string to revoke (as declared in config.yaml)")diff --git a/tests/gateway/test_shell_hook_resync.py b/tests/gateway/test_shell_hook_resync.pynew file mode 100644index 00000000000..90df6a21497--- /dev/null+++ b/tests/gateway/test_shell_hook_resync.py@@ -0,0 +1,146 @@+"""CLI-5 (#134889): shell hooks under the one-gateway runtime.++The gateway has no TTY and outlives every client, so (a) the classic CLI asks for first-use+consent on its own terminal before it opens its session, and (b) the gateway re-syncs the+profile's hooks on every local session open: added / approved hooks register, removed / revoked+ones stop firing, and the gateway itself never prompts.+"""+import json+import sys+from types import SimpleNamespace++import pytest++from agent import shell_hooks+++def home(tmp_path, monkeypatch):+ h = tmp_path / "home"+ h.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(h))+ for name in ("HERMES_ACCEPT_HOOKS", "HERMES_TUI_GATEWAY_URL", "HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG"):+ monkeypatch.delenv(name, raising=False)+ from hermes_cli import plugins+ monkeypatch.setattr(plugins.get_plugin_manager(), "_hooks", {})+ shell_hooks.reset_for_tests()+ yield h+ shell_hooks.reset_for_tests()+++def _script(tmp_path, name):+ path = tmp_path / name+ path.write_text("#!/bin/sh\nprintf '{}'\n")+ path.chmod(0o755)+ return str(path)+++def _cfg(*commands):+ return {"hooks": {"pre_tool_call": [{"command": c} for c in commands]}}+++def _wired(event="pre_tool_call"):+ from hermes_cli.plugins import get_plugin_manager+ return sorted(cb.__name__ for cb in get_plugin_manager()._hooks.get(event, []))+++def test_gateway_resync_follows_config_and_allowlist_without_prompting(home, tmp_path, monkeypatch):+ from gateway import run+ from gateway.session_policy import accept_launch_hooks, build_policy, refresh_profile_hooks+ a, b = _script(tmp_path, "a.sh"), _script(tmp_path, "b.sh")+ cfg = _cfg(a)+ monkeypatch.setattr(run, "_load_gateway_config", lambda: cfg)+ # A foreground gateway on a terminal still never asks: input() would hang the session open.+ monkeypatch.setattr(sys, "stdin", SimpleNamespace(isatty=lambda: True))+ monkeypatch.setattr("builtins.input", lambda *_: pytest.fail("the gateway prompted"))+ policy = build_policy({"source": "cli", "cwd": str(tmp_path)}, {})++ refresh_profile_hooks(policy)+ assert _wired() == [] # not approved yet: skipped+ accept_launch_hooks(build_policy({"source": "cli", "cwd": str(tmp_path), "accept_hooks": True}, {}))+ refresh_profile_hooks(policy) # a creation launch's --accept-hooks, then the open's re-sync+ assert _wired() == [f"shell_hook[pre_tool_call:{a}]"]++ # Approved on a client terminal after the gateway started (the allowlist is the hand-off).+ cfg["hooks"]["pre_tool_call"].append({"command": b})+ shell_hooks._record_approval("pre_tool_call", b)+ refresh_profile_hooks(policy)+ refresh_profile_hooks(policy) # idempotent+ assert _wired() == [f"shell_hook[pre_tool_call:{a}]", f"shell_hook[pre_tool_call:{b}]"]++ # Unreadable inputs never disarm a guard: an empty config (the loader fails open to {}), or a+ # corrupt allowlist.+ shell_hooks.sync_from_config({})+ assert len(_wired()) == 2+ allowlist = home / shell_hooks.ALLOWLIST_FILENAME+ saved = allowlist.read_text()+ allowlist.write_text("{corrupt")+ refresh_profile_hooks(policy)+ assert len(_wired()) == 2+ allowlist.write_text(saved)+ # An opt-in in force approves every configured hook, as on main: kept even with no allowlist+ # entry (an approval whose write failed).+ c = _script(tmp_path, "c.sh")+ cfg["hooks"]["pre_tool_call"].append({"command": c})+ cfg["hooks_auto_accept"] = True+ refresh_profile_hooks(policy)+ assert f"shell_hook[pre_tool_call:{c}]" in _wired() and shell_hooks.allowlist_entry_for("pre_tool_call", c) is None+ cfg["hooks"]["pre_tool_call"].pop()+ del cfg["hooks_auto_accept"]+ shell_hooks.revoke(a) # revoked: stops firing at the next session open+ refresh_profile_hooks(policy)+ assert _wired() == [f"shell_hook[pre_tool_call:{b}]"]+ cfg["hooks"]["pre_tool_call"] = [] # removed from config.yaml+ refresh_profile_hooks(policy)+ assert _wired() == []++ # A bypass (--safe-mode / --ignore-user-config) session leaves the registry alone.+ cfg["hooks"]["pre_tool_call"] = [{"command": b}]+ bypass = build_policy({"source": "cli", "cwd": str(tmp_path), "model": "m", "safe_mode": True,+ "accept_hooks": True}, {})+ accept_launch_hooks(bypass)+ refresh_profile_hooks(bypass)+ assert _wired() == []+++def test_classic_cli_asks_on_its_terminal_before_opening_the_session(home, tmp_path, monkeypatch):+ from hermes_cli import cli_init_mixin+ from hermes_cli.gateway_session_store import GatewaySessionStore+ import hermes_cli.config as config_mod+ hook = _script(tmp_path, "guard.sh")+ monkeypatch.setattr(config_mod, "load_config", lambda: _cfg(hook))+ monkeypatch.setattr(sys, "stdin", SimpleNamespace(isatty=lambda: True))+ answers = iter(["n", "y"])+ monkeypatch.setattr("builtins.input", lambda *_: next(answers))+ opened = []++ class Store(GatewaySessionStore):+ def __init__(self):+ pass++ def open_session(self, cli, launch=None):+ # The gateway reads the allowlist when this lands: consent is recorded first.+ opened.append(shell_hooks.allowlist_entry_for("pre_tool_call", hook) is not None)+ return "local-x"++ monkeypatch.setattr("hermes_cli.gateway_tools.bind_session", lambda *a: None)+ for _ in range(2):+ cli = SimpleNamespace(_session_db=Store(), session_id="local-x", _resumed=False)+ cli_init_mixin.CLIInitMixin._ensure_gateway_session(cli)+ assert opened == [False, True] # "n" records nothing, "y" lands before the second open++ # --accept-hooks / HERMES_ACCEPT_HOOKS approves without asking; a remote gateway is not asked for.+ other = _script(tmp_path, "other.sh")+ monkeypatch.setattr(config_mod, "load_config", lambda: _cfg(other))+ monkeypatch.setattr("builtins.input", lambda *_: pytest.fail("prompted"))+ monkeypatch.setenv("HERMES_TUI_GATEWAY_URL", "ws://remote.example/api/ws")+ cli_init_mixin._record_shell_hook_consent()+ assert shell_hooks.allowlist_entry_for("pre_tool_call", other) is None+ monkeypatch.delenv("HERMES_TUI_GATEWAY_URL")+ monkeypatch.setenv("HERMES_IGNORE_USER_CONFIG", "1")+ cli_init_mixin._record_shell_hook_consent()+ assert shell_hooks.allowlist_entry_for("pre_tool_call", other) is None+ monkeypatch.delenv("HERMES_IGNORE_USER_CONFIG")+ monkeypatch.setenv("HERMES_ACCEPT_HOOKS", "1")+ cli_init_mixin._record_shell_hook_consent()+ assert json.loads((home / shell_hooks.ALLOWLIST_FILENAME).read_text())["approvals"][-1]["command"] == otherdiff --git a/tests/hermes_cli/test_cli_startup_trim.py b/tests/hermes_cli/test_cli_startup_trim.pyindex 9c044247491..ce5a3466a96 100644--- a/tests/hermes_cli/test_cli_startup_trim.py+++ b/tests/hermes_cli/test_cli_startup_trim.py@@ -19,8 +19,12 @@ def _args(command):@pytest.mark.parametrize("command", [None, "chat"])def test_chat_launch_registers_no_shell_hooks_or_webhooks(monkeypatch, command):+ """... and ``--accept-hooks`` still reaches the gateway: exported as HERMES_ACCEPT_HOOKS, which+ rides session.create (env_launch_flags) and the classic CLI's consent check (CLI-5)."""from hermes_cli import main as main_modcalls = []+ monkeypatch.setenv("HERMES_ACCEPT_HOOKS", "") # recorded, so the export below is undone at teardown+ monkeypatch.delenv("HERMES_ACCEPT_HOOKS")monkeypatch.setattr(main_mod, "_resolve_use_tui", lambda _a: False)monkeypatch.setattr(main_mod, "_bypass_chat_launch", lambda _a: False, raising=False)monkeypatch.setattr(main_mod, "_guard_noninteractive_user_config", lambda _a: None)@@ -32,6 +36,7 @@ def test_chat_launch_registers_no_shell_hooks_or_webhooks(monkeypatch, command):register_from_config=lambda *a, **k: calls.append("webhooks")))main_mod._prepare_agent_startup(_args(command))assert calls == []+ assert main_mod.os.environ["HERMES_ACCEPT_HOOKS"] == "1"def test_non_chat_agent_command_still_registers_hooks(monkeypatch):diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex ea15a468b95..3d17cd9148e 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -2008,7 +2008,7 @@ printf '{}\n'### Consent model-Each unique `(event, command)` pair prompts the user for approval the first time Hermes sees it, then persists the decision to `~/.hermes/shell-hooks-allowlist.json`. Subsequent runs (CLI or gateway) skip the prompt.+Each unique `(event, command)` pair prompts the user for approval the first time Hermes sees it, then persists the decision to `~/.hermes/shell-hooks-allowlist.json`. Subsequent runs (CLI or gateway) skip the prompt. The classic CLI asks on its terminal before it opens its gateway session; the gateway re-reads `hooks:` and the allowlist whenever a local session (CLI, TUI, Desktop) is created or resumed, so a hook added, approved, removed or revoked since the gateway started takes effect then.Three escape hatches bypass the interactive prompt — any one is sufficient:@@ -2043,7 +2043,7 @@ The command string must match the configured hook command exactly. A path-keyed|---------|--------------|| `hermes hooks list` | Dump configured hooks with matcher, timeout, and consent status || `hermes hooks test <event> [--for-tool X] [--payload-file F]` | Fire every matching hook against a synthetic payload and print the parsed response |-| `hermes hooks revoke <command>` | Remove every allowlist entry matching `<command>` (takes effect on next restart) |+| `hermes hooks revoke <command>` | Remove every allowlist entry matching `<command>` (the gateway stops running it when the next local session opens; messaging-only gateways on restart) || `hermes hooks doctor` | For every configured hook: check exec bit, allowlist status, mtime drift, JSON output validity, and rough execution time |### Security