The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal): `hermes chat -q` never waits on a sudo prompt nobody answers
kshitijk4poor33c9b1d7796b
diff --git a/tests/tools/test_protected_instruction_cli_channel.py b/tests/tools/test_protected_instruction_cli_channel.pyindex 172f8f35770..f2b3148ef71 100644--- a/tests/tools/test_protected_instruction_cli_channel.py+++ b/tests/tools/test_protected_instruction_cli_channel.py@@ -1,164 +1,65 @@-"""Protected-instruction approval must be answerable on an interactive CLI-session, and must NOT pretend a human channel exists in a headless one-shot-(``hermes chat -q``) session.+"""Protected-instruction approval fails closed at once, without asking anyone, where nobody can answer.-Defect (kanban t_9691f08d): every write to a protected agent-instruction file-from a kanban worker failed with-- BLOCKED: ... approval prompt timed out without a user response.- Silence is not consent.--which reads as "a human ignored the prompt". In fact those workers are spawned-as ``hermes chat -q``, which never builds a prompt_toolkit Application — but-``HermesCLI.__init__`` had already registered ``_approval_callback`` as the-thread-local CLI approval callback. ``_request_protected_instruction_approval``-therefore saw a callback, believed a human channel existed, pushed a modal into-a layout that is never rendered, and blocked on a response queue no key binding-could ever fill until the approval timeout expired.--``_run_approval_gate`` learned about this context in #86878 via-``HERMES_SINGLE_QUERY_SESSION``; the protected-instruction gate deliberately-bypasses that gate (one-operation approval every time, no allowlist, no yolo)-and so never got the fix. These tests lock three invariants:--1. Interactive CLI: a registered approval callback that answers ``once`` lets- the write through, and ``deny`` blocks it. The channel works.-2. Headless one-shot: even with a callback registered, the gate fails closed- *immediately* with the honest "no interactive user or gateway is present"- message instead of manufacturing a timeout.-3. Single-query never auto-approves this gate, whatever- ``approvals.single_query_mode`` says — that config governs- ``_run_approval_gate``, not this one.--The real CLI modal round trip is covered by tests/hermes_cli/test_cli_approval_ui.py.+``hermes chat -q`` (how kanban spawns every worker), cron and unattended platforms can have the CLI approval+callback registered on the agent thread. The gate used to ask it, block for the full approvals timeout, then+report "timed out" — which reads as a human ignoring a prompt nobody saw. The interactive approve/deny paths+are covered in test_file_write_safety.py; the real CLI modal in tests/hermes_cli/test_cli_approval_ui.py."""import json-import timeimport pytest@pytest.fixture(autouse=True)def _gate_on(monkeypatch):- import tools.file_tools_write_guards as ft- monkeypatch.setattr(ft, "_protected_instruction_config", lambda: (True, []))- yield--[email protected](autouse=True)-def _clean_callbacks(monkeypatch):+ import tools.file_tools_write_guards as guardsfrom tools.terminal_tool import set_approval_callback- # Default every test to a NON single-query context; the headless tests- # opt in explicitly.- monkeypatch.delenv("HERMES_SINGLE_QUERY_SESSION", raising=False)+ monkeypatch.setattr(guards, "_protected_instruction_config", lambda: (True, []))+ for name in ("HERMES_SINGLE_QUERY_SESSION", "HERMES_CRON_SESSION", "HERMES_SESSION_PLATFORM"):+ monkeypatch.delenv(name, raising=False)set_approval_callback(None)yieldset_approval_callback(None)-def _write(path, content="content"):[email protected]("env", [+ {"HERMES_SINGLE_QUERY_SESSION": "1"},+ {"HERMES_CRON_SESSION": "1"},+ {"HERMES_SESSION_PLATFORM": "webhook"},+], ids=["single_query", "cron", "webhook"])+def test_registered_callback_is_never_asked_without_a_user(tmp_path, monkeypatch, env):+ from tools.terminal_tool import set_approval_callbackfrom tools.file_tools import write_file_tool- return json.loads(write_file_tool(str(path), content))---class TestInteractiveCliChannelDelivers:- """An interactive CLI session can actually answer the prompt."""-- def test_interactive_approval_allows_write(self, tmp_path):- from tools.terminal_tool import set_approval_callback-- seen = []-- def cb(command, description, **kwargs):- seen.append((command, description, kwargs))- return "once"- set_approval_callback(cb)- target = tmp_path / "SOUL.md"- res = _write(target, "approved by a live human")+ for name, value in env.items():+ monkeypatch.setenv(name, value)+ asked = []+ set_approval_callback(lambda command, description, **kw: asked.append(command) or "once")+ target = tmp_path / "SOUL.md"+ res = json.loads(write_file_tool(str(target), "content"))- assert not res.get("error"), res- assert target.read_text(encoding="utf-8") == "approved by a live human"- assert len(seen) == 1, "the human channel was never used"- assert "SOUL.md" in seen[0][0]- # One-operation only: no session/permanent scope is offered.- assert seen[0][2].get("allow_permanent") is False+ assert asked == []+ assert "no interactive user or gateway is present" in res["error"]+ assert "timed out" not in res["error"]+ assert not target.exists()- def test_interactive_denial_blocks_write(self, tmp_path):- from tools.terminal_tool import set_approval_callback- set_approval_callback(lambda c, d, **k: "deny")- target = tmp_path / "SOUL.md"- res = _write(target)- assert res.get("error") and "BLOCKED" in res["error"]- assert "denied by the user" in res["error"]- assert not target.exists()---class TestHeadlessOneShotFailsClosedHonestly:- """`hermes chat -q` must not claim a human channel it does not have."""-- def test_no_callback_reports_no_human_not_timeout(self, tmp_path):- target = tmp_path / "SOUL.md"- res = _write(target)- assert res.get("error") and "BLOCKED" in res["error"]- assert "no interactive user or gateway is present" in res["error"]- assert "timed out" not in res["error"], (- "headless run reported a timeout, implying a human ignored a "- "prompt that was never rendered"- )- assert not target.exists()-- def test_single_query_ignores_the_unreachable_modal_callback(- self, tmp_path, monkeypatch):- """The reported defect, verbatim.-- A callback IS registered (HermesCLI.__init__ always registers one),- but there is no Application to render it. The gate must not call it- and must not report a timeout.- """- from tools.terminal_tool import set_approval_callback-- called = []-- def never_answers(command, description, **kwargs):- called.append(command)- time.sleep(30) # what the unrendered modal effectively did- return "timeout"-- set_approval_callback(never_answers)- monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")-- target = tmp_path / "SOUL.md"- started = time.time()- res = _write(target)- elapsed = time.time() - started-- assert not called, (- "single-query session dispatched to a modal nothing can render")- assert elapsed < 5, f"gate blocked for {elapsed:.1f}s with no human"- assert res.get("error") and "BLOCKED" in res["error"]- assert "no interactive user or gateway is present" in res["error"]- assert "timed out" not in res["error"]- assert not target.exists()-- @pytest.mark.parametrize("mode", ["approve", "deny"])- def test_single_query_mode_never_auto_approves_this_gate(- self, tmp_path, monkeypatch, mode):- """``approvals.single_query_mode`` governs _run_approval_gate only.-- Protected-instruction writes always need a live human, so even- ``single_query_mode: approve`` must not let one through.- """- from tools import approval_context- from tools.terminal_tool import set_approval_callback[email protected]("mode", ["approve", "deny"])+def test_single_query_mode_never_auto_approves_this_gate(tmp_path, monkeypatch, mode):+ """``approvals.single_query_mode`` governs the dangerous-command gate only: a protected-instruction write+ always needs a live human."""+ from tools import approval_context+ from tools.file_tools import write_file_tool+ from tools.terminal_tool import set_approval_callback- monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")- monkeypatch.setattr(approval_context, "_get_single_query_approval_mode", lambda: mode)- set_approval_callback(lambda c, d, **k: "once")+ monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")+ monkeypatch.setattr(approval_context, "_get_single_query_approval_mode", lambda: mode)+ asked = []+ set_approval_callback(lambda command, description, **kw: asked.append(command) or "once")+ target = tmp_path / "SOUL.md"+ res = json.loads(write_file_tool(str(target), "content"))- target = tmp_path / "SOUL.md"- res = _write(target)- assert res.get("error") and "BLOCKED" in res["error"]- assert not target.exists()+ assert asked == []+ assert "BLOCKED" in res["error"]+ assert not target.exists()diff --git a/tests/tools/test_subagent_sudo_prompt.py b/tests/tools/test_subagent_sudo_prompt.pyindex 66f74fd7717..3d80f418531 100644--- a/tests/tools/test_subagent_sudo_prompt.py+++ b/tests/tools/test_subagent_sudo_prompt.py@@ -124,7 +124,7 @@ class TestDelegatedChildFailureMessaging:out = tts._handle_sudo_failure("sudo: a password is required", env_type="local")- assert "Subagents cannot prompt" in out+ assert "cannot prompt for a sudo password" in outassert "SUDO_PASSWORD" in outdef test_parent_output_unchanged(self, monkeypatch):@@ -136,3 +136,37 @@ class TestDelegatedChildFailureMessaging:monkeypatch.setenv("HERMES_GATEWAY_SESSION", "1")out = tts._handle_sudo_failure("sudo: a password is required", env_type="local")assert "To enable sudo over messaging" in out+++def test_single_query_never_prompts(monkeypatch):+ """`hermes chat -q` exports HERMES_INTERACTIVE=1 and registers the CLI sudo callback, but never renders the+ panel (a 45 s wait per sudo call for nobody): it is headless, like a delegated child."""+ monkeypatch.setenv("HERMES_INTERACTIVE", "1")+ monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")+ calls = []+ tt.set_sudo_password_callback(lambda: calls.append(1) or "pw")+ monkeypatch.setattr(tts, "_prompt_for_sudo_password",+ lambda timeout_seconds=45, *, command="": calls.append(2) or "pw")++ transformed, sudo_stdin = tts._transform_sudo_command("sudo whoami")++ assert calls == []+ assert sudo_stdin is None+ assert transformed == "sudo whoami"+++def test_single_query_sudo_failure_gets_the_headless_tip_and_no_reprompt_promise(monkeypatch):+ """A -q sudo failure is told how to fix it (SUDO_PASSWORD), never promised a prompt it will not get."""+ from tools.terminal_tool_result import _sudo_annotations++ monkeypatch.setenv("HERMES_INTERACTIVE", "1")+ monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")+ monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)+ out = tts._handle_sudo_failure("sudo: a password is required", env_type="local")+ assert "cannot prompt for a sudo password" in out and "SUDO_PASSWORD" in out++ tt.set_sudo_password_callback(lambda: "pw")+ tts._set_cached_sudo_password("wrong")+ out, auth_failed, cache_cleared = _sudo_annotations("sudo whoami", "sudo: 3 incorrect password attempts", "local")+ assert auth_failed and cache_cleared+ assert "prompted again" not in outdiff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.pyindex 1784cabde9b..c6baec10aba 100644--- a/tools/file_tools_write_guards.py+++ b/tools/file_tools_write_guards.py@@ -319,12 +319,8 @@ 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)- # ...but a one-shot ``hermes chat -q`` session — which is exactly how the kanban dispatcher spawns- # every worker — registers that callback in ``HermesCLI.__init__`` and never builds a prompt_toolkit- # Application, so the modal is pushed into a layout nothing renders and the gate burned the whole- # approvals timeout, then reported "timed out" for a prompt no human saw. Detect that context the same- # way ``_run_approval_gate`` does (#86878) and fail closed immediately with the honest reason. Single-query- # runs are NEVER auto-approved here, whatever ``approvals.single_query_mode`` says.+ # -q (every kanban worker), cron and unattended platforms can have a callback registered that nobody+ # answers: fail closed now, and never auto-approve, whatever approvals.<context>_mode says.from tools.approval_context import _no_user_can_answerif _no_user_can_answer():return blocked.format(why=_NO_HUMAN)diff --git a/tools/terminal_tool_result.py b/tools/terminal_tool_result.pyindex 77ab7e45001..942b1780c19 100644--- a/tools/terminal_tool_result.py+++ b/tools/terminal_tool_result.py@@ -117,7 +117,7 @@ def _sudo_annotations(command: str, output: str, env_type: str) -> tuple[str, bo"""Sudo failure handling -> (output, auth_failed, cache_cleared)."""import tools.terminal_tool as ttfrom tools.terminal_tool_sudo import (- _handle_sudo_failure, _in_delegated_child_context, _invalidate_cached_sudo_on_auth_failure,+ _handle_sudo_failure, _invalidate_cached_sudo_on_auth_failure, _no_sudo_user,_sudo_wrong_password_failure,)from utils import env_var_enabled@@ -126,7 +126,7 @@ def _sudo_annotations(command: str, output: str, env_type: str) -> tuple[str, bocache_cleared = _invalidate_cached_sudo_on_auth_failure(command, output)can_reprompt = cache_cleared and (tt._get_sudo_password_callback() is not None or env_var_enabled("HERMES_INTERACTIVE")- ) and not _in_delegated_child_context()+ ) and not _no_sudo_user()if can_reprompt:output += ("\n\n⚠️ Sudo authentication failed — cached password ""cleared. You will be prompted again on the next sudo command.")diff --git a/tools/terminal_tool_sudo.py b/tools/terminal_tool_sudo.pyindex c0da6f916e8..643e1e280a1 100644--- a/tools/terminal_tool_sudo.py+++ b/tools/terminal_tool_sudo.py@@ -93,15 +93,15 @@ _SUDO_HEADLESS_FAILURES = ("sudo: a password is required", "sudo: no tty presentdef _handle_sudo_failure(output: str, env_type: str) -> str:"""Append a SUDO_PASSWORD tip when sudo failed in a headless context- (gateway session or delegate_task child); otherwise return *output* as is."""+ (gateway session, delegate_task child or `hermes chat -q`); otherwise return *output* as is."""is_gateway = env_var_enabled("HERMES_GATEWAY_SESSION")- is_delegated_child = _in_delegated_child_context()- if not (is_gateway or is_delegated_child) or not any(f in output for f in _SUDO_HEADLESS_FAILURES):+ no_user = _no_sudo_user()+ if not (is_gateway or no_user) or not any(f in output for f in _SUDO_HEADLESS_FAILURES):return outputfrom hermes_constants import display_hermes_home as _dhh- if is_delegated_child:+ if no_user:return output + (- "\n\n💡 Tip: Subagents cannot prompt for a sudo password. "+ "\n\n💡 Tip: This session cannot prompt for a sudo password. "f"Add SUDO_PASSWORD to {_dhh()}/.env on the agent machine, ""or run the command without sudo.")@@ -439,6 +439,13 @@ def _rewrite_compound_background(command: str) -> str:return result+def _no_sudo_user() -> bool:+ """A delegated child or a `hermes chat -q` run: nobody can answer a sudo prompt. Single-query only+ (not _no_user_can_answer): cron strips HERMES_INTERACTIVE and unattended platforms register no sudo callback."""+ from tools.approval_context import _is_single_query_approval_context+ return _in_delegated_child_context() or _is_single_query_approval_context()++def _transform_sudo_command(command: str | None,sudo_nopasswd_check: Callable[[], bool] | None = None,@@ -471,12 +478,12 @@ def _transform_sudo_command(has_configured_password = _configured_password is not Nonesudo_password = _configured_password if has_configured_password else _get_cached_sudo_password()- # delegate_task children inherit HERMES_INTERACTIVE=1 (and possibly a stale thread-local- # callback on a recycled worker) but have no user on the other side — always headless;- # configured password and session cache still apply.+ # delegate_task children and `hermes chat -q` inherit HERMES_INTERACTIVE=1 and (for -q) the CLI+ # panel callback, but have no user on the other side — always headless; configured password and+ # session cache still apply.should_prompt_for_sudo = (env_var_enabled("HERMES_INTERACTIVE") or _get_sudo_password_callback() is not None- ) and not _in_delegated_child_context()+ ) and not _no_sudo_user()if not has_configured_password and not sudo_password and should_prompt_for_sudo:# sudoers NOPASSWD must not be forced through the prompt or the -S pipe. The probe is# a round trip on the selected backend (an ssh exec for SSH), so it only runs when a