The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Inspired by Cursor: fail-closed hook semantics + exit-code-2 blocking
Teknium1dee73400e65
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.pyindex db44ddab2b9..f8af6a7cd12 100644--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@ -50,6 +50,28 @@ Wire protocol# Silent no-op:<empty or any non-matching JSON object>+**exit codes**++Exit code 2 from a ``pre_tool_call`` hook blocks the tool call even when+stdout carries no block JSON (Claude-Code / Cursor compatible). The block+message is taken from the stdout block JSON when present, then the first+400 characters of stderr, then a generic default. For events whose block+directive is not honored, exit 2 is logged at warning like any other+non-zero exit. All other non-zero exits log a warning and stdout is still+parsed normally.++**failure semantics**++Hooks fail *open* by default: a spawn error, timeout, or unparseable+stdout logs a warning and contributes nothing. A ``pre_tool_call`` entry+can opt into fail-*closed* semantics with ``fail_closed: true``+(``failClosed`` also accepted for Cursor/Claude-Code config compat) —+spawn errors, timeouts, and malformed stdout then BLOCK the tool call+with ``hook <command> failed closed: <reason>``. Use this for+security-gating hooks (secret scanners, policy checks) where a crashed+hook must not silently allow the action. On non-blocking events+``fail_closed`` is ignored with a warning.+Per-event ``extra`` keys~~~~~~~~~~~~~~~~~~~~~~~~@@ -140,6 +162,20 @@ MAX_TIMEOUT_SECONDS = 300ALLOWLIST_FILENAME = "shell-hooks-allowlist.json"_DEFAULT_BLOCK_MESSAGE = "Blocked by shell hook."+# Exit code that signals "block this action" from a hook script, independent+# of stdout content. Claude Code / Cursor compatible.+BLOCK_EXIT_CODE = 2++# Events whose block directive is actually honored downstream (see+# hermes_cli.plugins.get_pre_tool_call_block_message / _get_pre_tool_call_+# directive_details). Exit-code-2 blocking and ``fail_closed`` only make+# sense for these.+_BLOCKING_EVENTS = frozenset({"pre_tool_call"})++# Cap on stderr excerpt reused as a block message.+_STDERR_MESSAGE_LIMIT = 400++# (event, matcher, command) triples that have been wired to the plugin# manager in the current process. Matcher is part of the key because# the same script can legitimately register for different matchers under@@ -166,6 +202,7 @@ class ShellHookSpec:command: strmatcher: Optional[str] = Nonetimeout: int = DEFAULT_TIMEOUT_SECONDS+ fail_closed: bool = Falsecompiled_matcher: Optional[re.Pattern] = field(default=None, repr=False)def __post_init__(self) -> None:@@ -278,8 +315,10 @@ def register_from_config(_registered.add(key)registered.append(spec)logger.info(- "shell hook registered: %s -> %s (matcher=%s, timeout=%ds)",+ "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@@ -416,11 +455,33 @@ def _parse_single_entry()timeout = MAX_TIMEOUT_SECONDS+ # ``fail_closed`` (canonical) / ``failClosed`` (Cursor/Claude-Code+ # config compat). Canonical spelling wins when both are present.+ fail_closed_raw = raw.get("fail_closed", raw.get("failClosed", False))+ if not isinstance(fail_closed_raw, bool):+ logger.warning(+ "hooks.%s[%d].fail_closed must be a boolean (got %r); "+ "using default false (fail open)",+ event, index, fail_closed_raw,+ )+ fail_closed_raw = False+ fail_closed = fail_closed_raw++ if fail_closed and event not in _BLOCKING_EVENTS:+ logger.warning(+ "hooks.%s[%d].fail_closed=true will be ignored at runtime — "+ "fail_closed only applies to blocking-capable events (%s). "+ "The hook will fail open on %s like any other hook.",+ event, index, ", ".join(sorted(_BLOCKING_EVENTS)), event,+ )+ fail_closed = False+return ShellHookSpec(event=event,command=command.strip(),matcher=matcher,timeout=timeout,+ fail_closed=fail_closed,)@@ -501,38 +562,112 @@ def _make_callback(spec: ShellHookSpec) -> Callable[..., Optional[Dict[str, Any]return Noner = _spawn(spec, _serialize_payload(spec.event, kwargs))+ return _evaluate_result(spec, r)- if r["error"]:- logger.warning(- "shell hook failed (event=%s command=%s): %s",- spec.event, spec.command, r["error"],- )- return None- if r["timed_out"]:- logger.warning(- "shell hook timed out after %.2fs (event=%s command=%s)",- r["elapsed_seconds"], spec.event, spec.command,- )- return None+ _callback.__name__ = f"shell_hook[{spec.event}:{spec.command}]"+ _callback.__qualname__ = _callback.__name__+ return _callback+++def _fail_closed_block(spec: ShellHookSpec, reason: str) -> Dict[str, Any]:+ """Canonical block shape for a ``fail_closed`` hook that failed."""+ return {+ "action": "block",+ "message": f"hook {spec.command} failed closed: {reason}",+ }+++def _evaluate_result(+ spec: ShellHookSpec, r: Dict[str, Any],+) -> Optional[Dict[str, Any]]:+ """Turn a :func:`_spawn` diagnostic dict into the hook's contribution.++ Single place that encodes the failure semantics:- stderr = r["stderr"].strip()- if stderr:- logger.debug(- "shell hook stderr (event=%s command=%s): %s",- spec.event, spec.command, stderr[:400],+ * spawn error / timeout — fail open (log + ``None``) unless the spec+ is ``fail_closed`` on a blocking-capable event, in which case a+ canonical block shape is returned;+ * exit code 2 on a blocking-capable event — block, with the message+ taken from stdout block JSON, then stderr, then a default+ (Claude-Code / Cursor compatible);+ * other non-zero exits — warn, then parse stdout normally;+ * non-JSON / unparseable stdout on a ``fail_closed`` blocking hook —+ block instead of silently contributing nothing.++ Shared by the live callback path (:func:`_make_callback`) and the CLI+ test helper (:func:`run_once`) so ``hermes hooks test`` reflects+ production behaviour exactly.+ """+ blocking_event = spec.event in _BLOCKING_EVENTS+ fail_closed = spec.fail_closed and blocking_event++ if r["error"]:+ logger.warning(+ "shell hook failed (event=%s command=%s): %s",+ spec.event, spec.command, r["error"],+ )+ if fail_closed:+ return _fail_closed_block(spec, r["error"])+ return None+ if r["timed_out"]:+ logger.warning(+ "shell hook timed out after %.2fs (event=%s command=%s)",+ r["elapsed_seconds"], spec.event, spec.command,+ )+ if fail_closed:+ return _fail_closed_block(+ spec, f"timed out after {spec.timeout}s",)- # Non-zero exits: log but still parse stdout so scripts that- # signal failure via exit code can also return a block directive.- if r["returncode"] != 0:- logger.warning(- "shell hook exited %d (event=%s command=%s); stderr=%s",- r["returncode"], spec.event, spec.command, stderr[:400],+ return None++ stderr = r["stderr"].strip()+ if stderr:+ logger.debug(+ "shell hook stderr (event=%s command=%s): %s",+ spec.event, spec.command, stderr[:_STDERR_MESSAGE_LIMIT],+ )++ # Exit code 2 = block (Claude-Code / Cursor compatible), for events+ # whose block directive is honored downstream. stdout block JSON+ # still wins for the message; otherwise stderr, then a default.+ if r["returncode"] == BLOCK_EXIT_CODE and blocking_event:+ parsed = _parse_response(spec.event, r["stdout"])+ if isinstance(parsed, dict) and parsed.get("action") == "block":+ return parsed+ message = stderr[:_STDERR_MESSAGE_LIMIT] or _DEFAULT_BLOCK_MESSAGE+ logger.info(+ "shell hook exited %d — blocking (event=%s command=%s): %s",+ BLOCK_EXIT_CODE, spec.event, spec.command, message,+ )+ return {"action": "block", "message": message}++ # Other non-zero exits: log but still parse stdout so scripts that+ # signal failure via exit code can also return a block directive.+ if r["returncode"] != 0:+ logger.warning(+ "shell hook exited %d (event=%s command=%s); stderr=%s",+ r["returncode"], spec.event, spec.command,+ stderr[:_STDERR_MESSAGE_LIMIT],+ )++ stdout = (r["stdout"] or "").strip()+ parsed = _parse_response(spec.event, stdout)++ if parsed is None and fail_closed and stdout:+ # The hook produced output we could not turn into a directive.+ # A fail-closed gate must not silently allow the action on+ # garbage output (e.g. a stack trace on stdout).+ try:+ data = json.loads(stdout)+ valid_json = isinstance(data, dict)+ except json.JSONDecodeError:+ valid_json = False+ if not valid_json:+ return _fail_closed_block(+ spec, "unparseable stdout (expected a JSON object)",)- return _parse_response(spec.event, r["stdout"])- _callback.__name__ = f"shell_hook[{spec.event}:{spec.command}]"- _callback.__qualname__ = _callback.__name__- return _callback+ return parseddef _serialize_payload(event: str, kwargs: Dict[str, Any]) -> str:@@ -923,8 +1058,10 @@ def run_once(diverge silently from production behaviour.Returns the :func:`_spawn` diagnostic dict plus a ``parsed`` field- holding the canonical Hermes-wire-shape response."""+ holding the canonical Hermes-wire-shape response — including exit-code-2+ blocking and ``fail_closed`` semantics, so what ``hermes hooks test``+ prints is exactly what the dispatcher would receive."""stdin_json = _serialize_payload(spec.event, kwargs)result = _spawn(spec, stdin_json)- result["parsed"] = _parse_response(spec.event, result["stdout"])+ result["parsed"] = _evaluate_result(spec, result)return resultdiff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.pyindex af9d4b6c3eb..c71da88d5b4 100644--- a/hermes_cli/hooks.py+++ b/hermes_cli/hooks.py@@ -290,9 +290,11 @@ def _cmd_test(args) -> None:def _print_run_result(result: Dict[str, Any]) -> None:if result.get("error"):print(f" ✗ error: {result['error']}")+ _print_parsed(result)returnif result.get("timed_out"):print(f" ✗ timed out after {result['elapsed_seconds']}s")+ _print_parsed(result)returnrc = result.get("returncode")@@ -306,6 +308,10 @@ def _print_run_result(result: Dict[str, Any]) -> None:if stderr:print(f" stderr: {_truncate(stderr, 400)}")+ _print_parsed(result)+++def _print_parsed(result: Dict[str, Any]) -> None:parsed = result.get("parsed")if parsed:print(f" parsed (Hermes wire shape): {json.dumps(parsed)}")diff --git a/tests/agent/test_shell_hooks.py b/tests/agent/test_shell_hooks.pyindex 2dfcdc63d36..6fb8f78460e 100644--- a/tests/agent/test_shell_hooks.py+++ b/tests/agent/test_shell_hooks.py@@ -419,3 +419,274 @@ class TestAllowlistConcurrency:assert len(tmp_paths_seen) == 2assert tmp_paths_seen[0] != tmp_paths_seen[1]+++# ── fail_closed parsing ───────────────────────────────────────────────────+++class TestFailClosedParsing:+ def test_fail_closed_parsed(self):+ specs = shell_hooks._parse_hooks_block({+ "pre_tool_call": [+ {"command": "/tmp/h.sh", "fail_closed": True},+ ],+ })+ assert len(specs) == 1+ assert specs[0].fail_closed is True++ def test_fail_closed_defaults_false(self):+ specs = shell_hooks._parse_hooks_block({+ "pre_tool_call": [{"command": "/tmp/h.sh"}],+ })+ assert specs[0].fail_closed is False++ def test_failclosed_camel_alias(self):+ """Cursor/Claude Code configs spell it failClosed."""+ specs = shell_hooks._parse_hooks_block({+ "pre_tool_call": [+ {"command": "/tmp/h.sh", "failClosed": True},+ ],+ })+ assert specs[0].fail_closed is True++ def test_canonical_wins_over_alias(self):+ specs = shell_hooks._parse_hooks_block({+ "pre_tool_call": [+ {"command": "/tmp/h.sh", "fail_closed": False,+ "failClosed": True},+ ],+ })+ assert specs[0].fail_closed is False++ def test_non_bool_warns_and_defaults_false(self, caplog):+ import logging+ with caplog.at_level(logging.WARNING, logger=shell_hooks.logger.name):+ specs = shell_hooks._parse_hooks_block({+ "pre_tool_call": [+ {"command": "/tmp/h.sh", "fail_closed": "yes"},+ ],+ })+ assert specs[0].fail_closed is False+ assert any(+ "fail_closed must be a boolean" in r.getMessage()+ for r in caplog.records+ )++ def test_fail_closed_on_non_blocking_event_warns_and_ignores(self, caplog):+ import logging+ with caplog.at_level(logging.WARNING, logger=shell_hooks.logger.name):+ specs = shell_hooks._parse_hooks_block({+ "on_session_start": [+ {"command": "/tmp/h.sh", "fail_closed": True},+ ],+ })+ assert specs[0].fail_closed is False+ assert any(+ "fail_closed" in r.getMessage() and "ignored" in r.getMessage()+ for r in caplog.records+ )+++# ── _evaluate_result semantics ────────────────────────────────────────────+++def _spawn_result(**overrides):+ base = {+ "returncode": 0,+ "stdout": "",+ "stderr": "",+ "timed_out": False,+ "elapsed_seconds": 0.1,+ "error": None,+ }+ base.update(overrides)+ return base+++class TestEvaluateResult:+ def _spec(self, event="pre_tool_call", fail_closed=False):+ return shell_hooks.ShellHookSpec(+ event=event, command="/tmp/h.sh", fail_closed=fail_closed,+ )++ # -- exit code 2 = block --------------------------------------------++ def test_exit_2_blocks_with_stderr_message(self):+ r = shell_hooks._evaluate_result(+ self._spec(),+ _spawn_result(returncode=2, stderr="policy violation\n"),+ )+ assert r == {"action": "block", "message": "policy violation"}++ def test_exit_2_blocks_with_default_message(self):+ r = shell_hooks._evaluate_result(+ self._spec(), _spawn_result(returncode=2),+ )+ assert r == {+ "action": "block",+ "message": shell_hooks._DEFAULT_BLOCK_MESSAGE,+ }++ def test_exit_2_stdout_block_json_wins(self):+ r = shell_hooks._evaluate_result(+ self._spec(),+ _spawn_result(+ returncode=2,+ stdout='{"decision": "block", "reason": "from stdout"}',+ stderr="from stderr",+ ),+ )+ assert r == {"action": "block", "message": "from stdout"}++ def test_exit_2_on_non_blocking_event_does_not_block(self):+ r = shell_hooks._evaluate_result(+ self._spec(event="on_session_start"),+ _spawn_result(returncode=2, stderr="boom"),+ )+ assert r is None++ def test_other_nonzero_exit_still_parses_stdout(self):+ r = shell_hooks._evaluate_result(+ self._spec(),+ _spawn_result(+ returncode=1,+ stdout='{"decision": "block", "reason": "nope"}',+ ),+ )+ assert r == {"action": "block", "message": "nope"}++ def test_nonzero_exit_without_directive_is_none(self):+ r = shell_hooks._evaluate_result(+ self._spec(), _spawn_result(returncode=1, stderr="oops"),+ )+ assert r is None++ # -- fail_closed ------------------------------------------------------++ def test_spawn_error_fails_open_by_default(self):+ r = shell_hooks._evaluate_result(+ self._spec(), _spawn_result(error="No such file"),+ )+ assert r is None++ def test_spawn_error_fail_closed_blocks(self):+ r = shell_hooks._evaluate_result(+ self._spec(fail_closed=True), _spawn_result(error="No such file"),+ )+ assert r["action"] == "block"+ assert "failed closed" in r["message"]+ assert "No such file" in r["message"]++ def test_timeout_fails_open_by_default(self):+ r = shell_hooks._evaluate_result(+ self._spec(), _spawn_result(timed_out=True),+ )+ assert r is None++ def test_timeout_fail_closed_blocks(self):+ spec = self._spec(fail_closed=True)+ r = shell_hooks._evaluate_result(spec, _spawn_result(timed_out=True))+ assert r["action"] == "block"+ assert f"timed out after {spec.timeout}s" in r["message"]++ def test_unparseable_stdout_fail_closed_blocks(self):+ r = shell_hooks._evaluate_result(+ self._spec(fail_closed=True),+ _spawn_result(stdout="Traceback (most recent call last): ..."),+ )+ assert r["action"] == "block"+ assert "unparseable stdout" in r["message"]++ def test_unparseable_stdout_fails_open_by_default(self):+ r = shell_hooks._evaluate_result(+ self._spec(),+ _spawn_result(stdout="Traceback (most recent call last): ..."),+ )+ assert r is None++ def test_valid_noop_json_passes_fail_closed(self):+ """A clean {} no-op must NOT be blocked by fail_closed."""+ r = shell_hooks._evaluate_result(+ self._spec(fail_closed=True), _spawn_result(stdout="{}"),+ )+ assert r is None++ def test_empty_stdout_passes_fail_closed(self):+ r = shell_hooks._evaluate_result(+ self._spec(fail_closed=True), _spawn_result(stdout=""),+ )+ assert r is None++ def test_fail_closed_on_non_blocking_event_still_fails_open(self):+ """Defense in depth: even if a spec sneaks past parsing with+ fail_closed on a non-blocking event, runtime fails open."""+ r = shell_hooks._evaluate_result(+ self._spec(event="on_session_start", fail_closed=True),+ _spawn_result(error="boom"),+ )+ assert r is None+++# ── exit-2 / fail_closed end-to-end ──────────────────────────────────────+++class TestFailSemanticsEndToEnd:+ def test_exit_2_script_blocks(self, tmp_path):+ script = _write_script(+ tmp_path, "exit2.sh",+ "#!/usr/bin/env bash\n"+ 'echo "rm -rf is not permitted" >&2\n'+ "exit 2\n",+ )+ spec = shell_hooks.ShellHookSpec(+ event="pre_tool_call", command=str(script),+ )+ cb = shell_hooks._make_callback(spec)+ result = cb(tool_name="terminal", args={"command": "rm -rf /"})+ assert result == {+ "action": "block", "message": "rm -rf is not permitted",+ }++ def test_fail_closed_missing_command_blocks(self, tmp_path):+ spec = shell_hooks.ShellHookSpec(+ event="pre_tool_call",+ command=str(tmp_path / "does-not-exist.sh"),+ fail_closed=True,+ )+ cb = shell_hooks._make_callback(spec)+ result = cb(tool_name="terminal", args={"command": "ls"})+ assert result is not None and result["action"] == "block"+ assert "failed closed" in result["message"]++ def test_run_once_reflects_exit_2_block(self, tmp_path):+ """hermes hooks test must mirror production semantics."""+ script = _write_script(+ tmp_path, "exit2.sh",+ "#!/usr/bin/env bash\n"+ 'echo "denied" >&2\n'+ "exit 2\n",+ )+ spec = shell_hooks.ShellHookSpec(+ event="pre_tool_call", command=str(script),+ )+ result = shell_hooks.run_once(+ spec, {"tool_name": "terminal", "args": {"command": "ls"}},+ )+ assert result["returncode"] == 2+ assert result["parsed"] == {"action": "block", "message": "denied"}++ def test_run_once_reflects_fail_closed_timeout(self, tmp_path):+ script = _write_script(+ tmp_path, "sleepy.sh",+ "#!/usr/bin/env bash\nsleep 5\n",+ )+ spec = shell_hooks.ShellHookSpec(+ event="pre_tool_call", command=str(script),+ timeout=1, fail_closed=True,+ )+ result = shell_hooks.run_once(+ spec, {"tool_name": "terminal", "args": {"command": "ls"}},+ )+ assert result["timed_out"] is True+ assert result["parsed"]["action"] == "block"+ assert "failed closed" in result["parsed"]["message"]diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex bda14cef915..80b94966a03 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -1334,11 +1334,13 @@ hooks:- matcher: "<regex>" # Optional; used for pre/post_tool_call onlycommand: "<shell command>" # Required; runs via shlex.split, shell=Falsetimeout: <seconds> # Optional; default 60, capped at 300+ fail_closed: <bool> # Optional; default false. pre_tool_call only.+ # `failClosed` also accepted (Cursor/Claude Code compat)hooks_auto_accept: false # See "Consent model" below```-Event names must be one of the [plugin hook events](#plugin-hooks); typos produce a "Did you mean X?" warning and are skipped. Unknown keys inside a single entry are ignored; missing `command` is a skip-with-warning. `timeout > 300` is clamped with a warning.+Event names must be one of the [plugin hook events](#plugin-hooks); typos produce a "Did you mean X?" warning and are skipped. Unknown keys inside a single entry are ignored; missing `command` is a skip-with-warning. `timeout > 300` is clamped with a warning. `fail_closed: true` on an event other than `pre_tool_call` warns and is ignored (only blocking-capable events can fail closed).### JSON wire protocol@@ -1378,6 +1380,50 @@ Each time the event fires, Hermes spawns a subprocess for every matching hook (mMalformed JSON, non-zero exit codes, and timeouts log a warning but never abort the agent loop.+### Exit code 2 = block (Claude Code / Cursor compatible)++A `pre_tool_call` hook that exits with code **2** blocks the tool call even when its stdout carries no block JSON. The block message is resolved in priority order:++1. stdout block JSON (`reason` / `message`), when present;+2. the first 400 characters of stderr;+3. a generic `"Blocked by shell hook."` default.++So the simplest possible blocking hook is:++```bash+#!/usr/bin/env bash+echo "policy violation: rm -rf is not permitted" >&2+exit 2+```++For events whose block directive is not honored (everything except `pre_tool_call`), exit 2 is treated like any other non-zero exit: a warning is logged and stdout is still parsed.++### Fail-open vs fail-closed++By default shell hooks **fail open**: a spawn error, timeout, or unparseable stdout logs a warning and the action proceeds. That is the right default for observability hooks — but wrong for security gates. A crashed secret-scanner must not silently allow the tool call it was supposed to vet.++Set `fail_closed: true` (or `failClosed: true`, the Cursor/Claude Code spelling) on a `pre_tool_call` entry to invert that:++```yaml+hooks:+ pre_tool_call:+ - matcher: "terminal|write_file|patch"+ command: "~/.hermes/agent-hooks/secret-scan.sh"+ timeout: 10+ fail_closed: true+```++With `fail_closed: true`, each of these now **blocks** the tool call with `hook <command> failed closed: <reason>`:++| Failure | Fail-open (default) | `fail_closed: true` |+|---------|--------------------|--------------------|+| Command not found / not executable | warn, proceed | **block** |+| Timeout | warn, proceed | **block** |+| Non-JSON stdout (e.g. a stack trace) | warn, proceed | **block** |+| Clean exit, valid no-op JSON (`{}`) | proceed | proceed |++`fail_closed` only applies to blocking-capable events (`pre_tool_call` today); setting it on any other event logs a warning at config-parse time and is ignored. `hermes hooks test` reflects these semantics — the `parsed` line shows exactly the block shape the dispatcher would receive.+### Worked examples#### 1. Auto-format Python files after every write