Skip to content

The agent that grows with you

fix(gateway): register a shell hook once its consent is recorded, without a restart

Teknium5a18d0f5f4e9
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py
index fff843cd67a..f3ac817de7a 100644
--- a/agent/shell_hooks.py
+++ b/agent/shell_hooks.py
@@ -776,7 +776,7 @@ def _record_approval(event: str, command: str) -> None:
def revoke(command: str) -> int:
"""Remove every allowlist entry for ``command``; returns the count. A gateway unregisters it at its
- next local session open (``sync_from_config``) unless an opt-in approves every hook; other live
+ next allowlist check (``sync_from_config``, about every 30 s) unless an opt-in approves every hook; other live
processes keep it until restart."""
with _locked_update_approvals() as data:
before = len(data.get("approvals", []))
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index aab7bb29c85..7288d90d5e1 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -12,12 +12,18 @@ verb (``hermes_cli/profiles.py`` create/delete fire it through the control socke
``_profile_reconcile_watcher`` every ``_PROFILE_RESCAN_INTERVAL_SECS`` as the safety net. A served profile whose ``config.yaml``/``.env``
changed since its adapters were last built is re-scanned too: creators make the profile first and add the
bot token afterwards, and without this an adapter-less profile would stay adapter-less forever.
+
+The same watcher tick (on every gateway, multiplexed or not) re-syncs a home's shell hooks when its
+``shell-hooks-allowlist.json`` changed: a non-TTY gateway skips unconsented hooks, so consent recorded
+afterwards must register them without a restart (#132993). That re-runs hook registration only, never
+an adapter rebuild.
"""
from __future__ import annotations
import asyncio
import logging
import os
+from functools import partial
from pathlib import Path
from typing import Any, Dict, Optional
@@ -54,6 +60,7 @@ class GatewayProfileReconcileMixin:
_profile_reconcile_lock: Optional[asyncio.Lock] = None
_profile_own_gateway_warned: Optional[set[str]] = None
_profile_probe_timeout_warned: Optional[set[str]] = None
+ _hook_consent_signatures: Optional[dict[str, Optional[tuple]]] = None
# ── state helpers ─────────────────────────────────────────────────────────────────────────────
@@ -79,21 +86,53 @@ class GatewayProfileReconcileMixin:
# ── watcher ───────────────────────────────────────────────────────────────────────────────────
async def _profile_reconcile_watcher(self, interval: float = _PROFILE_RESCAN_INTERVAL_SECS) -> None:
- """Supervised safety net: rescan ``profiles/`` every ``interval`` seconds (creators signal the
- control socket for an immediate rescan). Returns at once, never respawned, when multiplexing is off."""
- if not self._multiplex_on():
- return
+ """Supervised safety net, every ``interval`` seconds: re-sync shell hooks whose consent changed
+ (every gateway), then rescan ``profiles/`` when multiplexing (creators signal the control
+ socket for an immediate rescan)."""
while self._running:
await asyncio.sleep(interval)
if not self._running:
return
try:
- await self.reconcile_served_profiles(reason="watcher")
+ await self._sync_hooks_on_consent_change()
+ if self._multiplex_on():
+ await self.reconcile_served_profiles(reason="watcher")
except asyncio.CancelledError:
raise
except Exception:
logger.warning("Served-profile reconcile failed; retrying next cycle", exc_info=True)
+ async def _sync_hooks_on_consent_change(self) -> None:
+ """Re-sync the shell hooks of each home (launch + served) whose consent allowlist changed since
+ the last tick, under that home's scope: hooks consented since start register, revoked ones stop
+ firing. A home seen for the first time syncs once (consent may have landed after startup
+ registered). Hook registration only: adapters and sessions are never touched."""
+ from hermes_constants import get_process_hermes_home
+ homes = {Path(h) for h in (get_process_hermes_home(), *(self._served_profile_homes or {}).values())}
+ self._hook_consent_signatures = await asyncio.to_thread(
+ self._resync_changed_hook_consent, homes, self._hook_consent_signatures or {})
+
+ def _resync_changed_hook_consent(self, homes, seen: dict) -> dict:
+ """Blocking half of ``_sync_hooks_on_consent_change``; returns the signatures it observed."""
+ from agent.shell_hooks import ALLOWLIST_FILENAME, sync_from_config
+ from gateway.run import _load_gateway_config, _profile_runtime_scope
+ current = {}
+ for home in (h.resolve() for h in homes):
+ try:
+ current[str(home)] = sig = file_signature(os.stat(home / ALLOWLIST_FILENAME))
+ except OSError:
+ current[str(home)] = sig = None
+ if str(home) in seen and seen[str(home)] == sig:
+ continue
+ load = partial(_load_gateway_config, home / "config.yaml")
+ with _log_suppressed(logging.WARNING, "shell-hook re-sync failed for %s", home, exc_info=True):
+ if not self._multiplex_on():
+ sync_from_config(load)
+ continue
+ with _profile_runtime_scope(home):
+ sync_from_config(load)
+ return current
+
# ── reconcile ─────────────────────────────────────────────────────────────────────────────────
async def reconcile_served_profiles(self, *, reason: str = "request") -> dict[str, Any]:
diff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.py
index 011fb9a3db1..da7b1e9ec59 100644
--- a/hermes_cli/hooks.py
+++ b/hermes_cli/hooks.py
@@ -260,7 +260,7 @@ def _cmd_revoke(args) -> None:
return
print(f"Removed {removed} allowlist entry/entries for: {args.command}")
print(
- "Note: a running gateway stops running it when the next local session opens (unless "
+ "Note: a running gateway stops running it within about 30 seconds (unless "
"--accept-hooks / HERMES_ACCEPT_HOOKS / hooks_auto_accept approves every hook there); "
"other running processes keep it until they restart."
)
diff --git a/hermes_cli/subcommands/hooks.py b/hermes_cli/subcommands/hooks.py
index 0c29337c207..0ea3d941d32 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 (a running gateway drops it at the next local session open)")
+ help="Remove a command's allowlist entries (a running gateway drops it within about 30 seconds)")
_hk_revoke.add_argument(
"command", help="The exact command string to revoke (as declared in config.yaml)")
diff --git a/tests/gateway/test_hook_consent_resync.py b/tests/gateway/test_hook_consent_resync.py
new file mode 100644
index 00000000000..64839fc1f99
--- /dev/null
+++ b/tests/gateway/test_hook_consent_resync.py
@@ -0,0 +1,84 @@
+"""#132993: a running gateway registers a shell hook once its consent is recorded, and drops it
+once revoked, without a restart or a session open, for the launch profile of a single-profile
+gateway and for a profile a multiplexer serves. Hooks only: adapters are never rebuilt for it."""
+import asyncio
+from pathlib import Path
+
+import pytest
+
+from agent import shell_hooks
+from gateway.config import GatewayConfig
+from gateway.run import GatewayRunner
+from tests.waiting import async_wait_until
+
+
+def _hooks_in(home: Path) -> list:
+ from hermes_cli.plugins import get_plugin_manager
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ token = set_hermes_home_override(str(home))
+ try:
+ return [cb for cb in get_plugin_manager()._hooks.get("pre_tool_call", [])
+ if getattr(cb, "shell_hook_key", None)]
+ finally:
+ reset_hermes_home_override(token)
+
+
+def _approve(home: Path, command: str, approve: bool) -> None:
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ token = set_hermes_home_override(str(home))
+ try:
+ shell_hooks._record_approval("pre_tool_call", command) if approve else shell_hooks.revoke(command)
+ finally:
+ reset_hermes_home_override(token)
+
+
[email protected]("multiplex", [False, True])
+async def test_consent_change_registers_and_revokes_hook_without_restart(tmp_path, monkeypatch, multiplex):
+ launch = tmp_path / ".hermes"
+ profile = launch / "profiles" / "guarded"
+ profile.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.delenv("HERMES_ACCEPT_HOOKS", raising=False)
+ shell_hooks.reset_for_tests()
+ command = str(tmp_path / "guard.sh")
+ hook_cfg = f"hooks:\n pre_tool_call:\n - command: {command}\n fail_closed: true\n"
+ target = profile if multiplex else launch
+ (target / "config.yaml").write_text(hook_cfg, encoding="utf-8")
+
+ runner = object.__new__(GatewayRunner)
+ runner.config = GatewayConfig(multiplex_profiles=multiplex)
+ runner._running = True
+ runner._served_profile_homes = {"guarded": profile} if multiplex else None
+ passes = []
+
+ async def _reconcile(**_kw): # runs once per watcher pass when multiplexing
+ passes.append(1)
+ return {}
+
+ runner.reconcile_served_profiles = _reconcile
+
+ async def _passes(n):
+ start = len(passes)
+ await async_wait_until(lambda: len(passes) >= start + n, timeout=10, what="watcher passes")
+
+ watcher = asyncio.create_task(runner._profile_reconcile_watcher(interval=0.01))
+ try:
+ if multiplex:
+ await _passes(2)
+ assert _hooks_in(target) == [] # no consent yet: skipped
+
+ _approve(target, command, True)
+ await async_wait_until(lambda: len(_hooks_in(target)) == 1, timeout=10, what="hook registered")
+ if multiplex:
+ await _passes(3) # later passes with unchanged consent never double-register
+ assert len(_hooks_in(target)) == 1
+
+ _approve(target, command, False)
+ await async_wait_until(lambda: _hooks_in(target) == [], timeout=10, what="hook unregistered")
+ assert bool(passes) == multiplex
+ finally:
+ runner._running = False
+ watcher.cancel()
+ await asyncio.gather(watcher, return_exceptions=True)
+ shell_hooks.reset_for_tests()
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index cc9b3034e0e..cdddeb48bed 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -2070,7 +2070,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. 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.
+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. A change to a profile's allowlist alone (an approval or `hermes hooks revoke`) also takes effect within about 30 seconds without any session opening, on every profile a gateway serves.
Three escape hatches bypass the interactive prompt — any one is sufficient:
@@ -2105,7 +2105,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>` (the gateway stops running it when the next local session opens; messaging-only gateways on restart) |
+| `hermes hooks revoke <command>` | Remove every allowlist entry matching `<command>` (a running gateway stops running it within about 30 seconds) |
| `hermes hooks doctor` | For every configured hook: check exec bit, allowlist status, mtime drift, JSON output validity, and rough execution time |
### Security