Skip to content

The agent that grows with you

fix(terminal): subagents no longer hijack the tty with an interactive sudo prompt

Teknium081cdd991159
diff --git a/tests/tools/test_subagent_sudo_prompt.py b/tests/tools/test_subagent_sudo_prompt.py
new file mode 100644
index 00000000000..1f5bb4bb5d1
--- /dev/null
+++ b/tests/tools/test_subagent_sudo_prompt.py
@@ -0,0 +1,139 @@
+"""delegate_task children must never trigger the interactive sudo prompt.
+
+Subagents run on worker threads of the parent process and inherit
+process-wide interactivity signals (``HERMES_INTERACTIVE=1`` set by the CLI
+at startup). Before the fix, ``_transform_sudo_command`` passed the
+interactive gate inside a child, found no thread-local sudo callback, and
+fell through to the raw ``/dev/tty`` password prompt — printed mid-TUI from
+a background thread and blocking the child for the full 45s timeout.
+
+The delegated-child ContextVar (``agent.delegation_context``) is the
+authoritative "this execution context has no user" signal: it is set around
+every child run and propagates through ``contextvars.copy_context`` onto the
+executor thread.
+"""
+
+import contextvars
+import os
+import threading
+
+import pytest
+
+from agent.delegation_context import delegated_child_context
+from tools import terminal_tool as tt
+
+
[email protected](autouse=True)
+def _clean_sudo_state(monkeypatch):
+ """Isolate sudo-related process/thread state per test."""
+ monkeypatch.delenv("SUDO_PASSWORD", raising=False)
+ monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)
+ # Host sudoers NOPASSWD must not short-circuit the path under test.
+ monkeypatch.setattr(tt, "_sudo_nopasswd_works", lambda: False)
+ tt._reset_cached_sudo_passwords()
+ tt.set_sudo_password_callback(None)
+ yield
+ tt.set_sudo_password_callback(None)
+ tt._reset_cached_sudo_passwords()
+
+
+def _transform_in_child(command: str):
+ """Run _transform_sudo_command the way delegate_tool runs children:
+
+ inside delegated_child_context(), through contextvars.copy_context(),
+ on a separate worker thread.
+ """
+ result = {}
+
+ def _parent_side():
+ with delegated_child_context("child-session"):
+ ctx = contextvars.copy_context()
+
+ def _worker():
+ result["value"] = ctx.run(tt._transform_sudo_command, command)
+
+ t = threading.Thread(target=_worker)
+ t.start()
+ t.join(timeout=10)
+ assert not t.is_alive(), "child transform blocked (prompt fired?)"
+
+ _parent_side()
+ return result["value"]
+
+
+class TestDelegatedChildNeverPrompts:
+ def test_interactive_env_does_not_prompt_in_child(self, monkeypatch):
+ monkeypatch.setenv("HERMES_INTERACTIVE", "1")
+ calls = []
+ monkeypatch.setattr(
+ tt,
+ "_prompt_for_sudo_password",
+ lambda timeout_seconds=45: calls.append(1) or "hunter2",
+ )
+
+ transformed, sudo_stdin = _transform_in_child("sudo apt-get update")
+
+ assert calls == [], "child must not reach the interactive sudo prompt"
+ assert sudo_stdin is None
+ assert transformed == "sudo apt-get update"
+
+ def test_stale_thread_callback_does_not_prompt_in_child(self, monkeypatch):
+ # Precondition sanity: the interactive gate WOULD fire outside a child.
+ monkeypatch.delenv("HERMES_INTERACTIVE", raising=False)
+ calls = []
+
+ def _run_child_with_stale_callback():
+ # Simulate a recycled worker thread that still holds a parent
+ # CLI callback in its thread-local slot.
+ tt.set_sudo_password_callback(lambda: calls.append(1) or "pw")
+ try:
+ with delegated_child_context("child-session"):
+ return tt._transform_sudo_command("sudo systemctl restart foo")
+ finally:
+ tt.set_sudo_password_callback(None)
+
+ transformed, sudo_stdin = _run_child_with_stale_callback()
+ assert calls == []
+ assert sudo_stdin is None
+ assert transformed == "sudo systemctl restart foo"
+
+ def test_parent_context_still_prompts(self, monkeypatch):
+ """The fix must not break interactive prompting outside children."""
+ monkeypatch.setenv("HERMES_INTERACTIVE", "1")
+ monkeypatch.setattr(
+ tt, "_prompt_for_sudo_password", lambda timeout_seconds=45: "hunter2"
+ )
+
+ transformed, sudo_stdin = tt._transform_sudo_command("sudo whoami")
+
+ assert sudo_stdin == "hunter2\n"
+ assert "sudo -S -p ''" in transformed
+
+ def test_configured_password_still_works_in_child(self, monkeypatch):
+ monkeypatch.setenv("SUDO_PASSWORD", "s3cret")
+ monkeypatch.setenv("HERMES_INTERACTIVE", "1")
+
+ transformed, sudo_stdin = _transform_in_child("sudo whoami")
+
+ assert sudo_stdin == "s3cret\n"
+ assert "sudo -S -p ''" in transformed
+
+
+class TestDelegatedChildFailureMessaging:
+ def test_child_gets_headless_sudo_tip(self):
+ with delegated_child_context("child-session"):
+ out = tt._handle_sudo_failure(
+ "sudo: a password is required", env_type="local"
+ )
+ assert "Subagents cannot prompt" in out
+ assert "SUDO_PASSWORD" in out
+
+ def test_parent_output_unchanged(self, monkeypatch):
+ monkeypatch.delenv("HERMES_GATEWAY_SESSION", raising=False)
+ out = tt._handle_sudo_failure("sudo: a password is required", env_type="local")
+ assert out == "sudo: a password is required"
+
+ def test_gateway_tip_preserved(self, monkeypatch):
+ monkeypatch.setenv("HERMES_GATEWAY_SESSION", "1")
+ out = tt._handle_sudo_failure("sudo: a password is required", env_type="local")
+ assert "To enable sudo over messaging" in out
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 0f4bac978f6..69089a3722d 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -429,15 +429,39 @@ def _validate_workdir(workdir: str) -> str | None:
return None
+def _in_delegated_child_context() -> bool:
+ """Return True while running inside a delegate_task child.
+
+ Subagents execute on worker threads of the parent process, so they
+ inherit process-wide interactivity signals (``HERMES_INTERACTIVE=1`` set
+ by the CLI at startup) that do NOT mean *this* execution context can
+ reach the user. A child that passes the interactive gate with no sudo
+ callback falls through to the raw ``/dev/tty`` prompt — printed mid-TUI
+ from a background thread, racing siblings for the tty, and blocking the
+ child for the full timeout. Children must always behave as headless for
+ sudo prompting. The ContextVar is set by ``delegated_child_context()``
+ around every child run and propagates through ``contextvars.copy_context``
+ onto the executor thread.
+ """
+ try:
+ from agent.delegation_context import is_delegated_child_context
+
+ return is_delegated_child_context()
+ except Exception:
+ return False
+
+
def _handle_sudo_failure(output: str, env_type: str) -> str:
"""
- Check for sudo failure and add helpful message for messaging contexts.
-
- Returns enhanced output if sudo failed in messaging context, else original.
+ Check for sudo failure and add helpful message for headless contexts
+ (messaging gateway sessions and delegate_task subagents).
+
+ Returns enhanced output if sudo failed in such a context, else original.
"""
is_gateway = env_var_enabled("HERMES_GATEWAY_SESSION")
-
- if not is_gateway:
+ is_delegated_child = _in_delegated_child_context()
+
+ if not is_gateway and not is_delegated_child:
return output
# Check for sudo failure indicators
@@ -450,6 +474,12 @@ def _handle_sudo_failure(output: str, env_type: str) -> str:
for failure in sudo_failures:
if failure in output:
from hermes_constants import display_hermes_home as _dhh
+ if is_delegated_child:
+ return output + (
+ "\n\n💡 Tip: Subagents cannot prompt for a sudo password. "
+ f"Add SUDO_PASSWORD to {_dhh()}/.env on the agent machine, "
+ "or run the command without sudo."
+ )
return output + f"\n\n💡 Tip: To enable sudo over messaging, add SUDO_PASSWORD to {_dhh()}/.env on the agent machine."
return output
@@ -1053,9 +1083,16 @@ def _transform_sudo_command(command: str | None) -> tuple[str | None, str | None
return command, None
has_sudo_prompt_callback = _get_sudo_password_callback() is not None
+ # delegate_task children inherit the parent's process-wide
+ # HERMES_INTERACTIVE=1 (and, on a recycled worker thread, potentially a
+ # stale thread-local callback), but there is no user on the other side of
+ # this execution context: prompting from a subagent thread fights the
+ # parent's TUI for /dev/tty and blocks the child for the full timeout.
+ # Children always behave as headless — configured SUDO_PASSWORD, the
+ # session cache, and the NOPASSWD probe above all still work.
should_prompt_for_sudo = (
env_var_enabled("HERMES_INTERACTIVE") or has_sudo_prompt_callback
- )
+ ) and not _in_delegated_child_context()
if not has_configured_password and not sudo_password and should_prompt_for_sudo:
sudo_password = _prompt_for_sudo_password(timeout_seconds=45)
if sudo_password:
@@ -3459,7 +3496,10 @@ def terminal_tool(
)
if sudo_cache_cleared:
has_sudo_prompt_callback = _get_sudo_password_callback() is not None
- if has_sudo_prompt_callback or env_var_enabled("HERMES_INTERACTIVE"):
+ can_reprompt = (
+ has_sudo_prompt_callback or env_var_enabled("HERMES_INTERACTIVE")
+ ) and not _in_delegated_child_context()
+ if can_reprompt:
output += (
"\n\n⚠️ Sudo authentication failed — cached password "
"cleared. You will be prompted again on the next sudo "