Skip to content

The agent that grows with you

feat(plugins): on_human_input_request / on_human_input_resolved hooks

Tekniumc958e1a7b97c
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 892a55fff20..f28cf6c4658 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -143,8 +143,8 @@ VALID_HOOKS: Set[str] = {
"agent_loop_stopped",
# Approval observers (returns ignored; veto via pre_tool_call). Kwargs: command, description, pattern_key,
# pattern_keys, session_key, surface ("cli"|"gateway"|"smart"|"mcp-elicitation/<server>"|"mcp-trust/<server>"|
- # "vault-payment"); post_approval_response adds choice ("once"|"session"|"deny"|"timeout"|...) and decided_by.
- "pre_approval_request", "post_approval_response",
+ # "vault-payment"); post_approval_response adds choice/decided_by. on_human_input_*: tools/human_input_hooks.py.
+ "pre_approval_request", "post_approval_response", "on_human_input_request", "on_human_input_resolved",
# 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,
# member_id, turn_id, task_id, execution_generation. Observer, queued per consumer off the token
diff --git a/tests/tools/test_human_input_hooks.py b/tests/tools/test_human_input_hooks.py
new file mode 100644
index 00000000000..151379f7755
--- /dev/null
+++ b/tests/tools/test_human_input_hooks.py
@@ -0,0 +1,170 @@
+"""on_human_input_request / on_human_input_resolved fire wherever the agent blocks for a human (#132333).
+
+Each surface's real choke point is driven end to end — sudo password prompt, clarify, dangerous-command
+approval on the CLI callback path and the gateway poll path — with only the plugin hook delivery captured.
+Every request pairs with exactly one resolution carrying the same ``request_id``, and no typed secret (the
+sudo password, a clarify answer) or unredacted credential ever appears in any payload.
+"""
+
+import threading
+from unittest.mock import patch
+
+import pytest
+
+from tools import approval as approval_module
+from tools import approval_context, approval_gateway_wait, terminal_tool, terminal_tool_sudo
+from tools.approval_prompt import prompt_dangerous_approval
+from tools.clarify_tool import clarify_tool
+
+PASSWORD = "hunter2-do-not-leak"
+TOKEN = "ghp_" + "Z" * 36
+SECRET_COMMAND = f"sudo env GITHUB_TOKEN={TOKEN} apt-get install -y jq"
+HOOKS = ("on_human_input_request", "on_human_input_resolved")
+
+
+def captured(monkeypatch):
+ calls: list[tuple[str, dict]] = []
+
+ def fake_invoke_hook(name, **kwargs):
+ if name in HOOKS:
+ calls.append((name, kwargs))
+ return []
+
+ monkeypatch.setattr(terminal_tool, "_callback_tls", threading.local())
+ monkeypatch.setattr(terminal_tool_sudo, "_sudo_password_cache", {})
+ with patch("hermes_cli.plugins.invoke_hook", side_effect=fake_invoke_hook):
+ yield calls
+
+
+def _single_pair(calls, kind):
+ assert [name for name, _ in calls] == list(HOOKS), calls
+ request, resolved = calls[0][1], calls[1][1]
+ assert request["kind"] == resolved["kind"] == kind
+ assert request["request_id"] and request["request_id"] == resolved["request_id"]
+ assert "outcome" not in request
+ for key in ("session_id", "session_key", "platform", "prompt"):
+ assert key in request and request[key] == resolved[key]
+ return request, resolved
+
+
+def _assert_no_secret(calls, *secrets):
+ blob = repr(calls)
+ for secret in secrets:
+ assert secret not in blob
+
+
+def test_hooks_are_registered():
+ from hermes_cli.plugins import VALID_HOOKS
+
+ assert set(HOOKS) <= VALID_HOOKS
+
+
+class TestSudo:
+ def test_callback_prompt_fires_pair_without_password(self, captured):
+ terminal_tool.set_sudo_password_callback(lambda: PASSWORD)
+
+ assert terminal_tool_sudo._prompt_for_sudo_password(command=SECRET_COMMAND) == PASSWORD
+
+ request, resolved = _single_pair(captured, "sudo")
+ assert resolved["outcome"] == "provided"
+ assert "apt-get install" in request["prompt"]
+ _assert_no_secret(captured, PASSWORD, TOKEN)
+
+ def test_empty_answer_is_skipped(self, captured):
+ terminal_tool.set_sudo_password_callback(lambda: "")
+
+ assert terminal_tool_sudo._prompt_for_sudo_password(command="sudo true") == ""
+
+ assert _single_pair(captured, "sudo")[1]["outcome"] == "skipped"
+
+ def test_tty_fallback_timeout_resolves_as_timeout(self, captured, monkeypatch):
+ monkeypatch.setattr(terminal_tool_sudo, "_read_hidden_password", lambda result: None)
+
+ assert terminal_tool_sudo._prompt_for_sudo_password(timeout_seconds=0, command="sudo true") == ""
+
+ assert _single_pair(captured, "sudo")[1]["outcome"] == "timeout"
+
+
+class TestClarify:
+ QUESTIONS = [{"question": "Which database?", "choices": ["postgres", "sqlite"]}]
+
+ @pytest.mark.parametrize("outcome", ["submitted", "timed_out", "cancelled"])
+ def test_callback_outcome_is_reported_without_answers(self, captured, outcome):
+ def callback(normalized):
+ return {"answers": {normalized[0]["qid"]: PASSWORD}, "outcome": outcome}
+
+ clarify_tool(self.QUESTIONS, callback=callback)
+
+ request, resolved = _single_pair(captured, "clarify")
+ assert resolved["outcome"] == outcome
+ assert "Which database?" in request["prompt"]
+ _assert_no_secret(captured, PASSWORD)
+
+ def test_callback_failure_resolves_as_error(self, captured):
+ def callback(normalized):
+ raise RuntimeError("ui gone")
+
+ clarify_tool(self.QUESTIONS, callback=callback)
+
+ assert _single_pair(captured, "clarify")[1]["outcome"] == "error"
+
+
+class TestApproval:
+ def test_cli_callback_prompt_redacts_command(self, captured):
+ choice = prompt_dangerous_approval(SECRET_COMMAND, "privileged install",
+ approval_callback=lambda *a, **k: "once")
+
+ assert choice == "once"
+ request, resolved = _single_pair(captured, "approval")
+ assert resolved["outcome"] == "once"
+ assert "apt-get install" in request["prompt"]
+ _assert_no_secret(captured, TOKEN)
+
+ def test_gateway_decision_fires_pair(self, captured, monkeypatch):
+ session_key = "human-input-gateway"
+ monkeypatch.setattr(approval_context, "_get_approval_timeout", lambda: 5)
+ approval_module._gateway_queues.pop(session_key, None)
+
+ def notify(data):
+ threading.Timer(0.05, approval_module.resolve_gateway_approval, (session_key, "session")).start()
+
+ approval_data = {"command": SECRET_COMMAND, "description": "privileged install",
+ "pattern_key": "sudo", "pattern_keys": ["sudo"]}
+ decision = approval_gateway_wait._await_gateway_decision(session_key, notify, approval_data)
+
+ assert decision["choice"] == "session"
+ request, resolved = _single_pair(captured, "approval")
+ assert request["session_key"] == session_key
+ assert resolved["outcome"] == "session"
+ _assert_no_secret(captured, TOKEN)
+
+ def test_gateway_notify_failure_still_resolves(self, captured):
+ def notify(data):
+ raise ConnectionError("adapter offline")
+
+ approval_data = {"command": "rm -rf build", "description": "d", "pattern_key": "rm", "pattern_keys": ["rm"]}
+ decision = approval_gateway_wait._await_gateway_decision("human-input-notify-fail", notify, approval_data)
+
+ assert decision.get("notify_failed") is True
+ assert _single_pair(captured, "approval")[1]["outcome"] == "notify_failed"
+
+ def test_plugin_transport_fires_pair(self, captured, monkeypatch):
+ from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest
+ from tools import approval_prompt
+
+ manager = PluginManager()
+ manifest = PluginManifest(name="phone-fixture", version="1.0.0", description="", source="user", key="phone")
+ PluginContext(manifest, manager).register_approval_transport("phone", lambda req: req.respond("deny"))
+ monkeypatch.setattr(approval_prompt, "get_plugin_manager", lambda: manager)
+ monkeypatch.setattr(approval_context, "_get_approval_transport_config", lambda: ("phone", None))
+
+ attempt = approval_prompt._present_with_selected_transport(
+ command=SECRET_COMMAND, description="d", pattern_key="sudo", pattern_keys=["sudo"],
+ session_key="human-input-transport", surface="cli", allow_session=True, allow_permanent=True)
+
+ assert attempt["choice"] == "deny"
+ request, resolved = _single_pair(captured, "approval")
+ assert request["session_key"] == "human-input-transport"
+ assert resolved["outcome"] == "deny"
+ _assert_no_secret(captured, TOKEN)
diff --git a/tests/tui_gateway/test_human_input_hooks_tui.py b/tests/tui_gateway/test_human_input_hooks_tui.py
new file mode 100644
index 00000000000..cb7c0d1041e
--- /dev/null
+++ b/tests/tui_gateway/test_human_input_hooks_tui.py
@@ -0,0 +1,61 @@
+"""The Ink TUI / Desktop sudo card fires the human-input hook pair without the typed password (#132333)."""
+
+import sys
+import threading
+from unittest.mock import patch
+
+PASSWORD = "hunter2-tui-do-not-leak"
+
+
+def test_tui_sudo_request_fires_human_input_hooks(monkeypatch):
+ from hermes_cli import banner
+
+ # The real server binds callbacks on import; isolate only its process-wide side effects.
+ monkeypatch.setattr(banner, "prefetch_update_check", lambda: None)
+ monkeypatch.setattr(sys, "stdout", sys.stdout)
+ monkeypatch.setattr(sys, "excepthook", sys.excepthook)
+ monkeypatch.setattr(threading, "excepthook", threading.excepthook)
+ from tui_gateway import server, server_requests
+ from agent.vault_backends import unlock
+ from tools import project_tools, skills_tool, terminal_tool, terminal_tool_sudo
+
+ monkeypatch.setattr(terminal_tool, "_callback_tls", threading.local())
+ monkeypatch.setattr(unlock, "_callback_tls", threading.local())
+ monkeypatch.setattr(unlock, "_current_session_tls", threading.local())
+ monkeypatch.setattr(project_tools, "_workspace_callback", None)
+ monkeypatch.setattr(skills_tool, "_secret_capture_callback", None)
+ monkeypatch.setattr(terminal_tool_sudo, "_sudo_password_cache", {})
+
+ sid, session_key = "human-input-tui", "human-input-conversation"
+ monkeypatch.setitem(server._sessions, sid, {"session_key": session_key, "source": "desktop"})
+
+ def answer(frame):
+ assert server_requests.resolve_response(
+ {"jsonrpc": "2.0", "id": frame["id"], "result": {"value": PASSWORD}}
+ )
+ return True
+
+ monkeypatch.setattr(server, "write_json", answer)
+ calls = []
+
+ def capture(name, **kwargs):
+ if name.startswith("on_human_input_"):
+ calls.append((name, kwargs))
+ return []
+
+ tokens = server._set_session_context(session_key, ui_session_id=sid)
+ try:
+ server._wire_callbacks(sid)
+ with patch("hermes_cli.plugins.invoke_hook", side_effect=capture):
+ assert terminal_tool_sudo._prompt_for_sudo_password(command="sudo systemctl restart nginx") == PASSWORD
+ finally:
+ server._clear_session_context(tokens)
+ server_requests.reset_for_tests()
+
+ assert [name for name, _ in calls] == ["on_human_input_request", "on_human_input_resolved"]
+ request, resolved = calls[0][1], calls[1][1]
+ assert request["kind"] == "sudo" and request["request_id"] == resolved["request_id"]
+ assert request["platform"] == "desktop" and request["session_key"] == session_key
+ assert "systemctl restart nginx" in request["prompt"]
+ assert resolved["outcome"] == "provided"
+ assert PASSWORD not in repr(calls)
diff --git a/tools/approval_gateway_wait.py b/tools/approval_gateway_wait.py
index c564997e815..f11e221e60d 100644
--- a/tools/approval_gateway_wait.py
+++ b/tools/approval_gateway_wait.py
@@ -90,14 +90,17 @@ def _finish(payload: dict, resolved: bool, choice: str | None, reason, **extra)
"""Fire the post hook and build the decision dict. Unresolved (timeout) and
a None choice both mean the user never answered; ``cancelled`` carries the
cause when the prompt was withdrawn rather than answered."""
- if extra.get("cancelled"):
- hook_choice = "cancelled"
- else:
- hook_choice = "timeout" if not resolved else (choice or "timeout")
- _ctx._fire_approval_hook("post_approval_response", **payload, choice=hook_choice, **extra)
+ _ctx._fire_approval_hook("post_approval_response", **payload, choice=_hook_choice(resolved, choice, extra), **extra)
return {"resolved": resolved, "choice": choice, "reason": reason, **extra}
+def _hook_choice(resolved: bool, choice: str | None, extra: dict) -> str:
+ """Observer-facing outcome of a wait: the choice, else ``cancelled`` / ``timeout``."""
+ if extra.get("cancelled"):
+ return "cancelled"
+ return (choice or "timeout") if resolved else "timeout"
+
+
def _await_coalesced_leader(session_key: str, leader, payload: dict):
"""Wait on an already-pending identical approval instead of re-prompting.
Adopts the leader's decision: ``session``/``always`` → approval (same dict
@@ -194,31 +197,35 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
logger.debug("approval settle hook failed", exc_info=True)
return choice
- # Plugins hear about the request before the gateway does (real-time observers).
- _ctx._fire_approval_hook("pre_approval_request", **payload)
- # Bridges sync agent thread → async gateway.
- try:
- notify_cb(dict(entry.data))
- approval_published()
- except Exception as exc:
- logger.warning("Gateway approval notify failed: %s", exc)
- _drop_entry("notify_failed")
- _ctx._fire_approval_hook("post_approval_response", **payload, choice="notify_failed")
- return {"resolved": False, "choice": None, "notify_failed": True}
-
- state = _poll_event(entry.event, session_key,
- interrupt_log="Approval wait interrupted — returning deny for session %s")
- cancelled = _cancel_cause(state, entry)
- if state == "interrupted":
- # Coalesced followers wake with the cause instead of a deny nobody issued.
- entry.cancelled = cancelled
- entry.event.set()
- choice = _drop_entry(state)
- if state == "interrupted":
- # Our own decision stays a fail-closed deny.
- choice = "deny"
- # A choice that landed in the gap between the deadline check and leaving the queue is an answer,
- # not a timeout (#112548) — the same first-settlement rule as server_requests.send().
- resolved = state != "timeout" or choice is not None
- extra = {"cancelled": cancelled} if cancelled else {}
- return _finish(payload, resolved, choice, entry.reason, **extra)
+ from tools.human_input_hooks import human_input_request
+ with human_input_request("approval", prompt=payload["command"], session_key=session_key) as human:
+ # Plugins hear about the request before the gateway does (real-time observers).
+ _ctx._fire_approval_hook("pre_approval_request", **payload)
+ # Bridges sync agent thread → async gateway.
+ try:
+ notify_cb(dict(entry.data))
+ approval_published()
+ except Exception as exc:
+ logger.warning("Gateway approval notify failed: %s", exc)
+ _drop_entry("notify_failed")
+ _ctx._fire_approval_hook("post_approval_response", **payload, choice="notify_failed")
+ human.outcome = "notify_failed"
+ return {"resolved": False, "choice": None, "notify_failed": True}
+
+ state = _poll_event(entry.event, session_key,
+ interrupt_log="Approval wait interrupted — returning deny for session %s")
+ cancelled = _cancel_cause(state, entry)
+ if state == "interrupted":
+ # Coalesced followers wake with the cause instead of a deny nobody issued.
+ entry.cancelled = cancelled
+ entry.event.set()
+ choice = _drop_entry(state)
+ if state == "interrupted":
+ # Our own decision stays a fail-closed deny.
+ choice = "deny"
+ # A choice that landed in the gap between the deadline check and leaving the queue is an answer,
+ # not a timeout (#112548) — the same first-settlement rule as server_requests.send().
+ resolved = state != "timeout" or choice is not None
+ extra = {"cancelled": cancelled} if cancelled else {}
+ human.outcome = _hook_choice(resolved, choice, extra)
+ return _finish(payload, resolved, choice, entry.reason, **extra)
diff --git a/tools/approval_prompt.py b/tools/approval_prompt.py
index decd2b18f29..b10812dcb1e 100644
--- a/tools/approval_prompt.py
+++ b/tools/approval_prompt.py
@@ -45,12 +45,14 @@ def prompt_dangerous_approval(command: str, description: str, timeout_seconds: i
"""
if timeout_seconds is None:
timeout_seconds = _ctx._get_approval_timeout()
+ from tools.human_input_hooks import human_input_request
# Everything below is a human prompt (callback panel or input() fallback, both bounded by the approval deadline):
# record it as human-wait time so the concurrent batch deadline excludes it.
# See #79719.
- with human_wait_window():
- return _ask_human(command, description, timeout_seconds, allow_permanent,
- approval_callback, allow_session, smart_denied, title=title)
+ with human_input_request("approval", prompt=command) as human, human_wait_window():
+ human.outcome = choice = _ask_human(command, description, timeout_seconds, allow_permanent,
+ approval_callback, allow_session, smart_denied, title=title)
+ return choice
class Unanswered(str):
@@ -239,14 +241,16 @@ def _present_with_selected_transport(*, command: str, description: str, pattern_
request_id=request.request_id, request_digest=request.digest,
)
_ctx._fire_approval_hook("pre_approval_request", **hook_kwargs)
- with human_wait_window(session_key):
+ from tools.human_input_hooks import human_input_request
+ with human_input_request("approval", prompt=request.command, session_key=session_key) as human, \
+ human_wait_window(session_key):
result = invoke_approval_transport(
registered.present, request, timeout_seconds=timeout_seconds,
on_poll=activity_heartbeat("waiting for plugin approval transport"),
is_interrupted=is_interrupted,
)
- hook_choice = result.choice if result.failure is None else f"transport_{result.failure}"
- _ctx._fire_approval_hook("post_approval_response", **hook_kwargs, choice=hook_choice)
+ human.outcome = result.choice if result.failure is None else f"transport_{result.failure}"
+ _ctx._fire_approval_hook("post_approval_response", **hook_kwargs, choice=human.outcome)
return _attempt(name, result.choice, result.failure, fallback)
diff --git a/tools/clarify_tool.py b/tools/clarify_tool.py
index b2c0f6f766f..7d0b98feab2 100644
--- a/tools/clarify_tool.py
+++ b/tools/clarify_tool.py
@@ -116,10 +116,16 @@ def clarify_tool(questions, callback: Optional[Callable] = None) -> str:
return tool_error(error)
if callback is None:
return tool_error(_UNAVAILABLE)
- try:
- return _result(normalized, callback(normalized))
- except Exception as exc:
- return tool_error(f"Failed to get user input: {exc}")
+ from tools.human_input_hooks import human_input_request
+ # Observers see the questions only; the answers stay in the tool result.
+ with human_input_request("clarify", prompt="\n".join(q["question"] for q in normalized)) as human:
+ try:
+ reply = callback(normalized)
+ human.outcome = str(reply.get("outcome") or "")
+ return _result(normalized, reply)
+ except Exception as exc:
+ human.outcome = "error"
+ return tool_error(f"Failed to get user input: {exc}")
def check_clarify_requirements() -> bool:
diff --git a/tools/human_input_hooks.py b/tools/human_input_hooks.py
new file mode 100644
index 00000000000..99c32e4d0fb
--- /dev/null
+++ b/tools/human_input_hooks.py
@@ -0,0 +1,72 @@
+"""Plugin observers for every point where the agent blocks waiting on a human (#132333).
+
+``on_human_input_request`` fires right before a prompt is shown (sudo password, clarify question,
+dangerous-command approval) and ``on_human_input_resolved`` fires exactly once when the wait ends,
+with the same ``request_id`` and an ``outcome``. Observers only: return values are ignored and a
+failing plugin never affects the prompt. Payloads never carry what the human typed (password,
+answers), and ``prompt`` is force-redacted so credentials in a command never reach a plugin.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import os
+import uuid
+from dataclasses import dataclass
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class HumanInputRequest:
+ """Handle yielded by :func:`human_input_request`; set ``outcome`` before the block exits."""
+
+ request_id: str
+ outcome: str = ""
+
+
+def _redacted(text: str) -> str:
+ try:
+ from agent.redact import redact_sensitive_text
+ return redact_sensitive_text(str(text or ""), force=True)
+ except Exception:
+ logger.debug("human-input hook prompt redaction failed", exc_info=True)
+ return "" # never fall back to the raw text
+
+
+def _identity() -> dict:
+ try:
+ from gateway.session_context import get_session_env
+ from tools import approval_context
+ session_id = approval_context._approval_session_id.get() or get_session_env("HERMES_SESSION_ID")
+ platform = (os.getenv("HERMES_PLATFORM") or get_session_env("HERMES_SESSION_PLATFORM")
+ or get_session_env("HERMES_SESSION_SOURCE") or "cli")
+ return {"session_id": session_id, "session_key": approval_context.get_current_session_key(default=""),
+ "platform": platform}
+ except Exception: # a broken lookup must not take the human prompt down with it
+ logger.debug("human-input hook identity lookup failed", exc_info=True)
+ return {"session_id": "", "session_key": "", "platform": ""}
+
+
+def _fire(hook_name: str, payload: dict) -> None:
+ try:
+ from hermes_cli.lifecycle import invoke_hook
+ invoke_hook(hook_name, **payload)
+ except Exception: # observability must never break a human prompt
+ logger.debug("%s dispatch failed", hook_name, exc_info=True)
+
+
+def human_input_request(kind: str, *, prompt: str = "", session_key: str | None = None, **extra):
+ """Fire the request hook, run the block (the human wait), then fire the resolved hook.
+ An exception escaping the block, or a block that never sets ``outcome``, resolves as ``error``."""
+ payload = {"kind": kind, "request_id": uuid.uuid4().hex, **_identity(), "prompt": _redacted(prompt), **extra}
+ if session_key is not None:
+ payload["session_key"] = session_key
+ request = HumanInputRequest(payload["request_id"])
+ _fire("on_human_input_request", payload)
+ try:
+ yield request
+ finally:
+ _fire("on_human_input_resolved", {**payload, "outcome": str(request.outcome or "error")})
diff --git a/tools/terminal_tool_sudo.py b/tools/terminal_tool_sudo.py
index f3499a4c182..c0da6f916e8 100644
--- a/tools/terminal_tool_sudo.py
+++ b/tools/terminal_tool_sudo.py
@@ -186,62 +186,72 @@ def _prompt_for_sudo_password(timeout_seconds: int = 45, *, command: str = "") -
"""Prompt for a sudo password; "" on skip (empty Enter), timeout, or error. Prefers the
CLI-registered callback (prompt_toolkit-integrated); otherwise reads /dev/tty (msvcrt on
Windows) with echo disabled. Human wait time is excluded from tool deadlines (``human_wait_window``)."""
- from tools.terminal_tool import _get_sudo_password_callback
- _sudo_cb = _get_sudo_password_callback()
- if _sudo_cb is not None:
- token = _sudo_prompt_command.set(command)
+ from tools.human_input_hooks import human_input_request
+ # The password never reaches the hook; only how the prompt ended.
+ with human_input_request("sudo", prompt=command) as human:
+ from tools.terminal_tool import _get_sudo_password_callback
+ _sudo_cb = _get_sudo_password_callback()
+ if _sudo_cb is not None:
+ token = _sudo_prompt_command.set(command)
+ try:
+ from tools.approval_human_wait import human_wait_window
+ with human_wait_window():
+ password = _sudo_cb() or ""
+ human.outcome = "provided" if password else "skipped"
+ return password
+ except Exception:
+ human.outcome = "error"
+ return ""
+ finally:
+ _sudo_prompt_command.reset(token)
+
+ result = {"password": None, "done": False}
try:
+ os.environ["HERMES_SPINNER_PAUSE"] = "1"
+ time.sleep(0.2)
+ print("\n".join((
+ "",
+ "┌" + "─" * 58 + "┐",
+ "│ 🔐 SUDO PASSWORD REQUIRED" + " " * 30 + "│",
+ "├" + "─" * 58 + "┤",
+ "│ Enter password below (input is hidden), or: │",
+ "│ • Press Enter to skip (command fails gracefully) │",
+ f"│ • Wait {timeout_seconds}s to auto-skip" + " " * 27 + "│",
+ "└" + "─" * 58 + "┘",
+ "",
+ )))
+ print(" Password (hidden): ", end="", flush=True)
+ password_thread = threading.Thread(target=_read_hidden_password, args=(result,), daemon=True)
+ password_thread.start()
from tools.approval_human_wait import human_wait_window
with human_wait_window():
- return _sudo_cb() or ""
- except Exception:
+ password_thread.join(timeout=timeout_seconds)
+ if not result["done"]:
+ print("\n ⏱ Timeout - continuing without sudo\n (Press Enter to dismiss)\n")
+ sys.stdout.flush()
+ human.outcome = "timeout"
+ return ""
+ password = result["password"] or ""
+ human.outcome = "provided" if password else "skipped"
+ # Newline after the hidden input, then the outcome line.
+ if password:
+ print("\n ✓ Password received (cached for this session)\n")
+ else:
+ print("\n ⏭ Skipped - continuing without sudo\n")
+ sys.stdout.flush()
+ return password
+ except (EOFError, KeyboardInterrupt):
+ print("\n ⏭ Cancelled - continuing without sudo\n")
+ sys.stdout.flush()
+ human.outcome = "cancelled"
return ""
- finally:
- _sudo_prompt_command.reset(token)
-
- result = {"password": None, "done": False}
- try:
- os.environ["HERMES_SPINNER_PAUSE"] = "1"
- time.sleep(0.2)
- print("\n".join((
- "",
- "┌" + "─" * 58 + "┐",
- "│ 🔐 SUDO PASSWORD REQUIRED" + " " * 30 + "│",
- "├" + "─" * 58 + "┤",
- "│ Enter password below (input is hidden), or: │",
- "│ • Press Enter to skip (command fails gracefully) │",
- f"│ • Wait {timeout_seconds}s to auto-skip" + " " * 27 + "│",
- "└" + "─" * 58 + "┘",
- "",
- )))
- print(" Password (hidden): ", end="", flush=True)
- password_thread = threading.Thread(target=_read_hidden_password, args=(result,), daemon=True)
- password_thread.start()
- from tools.approval_human_wait import human_wait_window
- with human_wait_window():
- password_thread.join(timeout=timeout_seconds)
- if not result["done"]:
- print("\n ⏱ Timeout - continuing without sudo\n (Press Enter to dismiss)\n")
+ except Exception as e:
+ print(f"\n [sudo prompt error: {e}] - continuing without sudo\n")
sys.stdout.flush()
+ human.outcome = "error"
return ""
- password = result["password"] or ""
- # Newline after the hidden input, then the outcome line.
- if password:
- print("\n ✓ Password received (cached for this session)\n")
- else:
- print("\n ⏭ Skipped - continuing without sudo\n")
- sys.stdout.flush()
- return password
- except (EOFError, KeyboardInterrupt):
- print("\n ⏭ Cancelled - continuing without sudo\n")
- sys.stdout.flush()
- return ""
- except Exception as e:
- print(f"\n [sudo prompt error: {e}] - continuing without sudo\n")
- sys.stdout.flush()
- return ""
- finally:
- os.environ.pop("HERMES_SPINNER_PAUSE", None)
+ finally:
+ os.environ.pop("HERMES_SPINNER_PAUSE", None)
def _looks_like_env_assignment(token: str) -> bool:
diff --git a/website/docs/developer-guide/observer-hooks.md b/website/docs/developer-guide/observer-hooks.md
index 3d9c636706f..5c7e95c6ae8 100644
--- a/website/docs/developer-guide/observer-hooks.md
+++ b/website/docs/developer-guide/observer-hooks.md
@@ -195,6 +195,17 @@ Tool hooks describe individual tool calls:
`post_tool_call` is emitted for blocked and cancelled paths so telemetry
plugins can close spans cleanly.
+### Human Input Lifecycle
+
+`on_human_input_request` / `on_human_input_resolved` fire around every point
+where the agent blocks for a person: sudo password prompts (`kind="sudo"`),
+`clarify` questions (`kind="clarify"`) and approval prompts
+(`kind="approval"`) on CLI, TUI/Desktop, ACP and gateway platforms. Fields:
+`kind`, `request_id` (shared by the pair), `session_id`, `session_key`,
+`platform`, and a force-redacted `prompt`; the resolved hook adds `outcome`.
+The typed password or answer is never included. Smart (aux-LLM) approvals do
+not fire it. Source: `tools/human_input_hooks.py`.
+
### Approval Lifecycle
Approval hooks describe dangerous-command approval prompts:
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index 7e0e4d45b13..b52eb982b19 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -480,6 +480,8 @@ Payload fields below are the exact event-specific fields supplied by each call s
| `pre_command` | Observer | Recognized slash command about to be dispatched, before the handler runs, on CLI and gateway cold-path dispatch; return ignored in v1 (directive-shaped dicts are logged at debug). Gateway running-agent intercept commands (`/stop`, `/approve` during an active run) are deliberately excluded — control-plane escape hatches must stay outside plugin reach. | `surface` (`"cli"` \| `"gateway"`), `command` (canonical name), `alias_used`, `args_raw`, `session_key`, `platform` | `args_raw` may contain user content or secrets typed after the command. |
| `pre_approval_request` | Observer | Before prompted or smart approval; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id` | Command may contain secrets; smart observer preparation force-redacts, but surfaces do not all have identical redaction. |
| `post_approval_response` | Observer | After a decision, timeout, or gateway notification failure; return ignored. | `command`, `description`, `pattern_key`, `pattern_keys`, `session_key`, `surface`, `turn_id`, `tool_call_id`, `choice`; smart path may add `decided_by` | Same command sensitivity plus decision metadata. |
+| `on_human_input_request` | Observer | The agent is about to block on a person — sudo password prompt, `clarify` question, or dangerous-command approval — on CLI, Ink TUI/Desktop, ACP and gateway platforms; return ignored. | `kind` (`"sudo"` \| `"clarify"` \| `"approval"`), `request_id`, `session_id`, `session_key`, `platform`, `prompt` | `prompt` is always force-redacted; the typed password or answer is never passed. |
+| `on_human_input_resolved` | Observer | Exactly once per `on_human_input_request`, when the wait ends (answered, skipped, timed out, withdrawn, or failed); return ignored. | Same as the request plus `outcome` | Outcome only — never the answer itself. |
| `on_room_member_activity` | Observer | While a hosted Group Chat member turn runs on the Bot Mode gateway, once per runtime event the member session emits (tool start/complete, approval request, message/reasoning deltas, errors); queued per consumer off the token path; return ignored. | `room_id`, `thread_id`, `member_id`, `turn_id`, `task_id`, `execution_generation`, `kind`, `seq`, `payload` | `payload` is the client-safe session event body: tool args and results, redacted approval commands, streamed member text. |
| `kanban_task_claimed` | Observer | After claim commit, in dispatcher process before worker spawn; return ignored. | `task_id`, `profile_name`, `board`, `assignee`, `run_id` | Board/task/profile/assignee identifiers. |
| `kanban_task_completed` | Observer | After completion and cleanup, usually in worker process; return ignored. | `task_id`, `profile_name`, `board`, `assignee`, `run_id`, `summary` | Summary may contain project/user content. |
@@ -1405,6 +1407,70 @@ def register(ctx):
---
+### `on_human_input_request`
+
+Fires right before Hermes blocks waiting for a person to type or click something, whatever the prompt is and wherever it shows up. One hook pair covers every blocking prompt, so a notifier ("Hermes is waiting on you") does not have to subscribe to a separate hook per prompt type or pattern-match tool arguments:
+
+| `kind` | Prompt | Surfaces |
+|--------|--------|----------|
+| `"sudo"` | Masked sudo password prompt before a `sudo` command runs | Interactive CLI, Ink TUI / Desktop (`sudo.request` card), `/dev/tty` fallback |
+| `"clarify"` | A `clarify` tool question | CLI, Ink TUI / Desktop, gateway platforms |
+| `"approval"` | Dangerous-command / write approval, MCP elicitation consent, plugin approval transports | CLI, Ink TUI / Desktop, ACP, gateway platforms, `ctx.register_approval_transport` plugins |
+
+`approvals.mode=smart` decisions made by the auxiliary LLM do not fire it, because no person is asked; neither do gateway approvals that join an identical prompt already pending (the person sees one prompt, and the pair fires once for it). New kinds can be added later, so ignore kinds you don't handle.
+
+**Callback signature:**
+
+```python
+def my_callback(kind: str, request_id: str, session_id: str, session_key: str,
+ platform: str, prompt: str, **kwargs):
+```
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `kind` | `str` | `"sudo"`, `"clarify"` or `"approval"` |
+| `request_id` | `str` | Unique per prompt; the matching `on_human_input_resolved` carries the same value |
+| `session_id` | `str` | Hermes session id when known, else `""` |
+| `session_key` | `str` | Session/chat routing key, useful for scoping notifications per chat |
+| `platform` | `str` | Gateway platform (`"telegram"`, `"discord"`, ...) or local source (`"cli"`, `"tui"`, `"desktop"`, ...) |
+| `prompt` | `str` | What the person is asked about: the command for `sudo`/`approval`, the question text for `clarify`. Always redacted with the secret redactor, even when `security.redact_secrets` is off |
+
+The sudo password and clarify answers are **never** passed to either hook. **Return value:** ignored; a raising callback is logged and the prompt proceeds. Callbacks run on the thread that is about to block, so keep them fast — hand network calls (push services, webhooks) to a background thread.
+
+### `on_human_input_resolved`
+
+Fires exactly once for every `on_human_input_request`, after the wait ends. Same kwargs plus `outcome`:
+
+| `kind` | `outcome` values |
+|--------|------------------|
+| `"sudo"` | `"provided"`, `"skipped"` (empty answer), `"timeout"`, `"cancelled"`, `"error"` |
+| `"clarify"` | The surface's outcome: `"submitted"`, `"timed_out"`, `"cancelled"`, `"undelivered"`, `"terminated"`, or `"error"` |
+| `"approval"` | `"once"`, `"session"`, `"always"`, `"deny"`, `"timeout"`, `"cancelled"`, `"notify_failed"`, or `"transport_<failure>"` for a failed plugin transport |
+
+```python
+import threading
+
+def push_notification(text):
+ ... # call your push service here
+
+def register(ctx):
+ pending = {}
+
+ def on_request(kind, request_id, prompt, session_key, **kwargs):
+ pending[request_id] = threading.Timer(30, push_notification, (f"Hermes needs you ({kind}): {prompt[:80]}",))
+ pending[request_id].start() # only page if nobody answers within 30s
+
+ def on_resolved(request_id, **kwargs):
+ timer = pending.pop(request_id, None)
+ if timer:
+ timer.cancel()
+
+ ctx.register_hook("on_human_input_request", on_request)
+ ctx.register_hook("on_human_input_resolved", on_resolved)
+```
+
+---
+
### `on_room_member_activity`
Fires while a hosted [Group Chat](../bot-mode.md#groups-and-group-chats) member turn runs. A member executes on a hidden `Group: <room>` session that no client is attached to, so between the room log's `turn.started` and `turn.settled` the turn is a black box. This hook projects the runtime events that session already produces — tool start/complete, approval requests, streamed text and reasoning, errors — stamped with the room coordinates, so a client (Hermes Crew, a dashboard, an audit log) can render tool cards, approval prompts and live member status without inferring anything from text. The Group Chat runtime keeps ownership of execution, scheduling and the durable log; plugins only observe.
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index c58dd0f6d64..8777cd89e64 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -327,7 +327,7 @@ Plugins can register the 27 lifecycle events currently accepted by `hermes_cli.p
|---|---|
| **Directive/control** | `pre_tool_call`, `pre_llm_call`, `pre_verify`, `pre_gateway_dispatch` |
| **Transform** | `transform_tool_result`, `transform_terminal_output`, `transform_llm_output`, `pre_transcription` |
-| **Observer** | `post_tool_call`, `post_llm_call`, `pre_api_request`, `post_api_request`, `api_request_error`, `pre_auxiliary_call`, `post_auxiliary_call`, `on_stream_start`, `on_stream_delta`, `on_stream_end`, `on_interim_message`, `on_session_start`, `on_session_end`, `on_session_finalize`, `on_session_reset`, `agent_loop_stopped`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `pre_command`, `kanban_task_claimed`, `kanban_task_completed`, `kanban_task_blocked` |
+| **Observer** | `post_tool_call`, `post_llm_call`, `pre_api_request`, `post_api_request`, `api_request_error`, `pre_auxiliary_call`, `post_auxiliary_call`, `on_stream_start`, `on_stream_delta`, `on_stream_end`, `on_interim_message`, `on_session_start`, `on_session_end`, `on_session_finalize`, `on_session_reset`, `agent_loop_stopped`, `on_skill_lifecycle`, `subagent_start`, `subagent_stop`, `pre_approval_request`, `post_approval_response`, `on_human_input_request`, `on_human_input_resolved`, `pre_command`, `kanban_task_claimed`, `kanban_task_completed`, `kanban_task_blocked` |
These categories describe current behavior rather than defining future naming rules. Plugin middleware remains a separate registry/surface.
## Plugin types