The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(terminal): extract sudo/shell-rewrite cluster to terminal_tool_sudo and backend builders/checkers to terminal_tool_backends
Teknium21c703797595
diff --git a/tests/tools/test_terminal_requirements.py b/tests/tools/test_terminal_requirements.pyindex 4923d6320ab..416d7b8530f 100644--- a/tests/tools/test_terminal_requirements.py+++ b/tests/tools/test_terminal_requirements.py@@ -88,7 +88,7 @@ def test_modal_backend_managed_mode_without_feature_flag_logs_clear_error(monkeydef test_vercel_backend_without_sdk_logs_specific_error(monkeypatch, caplog):_clear_terminal_env(monkeypatch)monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: None)+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: None)with caplog.at_level(logging.ERROR):ok = terminal_tool_module.check_terminal_requirements()@@ -103,7 +103,7 @@ def test_vercel_backend_without_sdk_logs_specific_error(monkeypatch, caplog):def test_vercel_backend_without_auth_logs_specific_error(monkeypatch, caplog):_clear_terminal_env(monkeypatch)monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())with caplog.at_level(logging.ERROR):ok = terminal_tool_module.check_terminal_requirements()@@ -119,7 +119,7 @@ def test_vercel_backend_accepts_oidc_auth(monkeypatch):_clear_terminal_env(monkeypatch)monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())assert terminal_tool_module.check_terminal_requirements() is True@@ -130,7 +130,7 @@ def test_vercel_backend_accepts_token_tuple_auth(monkeypatch):monkeypatch.setenv("VERCEL_TOKEN", "token")monkeypatch.setenv("VERCEL_PROJECT_ID", "project")monkeypatch.setenv("VERCEL_TEAM_ID", "team")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())assert terminal_tool_module.check_terminal_requirements() is True@@ -141,7 +141,7 @@ def test_vercel_backend_accepts_supported_runtimes(monkeypatch, runtime):monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", runtime)monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())assert terminal_tool_module.check_terminal_requirements() is True@@ -151,7 +151,7 @@ def test_vercel_backend_accepts_blank_runtime(monkeypatch):monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", " ")monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())assert terminal_tool_module.check_terminal_requirements() is True@@ -161,7 +161,7 @@ def test_vercel_backend_rejects_unsupported_runtime(monkeypatch, caplog):monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")monkeypatch.setenv("TERMINAL_VERCEL_RUNTIME", "node20")monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())with caplog.at_level(logging.ERROR):ok = terminal_tool_module.check_terminal_requirements()@@ -179,7 +179,7 @@ def test_vercel_backend_rejects_nondefault_disk(monkeypatch, caplog):monkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")monkeypatch.setenv("TERMINAL_CONTAINER_DISK", "8192")monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())with caplog.at_level(logging.ERROR):ok = terminal_tool_module.check_terminal_requirements()@@ -196,7 +196,7 @@ def test_vercel_backend_rejects_malformed_disk_without_raising(monkeypatch, caplmonkeypatch.setenv("TERMINAL_ENV", "vercel_sandbox")monkeypatch.setenv("TERMINAL_CONTAINER_DISK", "large")monkeypatch.setenv("VERCEL_OIDC_TOKEN", "oidc-token")- monkeypatch.setattr(terminal_tool_module.importlib.util, "find_spec", lambda _name: object())+ monkeypatch.setattr(importlib.util, "find_spec", lambda _name: object())with caplog.at_level(logging.ERROR):ok = terminal_tool_module.check_terminal_requirements()diff --git a/tests/tools/test_terminal_tool_requirements.py b/tests/tools/test_terminal_tool_requirements.pyindex bdf85c9d044..025b21fb4ad 100644--- a/tests/tools/test_terminal_tool_requirements.py+++ b/tests/tools/test_terminal_tool_requirements.py@@ -304,7 +304,7 @@ class TestCheckFnTransientFailureSuppression:lambda: {"env_type": "vercel_sandbox", "container_disk": 51200},)monkeypatch.setattr(- terminal_tool_module.importlib.util,+ importlib.util,"find_spec",lambda _name: object(),)@@ -326,7 +326,7 @@ class TestCheckFnTransientFailureSuppression:},)monkeypatch.setattr(- terminal_tool_module.importlib.util,+ importlib.util,"find_spec",lambda _name: object(),)@@ -351,7 +351,7 @@ class TestCheckFnTransientFailureSuppression:},)monkeypatch.setattr(- terminal_tool_module.importlib.util,+ importlib.util,"find_spec",lambda _name: object(),)diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex d4987d5d4ca..7732ef76601 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -14,24 +14,20 @@ Companion modules: ``terminal_tool_guards`` (pre-exec blocks),(foreground result post-processing)."""-import importlib.utilimport inspectimport jsonimport loggingimport os-import platform-import re-import sysimport timeimport threadingimport atexitimport shutil-import subprocessfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Optional, Dict, Any, List-from utils import env_var_enabled++from utils import env_var_enabled # noqa: F401 (terminal_tool_result imports it lazily via origin)logger = logging.getLogger(__name__)@@ -47,14 +43,59 @@ def _redact_terminal_error_text(value: Any) -> str:# kill long-running subprocesses instead of blocking until timeout.from tools.interrupt import is_interrupted, _interrupt_event # noqa: F401 — re-exportedfrom tools.registry import tool_error+from tools.terminal_tool_backends import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.<name>)+ _ENV_BUILDERS,+ _REQUIREMENT_CHECKERS,+ _SUPPORTED_VERCEL_RUNTIMES,+ _VERCEL_SANDBOX_DEFAULT_CWD,+ _build_daytona_env,+ _build_docker_env,+ _build_local_env,+ _build_modal_env,+ _build_plugin_env,+ _build_singularity_env,+ _build_ssh_env,+ _build_vercel_env,+ _check_daytona_requirements,+ _check_docker_requirements,+ _check_modal_requirements,+ _check_plugin_requirements,+ _check_singularity_requirements,+ _check_ssh_requirements,+ _check_vercel_sandbox_requirements,+ _container_config_from_config,+ _create_environment,+ _get_modal_backend_state,+ _is_supported_vercel_runtime,+ _resources,+ _ssh_config_from_config,+)+from tools.terminal_tool_sudo import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.<name>)+ _SUDO_WRONG_PASSWORD_MARKERS,+ _count_real_sudo_invocations,+ _get_cached_sudo_password,+ _get_sudo_password_cache_scope,+ _handle_sudo_failure,+ _in_delegated_child_context,+ _invalidate_cached_sudo_on_auth_failure,+ _looks_like_env_assignment,+ _prompt_for_sudo_password,+ _read_shell_token,+ _reset_cached_sudo_passwords,+ _rewrite_compound_background,+ _rewrite_real_sudo_invocations,+ _set_cached_sudo_password,+ _sudo_nopasswd_works,+ _sudo_password_cache,+ _sudo_password_cache_lock,+ _sudo_wrong_password_failure,+ _transform_sudo_command,+)# display_hermes_home imported lazily at call site (stale-module safety during hermes update)from tools.environments.singularity import _get_scratch_dir-from tools.tool_backend_helpers import (+from tools.tool_backend_helpers import ( # noqa: F401 (managed_nous_tools_enabled: test patch target)coerce_modal_mode,- has_direct_modal_credentials,managed_nous_tools_enabled,- nous_tool_gateway_unavailable_message,- resolve_modal_backend_state,)@@ -97,71 +138,6 @@ DISK_USAGE_WARNING_THRESHOLD_GB = _safe_parse_import_env(float,"number",)-_VERCEL_SANDBOX_DEFAULT_CWD = "/vercel/sandbox"-_SUPPORTED_VERCEL_RUNTIMES = ("node24", "node22", "python3.13")---def _is_supported_vercel_runtime(runtime: str) -> bool:- return not runtime or runtime in _SUPPORTED_VERCEL_RUNTIMES---def _check_vercel_sandbox_requirements(config: dict[str, Any]) -> bool:- """Validate Vercel Sandbox terminal backend requirements."""- runtime = (config.get("vercel_runtime") or "").strip()- if not _is_supported_vercel_runtime(runtime):- supported = ", ".join(_SUPPORTED_VERCEL_RUNTIMES)- logger.error(- "Vercel Sandbox runtime %r is not supported. "- "Set TERMINAL_VERCEL_RUNTIME to one of: %s.",- runtime,- supported,- )- return False-- disk = config.get("container_disk", 51200)- if disk not in {0, 51200}:- logger.error(- "Vercel Sandbox does not support custom TERMINAL_CONTAINER_DISK=%s. "- "Use the default shared setting (51200 MB).",- disk,- )- return False-- if importlib.util.find_spec("vercel") is None:- logger.error(- "vercel is required for the Vercel Sandbox terminal backend: pip install vercel"- )- return False-- from agent.secret_scope import get_secret-- has_oidc = bool(get_secret("VERCEL_OIDC_TOKEN"))- has_token = bool(get_secret("VERCEL_TOKEN"))- has_project = bool(get_secret("VERCEL_PROJECT_ID"))- has_team = bool(get_secret("VERCEL_TEAM_ID"))-- if has_oidc:- return True-- if has_token or has_project or has_team:- if has_token and has_project and has_team:- return True- logger.error(- "Vercel Sandbox backend selected with token auth, but "- "VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID must all "- "be set together. VERCEL_OIDC_TOKEN is supported for one-off "- "local development only."- )- return False-- logger.error(- "Vercel Sandbox backend selected but no supported auth configuration "- "was found. Set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID "- "for normal use. VERCEL_OIDC_TOKEN is supported for one-off local "- "development only."- )- return False-# Advisory disk-usage check; cached so the recursive scan doesn't run on# every command (a result up to 5 minutes stale is harmless).@@ -200,12 +176,6 @@ def _check_disk_usage_warning():return False-# Interactive sudo password cache, scoped to the session key when present,-# else callback identity (ACP / CLI), else the current thread — so one-# session can never reuse another's cached password in a long-lived process.-_sudo_password_cache: dict[str, str] = {}-_sudo_password_cache_lock = threading.Lock()-# Approval / sudo-prompt UI callbacks (CLI registers prompt_toolkit-aware# ones). Thread-local so overlapping ACP sessions, each on its own executor# thread, can't stomp on each other (GHSA-qg5c-hvr5-hjgr). Gateway mode@@ -239,45 +209,6 @@ def set_approval_callback(cb):_callback_tls.approval = cb-def _get_sudo_password_cache_scope() -> str:- """Return the cache scope for interactive sudo passwords."""- session_key = _current_session_key()- if session_key:- return f"session:{session_key}"-- callback = _get_sudo_password_callback()- if callback is not None:- owner = getattr(callback, "__self__", None)- func = getattr(callback, "__func__", None)- if owner is not None and func is not None:- return f"callback-owner:{id(owner)}:{id(func)}"- return f"callback:{id(callback)}"-- return f"thread:{threading.get_ident()}"---def _get_cached_sudo_password() -> str:- """Return the cached sudo password for the current scope."""- scope = _get_sudo_password_cache_scope()- with _sudo_password_cache_lock:- return _sudo_password_cache.get(scope, "")---def _set_cached_sudo_password(password: str) -> None:- """Persist a sudo password for the current scope."""- scope = _get_sudo_password_cache_scope()- with _sudo_password_cache_lock:- if password:- _sudo_password_cache[scope] = password- else:- _sudo_password_cache.pop(scope, None)---def _reset_cached_sudo_passwords() -> None:- """Clear all cached sudo passwords (tests / process teardown)."""- with _sudo_password_cache_lock:- _sudo_password_cache.clear()-from tools.approval import (check_all_command_guards as _check_all_guards_impl,)@@ -312,580 +243,11 @@ def _check_all_guards(command: str, env_type: str,has_host_access=has_host_access)---def _in_delegated_child_context() -> bool:- """True while running inside a delegate_task child.-- Subagents run on parent-process worker threads and inherit process-wide- ``HERMES_INTERACTIVE=1``, which does NOT mean this context can reach the- user: a raw ``/dev/tty`` sudo prompt from a child races the TUI for the- tty and blocks the child for the full timeout. Children must always be- headless for sudo prompting. The ContextVar is set by- ``delegated_child_context()`` and propagates via ``copy_context``.- """- 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:- """Append a SUDO_PASSWORD tip when sudo failed in a headless context- (gateway session or delegate_task child); otherwise return *output* as is."""- is_gateway = env_var_enabled("HERMES_GATEWAY_SESSION")- is_delegated_child = _in_delegated_child_context()-- if not is_gateway and not is_delegated_child:- return output-- sudo_failures = [- "sudo: a password is required",- "sudo: no tty present",- "sudo: a terminal is required",- ]-- 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---# sudo -S rejects a bad cached/interactive password with these messages.-_SUDO_WRONG_PASSWORD_MARKERS = (- "sudo: authentication failed",- "sudo: incorrect password attempt",- "sudo: maximum 3 incorrect authentication attempts",- "sudo: 3 incorrect password attempts",-)---def _sudo_wrong_password_failure(output: str) -> bool:- """Return True when sudo rejected a piped password."""- if not output:- return False- lowered = output.lower()- return any(marker in lowered for marker in _SUDO_WRONG_PASSWORD_MARKERS)---def _invalidate_cached_sudo_on_auth_failure(- command: str | None, output: str-) -> bool:- """Drop a session-cached sudo password after sudo rejects it.-- Env-configured ``SUDO_PASSWORD`` is left alone — that is an explicit- operator choice, not an interactive cache entry.- """- if "SUDO_PASSWORD" in os.environ:- return False- if not _sudo_wrong_password_failure(output):- return False- if _count_real_sudo_invocations(command or "") == 0:- return False- if not _get_cached_sudo_password():- return False- _set_cached_sudo_password("")- return True---def _prompt_for_sudo_password(timeout_seconds: int = 45) -> 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. Time spent waiting- on the human is excluded from tool deadlines via ``human_wait_window``.- """- _sudo_cb = _get_sudo_password_callback()- if _sudo_cb is not None:- try:- from tools.approval import human_wait_window- with human_wait_window():- return _sudo_cb() or ""- except Exception:- return ""-- result = {"password": None, "done": False}-- def read_password_thread():- """Read password with echo disabled. Uses msvcrt on Windows, /dev/tty on Unix."""- tty_fd = None- old_attrs = None- try:- if platform.system() == "Windows":- import msvcrt- chars = []- while True:- c = msvcrt.getwch()- if c in {"\r", "\n"}:- break- if c == "\x03":- raise KeyboardInterrupt- chars.append(c)- result["password"] = "".join(chars)- else:- import termios- tty_fd = os.open("/dev/tty", os.O_RDONLY)- old_attrs = termios.tcgetattr(tty_fd)- new_attrs = termios.tcgetattr(tty_fd)- new_attrs[3] = new_attrs[3] & ~termios.ECHO- termios.tcsetattr(tty_fd, termios.TCSAFLUSH, new_attrs)- chars = []- while True:- b = os.read(tty_fd, 1)- if not b or b in {b"\n", b"\r"}:- break- chars.append(b)- result["password"] = b"".join(chars).decode("utf-8", errors="replace")- except (EOFError, KeyboardInterrupt, OSError):- result["password"] = ""- except Exception:- result["password"] = ""- finally:- if tty_fd is not None and old_attrs is not None:- try:- import termios as _termios- _termios.tcsetattr(tty_fd, _termios.TCSAFLUSH, old_attrs)- except Exception as e:- logger.debug("Failed to restore terminal attributes: %s", e)- if tty_fd is not None:- try:- os.close(tty_fd)- except Exception as e:- logger.debug("Failed to close tty fd: %s", e)- result["done"] = True-- try:- os.environ["HERMES_SPINNER_PAUSE"] = "1"- time.sleep(0.2)-- print()- print("┌" + "─" * 58 + "┐")- print("│ 🔐 SUDO PASSWORD REQUIRED" + " " * 30 + "│")- print("├" + "─" * 58 + "┤")- print("│ Enter password below (input is hidden), or: │")- print("│ • Press Enter to skip (command fails gracefully) │")- print(f"│ • Wait {timeout_seconds}s to auto-skip" + " " * 27 + "│")- print("└" + "─" * 58 + "┘")- print()- print(" Password (hidden): ", end="", flush=True)-- password_thread = threading.Thread(target=read_password_thread, daemon=True)- password_thread.start()- from tools.approval import human_wait_window- with human_wait_window():- password_thread.join(timeout=timeout_seconds)-- if result["done"]:- password = result["password"] or ""- print() # newline after hidden input- if password:- print(" ✓ Password received (cached for this session)")- else:- print(" ⏭ Skipped - continuing without sudo")- print()- sys.stdout.flush()- return password- else:- print("\n ⏱ Timeout - continuing without sudo")- print(" (Press Enter to dismiss)")- print()- sys.stdout.flush()- return ""-- except (EOFError, KeyboardInterrupt):- print()- print(" ⏭ Cancelled - continuing without sudo")- print()- sys.stdout.flush()- return ""- except Exception as e:- print(f"\n [sudo prompt error: {e}] - continuing without sudo\n")- sys.stdout.flush()- return ""- finally:- if "HERMES_SPINNER_PAUSE" in os.environ:- del os.environ["HERMES_SPINNER_PAUSE"]---def _looks_like_env_assignment(token: str) -> bool:- """Return True when *token* is a leading shell environment assignment."""- if "=" not in token or token.startswith("="):- return False- name, _value = token.split("=", 1)- return bool(re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name))---def _read_shell_token(command: str, start: int) -> tuple[str, int]:- """Read one shell token, preserving quotes/escapes, starting at *start*."""- i = start- n = len(command)-- while i < n:- ch = command[i]- if ch.isspace() or ch in ";|&()":- break- if ch == "'":- i += 1- while i < n and command[i] != "'":- i += 1- if i < n:- i += 1- continue- if ch == '"':- i += 1- while i < n:- inner = command[i]- if inner == "\\" and i + 1 < n:- i += 2- continue- if inner == '"':- i += 1- break- i += 1- continue- if ch == "\\" and i + 1 < n:- i += 2- continue- i += 1-- return command[start:i], i---def _rewrite_real_sudo_invocations(command: str) -> tuple[str, int]:- """Rewrite only real unquoted sudo command words, not plain text mentions.-- Walks the command with the shared tokenizer, tracking whether the cursor- sits at a command-start position (after newline, ``;``/``|``/``&``/``(``,- ``&&``/``||``/``;;``, or a leading ``VAR=val`` assignment); comments at- command start are copied through verbatim. Returns the rewritten command- and the number of sudo invocations rewritten.- """- out: list[str] = []- i = 0- n = len(command)- command_start = True- sudo_count = 0-- while i < n:- ch = command[i]-- if ch.isspace():- out.append(ch)- if ch == "\n":- command_start = True- i += 1- continue-- if ch == "#" and command_start:- comment_end = command.find("\n", i)- if comment_end == -1:- out.append(command[i:])- break- out.append(command[i:comment_end])- i = comment_end- continue-- if command.startswith(("&&", "||", ";;"), i):- out.append(command[i:i + 2])- i += 2- command_start = True- continue-- if ch in ";|&(":- out.append(ch)- i += 1- command_start = True- continue-- if ch == ")":- out.append(ch)- i += 1- command_start = False- continue-- token, next_i = _read_shell_token(command, i)- if command_start and token == "sudo":- out.append("sudo -S -p ''")- sudo_count += 1- else:- out.append(token)-- command_start = bool(command_start and _looks_like_env_assignment(token))- i = next_i-- return "".join(out), sudo_count---def _count_real_sudo_invocations(command: str) -> int:- """Return how many real sudo command words appear in *command*."""- return _rewrite_real_sudo_invocations(command)[1]---def _sudo_nopasswd_works() -> bool:- """True when local sudo currently works without prompting.-- Local backend only — Docker/SSH/Modal must not inherit host sudo state.- Re-probes every call (no cache) so an expired sudo timestamp can't make a- later command silently block waiting for a password.- """- terminal_env = _tenv("TERMINAL_ENV", "local").strip().lower() or "local"- if terminal_env != "local":- return False-- try:- probe = subprocess.run(- ["sudo", "-n", "true"],- stdin=subprocess.DEVNULL,- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- timeout=3,- check=False,- )- return probe.returncode == 0- except Exception:- return False---def _rewrite_compound_background(command: str) -> str:- """Wrap `A && B &` (or `A || B &`) to `A && { B & }` at depth 0.-- Bash binds `&&` tighter than `&`, so `A && B &` backgrounds a subshell- that runs B in the foreground and waits for it; a long-running B leaves- that subshell stuck in ``wait4`` forever, and its open stdout pipe can- keep the terminal tool from returning. The brace group keeps `&&`'s- skip-B-on-failure semantics without a fork: bash backgrounds B as a- simple command and exits immediately, orphaning B normally.-- Handles redirects (``&>``, ``2>&1``) and skips quoted strings and- parenthesised subshells. Simple ``cmd &`` is left alone — it doesn't- have the subshell-wait bug.- """- n = len(command)- i = 0- paren_depth = 0- brace_depth = 0- # Position in *command* just after the most recent `&&` / `||` at depth 0- # in the current statement; -1 when no chain operator is active.- last_chain_op_end = -1- rewrites: list[tuple[int, int]] = [] # (chain_op_end, amp_pos)-- while i < n:- ch = command[i]-- # Newline terminates a statement at depth 0 — reset chain state.- # Checked before the whitespace skip so we don't miss it.- if ch == "\n" and paren_depth == 0 and brace_depth == 0:- last_chain_op_end = -1- i += 1- continue-- if ch.isspace():- i += 1- continue-- # Comments (only at statement start — conservative: any `#` not inside- # a token ends the line). `_read_shell_token` handles quoted strings- # below so `#` inside quotes is safe.- if ch == "#":- nl = command.find("\n", i)- if nl == -1:- break- i = nl- continue-- if ch == "\\" and i + 1 < n:- i += 2- continue-- # Quoted tokens — consume whole string via the shared tokenizer.- if ch in {"'", '"'}:- _, next_i = _read_shell_token(command, i)- i = max(next_i, i + 1)- continue-- if ch == "(":- paren_depth += 1- i += 1- continue-- if ch == ")":- paren_depth = max(0, paren_depth - 1)- i += 1- continue-- # Brace groups: `{ ... }` is a group (no subshell fork), and bash- # requires whitespace after `{`. We track depth so already-rewritten- # output (`A && { B & }`) is idempotent — the inner `&` is part of- # the group, not a new compound to rewrite. Also skip content inside- # the group since `A && B &` there is separately well-formed.- if ch == "{" and i + 1 < n and (command[i + 1].isspace() or command[i + 1] == "\n"):- brace_depth += 1- i += 1- continue- if ch == "}" and brace_depth > 0:- brace_depth -= 1- # Closing a group completes a compound statement; reset chain.- last_chain_op_end = -1- i += 1- continue-- # Inside parens or brace groups, skip operators — they parse in their- # own scope. `(...)` subshells have the same bug class but are not the- # common agent pattern; leave for a follow-up.- if paren_depth > 0 or brace_depth > 0:- i += 1- continue-- # Chain operators at depth 0- if command.startswith("&&", i) or command.startswith("||", i):- last_chain_op_end = i + 2- i += 2- continue-- # Statement terminators reset the chain state- if ch == ";":- last_chain_op_end = -1- i += 1- continue-- # Single `|` (pipe) starts a new pipeline stage; don't rewrite- # across it. `||` handled above.- if ch == "|":- last_chain_op_end = -1- i += 1- continue-- # `&` handling: distinguish `&&`, `&>`, fd redirect (`>&`, `<&`),- # and a true backgrounding `&`.- if ch == "&":- # `&&` handled above; won't reach here- if i + 1 < n and command[i + 1] == ">":- # `&>` redirect — consume- i += 2- continue- # `>&` / `<&` fd target — look back past whitespace- j = i - 1- while j >= 0 and command[j].isspace():- j -= 1- if j >= 0 and command[j] in "<>":- i += 1- continue- # Real background operator- if last_chain_op_end >= 0:- rewrites.append((last_chain_op_end, i))- last_chain_op_end = -1- i += 1- continue-- # Regular unquoted token — advance past it via the shared tokenizer- _, next_i = _read_shell_token(command, i)- i = max(next_i, i + 1)-- if not rewrites:- return command-- # Apply rewrites back-to-front so earlier indices remain valid.- result = command- for chain_end, amp_pos in reversed(rewrites):- # Skip whitespace right after the `&&`/`||` so the brace group- # opens flush against the inner command.- insert_pos = chain_end- while insert_pos < amp_pos and result[insert_pos].isspace():- insert_pos += 1- prefix = result[:insert_pos]- middle = result[insert_pos:amp_pos] # inner command + trailing space- suffix = result[amp_pos + 1 :]- # `{` needs a trailing space in bash; the closing `}` needs to be- # preceded by `;` or `&` — we're providing `&` from the backgrounding.- result = prefix + "{ " + middle + "& }" + suffix-- return result---def _transform_sudo_command(command: str | None) -> tuple[str | None, str | None]:- """Rewrite bare ``sudo`` to ``sudo -S -p ''`` when a password is available.-- Shared by every execution environment. Returns ``(command, sudo_stdin)``:- ``sudo_stdin`` is one password line per sudo invocation that the caller- must PREPEND to the process stdin (sudo -S consumes exactly one line and- passes the rest through, so it's safe alongside the caller's own- stdin_data). Backends that can't pipe stdin (modal, daytona,- vercel_sandbox) embed the password in the command string themselves.- With no password available the command is returned unchanged and- ``sudo_stdin`` is None, so it fails gracefully with- "sudo: a password is required". Password sources, in order: configured- SUDO_PASSWORD, the session cache, then an interactive prompt (45s- timeout, cached on success) when a UI is reachable.- """- if command is None:- return None, None- transformed, sudo_count = _rewrite_real_sudo_invocations(command)- if sudo_count == 0:- return command, None-- # Scope-aware read: under multiplex the process env may hold another- # profile's SUDO_PASSWORD; unscoped callers keep the os.environ read.- try:- from agent.secret_scope import UnscopedSecretError, get_secret-- try:- _configured_password = get_secret("SUDO_PASSWORD")- except UnscopedSecretError:- _configured_password = os.environ.get("SUDO_PASSWORD")- except Exception:- _configured_password = os.environ.get("SUDO_PASSWORD")- has_configured_password = _configured_password is not None- sudo_password = (- _configured_password- if has_configured_password- else _get_cached_sudo_password()- )-- # sudoers NOPASSWD hosts must not be forced through the prompt or the- # -S password pipe (local backend only; re-probed every call).- if not has_configured_password and not sudo_password and _sudo_nopasswd_works():- return command, None-- has_sudo_prompt_callback = _get_sudo_password_callback() is not None- # 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 — they always behave as headless; configured password,- # session cache and the NOPASSWD probe still apply.- 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:- _set_cached_sudo_password(sudo_password)-- if has_configured_password or sudo_password:- # Trailing newline is required: sudo -S reads one line per invocation.- # Compound commands (`sudo a && sudo b`) need one password line each.- password_line = sudo_password + "\n"- return transformed, password_line * sudo_count-- return command, None--from tools.environments.base import EnvironmentConnectionError-from tools.environments.local import LocalEnvironment as _LocalEnvironment-from tools.environments.singularity import SingularityEnvironment as _SingularityEnvironment-from tools.environments.ssh import SSHEnvironment as _SSHEnvironment-from tools.environments.docker import DockerEnvironment as _DockerEnvironment-from tools.environments.modal import ModalEnvironment as _ModalEnvironment-from tools.environments.managed_modal import ManagedModalEnvironment as _ManagedModalEnvironment-from tools.managed_tool_gateway import is_managed_tool_gateway_ready+# Resolved lazily by terminal_tool_backends through this module so tests can+# monkeypatch ``tools.terminal_tool._DockerEnvironment`` / the gateway probes.+from tools.environments.docker import DockerEnvironment as _DockerEnvironment # noqa: F401+from tools.managed_tool_gateway import is_managed_tool_gateway_ready # noqa: F401# Tool description for LLM@@ -1511,264 +873,6 @@ def _get_env_config() -> Dict[str, Any]:}-def _get_modal_backend_state(modal_mode: object | None) -> Dict[str, Any]:- """Resolve direct vs managed Modal backend selection."""- return resolve_modal_backend_state(- modal_mode,- has_direct=has_direct_modal_credentials(),- managed_ready=is_managed_tool_gateway_ready("modal"),- )---def _ssh_config_from_config(config: Dict[str, Any]) -> dict:- """``ssh_config`` for :func:`_create_environment` (shared by terminal_tool- and the lazy :func:`ensure_task_env` bring-up)."""- return {- "host": config.get("ssh_host", ""),- "user": config.get("ssh_user", ""),- "port": config.get("ssh_port", 22),- "key": config.get("ssh_key", ""),- "persistent": config.get("ssh_persistent", False),- }---def _container_config_from_config(config: Dict[str, Any]) -> dict:- """``container_config`` for :func:`_create_environment` (shared by- terminal_tool and the lazy :func:`ensure_task_env` bring-up)."""- return {- "container_cpu": config.get("container_cpu", 1),- "container_memory": config.get("container_memory", 5120),- "container_disk": config.get("container_disk", 51200),- "container_persistent": config.get("container_persistent", True),- "modal_mode": config.get("modal_mode", "auto"),- "vercel_runtime": config.get("vercel_runtime", ""),- "docker_volumes": config.get("docker_volumes", []),- "docker_mount_cwd_to_workspace": config.get("docker_mount_cwd_to_workspace", False),- "docker_forward_env": config.get("docker_forward_env", []),- "docker_env": config.get("docker_env", {}),- "docker_run_as_host_user": config.get("docker_run_as_host_user", False),- "docker_extra_args": config.get("docker_extra_args", []),- "docker_shm_size": config.get("docker_shm_size", "1g"),- "docker_network": config.get("docker_network", True),- "docker_persist_across_processes": config.get("docker_persist_across_processes", True),- "docker_shared_container_key": config.get("docker_shared_container_key", ""),- "docker_orphan_reaper": config.get("docker_orphan_reaper", True),- }---def _resources(cc: Dict[str, Any]) -> dict:- """Common sandbox resource kwargs (cpu/memory in MB/disk in MB/persistence)."""- return {- "cpu": cc.get("container_cpu", 1),- "memory": cc.get("container_memory", 5120),- "disk": cc.get("container_disk", 51200),- "persistent_filesystem": cc.get("container_persistent", True),- }---def _build_local_env(*, cwd, timeout, **_):- return _LocalEnvironment(cwd=cwd, timeout=timeout)---def _build_docker_env(*, image, cwd, timeout, cc, task_id, host_cwd, **_):- # One-shot orphan reaper for labeled containers left behind by prior- # Hermes processes that died before atexit (SIGKILL / OOM / closed- # terminal); once per process, ``terminal.docker_orphan_reaper: false``- # disables it.- _maybe_reap_docker_orphans(cc)- # Per-session container isolation: a session-keyed container must not- # outlive its session, so cross-process reuse/persist is disabled for it —- # cleanup_vm()/the idle reaper stop+rm it. The shared "default" container- # and RL/benchmark override sandboxes keep their existing lifecycle.- session_scoped = (- _docker_session_isolation_enabled()- and task_id != "default"- and not _has_isolation_overrides(task_id)- )- docker_env_obj = _DockerEnvironment(- image=image, cwd=cwd, timeout=timeout, task_id=task_id,- **_resources(cc),- volumes=cc.get("docker_volumes", []),- host_cwd=host_cwd,- auto_mount_cwd=cc.get("docker_mount_cwd_to_workspace", False),- forward_env=cc.get("docker_forward_env", []),- env=cc.get("docker_env", {}),- run_as_host_user=cc.get("docker_run_as_host_user", False),- network=cc.get("docker_network", True),- extra_args=cc.get("docker_extra_args", []),- persist_across_processes=(- False if session_scoped- else cc.get("docker_persist_across_processes", True)- ),- shared_container_key=cc.get("docker_shared_container_key", ""),- shm_size=cc.get("docker_shm_size", "1g"),- )- # Marker read by is_persistent_env(): a session-scoped container survives- # BETWEEN turns (skip per-turn teardown) but is removed at session close /- # idle timeout. Guarded: test doubles may not accept attributes.- if session_scoped:- try:- docker_env_obj._session_scoped = True- except AttributeError:- pass- return docker_env_obj---def _build_singularity_env(*, image, cwd, timeout, cc, task_id, **_):- return _SingularityEnvironment(- image=image, cwd=cwd, timeout=timeout, task_id=task_id, **_resources(cc),- )---def _build_modal_env(*, image, cwd, timeout, cc, task_id, **_):- res = _resources(cc)- persistent = res["persistent_filesystem"]- sandbox_kwargs = {k: res[k] for k in ("cpu", "memory") if res[k] > 0}- if res["disk"] > 0:- try:- import modal- if "ephemeral_disk" in inspect.signature(modal.Sandbox.create).parameters:- sandbox_kwargs["ephemeral_disk"] = res["disk"]- except Exception:- pass-- modal_state = _get_modal_backend_state(cc.get("modal_mode"))-- if modal_state["selected_backend"] == "managed":- return _ManagedModalEnvironment(- image=image, cwd=cwd, timeout=timeout,- modal_sandbox_kwargs=sandbox_kwargs,- persistent_filesystem=persistent, task_id=task_id,- )-- if modal_state["selected_backend"] != "direct":- if modal_state["managed_mode_blocked"]:- raise ValueError(- "Modal backend is configured for managed mode, but "- "Nous Tool Gateway access is not currently available and no direct "- "Modal credentials/config were found. "- + nous_tool_gateway_unavailable_message(- "managed Modal execution",- )- + " Choose TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials."- )- if modal_state["mode"] == "managed":- raise ValueError(- "Modal backend is configured for managed mode, but the managed tool gateway is unavailable. "- + nous_tool_gateway_unavailable_message(- "managed Modal execution",- )- )- if modal_state["mode"] == "direct":- raise ValueError(- "Modal backend is configured for direct mode, but no direct Modal credentials/config were found."- )- message = "Modal backend selected but no direct Modal credentials/config was found."- if managed_nous_tools_enabled():- message = (- "Modal backend selected but no direct Modal credentials/config or managed tool gateway was found."- )- raise ValueError(message)-- return _ModalEnvironment(- image=image, cwd=cwd, timeout=timeout,- modal_sandbox_kwargs=sandbox_kwargs,- persistent_filesystem=persistent, task_id=task_id,- )---def _build_daytona_env(*, image, cwd, timeout, cc, task_id, **_):- # Lazy import so daytona SDK is only required when backend is selected.- from tools.environments.daytona import DaytonaEnvironment as _DaytonaEnvironment- res = _resources(cc)- res["cpu"] = int(res["cpu"])- return _DaytonaEnvironment(image=image, cwd=cwd, timeout=timeout, task_id=task_id, **res)---def _build_vercel_env(*, cwd, timeout, cc, task_id, **_):- from tools.environments.vercel_sandbox import (- VercelSandboxEnvironment as _VercelSandboxEnvironment,- )- return _VercelSandboxEnvironment(- runtime=cc.get("vercel_runtime") or None,- cwd=cwd, timeout=timeout, task_id=task_id, **_resources(cc),- )---def _build_ssh_env(*, cwd, timeout, ssh_config, **_):- if not ssh_config or not ssh_config.get("host") or not ssh_config.get("user"):- raise ValueError("SSH environment requires ssh_host and ssh_user to be configured")- return _SSHEnvironment(- host=ssh_config["host"],- user=ssh_config["user"],- port=ssh_config.get("port", 22),- key_path=ssh_config.get("key", ""),- cwd=cwd,- timeout=timeout,- )---def _build_plugin_env(*, env_type, image, cwd, timeout, cc, task_id, **_):- provider = _get_plugin_env_provider(env_type)- if provider is not None:- env_obj = provider.create_environment(- cwd=cwd, timeout=timeout, task_id=task_id,- image=image, container_config=cc,- )- # Stamp the backend name so path-resolution and progress surfaces- # can identify plugin backends without class-name sniffing.- try:- env_obj._hermes_backend_name = provider.name.strip().lower()- except AttributeError:- pass # test doubles may reject attributes- return env_obj- try:- from agent.terminal_env_registry import plugin_backend_names-- plugin_names = plugin_backend_names()- except Exception:- plugin_names = []- extra = (- ", " + ", ".join(f"'{n}'" for n in plugin_names) if plugin_names else ""- )- raise ValueError(- f"Unknown environment type: {env_type}. Use 'local', 'docker', "- f"'singularity', 'modal', 'daytona', 'vercel_sandbox', 'ssh'{extra}"- )---# Built-in backend -> builder. Anything else is looked up in the plugin registry.-_ENV_BUILDERS = {- "local": _build_local_env,- "docker": _build_docker_env,- "singularity": _build_singularity_env,- "modal": _build_modal_env,- "daytona": _build_daytona_env,- "vercel_sandbox": _build_vercel_env,- "ssh": _build_ssh_env,-}---def _create_environment(env_type: str, image: str, cwd: str, timeout: int,- ssh_config: dict = None, container_config: dict = None,- local_config: dict = None,- task_id: str = "default",- host_cwd: Optional[str] = None):- """Create an execution environment (instance with ``execute()``) for *env_type*.-- ``image`` is ignored for local/ssh/vercel; ``container_config`` carries the- container_*/docker_* resource keys; ``host_cwd`` is the host directory to- bind into Docker when cwd mounting is explicitly enabled. Unknown- ``env_type`` values fall through to plugin-registered backends.- """- builder = _ENV_BUILDERS.get(env_type, _build_plugin_env)- return builder(- env_type=env_type, image=image, cwd=cwd, timeout=timeout,- cc=container_config or {}, task_id=task_id,- ssh_config=ssh_config, host_cwd=host_cwd,- )--def _teardown_env(env: Any, task_id: str, *, force_remove: Optional[bool] = None, done_msg: str = "Cleaned up inactive environment for task: %s") -> None:"""Stop *env* via cleanup()/stop()/terminate(), whichever it has; log the outcome.@@ -1966,8 +1070,6 @@ def is_persistent_env(task_id: str) -> bool:return bool(getattr(env, "_persistent", False))--def cleanup_all_environments():"""Clean up ALL active environments. Use with caution."""task_ids = list(_active_environments.keys())@@ -2050,8 +1152,6 @@ def _atexit_cleanup():atexit.register(_atexit_cleanup)--def _command_requires_pipe_stdin(command: str) -> bool:"""True when PTY mode would break a stdin-driven command: `gh auth login--with-token` waits for EOF on piped stdin, and under a PTY@@ -2566,126 +1666,6 @@ def _evict_environment_for_task(task_id: Optional[str]) -> None:logger.debug("cleanup of degraded environment failed", exc_info=True)-def _check_docker_requirements(config: Dict[str, Any]) -> bool:- from tools.environments.docker import find_docker- docker = find_docker()- if not docker:- logger.error("Docker executable not found in PATH or common install locations")- return False- result = subprocess.run([docker, "version"], capture_output=True, timeout=5, stdin=subprocess.DEVNULL)- return result.returncode == 0---def _check_singularity_requirements(config: Dict[str, Any]) -> bool:- executable = shutil.which("apptainer") or shutil.which("singularity")- if executable:- result = subprocess.run([executable, "--version"], capture_output=True, timeout=5, stdin=subprocess.DEVNULL)- return result.returncode == 0- return False---def _check_ssh_requirements(config: Dict[str, Any]) -> bool:- if not config.get("ssh_host") or not config.get("ssh_user"):- logger.error(- "SSH backend selected but TERMINAL_SSH_HOST and TERMINAL_SSH_USER "- "are not both set. Configure both or switch TERMINAL_ENV to 'local'."- )- return False- return True---def _check_modal_requirements(config: Dict[str, Any]) -> bool:- modal_state = _get_modal_backend_state(config.get("modal_mode"))- if modal_state["selected_backend"] == "managed":- return True-- if modal_state["selected_backend"] != "direct":- if modal_state["managed_mode_blocked"]:- logger.error(- "Modal backend selected with TERMINAL_MODAL_MODE=managed, but "- "Nous Tool Gateway access is not currently available and no direct "- "Modal credentials/config were found. %s Choose "- "TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials.",- nous_tool_gateway_unavailable_message(- "managed Modal execution",- ),- )- return False- if modal_state["mode"] == "managed":- logger.error(- "Modal backend selected with TERMINAL_MODAL_MODE=managed, but the managed "- "tool gateway is unavailable. %s",- nous_tool_gateway_unavailable_message(- "managed Modal execution",- ),- )- return False- elif modal_state["mode"] == "direct":- if managed_nous_tools_enabled():- logger.error(- "Modal backend selected with TERMINAL_MODAL_MODE=direct, but no direct "- "Modal credentials/config were found. Configure Modal or choose "- "TERMINAL_MODAL_MODE=managed/auto."- )- else:- logger.error(- "Modal backend selected with TERMINAL_MODAL_MODE=direct, but no direct "- "Modal credentials/config were found. Configure Modal or choose "- "TERMINAL_MODAL_MODE=auto."- )- return False- else:- if managed_nous_tools_enabled():- logger.error(- "Modal backend selected but no direct Modal credentials/config or managed "- "tool gateway was found. Configure Modal, set up the managed gateway, "- "or choose a different TERMINAL_ENV."- )- else:- logger.error(- "Modal backend selected but no direct Modal credentials/config was found. "- "Configure Modal or choose a different TERMINAL_ENV."- )- return False-- if importlib.util.find_spec("modal") is None:- logger.error("modal is required for direct modal terminal backend: pip install modal")- return False-- return True---def _check_daytona_requirements(config: Dict[str, Any]) -> bool:- from daytona import Daytona # noqa: F401 — SDK presence check- from agent.secret_scope import get_secret- return get_secret("DAYTONA_API_KEY") is not None---def _check_plugin_requirements(config: Dict[str, Any]) -> bool:- env_type = config["env_type"]- provider = _get_plugin_env_provider(env_type)- if provider is not None:- return bool(provider.check_requirements(config))- logger.error(- "Unknown TERMINAL_ENV '%s'. Use one of: local, docker, singularity, "- "modal, daytona, vercel_sandbox, ssh, or a plugin-registered backend.",- env_type,- )- return False---# Built-in backend -> requirements checker; unknown backends go to the plugin registry.-_REQUIREMENT_CHECKERS = {- "local": lambda config: True,- "docker": _check_docker_requirements,- "singularity": _check_singularity_requirements,- "ssh": _check_ssh_requirements,- "modal": _check_modal_requirements,- "vercel_sandbox": _check_vercel_sandbox_requirements,- "daytona": _check_daytona_requirements,-}--def check_terminal_requirements() -> bool:"""Check if all requirements for the terminal tool are met."""try:diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.pynew file mode 100644index 00000000000..1412b0d2d37--- /dev/null+++ b/tools/terminal_tool_backends.py@@ -0,0 +1,481 @@+"""Execution-environment backends for the terminal tool: per-backend builders (local/docker/singularity/modal/daytona/vercel/ssh/plugin), the config-to-kwargs shapers, and the per-backend requirement checkers, both routed by dispatch table.++Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there,+so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.+"""++import logging+import importlib.util+import inspect+import shutil+import subprocess+from typing import Any, Dict, Optional+from tools.environments.local import LocalEnvironment as _LocalEnvironment+from tools.environments.managed_modal import (+ ManagedModalEnvironment as _ManagedModalEnvironment,+)+from tools.environments.modal import ModalEnvironment as _ModalEnvironment+from tools.environments.singularity import (+ SingularityEnvironment as _SingularityEnvironment,+)+from tools.environments.ssh import SSHEnvironment as _SSHEnvironment+from tools.tool_backend_helpers import (+ has_direct_modal_credentials,+ nous_tool_gateway_unavailable_message,+ resolve_modal_backend_state,+)++# Log-record parity with the origin module.+logger = logging.getLogger("tools.terminal_tool")+++_VERCEL_SANDBOX_DEFAULT_CWD = "/vercel/sandbox"+++_SUPPORTED_VERCEL_RUNTIMES = ("node24", "node22", "python3.13")+++def _is_supported_vercel_runtime(runtime: str) -> bool:+ return not runtime or runtime in _SUPPORTED_VERCEL_RUNTIMES+++def _check_vercel_sandbox_requirements(config: dict[str, Any]) -> bool:+ """Validate Vercel Sandbox terminal backend requirements."""+ runtime = (config.get("vercel_runtime") or "").strip()+ if not _is_supported_vercel_runtime(runtime):+ supported = ", ".join(_SUPPORTED_VERCEL_RUNTIMES)+ logger.error(+ "Vercel Sandbox runtime %r is not supported. "+ "Set TERMINAL_VERCEL_RUNTIME to one of: %s.",+ runtime,+ supported,+ )+ return False++ disk = config.get("container_disk", 51200)+ if disk not in {0, 51200}:+ logger.error(+ "Vercel Sandbox does not support custom TERMINAL_CONTAINER_DISK=%s. "+ "Use the default shared setting (51200 MB).",+ disk,+ )+ return False++ if importlib.util.find_spec("vercel") is None:+ logger.error(+ "vercel is required for the Vercel Sandbox terminal backend: pip install vercel"+ )+ return False++ from agent.secret_scope import get_secret++ has_oidc = bool(get_secret("VERCEL_OIDC_TOKEN"))+ has_token = bool(get_secret("VERCEL_TOKEN"))+ has_project = bool(get_secret("VERCEL_PROJECT_ID"))+ has_team = bool(get_secret("VERCEL_TEAM_ID"))++ if has_oidc:+ return True++ if has_token or has_project or has_team:+ if has_token and has_project and has_team:+ return True+ logger.error(+ "Vercel Sandbox backend selected with token auth, but "+ "VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID must all "+ "be set together. VERCEL_OIDC_TOKEN is supported for one-off "+ "local development only."+ )+ return False++ logger.error(+ "Vercel Sandbox backend selected but no supported auth configuration "+ "was found. Set VERCEL_TOKEN, VERCEL_PROJECT_ID, and VERCEL_TEAM_ID "+ "for normal use. VERCEL_OIDC_TOKEN is supported for one-off local "+ "development only."+ )+ return False+++def _get_modal_backend_state(modal_mode: object | None) -> Dict[str, Any]:+ """Resolve direct vs managed Modal backend selection."""+ from tools.terminal_tool import is_managed_tool_gateway_ready+ return resolve_modal_backend_state(+ modal_mode,+ has_direct=has_direct_modal_credentials(),+ managed_ready=is_managed_tool_gateway_ready("modal"),+ )+++def _ssh_config_from_config(config: Dict[str, Any]) -> dict:+ """``ssh_config`` for :func:`_create_environment` (shared by terminal_tool+ and the lazy :func:`ensure_task_env` bring-up)."""+ return {+ "host": config.get("ssh_host", ""),+ "user": config.get("ssh_user", ""),+ "port": config.get("ssh_port", 22),+ "key": config.get("ssh_key", ""),+ "persistent": config.get("ssh_persistent", False),+ }+++def _container_config_from_config(config: Dict[str, Any]) -> dict:+ """``container_config`` for :func:`_create_environment` (shared by+ terminal_tool and the lazy :func:`ensure_task_env` bring-up)."""+ return {+ "container_cpu": config.get("container_cpu", 1),+ "container_memory": config.get("container_memory", 5120),+ "container_disk": config.get("container_disk", 51200),+ "container_persistent": config.get("container_persistent", True),+ "modal_mode": config.get("modal_mode", "auto"),+ "vercel_runtime": config.get("vercel_runtime", ""),+ "docker_volumes": config.get("docker_volumes", []),+ "docker_mount_cwd_to_workspace": config.get("docker_mount_cwd_to_workspace", False),+ "docker_forward_env": config.get("docker_forward_env", []),+ "docker_env": config.get("docker_env", {}),+ "docker_run_as_host_user": config.get("docker_run_as_host_user", False),+ "docker_extra_args": config.get("docker_extra_args", []),+ "docker_shm_size": config.get("docker_shm_size", "1g"),+ "docker_network": config.get("docker_network", True),+ "docker_persist_across_processes": config.get("docker_persist_across_processes", True),+ "docker_shared_container_key": config.get("docker_shared_container_key", ""),+ "docker_orphan_reaper": config.get("docker_orphan_reaper", True),+ }+++def _resources(cc: Dict[str, Any]) -> dict:+ """Common sandbox resource kwargs (cpu/memory in MB/disk in MB/persistence)."""+ return {+ "cpu": cc.get("container_cpu", 1),+ "memory": cc.get("container_memory", 5120),+ "disk": cc.get("container_disk", 51200),+ "persistent_filesystem": cc.get("container_persistent", True),+ }+++def _build_local_env(*, cwd, timeout, **_):+ return _LocalEnvironment(cwd=cwd, timeout=timeout)+++def _build_docker_env(*, image, cwd, timeout, cc, task_id, host_cwd, **_):+ # One-shot orphan reaper for labeled containers left behind by prior+ # Hermes processes that died before atexit (SIGKILL / OOM / closed+ # terminal); once per process, ``terminal.docker_orphan_reaper: false``+ # disables it.+ from tools.terminal_tool import _DockerEnvironment, _docker_session_isolation_enabled, _has_isolation_overrides, _maybe_reap_docker_orphans+ _maybe_reap_docker_orphans(cc)+ # Per-session container isolation: a session-keyed container must not+ # outlive its session, so cross-process reuse/persist is disabled for it —+ # cleanup_vm()/the idle reaper stop+rm it. The shared "default" container+ # and RL/benchmark override sandboxes keep their existing lifecycle.+ session_scoped = (+ _docker_session_isolation_enabled()+ and task_id != "default"+ and not _has_isolation_overrides(task_id)+ )+ docker_env_obj = _DockerEnvironment(+ image=image, cwd=cwd, timeout=timeout, task_id=task_id,+ **_resources(cc),+ volumes=cc.get("docker_volumes", []),+ host_cwd=host_cwd,+ auto_mount_cwd=cc.get("docker_mount_cwd_to_workspace", False),+ forward_env=cc.get("docker_forward_env", []),+ env=cc.get("docker_env", {}),+ run_as_host_user=cc.get("docker_run_as_host_user", False),+ network=cc.get("docker_network", True),+ extra_args=cc.get("docker_extra_args", []),+ persist_across_processes=(+ False if session_scoped+ else cc.get("docker_persist_across_processes", True)+ ),+ shared_container_key=cc.get("docker_shared_container_key", ""),+ shm_size=cc.get("docker_shm_size", "1g"),+ )+ # Marker read by is_persistent_env(): a session-scoped container survives+ # BETWEEN turns (skip per-turn teardown) but is removed at session close /+ # idle timeout. Guarded: test doubles may not accept attributes.+ if session_scoped:+ try:+ docker_env_obj._session_scoped = True+ except AttributeError:+ pass+ return docker_env_obj+++def _build_singularity_env(*, image, cwd, timeout, cc, task_id, **_):+ return _SingularityEnvironment(+ image=image, cwd=cwd, timeout=timeout, task_id=task_id, **_resources(cc),+ )+++def _build_modal_env(*, image, cwd, timeout, cc, task_id, **_):+ from tools.terminal_tool import managed_nous_tools_enabled+ res = _resources(cc)+ persistent = res["persistent_filesystem"]+ sandbox_kwargs = {k: res[k] for k in ("cpu", "memory") if res[k] > 0}+ if res["disk"] > 0:+ try:+ import modal+ if "ephemeral_disk" in inspect.signature(modal.Sandbox.create).parameters:+ sandbox_kwargs["ephemeral_disk"] = res["disk"]+ except Exception:+ pass++ modal_state = _get_modal_backend_state(cc.get("modal_mode"))++ if modal_state["selected_backend"] == "managed":+ return _ManagedModalEnvironment(+ image=image, cwd=cwd, timeout=timeout,+ modal_sandbox_kwargs=sandbox_kwargs,+ persistent_filesystem=persistent, task_id=task_id,+ )++ if modal_state["selected_backend"] != "direct":+ if modal_state["managed_mode_blocked"]:+ raise ValueError(+ "Modal backend is configured for managed mode, but "+ "Nous Tool Gateway access is not currently available and no direct "+ "Modal credentials/config were found. "+ + nous_tool_gateway_unavailable_message(+ "managed Modal execution",+ )+ + " Choose TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials."+ )+ if modal_state["mode"] == "managed":+ raise ValueError(+ "Modal backend is configured for managed mode, but the managed tool gateway is unavailable. "+ + nous_tool_gateway_unavailable_message(+ "managed Modal execution",+ )+ )+ if modal_state["mode"] == "direct":+ raise ValueError(+ "Modal backend is configured for direct mode, but no direct Modal credentials/config were found."+ )+ message = "Modal backend selected but no direct Modal credentials/config was found."+ if managed_nous_tools_enabled():+ message = (+ "Modal backend selected but no direct Modal credentials/config or managed tool gateway was found."+ )+ raise ValueError(message)++ return _ModalEnvironment(+ image=image, cwd=cwd, timeout=timeout,+ modal_sandbox_kwargs=sandbox_kwargs,+ persistent_filesystem=persistent, task_id=task_id,+ )+++def _build_daytona_env(*, image, cwd, timeout, cc, task_id, **_):+ # Lazy import so daytona SDK is only required when backend is selected.+ from tools.environments.daytona import DaytonaEnvironment as _DaytonaEnvironment+ res = _resources(cc)+ res["cpu"] = int(res["cpu"])+ return _DaytonaEnvironment(image=image, cwd=cwd, timeout=timeout, task_id=task_id, **res)+++def _build_vercel_env(*, cwd, timeout, cc, task_id, **_):+ from tools.environments.vercel_sandbox import (+ VercelSandboxEnvironment as _VercelSandboxEnvironment,+ )+ return _VercelSandboxEnvironment(+ runtime=cc.get("vercel_runtime") or None,+ cwd=cwd, timeout=timeout, task_id=task_id, **_resources(cc),+ )+++def _build_ssh_env(*, cwd, timeout, ssh_config, **_):+ if not ssh_config or not ssh_config.get("host") or not ssh_config.get("user"):+ raise ValueError("SSH environment requires ssh_host and ssh_user to be configured")+ return _SSHEnvironment(+ host=ssh_config["host"],+ user=ssh_config["user"],+ port=ssh_config.get("port", 22),+ key_path=ssh_config.get("key", ""),+ cwd=cwd,+ timeout=timeout,+ )+++def _build_plugin_env(*, env_type, image, cwd, timeout, cc, task_id, **_):+ from tools.terminal_tool import _get_plugin_env_provider+ provider = _get_plugin_env_provider(env_type)+ if provider is not None:+ env_obj = provider.create_environment(+ cwd=cwd, timeout=timeout, task_id=task_id,+ image=image, container_config=cc,+ )+ # Stamp the backend name so path-resolution and progress surfaces+ # can identify plugin backends without class-name sniffing.+ try:+ env_obj._hermes_backend_name = provider.name.strip().lower()+ except AttributeError:+ pass # test doubles may reject attributes+ return env_obj+ try:+ from agent.terminal_env_registry import plugin_backend_names++ plugin_names = plugin_backend_names()+ except Exception:+ plugin_names = []+ extra = (+ ", " + ", ".join(f"'{n}'" for n in plugin_names) if plugin_names else ""+ )+ raise ValueError(+ f"Unknown environment type: {env_type}. Use 'local', 'docker', "+ f"'singularity', 'modal', 'daytona', 'vercel_sandbox', 'ssh'{extra}"+ )+++# Built-in backend -> builder. Anything else is looked up in the plugin registry.+_ENV_BUILDERS = {+ "local": _build_local_env,+ "docker": _build_docker_env,+ "singularity": _build_singularity_env,+ "modal": _build_modal_env,+ "daytona": _build_daytona_env,+ "vercel_sandbox": _build_vercel_env,+ "ssh": _build_ssh_env,+}+++def _create_environment(env_type: str, image: str, cwd: str, timeout: int,+ ssh_config: dict = None, container_config: dict = None,+ local_config: dict = None,+ task_id: str = "default",+ host_cwd: Optional[str] = None):+ """Create an execution environment (instance with ``execute()``) for *env_type*.++ ``image`` is ignored for local/ssh/vercel; ``container_config`` carries the+ container_*/docker_* resource keys; ``host_cwd`` is the host directory to+ bind into Docker when cwd mounting is explicitly enabled. Unknown+ ``env_type`` values fall through to plugin-registered backends.+ """+ builder = _ENV_BUILDERS.get(env_type, _build_plugin_env)+ return builder(+ env_type=env_type, image=image, cwd=cwd, timeout=timeout,+ cc=container_config or {}, task_id=task_id,+ ssh_config=ssh_config, host_cwd=host_cwd,+ )+++def _check_docker_requirements(config: Dict[str, Any]) -> bool:+ from tools.environments.docker import find_docker+ docker = find_docker()+ if not docker:+ logger.error("Docker executable not found in PATH or common install locations")+ return False+ result = subprocess.run([docker, "version"], capture_output=True, timeout=5, stdin=subprocess.DEVNULL)+ return result.returncode == 0+++def _check_singularity_requirements(config: Dict[str, Any]) -> bool:+ executable = shutil.which("apptainer") or shutil.which("singularity")+ if executable:+ result = subprocess.run([executable, "--version"], capture_output=True, timeout=5, stdin=subprocess.DEVNULL)+ return result.returncode == 0+ return False+++def _check_ssh_requirements(config: Dict[str, Any]) -> bool:+ if not config.get("ssh_host") or not config.get("ssh_user"):+ logger.error(+ "SSH backend selected but TERMINAL_SSH_HOST and TERMINAL_SSH_USER "+ "are not both set. Configure both or switch TERMINAL_ENV to 'local'."+ )+ return False+ return True+++def _check_modal_requirements(config: Dict[str, Any]) -> bool:+ from tools.terminal_tool import managed_nous_tools_enabled+ modal_state = _get_modal_backend_state(config.get("modal_mode"))+ if modal_state["selected_backend"] == "managed":+ return True++ if modal_state["selected_backend"] != "direct":+ if modal_state["managed_mode_blocked"]:+ logger.error(+ "Modal backend selected with TERMINAL_MODAL_MODE=managed, but "+ "Nous Tool Gateway access is not currently available and no direct "+ "Modal credentials/config were found. %s Choose "+ "TERMINAL_MODAL_MODE=direct/auto to use direct Modal credentials.",+ nous_tool_gateway_unavailable_message(+ "managed Modal execution",+ ),+ )+ return False+ if modal_state["mode"] == "managed":+ logger.error(+ "Modal backend selected with TERMINAL_MODAL_MODE=managed, but the managed "+ "tool gateway is unavailable. %s",+ nous_tool_gateway_unavailable_message(+ "managed Modal execution",+ ),+ )+ return False+ elif modal_state["mode"] == "direct":+ if managed_nous_tools_enabled():+ logger.error(+ "Modal backend selected with TERMINAL_MODAL_MODE=direct, but no direct "+ "Modal credentials/config were found. Configure Modal or choose "+ "TERMINAL_MODAL_MODE=managed/auto."+ )+ else:+ logger.error(+ "Modal backend selected with TERMINAL_MODAL_MODE=direct, but no direct "+ "Modal credentials/config were found. Configure Modal or choose "+ "TERMINAL_MODAL_MODE=auto."+ )+ return False+ else:+ if managed_nous_tools_enabled():+ logger.error(+ "Modal backend selected but no direct Modal credentials/config or managed "+ "tool gateway was found. Configure Modal, set up the managed gateway, "+ "or choose a different TERMINAL_ENV."+ )+ else:+ logger.error(+ "Modal backend selected but no direct Modal credentials/config was found. "+ "Configure Modal or choose a different TERMINAL_ENV."+ )+ return False++ if importlib.util.find_spec("modal") is None:+ logger.error("modal is required for direct modal terminal backend: pip install modal")+ return False++ return True+++def _check_daytona_requirements(config: Dict[str, Any]) -> bool:+ from daytona import Daytona # noqa: F401 — SDK presence check+ from agent.secret_scope import get_secret+ return get_secret("DAYTONA_API_KEY") is not None+++def _check_plugin_requirements(config: Dict[str, Any]) -> bool:+ from tools.terminal_tool import _get_plugin_env_provider+ env_type = config["env_type"]+ provider = _get_plugin_env_provider(env_type)+ if provider is not None:+ return bool(provider.check_requirements(config))+ logger.error(+ "Unknown TERMINAL_ENV '%s'. Use one of: local, docker, singularity, "+ "modal, daytona, vercel_sandbox, ssh, or a plugin-registered backend.",+ env_type,+ )+ return False+++# Built-in backend -> requirements checker; unknown backends go to the plugin registry.+_REQUIREMENT_CHECKERS = {+ "local": lambda config: True,+ "docker": _check_docker_requirements,+ "singularity": _check_singularity_requirements,+ "ssh": _check_ssh_requirements,+ "modal": _check_modal_requirements,+ "vercel_sandbox": _check_vercel_sandbox_requirements,+ "daytona": _check_daytona_requirements,+}diff --git a/tools/terminal_tool_sudo.py b/tools/terminal_tool_sudo.pynew file mode 100644index 00000000000..786a94a403d--- /dev/null+++ b/tools/terminal_tool_sudo.py@@ -0,0 +1,636 @@+"""Sudo password plumbing and shell-command rewrites for the terminal tool: the per-scope interactive password cache, the /dev/tty prompt, real-sudo tokenizer (sudo -S -p '' rewrite), NOPASSWD probe, and the compound-background brace-group rewrite.++Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there,+so ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before.+"""++import logging+import os+import platform+import re+import subprocess+import sys+import threading+import time+from utils import env_var_enabled++# Log-record parity with the origin module.+logger = logging.getLogger("tools.terminal_tool")+++# Interactive sudo password cache, scoped to the session key when present,+# else callback identity (ACP / CLI), else the current thread — so one+# session can never reuse another's cached password in a long-lived process.+_sudo_password_cache: dict[str, str] = {}+++_sudo_password_cache_lock = threading.Lock()+++def _get_sudo_password_cache_scope() -> str:+ """Return the cache scope for interactive sudo passwords."""+ from tools.terminal_tool import _current_session_key, _get_sudo_password_callback+ session_key = _current_session_key()+ if session_key:+ return f"session:{session_key}"++ callback = _get_sudo_password_callback()+ if callback is not None:+ owner = getattr(callback, "__self__", None)+ func = getattr(callback, "__func__", None)+ if owner is not None and func is not None:+ return f"callback-owner:{id(owner)}:{id(func)}"+ return f"callback:{id(callback)}"++ return f"thread:{threading.get_ident()}"+++def _get_cached_sudo_password() -> str:+ """Return the cached sudo password for the current scope."""+ scope = _get_sudo_password_cache_scope()+ with _sudo_password_cache_lock:+ return _sudo_password_cache.get(scope, "")+++def _set_cached_sudo_password(password: str) -> None:+ """Persist a sudo password for the current scope."""+ scope = _get_sudo_password_cache_scope()+ with _sudo_password_cache_lock:+ if password:+ _sudo_password_cache[scope] = password+ else:+ _sudo_password_cache.pop(scope, None)+++def _reset_cached_sudo_passwords() -> None:+ """Clear all cached sudo passwords (tests / process teardown)."""+ with _sudo_password_cache_lock:+ _sudo_password_cache.clear()+++def _in_delegated_child_context() -> bool:+ """True while running inside a delegate_task child.++ Subagents run on parent-process worker threads and inherit process-wide+ ``HERMES_INTERACTIVE=1``, which does NOT mean this context can reach the+ user: a raw ``/dev/tty`` sudo prompt from a child races the TUI for the+ tty and blocks the child for the full timeout. Children must always be+ headless for sudo prompting. The ContextVar is set by+ ``delegated_child_context()`` and propagates via ``copy_context``.+ """+ 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:+ """Append a SUDO_PASSWORD tip when sudo failed in a headless context+ (gateway session or delegate_task child); otherwise return *output* as is."""+ is_gateway = env_var_enabled("HERMES_GATEWAY_SESSION")+ is_delegated_child = _in_delegated_child_context()++ if not is_gateway and not is_delegated_child:+ return output++ sudo_failures = [+ "sudo: a password is required",+ "sudo: no tty present",+ "sudo: a terminal is required",+ ]++ 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+++# sudo -S rejects a bad cached/interactive password with these messages.+_SUDO_WRONG_PASSWORD_MARKERS = (+ "sudo: authentication failed",+ "sudo: incorrect password attempt",+ "sudo: maximum 3 incorrect authentication attempts",+ "sudo: 3 incorrect password attempts",+)+++def _sudo_wrong_password_failure(output: str) -> bool:+ """Return True when sudo rejected a piped password."""+ if not output:+ return False+ lowered = output.lower()+ return any(marker in lowered for marker in _SUDO_WRONG_PASSWORD_MARKERS)+++def _invalidate_cached_sudo_on_auth_failure(+ command: str | None, output: str+) -> bool:+ """Drop a session-cached sudo password after sudo rejects it.++ Env-configured ``SUDO_PASSWORD`` is left alone — that is an explicit+ operator choice, not an interactive cache entry.+ """+ from tools.terminal_tool import _count_real_sudo_invocations, _sudo_wrong_password_failure+ if "SUDO_PASSWORD" in os.environ:+ return False+ if not _sudo_wrong_password_failure(output):+ return False+ if _count_real_sudo_invocations(command or "") == 0:+ return False+ if not _get_cached_sudo_password():+ return False+ _set_cached_sudo_password("")+ return True+++def _prompt_for_sudo_password(timeout_seconds: int = 45) -> 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. Time spent waiting+ on the human is excluded from tool deadlines via ``human_wait_window``.+ """+ from tools.terminal_tool import _get_sudo_password_callback+ _sudo_cb = _get_sudo_password_callback()+ if _sudo_cb is not None:+ try:+ from tools.approval import human_wait_window+ with human_wait_window():+ return _sudo_cb() or ""+ except Exception:+ return ""++ result = {"password": None, "done": False}++ def read_password_thread():+ """Read password with echo disabled. Uses msvcrt on Windows, /dev/tty on Unix."""+ tty_fd = None+ old_attrs = None+ try:+ if platform.system() == "Windows":+ import msvcrt+ chars = []+ while True:+ c = msvcrt.getwch()+ if c in {"\r", "\n"}:+ break+ if c == "\x03":+ raise KeyboardInterrupt+ chars.append(c)+ result["password"] = "".join(chars)+ else:+ import termios+ tty_fd = os.open("/dev/tty", os.O_RDONLY)+ old_attrs = termios.tcgetattr(tty_fd)+ new_attrs = termios.tcgetattr(tty_fd)+ new_attrs[3] = new_attrs[3] & ~termios.ECHO+ termios.tcsetattr(tty_fd, termios.TCSAFLUSH, new_attrs)+ chars = []+ while True:+ b = os.read(tty_fd, 1)+ if not b or b in {b"\n", b"\r"}:+ break+ chars.append(b)+ result["password"] = b"".join(chars).decode("utf-8", errors="replace")+ except (EOFError, KeyboardInterrupt, OSError):+ result["password"] = ""+ except Exception:+ result["password"] = ""+ finally:+ if tty_fd is not None and old_attrs is not None:+ try:+ import termios as _termios+ _termios.tcsetattr(tty_fd, _termios.TCSAFLUSH, old_attrs)+ except Exception as e:+ logger.debug("Failed to restore terminal attributes: %s", e)+ if tty_fd is not None:+ try:+ os.close(tty_fd)+ except Exception as e:+ logger.debug("Failed to close tty fd: %s", e)+ result["done"] = True++ try:+ os.environ["HERMES_SPINNER_PAUSE"] = "1"+ time.sleep(0.2)++ print()+ print("┌" + "─" * 58 + "┐")+ print("│ 🔐 SUDO PASSWORD REQUIRED" + " " * 30 + "│")+ print("├" + "─" * 58 + "┤")+ print("│ Enter password below (input is hidden), or: │")+ print("│ • Press Enter to skip (command fails gracefully) │")+ print(f"│ • Wait {timeout_seconds}s to auto-skip" + " " * 27 + "│")+ print("└" + "─" * 58 + "┘")+ print()+ print(" Password (hidden): ", end="", flush=True)++ password_thread = threading.Thread(target=read_password_thread, daemon=True)+ password_thread.start()+ from tools.approval import human_wait_window+ with human_wait_window():+ password_thread.join(timeout=timeout_seconds)++ if result["done"]:+ password = result["password"] or ""+ print() # newline after hidden input+ if password:+ print(" ✓ Password received (cached for this session)")+ else:+ print(" ⏭ Skipped - continuing without sudo")+ print()+ sys.stdout.flush()+ return password+ else:+ print("\n ⏱ Timeout - continuing without sudo")+ print(" (Press Enter to dismiss)")+ print()+ sys.stdout.flush()+ return ""++ except (EOFError, KeyboardInterrupt):+ print()+ print(" ⏭ Cancelled - continuing without sudo")+ print()+ sys.stdout.flush()+ return ""+ except Exception as e:+ print(f"\n [sudo prompt error: {e}] - continuing without sudo\n")+ sys.stdout.flush()+ return ""+ finally:+ if "HERMES_SPINNER_PAUSE" in os.environ:+ del os.environ["HERMES_SPINNER_PAUSE"]+++def _looks_like_env_assignment(token: str) -> bool:+ """Return True when *token* is a leading shell environment assignment."""+ if "=" not in token or token.startswith("="):+ return False+ name, _value = token.split("=", 1)+ return bool(re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name))+++def _read_shell_token(command: str, start: int) -> tuple[str, int]:+ """Read one shell token, preserving quotes/escapes, starting at *start*."""+ i = start+ n = len(command)++ while i < n:+ ch = command[i]+ if ch.isspace() or ch in ";|&()":+ break+ if ch == "'":+ i += 1+ while i < n and command[i] != "'":+ i += 1+ if i < n:+ i += 1+ continue+ if ch == '"':+ i += 1+ while i < n:+ inner = command[i]+ if inner == "\\" and i + 1 < n:+ i += 2+ continue+ if inner == '"':+ i += 1+ break+ i += 1+ continue+ if ch == "\\" and i + 1 < n:+ i += 2+ continue+ i += 1++ return command[start:i], i+++def _rewrite_real_sudo_invocations(command: str) -> tuple[str, int]:+ """Rewrite only real unquoted sudo command words, not plain text mentions.++ Walks the command with the shared tokenizer, tracking whether the cursor+ sits at a command-start position (after newline, ``;``/``|``/``&``/``(``,+ ``&&``/``||``/``;;``, or a leading ``VAR=val`` assignment); comments at+ command start are copied through verbatim. Returns the rewritten command+ and the number of sudo invocations rewritten.+ """+ out: list[str] = []+ i = 0+ n = len(command)+ command_start = True+ sudo_count = 0++ while i < n:+ ch = command[i]++ if ch.isspace():+ out.append(ch)+ if ch == "\n":+ command_start = True+ i += 1+ continue++ if ch == "#" and command_start:+ comment_end = command.find("\n", i)+ if comment_end == -1:+ out.append(command[i:])+ break+ out.append(command[i:comment_end])+ i = comment_end+ continue++ if command.startswith(("&&", "||", ";;"), i):+ out.append(command[i:i + 2])+ i += 2+ command_start = True+ continue++ if ch in ";|&(":+ out.append(ch)+ i += 1+ command_start = True+ continue++ if ch == ")":+ out.append(ch)+ i += 1+ command_start = False+ continue++ token, next_i = _read_shell_token(command, i)+ if command_start and token == "sudo":+ out.append("sudo -S -p ''")+ sudo_count += 1+ else:+ out.append(token)++ command_start = bool(command_start and _looks_like_env_assignment(token))+ i = next_i++ return "".join(out), sudo_count+++def _count_real_sudo_invocations(command: str) -> int:+ """Return how many real sudo command words appear in *command*."""+ return _rewrite_real_sudo_invocations(command)[1]+++def _sudo_nopasswd_works() -> bool:+ """True when local sudo currently works without prompting.++ Local backend only — Docker/SSH/Modal must not inherit host sudo state.+ Re-probes every call (no cache) so an expired sudo timestamp can't make a+ later command silently block waiting for a password.+ """+ from tools.terminal_tool import _tenv+ terminal_env = _tenv("TERMINAL_ENV", "local").strip().lower() or "local"+ if terminal_env != "local":+ return False++ try:+ probe = subprocess.run(+ ["sudo", "-n", "true"],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ timeout=3,+ check=False,+ )+ return probe.returncode == 0+ except Exception:+ return False+++def _rewrite_compound_background(command: str) -> str:+ """Wrap `A && B &` (or `A || B &`) to `A && { B & }` at depth 0.++ Bash binds `&&` tighter than `&`, so `A && B &` backgrounds a subshell+ that runs B in the foreground and waits for it; a long-running B leaves+ that subshell stuck in ``wait4`` forever, and its open stdout pipe can+ keep the terminal tool from returning. The brace group keeps `&&`'s+ skip-B-on-failure semantics without a fork: bash backgrounds B as a+ simple command and exits immediately, orphaning B normally.++ Handles redirects (``&>``, ``2>&1``) and skips quoted strings and+ parenthesised subshells. Simple ``cmd &`` is left alone — it doesn't+ have the subshell-wait bug.+ """+ n = len(command)+ i = 0+ paren_depth = 0+ brace_depth = 0+ # Position in *command* just after the most recent `&&` / `||` at depth 0+ # in the current statement; -1 when no chain operator is active.+ last_chain_op_end = -1+ rewrites: list[tuple[int, int]] = [] # (chain_op_end, amp_pos)++ while i < n:+ ch = command[i]++ # Newline terminates a statement at depth 0 — reset chain state.+ # Checked before the whitespace skip so we don't miss it.+ if ch == "\n" and paren_depth == 0 and brace_depth == 0:+ last_chain_op_end = -1+ i += 1+ continue++ if ch.isspace():+ i += 1+ continue++ # Comments (only at statement start — conservative: any `#` not inside+ # a token ends the line). `_read_shell_token` handles quoted strings+ # below so `#` inside quotes is safe.+ if ch == "#":+ nl = command.find("\n", i)+ if nl == -1:+ break+ i = nl+ continue++ if ch == "\\" and i + 1 < n:+ i += 2+ continue++ # Quoted tokens — consume whole string via the shared tokenizer.+ if ch in {"'", '"'}:+ _, next_i = _read_shell_token(command, i)+ i = max(next_i, i + 1)+ continue++ if ch == "(":+ paren_depth += 1+ i += 1+ continue++ if ch == ")":+ paren_depth = max(0, paren_depth - 1)+ i += 1+ continue++ # Brace groups: `{ ... }` is a group (no subshell fork), and bash+ # requires whitespace after `{`. We track depth so already-rewritten+ # output (`A && { B & }`) is idempotent — the inner `&` is part of+ # the group, not a new compound to rewrite. Also skip content inside+ # the group since `A && B &` there is separately well-formed.+ if ch == "{" and i + 1 < n and (command[i + 1].isspace() or command[i + 1] == "\n"):+ brace_depth += 1+ i += 1+ continue+ if ch == "}" and brace_depth > 0:+ brace_depth -= 1+ # Closing a group completes a compound statement; reset chain.+ last_chain_op_end = -1+ i += 1+ continue++ # Inside parens or brace groups, skip operators — they parse in their+ # own scope. `(...)` subshells have the same bug class but are not the+ # common agent pattern; leave for a follow-up.+ if paren_depth > 0 or brace_depth > 0:+ i += 1+ continue++ # Chain operators at depth 0+ if command.startswith("&&", i) or command.startswith("||", i):+ last_chain_op_end = i + 2+ i += 2+ continue++ # Statement terminators reset the chain state+ if ch == ";":+ last_chain_op_end = -1+ i += 1+ continue++ # Single `|` (pipe) starts a new pipeline stage; don't rewrite+ # across it. `||` handled above.+ if ch == "|":+ last_chain_op_end = -1+ i += 1+ continue++ # `&` handling: distinguish `&&`, `&>`, fd redirect (`>&`, `<&`),+ # and a true backgrounding `&`.+ if ch == "&":+ # `&&` handled above; won't reach here+ if i + 1 < n and command[i + 1] == ">":+ # `&>` redirect — consume+ i += 2+ continue+ # `>&` / `<&` fd target — look back past whitespace+ j = i - 1+ while j >= 0 and command[j].isspace():+ j -= 1+ if j >= 0 and command[j] in "<>":+ i += 1+ continue+ # Real background operator+ if last_chain_op_end >= 0:+ rewrites.append((last_chain_op_end, i))+ last_chain_op_end = -1+ i += 1+ continue++ # Regular unquoted token — advance past it via the shared tokenizer+ _, next_i = _read_shell_token(command, i)+ i = max(next_i, i + 1)++ if not rewrites:+ return command++ # Apply rewrites back-to-front so earlier indices remain valid.+ result = command+ for chain_end, amp_pos in reversed(rewrites):+ # Skip whitespace right after the `&&`/`||` so the brace group+ # opens flush against the inner command.+ insert_pos = chain_end+ while insert_pos < amp_pos and result[insert_pos].isspace():+ insert_pos += 1+ prefix = result[:insert_pos]+ middle = result[insert_pos:amp_pos] # inner command + trailing space+ suffix = result[amp_pos + 1 :]+ # `{` needs a trailing space in bash; the closing `}` needs to be+ # preceded by `;` or `&` — we're providing `&` from the backgrounding.+ result = prefix + "{ " + middle + "& }" + suffix++ return result+++def _transform_sudo_command(command: str | None) -> tuple[str | None, str | None]:+ """Rewrite bare ``sudo`` to ``sudo -S -p ''`` when a password is available.++ Shared by every execution environment. Returns ``(command, sudo_stdin)``:+ ``sudo_stdin`` is one password line per sudo invocation that the caller+ must PREPEND to the process stdin (sudo -S consumes exactly one line and+ passes the rest through, so it's safe alongside the caller's own+ stdin_data). Backends that can't pipe stdin (modal, daytona,+ vercel_sandbox) embed the password in the command string themselves.+ With no password available the command is returned unchanged and+ ``sudo_stdin`` is None, so it fails gracefully with+ "sudo: a password is required". Password sources, in order: configured+ SUDO_PASSWORD, the session cache, then an interactive prompt (45s+ timeout, cached on success) when a UI is reachable.+ """+ from tools.terminal_tool import _get_sudo_password_callback, _prompt_for_sudo_password, _sudo_nopasswd_works+ if command is None:+ return None, None+ transformed, sudo_count = _rewrite_real_sudo_invocations(command)+ if sudo_count == 0:+ return command, None++ # Scope-aware read: under multiplex the process env may hold another+ # profile's SUDO_PASSWORD; unscoped callers keep the os.environ read.+ try:+ from agent.secret_scope import UnscopedSecretError, get_secret++ try:+ _configured_password = get_secret("SUDO_PASSWORD")+ except UnscopedSecretError:+ _configured_password = os.environ.get("SUDO_PASSWORD")+ except Exception:+ _configured_password = os.environ.get("SUDO_PASSWORD")+ has_configured_password = _configured_password is not None+ sudo_password = (+ _configured_password+ if has_configured_password+ else _get_cached_sudo_password()+ )++ # sudoers NOPASSWD hosts must not be forced through the prompt or the+ # -S password pipe (local backend only; re-probed every call).+ if not has_configured_password and not sudo_password and _sudo_nopasswd_works():+ return command, None++ has_sudo_prompt_callback = _get_sudo_password_callback() is not None+ # 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 — they always behave as headless; configured password,+ # session cache and the NOPASSWD probe still apply.+ 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:+ _set_cached_sudo_password(sudo_password)++ if has_configured_password or sudo_password:+ # Trailing newline is required: sudo -S reads one line per invocation.+ # Compound commands (`sudo a && sudo b`) need one password line each.+ password_line = sudo_password + "\n"+ return transformed, password_line * sudo_count++ return command, None