The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(approval): fire observer hooks for the two hookless classic-CLI prompts
liuhao10240df1837e819b
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 4fbf7394c85..253a5b8cfd1 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -143,8 +143,9 @@ VALID_HOOKS: Set[str] = {"agent_loop_stopped",# Approval observers (tools/approval.py); returns ignored — plugins cannot veto or pre-answer# (use pre_tool_call). Kwargs: command, description, pattern_key, pattern_keys, session_key,- # surface: "cli"|"gateway"|"smart"; post_approval_response adds choice ("once"|"session"|- # "always"|"deny"|"timeout"|"smart_approve"|"smart_deny") and decided_by.+ # surface: "cli"|"gateway"|"smart", or the caller's consent surface for MCP/vault prompts+ # ("mcp-elicitation/<server>", "mcp-trust/<server>", "vault-payment"); post_approval_response+ # adds choice ("once"|"session"|"always"|"deny"|"timeout"|"smart_approve"|"smart_deny") and decided_by."pre_approval_request", "post_approval_response",# on_room_member_activity: a hosted Group Chat member's live runtime events (tool.started/completed,# request.opened, message.delta, reasoning.delta, turn.error, ...) stamped with room_id, thread_id,diff --git a/tests/tools/test_approval_plugin_hooks.py b/tests/tools/test_approval_plugin_hooks.pyindex 86b17bcd769..23e9f4cb074 100644--- a/tests/tools/test_approval_plugin_hooks.py+++ b/tests/tools/test_approval_plugin_hooks.py@@ -15,6 +15,8 @@ from tools import approval_contextfrom tools import approval_smartfrom tools.approval import check_all_command_guards, check_execute_code_guard, clear_sessionfrom tools.approval_context import set_current_session_key+from tools.approval_prompt import request_elicitation_consent+from tools.file_tools_write_guards import _request_protected_instruction_approval@pytest.fixture@@ -335,3 +337,110 @@ class TestSmartModeFiresHooks:]+class TestProtectedWriteCliPathFiresHooks:+ """CLI protected agent-instruction write prompt: must fire the same observer+ hooks as its gateway twin so notifiers see the human wait (#131876)."""++ def test_pre_and_post_fire_with_expected_kwargs(self, monkeypatch):+ monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)+ token = set_current_session_key("test:session:protected_write")+ captured = []++ def cb(command, description, *, allow_permanent=True, allow_session=True,+ smart_denied=False):+ return "once"++ monkeypatch.setattr("tools.terminal_tool._get_approval_callback", lambda: cb)+ try:+ with patch("hermes_cli.plugins.invoke_hook",+ side_effect=lambda name, **kwargs: captured.append((name, kwargs)) or []):+ result = _request_protected_instruction_approval(["AGENTS.md"])+ finally:+ approval_context._approval_session_key.reset(token)++ assert result is None # one-operation grant+ assert [name for name, _ in captured] == ["pre_approval_request", "post_approval_response"]++ pre_kwargs = captured[0][1]+ assert pre_kwargs["command"] == "<write to AGENTS.md>"+ assert pre_kwargs["pattern_key"] == "protected_instruction_file"+ assert pre_kwargs["pattern_keys"] == ["protected_instruction_file"]+ assert pre_kwargs["surface"] == "cli"+ assert pre_kwargs["session_key"] == "test:session:protected_write"+ assert pre_kwargs["description"]++ post_kwargs = captured[1][1]+ assert post_kwargs["choice"] == "once"+ assert post_kwargs["surface"] == "cli"++ def test_no_human_channel_fails_closed_without_hooks(self, monkeypatch):+ """The no-callback branch never waits on a human, so observers must not+ be told a prompt is pending."""+ monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)+ token = set_current_session_key("test:session:protected_write")+ captured = []+ monkeypatch.setattr("tools.terminal_tool._get_approval_callback", lambda: None)+ try:+ with patch("hermes_cli.plugins.invoke_hook",+ side_effect=lambda name, **kwargs: captured.append((name, kwargs)) or []):+ result = _request_protected_instruction_approval(["AGENTS.md"])+ finally:+ approval_context._approval_session_key.reset(token)++ assert result is not None and "has NOT consented" in result+ assert captured == []+++class TestElicitationCliPathFiresHooks:+ """CLI MCP/vault consent prompt: must fire the same observer hooks as its+ gateway twin, carrying the caller's surface value (#131876)."""++ def test_pre_and_post_fire_with_caller_surface(self, monkeypatch):+ monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)+ monkeypatch.delenv("HERMES_EXEC_ASK", raising=False)+ token = set_current_session_key("test:session:elicitation")+ captured = []+ try:+ with patch("tools.approval_prompt.prompt_dangerous_approval", return_value="once"), \+ patch("hermes_cli.plugins.invoke_hook",+ side_effect=lambda name, **kwargs: captured.append((name, kwargs)) or []):+ verdict = request_elicitation_consent(+ "Allow server access?", "an MCP server asks",+ surface="mcp-elicitation/test-server")+ finally:+ approval_context._approval_session_key.reset(token)++ assert verdict == "accept"+ assert [name for name, _ in captured] == ["pre_approval_request", "post_approval_response"]++ pre_kwargs = captured[0][1]+ assert pre_kwargs["command"] == "Allow server access?"+ assert pre_kwargs["pattern_key"] == "mcp_elicitation"+ assert pre_kwargs["pattern_keys"] == ["mcp_elicitation"]+ assert pre_kwargs["surface"] == "mcp-elicitation/test-server"+ assert pre_kwargs["session_key"] == "test:session:elicitation"++ assert captured[1][1]["choice"] == "once"++ def test_prompt_failure_fails_closed_and_settles_observers(self, monkeypatch):+ """A raising panel still maps to "decline" AND settles the wait for+ observers (post hook with choice="cancelled")."""+ monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)+ token = set_current_session_key("test:session:elicitation")+ captured = []+ try:+ with patch("tools.approval_prompt.prompt_dangerous_approval",+ side_effect=RuntimeError("panel blew up")), \+ patch("hermes_cli.plugins.invoke_hook",+ side_effect=lambda name, **kwargs: captured.append((name, kwargs)) or []):+ verdict = request_elicitation_consent(+ "Confirm payment?", "the vault asks", surface="vault-payment")+ finally:+ approval_context._approval_session_key.reset(token)++ assert verdict == "decline"+ assert [name for name, _ in captured] == ["pre_approval_request", "post_approval_response"]+ assert captured[1][1]["choice"] == "cancelled"+ assert captured[1][1]["surface"] == "vault-payment"++diff --git a/tools/approval_prompt.py b/tools/approval_prompt.pyindex 85129a16a91..357a93e6b5e 100644--- a/tools/approval_prompt.py+++ b/tools/approval_prompt.py@@ -327,10 +327,20 @@ def request_elicitation_consent(message: str, description: str, *,return _consent(decision.get("choice"), "decline")# allow_permanent=False: elicitation is a per-call confirmation — no pattern to remember.+ # Same observer hooks as the gateway branch, carrying the caller's surface value, so+ # notifiers see this human wait in the classic CLI too; post fires in a finally so the+ # wait always settles for observers even when the prompt raises (#131876).+ hook_kwargs = dict(command=message, description=description, pattern_key="mcp_elicitation",+ pattern_keys=["mcp_elicitation"], session_key=session_key, surface=surface)+ _ctx._fire_approval_hook("pre_approval_request", **hook_kwargs)+ hook_choice = "cancelled"try:choice = prompt_dangerous_approval(message, description, timeout_seconds=timeout_seconds,allow_permanent=False, title=title)+ hook_choice = choiceexcept Exception as exc:logger.error("Elicitation CLI prompt failed: %s", exc, exc_info=True)return "decline"+ finally:+ _ctx._fire_approval_hook("post_approval_response", **hook_kwargs, choice=hook_choice)return _consent(choice, "cancel") # timeout mirrors the gateway's unresolved outcomediff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.pyindex 59f8e1c4677..7666cdcef36 100644--- a/tools/file_tools_write_guards.py+++ b/tools/file_tools_write_guards.py@@ -279,7 +279,7 @@ def _request_protected_instruction_approval(reasons: list[str], task_id: str = "try:import tools.approval as _approval- from tools.approval_context import get_current_session_key+ from tools.approval_context import _fire_approval_hook, get_current_session_keyfrom tools.approval_gateway_wait import _await_gateway_decisionfrom tools.approval_prompt import prompt_dangerous_approvalexcept Exception:@@ -319,8 +319,21 @@ def _request_protected_instruction_approval(reasons: list[str], task_id: str = "# No human channel (script, cron, background thread): fail closed —# auto-approving here would recreate the persistence vector.return blocked.format(why=_NO_HUMAN)- choice = prompt_dangerous_approval(- display, description, allow_permanent=False, allow_session=False, approval_callback=callback)+ # Observer hooks like the gateway branch above, with the classic-CLI surface+ # every other CLI prompt reports; the post hook fires in a finally so notifiers+ # see the wait settle even when the panel itself raises (#131876).+ hook_kwargs = dict(command=display, description=description,+ pattern_key="protected_instruction_file",+ pattern_keys=["protected_instruction_file"],+ session_key=session_key, surface="cli")+ _fire_approval_hook("pre_approval_request", **hook_kwargs)+ hook_choice = "cancelled"+ try:+ choice = prompt_dangerous_approval(+ display, description, allow_permanent=False, allow_session=False, approval_callback=callback)+ hook_choice = choice+ finally:+ _fire_approval_hook("post_approval_response", **hook_kwargs, choice=hook_choice)if choice == "cancelled":return blocked.format(why="approval prompt could not be delivered or was not answered "f"({getattr(choice, 'cause', 'no answer')}).")diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex d4ea6fd0d87..7e0e4d45b13 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -1315,7 +1315,7 @@ This hook is observer-only: it does **not** add raw-event access or adapter acce### `pre_approval_request`-Fires before an approval decision is requested. It covers prompted surfaces—interactive CLI, Ink TUI, gateway platforms, and ACP clients—and `approvals.mode=smart` decisions made without a human prompt (`surface="smart"`). In smart mode, the hook runs before the auxiliary LLM is called.+Fires before an approval decision is requested. It covers prompted surfaces—interactive CLI, Ink TUI, gateway platforms, and ACP clients—including protected agent-instruction write prompts and MCP/vault consent prompts, plus `approvals.mode=smart` decisions made without a human prompt (`surface="smart"`). In smart mode, the hook runs before the auxiliary LLM is called.This is the right place to wire a custom notifier — for example, a macOS menu-bar app that pops an allow/deny notification, or an audit log that records every approval request with context.@@ -1340,7 +1340,7 @@ def my_callback(| `pattern_key` | `str` | Primary pattern key that triggered the approval (e.g. `"rm_rf"`, `"sudo"`) || `pattern_keys` | `list[str]` | All pattern keys that matched || `session_key` | `str` | Session identifier, useful for scoping notifications per-chat |-| `surface` | `str` | `"cli"` for interactive CLI/TUI prompts, `"gateway"` for async platform approvals, or `"smart"` for auxiliary-LLM auto approve/deny decisions |+| `surface` | `str` | `"cli"` for classic interactive-CLI prompts (dangerous commands, protected agent-instruction writes, consent prompts), `"gateway"` for async platform approvals (the Ink TUI and Desktop app also report `"gateway"` today), `"smart"` for auxiliary-LLM auto approve/deny decisions, or the caller's consent surface for MCP/vault prompts (`"mcp-elicitation/<server>"`, `"mcp-trust/<server>"`, `"vault-payment"`) |**Return value:** ignored. Hooks here are observer-only; they cannot veto or pre-answer the approval. Use [`pre_tool_call`](#pre_tool_call) to block a tool before it reaches the approval system.