Skip to content

The agent that grows with you

fix(gateway): never prompt for shell-hook consent outside a foreground CLI

arcabotaiec2fe8c43e3b
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py
index d4b51fe32e7..c49bb479b9c 100644
--- a/agent/shell_hooks.py
+++ b/agent/shell_hooks.py
@@ -146,9 +146,16 @@ class ShellHookSpec(_ToolMatcherMixin):
# --- Public API ---
-def register_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool = False) -> list[ShellHookSpec]:
+def register_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool = False,
+ interactive: bool = False) -> list[ShellHookSpec]:
"""Register every configured shell hook (idempotent); returns the newly wired specs. Skipped
- entries (unknown, malformed, not allowlisted, already registered) are logged only."""
+ entries (unknown, malformed, not allowlisted, already registered) are logged only.
+
+ ``interactive=True`` lets a hook that is not yet allowlisted ask at the terminal; only a
+ foreground CLI command passes it. Every other caller (gateway startup and profile loads, cron
+ and managed workers, tui_gateway, force-reload re-registration) never prompts: ``isatty()``
+ cannot tell a hidden console or ``NUL`` from a person, and a prompt there blocks the event loop
+ until the liveness watchdog kills the gateway (#120356, #127822)."""
specs, _complete = _hook_specs(cfg)
if not specs:
return []
@@ -160,12 +167,12 @@ def register_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: bool =
# TTY prompt outside the lock; _wire takes the lock and re-checks.
consented = []
for spec in specs:
- if _consented(spec, accept, allowed):
+ if _consented(spec, accept, allowed, prompt=interactive):
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)
+ logger.warning("shell hook for %s (%s) not allowlisted in %s — skipped. Use --accept-hooks / "
+ "HERMES_ACCEPT_HOOKS=1 / hooks_auto_accept: true, or approve it at a CLI prompt "
+ "for this profile.", spec.event, spec.command, allowlist_path())
with _registered_lock:
return _wire(manager, home_key, consented)
@@ -235,7 +242,7 @@ def record_consent_from_config(cfg: Optional[dict[str, Any]], *, accept_hooks: b
if not specs:
return []
accept, allowed = _resolve_effective_accept(cfg, accept_hooks), allowlisted_pairs()
- return [spec for spec in specs if _consented(spec, accept, allowed)]
+ return [spec for spec in specs if _consented(spec, accept, allowed, prompt=True)]
def accept_for_launch(cfg: Optional[dict[str, Any]]) -> None:
@@ -304,11 +311,14 @@ def allowlisted_pairs() -> set[tuple[str, str]]:
return _approved_pairs(load_allowlist()["approvals"])
-def _consented(spec: ShellHookSpec, accept: bool, allowed: set[tuple[str, str]]) -> bool:
- """Allowlisted, or approved now (opt-in or TTY prompt, recorded); ``allowed`` caches one read."""
+def _consented(spec: ShellHookSpec, accept: bool, allowed: set[tuple[str, str]], *, prompt: bool) -> bool:
+ """Allowlisted, or approved now (opt-in, or a TTY prompt when ``prompt``; recorded); ``allowed``
+ caches one read."""
pair = (spec.event, spec.command)
if pair in allowed:
return True
+ if not (accept or prompt):
+ return False
if not _prompt_and_record(spec.event, spec.command, accept_hooks=accept):
return False
allowed.add(pair)
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 068da958488..3a72869114e 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -1118,8 +1118,10 @@ class GatewayStartupMixin:
def _register_config_hooks(fail_fmt: str, *fail_args, level: int = logging.DEBUG) -> None:
"""Register declarative shell hooks + outbound webhooks from the CURRENT scope's config.
- Gateway has no TTY, so consent must come from --accept-hooks, HERMES_ACCEPT_HOOKS, or
- hooks_auto_accept: true; ``accept_hooks=False`` lets register_from_config resolve env + config.
+ The gateway never prompts (register_from_config defaults to ``interactive=False``), even
+ when a hidden console makes stdin look like a TTY, so consent must come from the allowlist,
+ --accept-hooks, HERMES_ACCEPT_HOOKS, or hooks_auto_accept: true; ``accept_hooks=False`` lets
+ register_from_config resolve env + config.
Never raises (logged at ``level``).
"""
try:
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 907704054ec..fc3b717ecd5 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -2988,7 +2988,8 @@ def _prepare_agent_startup(args) -> None:
from agent.outbound_webhooks import register_from_config as register_outbound_webhooks
_hooks_cfg = load_config()
- register_from_config(_hooks_cfg, accept_hooks=_accept_hooks)
+ # A foreground command may ask at its terminal; ``gateway run`` is a service and never does.
+ register_from_config(_hooks_cfg, accept_hooks=_accept_hooks, interactive=args.command != "gateway")
if _accept_hooks and args.command == "gateway": # every session-open re-sync keeps honouring it
from agent.shell_hooks import accept_for_process
accept_for_process()
diff --git a/tests/agent/test_shell_hooks_consent.py b/tests/agent/test_shell_hooks_consent.py
index ba7de4708af..1c1bb9c9377 100644
--- a/tests/agent/test_shell_hooks_consent.py
+++ b/tests/agent/test_shell_hooks_consent.py
@@ -7,7 +7,12 @@ hooks_auto_accept: config key).
from __future__ import annotations
+import asyncio
+import json
+import logging
+import os
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -45,7 +50,7 @@ class TestTTYPromptFlow:
mock_stdin.isatty.return_value = True
registered = shell_hooks.register_from_config(
{"hooks": {"on_session_start": [{"command": str(script)}]}},
- accept_hooks=False,
+ accept_hooks=False, interactive=True,
)
assert len(registered) == 1
@@ -64,7 +69,7 @@ class TestTTYPromptFlow:
mock_stdin.isatty.return_value = True
registered = shell_hooks.register_from_config(
{"hooks": {"on_session_start": [{"command": str(script)}]}},
- accept_hooks=False,
+ accept_hooks=False, interactive=True,
)
assert registered == []
assert shell_hooks.allowlist_entry_for(
@@ -83,7 +88,7 @@ class TestTTYPromptFlow:
mock_stdin.isatty.return_value = True
shell_hooks.register_from_config(
{"hooks": {"on_session_start": [{"command": str(script)}]}},
- accept_hooks=False,
+ accept_hooks=False, interactive=True,
)
# Reset registration set but keep the allowlist on disk.
@@ -96,7 +101,7 @@ class TestTTYPromptFlow:
mock_stdin.isatty.return_value = True
registered = shell_hooks.register_from_config(
{"hooks": {"on_session_start": [{"command": str(script)}]}},
- accept_hooks=False,
+ accept_hooks=False, interactive=True,
)
assert len(registered) == 1
@@ -137,6 +142,97 @@ class TestNonTTYFlow:
+# ── Never prompt outside a foreground CLI command (#120356, #127822) ──────
+
+
+def _tty_stdin_that_nobody_answers(monkeypatch) -> list:
+ """A hidden console (Windows ``.vbs`` launcher) or ``NUL`` makes ``isatty()`` True with no
+ person behind it; record every ``input()`` instead of blocking on it."""
+ asked: list = []
+ monkeypatch.setattr("sys.stdin", SimpleNamespace(isatty=lambda: True))
+ monkeypatch.setattr("builtins.input", lambda *a: asked.append(a) or "y")
+ return asked
+
+
+def _write_config_with_hook(tmp_path: Path) -> Path:
+ script = _write_hook_script(tmp_path)
+ home = Path(os.environ["HERMES_HOME"])
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text(
+ f"hooks:\n on_session_start:\n - command: {json.dumps(str(script))}\n", encoding="utf-8")
+ return script
+
+
+class TestNeverPromptOutsideForegroundCLI:
+ def test_default_registration_declines_without_reading_a_tty_stdin(self, tmp_path, monkeypatch, caplog):
+ from hermes_cli import plugins
+
+ script = _write_hook_script(tmp_path)
+ plugins._plugin_manager = plugins.PluginManager()
+ asked = _tty_stdin_that_nobody_answers(monkeypatch)
+
+ with caplog.at_level(logging.WARNING, logger="agent.shell_hooks"):
+ registered = shell_hooks.register_from_config(
+ {"hooks": {"on_session_start": [{"command": str(script)}]}})
+
+ assert asked == []
+ assert registered == []
+ assert shell_hooks.allowlist_entry_for("on_session_start", str(script)) is None
+ assert str(shell_hooks.allowlist_path()) in caplog.text # names the profile home to approve in
+
+ def test_opt_in_still_approves_without_a_prompt(self, tmp_path, monkeypatch):
+ from hermes_cli import plugins
+
+ script = _write_hook_script(tmp_path)
+ plugins._plugin_manager = plugins.PluginManager()
+ asked = _tty_stdin_that_nobody_answers(monkeypatch)
+ monkeypatch.setenv("HERMES_ACCEPT_HOOKS", "1")
+
+ registered = shell_hooks.register_from_config(
+ {"hooks": {"on_session_start": [{"command": str(script)}]}})
+
+ assert asked == []
+ assert len(registered) == 1
+ assert shell_hooks.allowlist_entry_for("on_session_start", str(script)) is not None
+
+ def test_gateway_registration_on_the_event_loop_never_prompts(self, tmp_path, monkeypatch, caplog):
+ """The P0 shape: gateway startup and every secondary-profile load register from the loop
+ thread; a prompt there froze the loop until the liveness watchdog exited 75."""
+ from gateway.run_startup import GatewayStartupMixin
+ from hermes_cli import plugins
+
+ script = _write_config_with_hook(tmp_path)
+ plugins._plugin_manager = plugins.PluginManager()
+ asked = _tty_stdin_that_nobody_answers(monkeypatch)
+
+ async def _boot() -> None:
+ asyncio.get_running_loop() # registered from the loop thread, as startup does
+ GatewayStartupMixin._register_config_hooks("registration failed", level=logging.ERROR)
+
+ with caplog.at_level(logging.WARNING):
+ asyncio.run(_boot())
+
+ assert asked == []
+ assert "registration failed" not in caplog.text
+ assert "not allowlisted" in caplog.text and str(script) in caplog.text
+ assert shell_hooks.allowlist_entry_for("on_session_start", str(script)) is None
+ assert plugins._plugin_manager._hooks.get("on_session_start", []) == []
+
+ def test_force_reload_reregistration_never_prompts(self, tmp_path, monkeypatch, caplog):
+ from hermes_cli import plugins
+
+ script = _write_config_with_hook(tmp_path)
+ plugins._plugin_manager = plugins.PluginManager()
+ asked = _tty_stdin_that_nobody_answers(monkeypatch)
+
+ with caplog.at_level(logging.WARNING, logger="agent.shell_hooks"):
+ shell_hooks.re_register_config_hooks()
+
+ assert asked == []
+ assert "not allowlisted" in caplog.text
+ assert shell_hooks.allowlist_entry_for("on_session_start", str(script)) is None
+
+
# ── Allowlist + revoke + mtime ────────────────────────────────────────────
diff --git a/tests/hermes_cli/test_cli_startup_trim.py b/tests/hermes_cli/test_cli_startup_trim.py
index 16e6b406335..648e94367d7 100644
--- a/tests/hermes_cli/test_cli_startup_trim.py
+++ b/tests/hermes_cli/test_cli_startup_trim.py
@@ -56,6 +56,31 @@ def test_non_chat_agent_command_still_registers_hooks(monkeypatch):
assert calls == ["hooks", "webhooks"]
[email protected](("command", "subcommand", "interactive"), [
+ ("gateway", {"gateway_command": "run"}, False), # a service: a hidden console is not a person (#127822)
+ ("rl", {}, True), # a foreground command may still ask at its terminal
+])
+def test_only_foreground_commands_may_prompt_for_hook_consent(monkeypatch, command, subcommand, interactive):
+ from hermes_cli import main as main_mod
+ seen = []
+ monkeypatch.setitem(sys.modules, "hermes_cli.plugins", types.SimpleNamespace(
+ discover_plugins=lambda: None, start_background_plugin_discovery=lambda: None))
+ monkeypatch.setitem(sys.modules, "hermes_cli.config", types.SimpleNamespace(
+ load_config=dict, read_raw_config=dict))
+ monkeypatch.setitem(sys.modules, "agent.shell_hooks", types.SimpleNamespace(
+ register_from_config=lambda *a, **k: seen.append(k)))
+ monkeypatch.setitem(sys.modules, "agent.outbound_webhooks", types.SimpleNamespace(
+ register_from_config=lambda *a, **k: None))
+ from hermes_cli import mcp_startup
+ monkeypatch.setattr(mcp_startup, "start_background_mcp_discovery", lambda **k: None)
+ args = _args(command)
+ args.accept_hooks = False
+ for name, value in subcommand.items():
+ setattr(args, name, value)
+ main_mod._prepare_agent_startup(args)
+ assert seen == [{"accept_hooks": False, "interactive": interactive}]
+
+
def test_deferred_first_turn_discovers_no_plugins_spawns_no_mcp_and_registers_no_hooks(monkeypatch):
# Termux's deferred startup ran plugin discovery before the first turn; the gateway runs the turn
# and loads the plugins (PLG-7).