From 21c703797595cc19e3b16e68010d78801127a5f7 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:31:31 -0700 Subject: [PATCH 01/10] refactor(terminal): extract sudo/shell-rewrite cluster to terminal_tool_sudo and backend builders/checkers to terminal_tool_backends --- tests/tools/test_terminal_requirements.py | 18 +- .../tools/test_terminal_tool_requirements.py | 6 +- tools/terminal_tool.py | 1130 +---------------- tools/terminal_tool_backends.py | 481 +++++++ tools/terminal_tool_sudo.py | 636 ++++++++++ 5 files changed, 1184 insertions(+), 1087 deletions(-) create mode 100644 tools/terminal_tool_backends.py create mode 100644 tools/terminal_tool_sudo.py diff --git a/tests/tools/test_terminal_requirements.py b/tests/tools/test_terminal_requirements.py index 4923d6320a..416d7b8530 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(monkey def 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, capl monkeypatch.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.py index bdf85c9d04..025b21fb4a 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.py index d4987d5d4c..7732ef7660 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.util import inspect import json import logging import os -import platform -import re -import sys import time import threading import atexit import shutil -import subprocess from dataclasses import dataclass from pathlib import Path from 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-exported from tools.registry import tool_error +from tools.terminal_tool_backends import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.) + _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.) + _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.py new file mode 100644 index 0000000000..1412b0d2d3 --- /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.`` 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.py new file mode 100644 index 0000000000..786a94a403 --- /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.`` 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 From 7cfc90bae84732bc38df0bc45b8c5120708331cc Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:36:30 -0700 Subject: [PATCH 02/10] refactor(terminal): split terminal_tool() into _plan_execution/_acquire_env/_run_foreground (dataclass plan) and unify the error envelope via _error_json --- tools/terminal_tool.py | 507 ++++++++++++++++++++++------------------- 1 file changed, 274 insertions(+), 233 deletions(-) diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index 7732ef7660..b98e6caf7a 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -1237,6 +1237,15 @@ def _resolve_command_cwd( return recorded or default_cwd +def _error_json(error: str, *, exit_code: int = -1, status: Optional[str] = None, **extra) -> str: + """The terminal error envelope: ``output``/``exit_code``/``error`` (+ ``status``, extras).""" + body: Dict[str, Any] = {"output": "", "exit_code": exit_code, "error": error} + if status is not None: + body["status"] = status + body.update(extra) + return json.dumps(body, ensure_ascii=False) + + @dataclass class _ApprovalVerdict: """Outcome of the pre-exec guard pass. @@ -1262,37 +1271,30 @@ def _run_approval_guards(command: str, env_type: str, config: Dict[str, Any], *, ) if not approval["approved"]: if approval.get("status") == "pending_approval": # gateway ask mode - return _ApprovalVerdict(blocked_json=json.dumps({ - "output": "", - "exit_code": -1, - "error": "", - "status": "pending_approval", - "approval_pending": True, - "command": approval.get("command", command), - "description": approval.get("description", "command flagged"), - "pattern_key": approval.get("pattern_key", ""), - "smart_denied": approval.get("smart_denied", False), - "allow_permanent": approval.get("allow_permanent", True), - }, ensure_ascii=False)) + return _ApprovalVerdict(blocked_json=_error_json( + "", status="pending_approval", + approval_pending=True, + command=approval.get("command", command), + description=approval.get("description", "command flagged"), + pattern_key=approval.get("pattern_key", ""), + smart_denied=approval.get("smart_denied", False), + allow_permanent=approval.get("allow_permanent", True), + )) desc = approval.get("description", "command flagged") fallback_msg = ( f"Command denied: {desc}. " "Use the approval prompt to allow it, or rephrase the command." ) - return _ApprovalVerdict(blocked_json=json.dumps({ - "output": "", - "exit_code": -1, - "error": approval.get("message", fallback_msg), - "status": "blocked" - }, ensure_ascii=False)) + return _ApprovalVerdict(blocked_json=_error_json( + approval.get("message", fallback_msg), status="blocked", + )) + desc = approval.get("description", "flagged as dangerous") if approval.get("user_approved"): - desc = approval.get("description", "flagged as dangerous") return _ApprovalVerdict( note=f"Command required approval ({desc}) and was approved by the user.", approved_run=True, ) if approval.get("smart_approved"): - desc = approval.get("description", "flagged as dangerous") return _ApprovalVerdict( note=f"Command was flagged ({desc}) and auto-approved by smart approval.", ) @@ -1317,6 +1319,240 @@ def _fatal_error_json(e: BaseException) -> str: }, ensure_ascii=False) +@dataclass +class _ExecPlan: + """Per-call execution parameters resolved before any environment is touched.""" + config: Dict[str, Any] + env_type: str + effective_task_id: str + image: str + cwd: str + host_cwd: Optional[str] + effective_timeout: int + + +def _plan_execution( + command: Any, *, task_id: Optional[str], timeout: Optional[int], + background: bool, _host_local: bool, +) -> "_ExecPlan | str": + """Resolve backend, env-cache key, image, cwd and timeout for one call. + + Returns the finished error JSON instead of a plan when the call is rejected + up front (non-string command, non-positive or over-cap timeout, a + foreground command that must run in the background). + """ + if not isinstance(command, str): + logger.warning( + "Rejected invalid terminal command value: %s", + type(command).__name__, + ) + return _error_json( + f"Invalid command: expected string, got {type(command).__name__}", + status="error", + ) + + config = _get_env_config() + env_type = "local" if _host_local else config["env_type"] + + # Fail closed under a refusal scope: the routed profile's terminal + # policy could not be resolved, so running with the launch process's + # ambient policy is forbidden. + if not _host_local: + from tools.terminal_scope import enforce_no_refusal + + enforce_no_refusal() + + effective_task_id = _resolve_container_task_id(task_id) + if _host_local: + # Control-plane children run beside this interpreter, never inside + # the configured Docker/SSH backend; keep their env cache separate. + effective_task_id = f"host-local-{effective_task_id}" + + # Per-task overrides (RL/benchmark envs, ACP workspace cwd) win over + # the global env-var config; ``resolve_task_overrides`` reads the raw + # task id first, then the collapsed container id. + overrides = resolve_task_overrides(task_id) + image = _select_image(env_type, overrides, config) + + cwd = overrides.get("cwd") or get_session_cwd(task_id) or config["cwd"] + host_cwd = _resolve_task_host_cwd(config, task_id) + # config["cwd"] was sanitized for container backends in _get_env_config + # but an override / session record is raw: a host path would reach + # `docker run -w` and fail with exit 125. Re-apply the guard to the + # resolved cwd; when the host path IS this session's mounted workspace, + # remap to /workspace instead of discarding it. + if _is_container_backend(env_type) and _is_unusable_container_cwd(cwd): + remapped = "/workspace" if host_cwd else config["cwd"] + if cwd != remapped: + logger.info( + "Remapping host/relative cwd override %r for %s backend " + "(won't exist in sandbox). Using %r instead.", + cwd, env_type, remapped, + ) + cwd = remapped + # Reject non-positive timeouts before deadline math: ``timeout or + # default`` would silently turn 0 into the default, and a negative + # value is truthy and would fire an immediate "-Ns" timeout. + if timeout is not None and timeout <= 0: + return tool_error( + f"timeout must be a positive number of seconds (got {timeout})." + ) + effective_timeout = timeout or config["timeout"] + + if not background and timeout and timeout > FOREGROUND_MAX_TIMEOUT: + return tool_error( + f"Foreground timeout {timeout}s exceeds the maximum of " + f"{FOREGROUND_MAX_TIMEOUT}s. Use background=true with " + f"notify_on_complete=true for long-running commands." + ) + + if not background: + guidance = _foreground_background_guidance(command) + if guidance: + return _error_json(guidance, status="error") + + return _ExecPlan( + config=config, env_type=env_type, effective_task_id=effective_task_id, + image=image, cwd=cwd, host_cwd=host_cwd, effective_timeout=effective_timeout, + ) + + +def _acquire_env(plan: _ExecPlan, task_id: Optional[str]) -> Any: + """Cached env for the task, else create it under the per-task creation lock. + + Concurrent calls for the same task_id wait for the first sandbox instead + of each creating their own; the cache is re-checked under that lock. + Returns the ``"disabled"`` error JSON (a str) when creation raises + ImportError. + """ + _start_cleanup_thread() + env_type, eff = plan.env_type, plan.effective_task_id + + with _env_lock: + env: Any = _lookup_active_env(eff, task_id) + if env is not None: + return env + + with _creation_locks_lock: + task_lock = _creation_locks.setdefault(eff, threading.Lock()) + + with task_lock: + with _env_lock: + env = _lookup_active_env(eff, task_id) + if env is not None: + return env + + if env_type == "singularity": + _check_disk_usage_warning() + logger.info("Creating new %s environment for task %s...", env_type, eff[:8]) + try: + new_env = _create_environment( + env_type=env_type, + image=plan.image, + cwd=plan.cwd, + timeout=plan.effective_timeout, + ssh_config=_ssh_config_from_config(plan.config) if env_type == "ssh" else None, + container_config=( + _container_config_from_config(plan.config) + if _is_container_backend(env_type) else None + ), + local_config=( + {"persistent": plan.config.get("local_persistent", False)} + if env_type == "local" else None + ), + task_id=eff, + host_cwd=plan.host_cwd, + ) + except ImportError as e: + return _error_json( + _redact_terminal_error_text( + f"Terminal tool disabled: environment creation failed ({e})" + ), + status="disabled", + ) + + with _env_lock: + _active_environments[eff] = new_env + _last_activity[eff] = time.time() + logger.info("%s environment ready for task %s", env_type, eff[:8]) + return new_env + + +def _run_foreground( + command: str, env: Any, plan: _ExecPlan, *, + task_id: Optional[str], session_id: Optional[str], session_key: str, + workdir: Optional[str], approval_note: Optional[str], clear_interrupt: bool, +) -> str: + """Execute in the foreground with retry on transient errors, then finalize.""" + max_retries = 3 + retry_count = 0 + result = None + command_cwd = None + env_type, eff, effective_timeout = plan.env_type, plan.effective_task_id, plan.effective_timeout + + # Clean interrupt slate for an approved command, ONCE before the retry + # loop: drop a stale bit that landed during the approval-wait so it + # can't SIGINT the just-approved run. Do NOT re-clear inside the loop — + # a genuine interrupt during the backoff sleep must survive and abort + # the next attempt (rc 130). + if clear_interrupt: + from tools.interrupt import clear_current_thread_interrupt + clear_current_thread_interrupt() + + while retry_count <= max_retries: + try: + command_cwd = _resolve_command_cwd( + workdir=workdir, + default_cwd=plan.cwd, + session_key=session_key, + env_type=env_type, + ) + # bounded_capture: model-facing output keeps a head/tail window + # while streaming so a verbose command can't OOM the gateway; + # internal env.execute() consumers stay unbounded. + result = env.execute( + command, timeout=effective_timeout, cwd=command_cwd, + bounded_capture=True, + ) + except Exception as e: + error_str = str(e).lower() + if "timeout" in error_str: + return _error_json( + f"Command timed out after {effective_timeout} seconds", exit_code=124, + ) + + # Retry on transient errors + if retry_count < max_retries: + retry_count += 1 + wait_time = 2 ** retry_count + logger.warning("Execution error, retrying in %ds (attempt %d/%d) - Command: %s - Error: %s: %s - Task: %s, Backend: %s", + wait_time, retry_count, max_retries, _safe_command_preview(command), type(e).__name__, e, eff, env_type) + time.sleep(wait_time) + continue + + logger.error("Execution failed after %d retries - Command: %s - Error: %s: %s - Task: %s, Backend: %s", + max_retries, _safe_command_preview(command), type(e).__name__, e, eff, env_type) + return _error_json(_redact_terminal_error_text( + f"Command execution failed: {type(e).__name__}: {e}" + )) + + break + + return finalize_foreground_result( + command=command, + result=result, + env=env, + env_type=env_type, + effective_task_id=eff, + task_id=task_id, + session_id=session_id, + session_key=session_key, + workdir=workdir, + command_cwd=command_cwd, + approval_note=approval_note, + ) + + def terminal_tool( command: str, background: bool = False, @@ -1344,138 +1580,16 @@ def terminal_tool( children (kept in a separate env cache from the configured backend). """ try: - if not isinstance(command, str): - logger.warning( - "Rejected invalid terminal command value: %s", - type(command).__name__, - ) - return json.dumps({ - "output": "", - "exit_code": -1, - "error": f"Invalid command: expected string, got {type(command).__name__}", - "status": "error", - }, ensure_ascii=False) - - config = _get_env_config() - env_type = "local" if _host_local else config["env_type"] - - # Fail closed under a refusal scope: the routed profile's terminal - # policy could not be resolved, so running with the launch process's - # ambient policy is forbidden. - if not _host_local: - from tools.terminal_scope import enforce_no_refusal - - enforce_no_refusal() - - effective_task_id = _resolve_container_task_id(task_id) - if _host_local: - # Control-plane children run beside this interpreter, never inside - # the configured Docker/SSH backend; keep their env cache separate. - effective_task_id = f"host-local-{effective_task_id}" - - # Per-task overrides (RL/benchmark envs, ACP workspace cwd) win over - # the global env-var config; ``resolve_task_overrides`` reads the raw - # task id first, then the collapsed container id. - overrides = resolve_task_overrides(task_id) - image = _select_image(env_type, overrides, config) - - cwd = overrides.get("cwd") or get_session_cwd(task_id) or config["cwd"] - host_cwd = _resolve_task_host_cwd(config, task_id) - # config["cwd"] was sanitized for container backends in _get_env_config - # but an override / session record is raw: a host path would reach - # `docker run -w` and fail with exit 125. Re-apply the guard to the - # resolved cwd; when the host path IS this session's mounted workspace, - # remap to /workspace instead of discarding it. - if _is_container_backend(env_type) and _is_unusable_container_cwd(cwd): - remapped = "/workspace" if host_cwd else config["cwd"] - if cwd != remapped: - logger.info( - "Remapping host/relative cwd override %r for %s backend " - "(won't exist in sandbox). Using %r instead.", - cwd, env_type, remapped, - ) - cwd = remapped - # Reject non-positive timeouts before deadline math: ``timeout or - # default`` would silently turn 0 into the default, and a negative - # value is truthy and would fire an immediate "-Ns" timeout. - if timeout is not None and timeout <= 0: - return tool_error( - f"timeout must be a positive number of seconds (got {timeout})." - ) - effective_timeout = timeout or config["timeout"] - - if not background and timeout and timeout > FOREGROUND_MAX_TIMEOUT: - return tool_error( - f"Foreground timeout {timeout}s exceeds the maximum of " - f"{FOREGROUND_MAX_TIMEOUT}s. Use background=true with " - f"notify_on_complete=true for long-running commands." - ) - - if not background: - guidance = _foreground_background_guidance(command) - if guidance: - return json.dumps({ - "output": "", - "exit_code": -1, - "error": guidance, - "status": "error", - }, ensure_ascii=False) - - _start_cleanup_thread() - - # Get or create environment. A per-task creation lock makes concurrent - # calls for the same task_id wait for the first sandbox instead of each - # creating their own; the cache is re-checked under that lock. - with _env_lock: - env: Any = _lookup_active_env(effective_task_id, task_id) - - if env is None: - with _creation_locks_lock: - task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock()) - - with task_lock: - with _env_lock: - env = _lookup_active_env(effective_task_id, task_id) - - if env is None: - if env_type == "singularity": - _check_disk_usage_warning() - logger.info("Creating new %s environment for task %s...", env_type, effective_task_id[:8]) - try: - new_env = _create_environment( - env_type=env_type, - image=image, - cwd=cwd, - timeout=effective_timeout, - ssh_config=_ssh_config_from_config(config) if env_type == "ssh" else None, - container_config=( - _container_config_from_config(config) - if _is_container_backend(env_type) else None - ), - local_config=( - {"persistent": config.get("local_persistent", False)} - if env_type == "local" else None - ), - task_id=effective_task_id, - host_cwd=host_cwd, - ) - except ImportError as e: - return json.dumps({ - "output": "", - "exit_code": -1, - "error": _redact_terminal_error_text( - f"Terminal tool disabled: environment creation failed ({e})" - ), - "status": "disabled" - }, ensure_ascii=False) - - with _env_lock: - _active_environments[effective_task_id] = new_env - _last_activity[effective_task_id] = time.time() - env = new_env - logger.info("%s environment ready for task %s", env_type, effective_task_id[:8]) - - assert env is not None # all creation failure paths return above + plan = _plan_execution( + command, task_id=task_id, timeout=timeout, + background=background, _host_local=_host_local, + ) + if isinstance(plan, str): + return plan + env = _acquire_env(plan, task_id) + if isinstance(env, str): + return env + env_type, cwd, effective_task_id = plan.env_type, plan.cwd, plan.effective_task_id # Session key for cwd records: the contextvar doesn't cross tool-worker # threads, so fall back to the raw task_id (the top-level agent's @@ -1496,12 +1610,7 @@ def terminal_tool( if workdir_error: logger.warning("Blocked dangerous workdir: %s (command: %s)", workdir[:200], _safe_command_preview(command)) - return json.dumps({ - "output": "", - "exit_code": -1, - "error": workdir_error, - "status": "blocked" - }, ensure_ascii=False) + return _error_json(workdir_error, status="blocked") if env_type == "local": blocked = self_repo_block( @@ -1512,10 +1621,9 @@ def terminal_tool( # Pre-exec security checks (tirith + dangerous command detection); # force=True means the user already confirmed. - verdict = _run_approval_guards(command, env_type, config, force=force) + verdict = _run_approval_guards(command, env_type, plan.config, force=force) if verdict.blocked_json: return verdict.blocked_json - approval_note = verdict.note pty_disabled_reason = None effective_pty = pty @@ -1541,81 +1649,14 @@ def terminal_tool( effective_pty=effective_pty, notify_on_complete=notify_on_complete, watch_patterns=watch_patterns, - approval_note=approval_note, + approval_note=verdict.note, pty_disabled_reason=pty_disabled_reason, ) - # Foreground: run with retry on transient errors. - max_retries = 3 - retry_count = 0 - result = None - command_cwd = None - - # Clean interrupt slate for an approved command, ONCE before the retry - # loop: drop a stale bit that landed during the approval-wait so it - # can't SIGINT the just-approved run. Do NOT re-clear inside the loop — - # a genuine interrupt during the backoff sleep must survive and abort - # the next attempt (rc 130). - if verdict.approved_run: - from tools.interrupt import clear_current_thread_interrupt - clear_current_thread_interrupt() - - while retry_count <= max_retries: - try: - command_cwd = _resolve_command_cwd( - workdir=workdir, - default_cwd=cwd, - session_key=session_key, - env_type=env_type, - ) - # bounded_capture: model-facing output keeps a head/tail window - # while streaming so a verbose command can't OOM the gateway; - # internal env.execute() consumers stay unbounded. - result = env.execute( - command, timeout=effective_timeout, cwd=command_cwd, - bounded_capture=True, - ) - except Exception as e: - error_str = str(e).lower() - if "timeout" in error_str: - return json.dumps({ - "output": "", - "exit_code": 124, - "error": f"Command timed out after {effective_timeout} seconds" - }, ensure_ascii=False) - - # Retry on transient errors - if retry_count < max_retries: - retry_count += 1 - wait_time = 2 ** retry_count - logger.warning("Execution error, retrying in %ds (attempt %d/%d) - Command: %s - Error: %s: %s - Task: %s, Backend: %s", - wait_time, retry_count, max_retries, _safe_command_preview(command), type(e).__name__, e, effective_task_id, env_type) - time.sleep(wait_time) - continue - - logger.error("Execution failed after %d retries - Command: %s - Error: %s: %s - Task: %s, Backend: %s", - max_retries, _safe_command_preview(command), type(e).__name__, e, effective_task_id, env_type) - return json.dumps({ - "output": "", - "exit_code": -1, - "error": _redact_terminal_error_text( - f"Command execution failed: {type(e).__name__}: {e}" - ) - }, ensure_ascii=False) - - break - - return finalize_foreground_result( - command=command, - result=result, - env=env, - env_type=env_type, - effective_task_id=effective_task_id, - task_id=task_id, - session_id=session_id, - session_key=session_key, - workdir=workdir, - command_cwd=command_cwd, - approval_note=approval_note, + return _run_foreground( + command, env, plan, + task_id=task_id, session_id=session_id, session_key=session_key, + workdir=workdir, approval_note=verdict.note, + clear_interrupt=verdict.approved_run, ) except EnvironmentConnectionError as e: From 17df4741df608066e2a4ae0b37a39486efcfa770 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:42:26 -0700 Subject: [PATCH 03/10] refactor(terminal): extract scope-aware TERMINAL_* config readers/cwd sanitizers to terminal_tool_config --- tools/terminal_tool.py | 101 ++++----------------------------- tools/terminal_tool_config.py | 103 ++++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 89 deletions(-) create mode 100644 tools/terminal_tool_config.py diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index b98e6caf7a..f45c5b2473 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -43,6 +43,18 @@ 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-exported from tools.registry import tool_error +from tools.terminal_tool_config import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.) + _CONTAINER_BACKENDS, + _HOST_CWD_PREFIXES, + _get_plugin_env_provider, + _is_container_backend, + _is_unusable_container_cwd, + _parse_env_var, + _plugin_env_flag, + _safe_getcwd, + _tenv, + _tenv_bool, +) from tools.terminal_tool_backends import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.) _ENV_BUILDERS, _REQUIREMENT_CHECKERS, @@ -627,95 +639,6 @@ def _resolve_task_host_cwd(config: Dict[str, Any], task_id: Optional[str]) -> Op return candidate -def _parse_env_var(name: str, default: str, converter: Any = int, type_label: str = "integer"): - """Parse an env var with *converter*, raising a clear ValueError on bad - values (e.g. TERMINAL_TIMEOUT=5m) instead of an opaque crash. TERMINAL_* - names are read scope-aware via :func:`_tenv`.""" - raw = os.getenv(name, default) - if name.startswith("TERMINAL_"): - raw = _tenv(name, default) - try: - return converter(raw) - except (ValueError, json.JSONDecodeError): - raise ValueError( - f"Invalid value for {name}: {raw!r} (expected {type_label}). " - f"Check ~/.hermes/.env or environment variables." - ) - - -def _safe_getcwd() -> str: - """``os.getcwd()`` tolerant of a deleted cwd (FileNotFoundError) or a macOS - TCC-protected one without Full Disk Access (PermissionError); falls back - to TERMINAL_CWD, then the home directory.""" - try: - return os.getcwd() - except (FileNotFoundError, PermissionError): - return _tenv("TERMINAL_CWD") or os.path.expanduser("~") - - -# Host-cwd prefixes that cannot exist inside a container sandbox (POSIX user -# dirs and Windows drive paths as they leak toward a Linux ``-w`` flag). -_HOST_CWD_PREFIXES = ("/Users/", "/home/", "C:\\", "C:/") - -_CONTAINER_BACKENDS = frozenset({"docker", "singularity", "modal", "daytona", "vercel_sandbox"}) - - -def _plugin_env_flag(env_type: str, attr: str, default=False): - """Classification flag of a plugin-registered backend. Fail-soft: *default* - when the registry is unavailable, the backend unknown, or the provider - raises — a misbehaving plugin must never take the terminal tool down.""" - if not env_type or env_type in _CONTAINER_BACKENDS or env_type in {"local", "ssh", "managed_modal"}: - return default - try: - from agent.terminal_env_registry import provider_flag - - return provider_flag(env_type, attr, default) - except Exception: - return default - - -def _is_container_backend(env_type: str) -> bool: - """True for built-in container backends and plugins declaring ``is_container``.""" - return env_type in _CONTAINER_BACKENDS or _plugin_env_flag(env_type, "is_container") - - -def _get_plugin_env_provider(env_type: str): - """Return the registered plugin provider for *env_type*, or None.""" - if not env_type or env_type in _CONTAINER_BACKENDS or env_type in {"local", "ssh", "managed_modal"}: - return None - try: - from agent.terminal_env_registry import get_provider - - return get_provider(env_type) - except Exception: - return None - - -def _is_unusable_container_cwd(cwd: str) -> bool: - """True if *cwd* is a host or relative path that can't be a container - workdir: ``docker run -w`` needs an absolute in-sandbox path, otherwise the - container fails to start (exit 125). Windows drive paths aren't ``isabs`` - on POSIX, so they're caught by the prefix check.""" - if not cwd: - return False - return cwd.startswith(_HOST_CWD_PREFIXES) or not os.path.isabs(cwd) - - -def _tenv(name: str, default: str = "") -> str: - """Scope-aware read of a ``TERMINAL_*`` variable. Every terminal setting - must go through this: under gateway multiplexing the active profile's - config arrives via a per-turn scope, and a raw ``os.getenv`` would read - whatever a previous turn pinned into the process env (cross-profile leak).""" - from tools.terminal_scope import terminal_env - - return terminal_env(name, default) - - -def _tenv_bool(name: str, default: str) -> bool: - """Scope-aware boolean ``TERMINAL_*`` read: true/1/yes (case-insensitive).""" - return _tenv(name, default).lower() in {"true", "1", "yes"} - - # One-shot guard for the config-fallback bridge: after the first attempt # either TERMINAL_ENV is set or the import failed, so retrying is wasted work. _terminal_config_bridge_attempted = False diff --git a/tools/terminal_tool_config.py b/tools/terminal_tool_config.py new file mode 100644 index 0000000000..5e3e21bdf2 --- /dev/null +++ b/tools/terminal_tool_config.py @@ -0,0 +1,103 @@ +"""Terminal backend configuration: scope-aware TERMINAL_* reads, env-var parsing, container-cwd sanity checks, plugin-backend classification and the resolved config dict (_get_env_config). + +Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there, +so ``tools.terminal_tool.`` keeps resolving (and monkeypatching) as before. +""" + +import logging +import json +import os +from typing import Any + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.terminal_tool") + + +def _parse_env_var(name: str, default: str, converter: Any = int, type_label: str = "integer"): + """Parse an env var with *converter*, raising a clear ValueError on bad + values (e.g. TERMINAL_TIMEOUT=5m) instead of an opaque crash. TERMINAL_* + names are read scope-aware via :func:`_tenv`.""" + raw = os.getenv(name, default) + if name.startswith("TERMINAL_"): + raw = _tenv(name, default) + try: + return converter(raw) + except (ValueError, json.JSONDecodeError): + raise ValueError( + f"Invalid value for {name}: {raw!r} (expected {type_label}). " + f"Check ~/.hermes/.env or environment variables." + ) + + +def _safe_getcwd() -> str: + """``os.getcwd()`` tolerant of a deleted cwd (FileNotFoundError) or a macOS + TCC-protected one without Full Disk Access (PermissionError); falls back + to TERMINAL_CWD, then the home directory.""" + try: + return os.getcwd() + except (FileNotFoundError, PermissionError): + return _tenv("TERMINAL_CWD") or os.path.expanduser("~") + + +# Host-cwd prefixes that cannot exist inside a container sandbox (POSIX user +# dirs and Windows drive paths as they leak toward a Linux ``-w`` flag). +_HOST_CWD_PREFIXES = ("/Users/", "/home/", "C:\\", "C:/") + + +_CONTAINER_BACKENDS = frozenset({"docker", "singularity", "modal", "daytona", "vercel_sandbox"}) + + +def _plugin_env_flag(env_type: str, attr: str, default=False): + """Classification flag of a plugin-registered backend. Fail-soft: *default* + when the registry is unavailable, the backend unknown, or the provider + raises — a misbehaving plugin must never take the terminal tool down.""" + if not env_type or env_type in _CONTAINER_BACKENDS or env_type in {"local", "ssh", "managed_modal"}: + return default + try: + from agent.terminal_env_registry import provider_flag + + return provider_flag(env_type, attr, default) + except Exception: + return default + + +def _is_container_backend(env_type: str) -> bool: + """True for built-in container backends and plugins declaring ``is_container``.""" + return env_type in _CONTAINER_BACKENDS or _plugin_env_flag(env_type, "is_container") + + +def _get_plugin_env_provider(env_type: str): + """Return the registered plugin provider for *env_type*, or None.""" + if not env_type or env_type in _CONTAINER_BACKENDS or env_type in {"local", "ssh", "managed_modal"}: + return None + try: + from agent.terminal_env_registry import get_provider + + return get_provider(env_type) + except Exception: + return None + + +def _is_unusable_container_cwd(cwd: str) -> bool: + """True if *cwd* is a host or relative path that can't be a container + workdir: ``docker run -w`` needs an absolute in-sandbox path, otherwise the + container fails to start (exit 125). Windows drive paths aren't ``isabs`` + on POSIX, so they're caught by the prefix check.""" + if not cwd: + return False + return cwd.startswith(_HOST_CWD_PREFIXES) or not os.path.isabs(cwd) + + +def _tenv(name: str, default: str = "") -> str: + """Scope-aware read of a ``TERMINAL_*`` variable. Every terminal setting + must go through this: under gateway multiplexing the active profile's + config arrives via a per-turn scope, and a raw ``os.getenv`` would read + whatever a previous turn pinned into the process env (cross-profile leak).""" + from tools.terminal_scope import terminal_env + + return terminal_env(name, default) + + +def _tenv_bool(name: str, default: str) -> bool: + """Scope-aware boolean ``TERMINAL_*`` read: true/1/yes (case-insensitive).""" + return _tenv(name, default).lower() in {"true", "1", "yes"} From 048b1406f73963ce2eb61c26daf36743f0d6dd86 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:45:59 -0700 Subject: [PATCH 04/10] refactor(terminal): unify env-creation kwargs (_create_configured_env) and extract sandbox lifecycle (reaper/teardown/cleanup/ensure_task_env) to terminal_tool_lifecycle --- tools/terminal_tool.py | 308 ++--------------------------- tools/terminal_tool_lifecycle.py | 327 +++++++++++++++++++++++++++++++ 2 files changed, 345 insertions(+), 290 deletions(-) create mode 100644 tools/terminal_tool_lifecycle.py diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index f45c5b2473..7cb7a6d63a 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -14,16 +14,13 @@ Companion modules: ``terminal_tool_guards`` (pre-exec blocks), (foreground result post-processing). """ -import inspect import json import logging import os import time import threading import atexit -import shutil from dataclasses import dataclass -from pathlib import Path from typing import Optional, Dict, Any, List @@ -43,6 +40,21 @@ 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-exported from tools.registry import tool_error +from tools.terminal_tool_lifecycle import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.) + _DISK_USAGE_CACHE_TTL, + _check_disk_usage_warning, + _cleanup_inactive_envs, + _clear_file_ops_cache, + _create_configured_env, + _disk_usage_cache, + _evict_environment_for_task, + _teardown_env, + cleanup_all_environments, + cleanup_vm, + ensure_task_env, + get_active_env, + is_persistent_env, +) from tools.terminal_tool_config import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.) _CONTAINER_BACKENDS, _HOST_CWD_PREFIXES, @@ -104,7 +116,6 @@ from tools.terminal_tool_sudo import ( # noqa: F401 (re-exported; tests patch _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 ( # noqa: F401 (managed_nous_tools_enabled: test patch target) coerce_modal_mode, managed_nous_tools_enabled, @@ -151,42 +162,6 @@ DISK_USAGE_WARNING_THRESHOLD_GB = _safe_parse_import_env( "number", ) -# Advisory disk-usage check; cached so the recursive scan doesn't run on -# every command (a result up to 5 minutes stale is harmless). -_disk_usage_cache: dict = {"timestamp": 0.0, "result": False} -_DISK_USAGE_CACHE_TTL = 300.0 # seconds - - -def _check_disk_usage_warning(): - """True when hermes scratch dirs exceed the warning threshold (cached, advisory).""" - import time as _time_mod - now = _time_mod.monotonic() - if now - _disk_usage_cache["timestamp"] < _DISK_USAGE_CACHE_TTL: - return _disk_usage_cache["result"] - try: - scratch_dir = _get_scratch_dir() - total_bytes = 0 - import glob - for path in glob.glob(str(scratch_dir / "hermes-*")): - for f in Path(path).rglob('*'): - if f.is_file(): - try: - total_bytes += f.stat().st_size - except OSError as e: - logger.debug("Could not stat file %s: %s", f, e) - total_gb = total_bytes / (1024 ** 3) - exceeded = total_gb > DISK_USAGE_WARNING_THRESHOLD_GB - if exceeded: - logger.warning("Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().", - total_gb, DISK_USAGE_WARNING_THRESHOLD_GB) - _disk_usage_cache["timestamp"] = _time_mod.monotonic() - _disk_usage_cache["result"] = exceeded - return exceeded - except Exception as e: - logger.debug("Disk usage warning check failed: %s", e, exc_info=True) - # Don't update cache on error so the next call retries. - return False - # Approval / sudo-prompt UI callbacks (CLI registers prompt_toolkit-aware # ones). Thread-local so overlapping ACP sessions, each on its own executor @@ -796,77 +771,6 @@ def _get_env_config() -> Dict[str, Any]: } -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. - - ``force_remove`` is forwarded to ``cleanup()`` only when given and the - backend's signature accepts it (DockerEnvironment; others don't). A - 404/"not found" error means the sandbox is already gone — logged at info. - """ - try: - if hasattr(env, 'cleanup'): - if force_remove is not None and "force_remove" in inspect.signature(env.cleanup).parameters: - env.cleanup(force_remove=force_remove) - else: - env.cleanup() - elif hasattr(env, 'stop'): - env.stop() - elif hasattr(env, 'terminate'): - env.terminate() - logger.info(done_msg, task_id) - except Exception as e: - error_str = str(e) - if "404" in error_str or "not found" in error_str.lower(): - logger.info("Environment for task %s already cleaned up", task_id) - else: - logger.warning("Error cleaning up environment for task %s: %s", task_id, e) - - -def _clear_file_ops_cache(task_id: str) -> None: - """Invalidate the file_ops cache entry so ShellFileOperations can't reference a dead sandbox.""" - try: - from tools.file_tools import clear_file_ops_cache - clear_file_ops_cache(task_id) - except ImportError: - pass - - -def _cleanup_inactive_envs(lifetime_seconds: int = 300): - """Clean up environments that have been inactive for longer than lifetime_seconds.""" - current_time = time.time() - - # Sandboxes with active background processes stay alive (refresh activity). - try: - from tools.process_registry import process_registry - for task_id in list(_last_activity.keys()): - if process_registry.has_active_processes(task_id): - _last_activity[task_id] = current_time - except ImportError: - pass - - # Phase 1: unregister stale entries under the lock. Do NOT call - # env.cleanup() inside the lock — Modal/Docker teardown can block 10-15s - # and would stall every concurrent terminal/file tool call. - envs_to_stop = [] # list of (task_id, env) pairs - - with _env_lock: - for task_id, last_time in list(_last_activity.items()): - if current_time - last_time > lifetime_seconds: - env = _active_environments.pop(task_id, None) - _last_activity.pop(task_id, None) - if env is not None: - envs_to_stop.append((task_id, env)) - - with _creation_locks_lock: - for task_id, _ in envs_to_stop: - _creation_locks.pop(task_id, None) - - # Phase 2: stop the sandboxes outside the lock. - for task_id, env in envs_to_stop: - _clear_file_ops_cache(task_id) - _teardown_env(env, task_id) - - def _cleanup_thread_worker(): """Background thread worker that periodically cleans up inactive environments.""" while _cleanup_running: @@ -904,153 +808,6 @@ def _stop_cleanup_thread(): pass -def get_active_env(task_id: str): - """Return the active BaseEnvironment for *task_id*, or None.""" - lookup = _resolve_container_task_id(task_id) - with _env_lock: - return _active_environments.get(lookup) or _active_environments.get(task_id) - - -def ensure_task_env(task_id: Optional[str] = None): - """Lazily create and cache the sandbox env for *task_id* if none is active. - - Lets non-terminal callers (``tools.image_source`` reading container-only - paths) bring the sandbox up on demand with the same machinery as the - terminal tool. No-op on local. Returns the env, or ``None`` when local or - when creation fails (best-effort; the caller's fail-closed path stays intact). - """ - config = _get_env_config() - env_type = config["env_type"] - if env_type == "local": - return None - - effective_task_id = _resolve_container_task_id(task_id) - - existing = get_active_env(effective_task_id) - if existing is not None: - with _env_lock: - _last_activity[effective_task_id] = time.time() - return existing - - overrides = resolve_task_overrides(task_id) - image = _select_image(env_type, overrides, config) - - _start_cleanup_thread() - - with _creation_locks_lock: - task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock()) - - with task_lock: - existing = get_active_env(effective_task_id) - if existing is not None: - return existing - try: - new_env = _create_environment( - env_type=env_type, - image=image, - cwd=config["cwd"], - timeout=config["timeout"], - ssh_config=_ssh_config_from_config(config) if env_type == "ssh" else None, - container_config=( - _container_config_from_config(config) - if _is_container_backend(env_type) else None - ), - local_config=None, - task_id=effective_task_id, - host_cwd=_resolve_task_host_cwd(config, task_id), - ) - except Exception as exc: # noqa: BLE001 — best-effort bring-up - logger.warning( - "Lazy %s environment init failed for task %s: %s", - env_type, effective_task_id[:8], exc, - ) - return None - - with _env_lock: - _active_environments[effective_task_id] = new_env - _last_activity[effective_task_id] = time.time() - logger.info( - "%s environment lazily initialized for task %s", - env_type, effective_task_id[:8], - ) - return new_env - - -def is_persistent_env(task_id: str) -> bool: - """True if *task_id*'s active env persists across turns. - - The agent loop skips per-turn teardown for these (persistent docker, - daytona, modal, …); non-persistent backends are torn down at end of turn - to prevent leakage, and the idle reaper handles the rest. Session-scoped - docker containers count as persistent HERE: their lifetime is the session - (removed by ``AIAgent.close()`` → ``cleanup_vm`` and the idle reaper). - """ - env = get_active_env(task_id) - if env is None: - return False - if getattr(env, "_session_scoped", False): - return True - return bool(getattr(env, "_persistent", False)) - - -def cleanup_all_environments(): - """Clean up ALL active environments. Use with caution.""" - task_ids = list(_active_environments.keys()) - cleaned = 0 - - for task_id in task_ids: - try: - cleanup_vm(task_id) - cleaned += 1 - except Exception as e: - logger.error("Error cleaning %s: %s", task_id, e, exc_info=True) - - # Also clean any orphaned directories - scratch_dir = _get_scratch_dir() - import glob - for path in glob.glob(str(scratch_dir / "hermes-*")): - try: - shutil.rmtree(path, ignore_errors=True) - logger.info("Removed orphaned: %s", path) - except OSError as e: - logger.debug("Failed to remove orphaned path %s: %s", path, e) - - if cleaned > 0: - logger.info("Cleaned %d environments", cleaned) - return cleaned - - -def cleanup_vm(task_id: str, *, force_remove: bool = False): - """Manually clean up a specific environment by task_id. - - *force_remove* is forwarded to backends that accept it (currently only - ``DockerEnvironment``). Default False matches session-lifecycle semantics: - callers (``AIAgent.close()`` on TUI/gateway session teardown, the per-turn - cleanup of non-persistent envs) must honor the user's persist-mode - preference — stopping the container here would break the "ONE long-lived - container shared across sessions" contract. Pass ``force_remove=True`` - only for user-initiated teardown. The idle reaper calls ``env.cleanup()`` - directly, so persist-mode idle envs are likewise no-op'd; only the orphan - reaper at next startup reclaims them. - """ - # Unregister under the lock; run the (slow) cleanup outside it. - with _env_lock: - env = _active_environments.pop(task_id, None) - _last_activity.pop(task_id, None) - - with _creation_locks_lock: - _creation_locks.pop(task_id, None) - - _clear_file_ops_cache(task_id) - - if env is None: - return - _teardown_env( - env, task_id, force_remove=force_remove, - done_msg="Manually cleaned up environment for task: %s", - ) - - def _atexit_cleanup(): """Stop the cleanup thread and shut down all remaining sandboxes on exit.""" _stop_cleanup_thread() @@ -1369,22 +1126,13 @@ def _acquire_env(plan: _ExecPlan, task_id: Optional[str]) -> Any: _check_disk_usage_warning() logger.info("Creating new %s environment for task %s...", env_type, eff[:8]) try: - new_env = _create_environment( - env_type=env_type, - image=plan.image, - cwd=plan.cwd, - timeout=plan.effective_timeout, - ssh_config=_ssh_config_from_config(plan.config) if env_type == "ssh" else None, - container_config=( - _container_config_from_config(plan.config) - if _is_container_backend(env_type) else None - ), + new_env = _create_configured_env( + plan.config, env_type, image=plan.image, cwd=plan.cwd, + timeout=plan.effective_timeout, task_id=eff, host_cwd=plan.host_cwd, local_config=( {"persistent": plan.config.get("local_persistent", False)} if env_type == "local" else None ), - task_id=eff, - host_cwd=plan.host_cwd, ) except ImportError as e: return _error_json( @@ -1610,26 +1358,6 @@ def terminal_tool( return _fatal_error_json(e) -def _evict_environment_for_task(task_id: Optional[str]) -> None: - """Drop any cached env for *task_id* (and its collapsed key) after an - infrastructure failure, so later calls don't reuse a dead connection.""" - keys = {_resolve_container_task_id(task_id)} - if task_id: - keys.add(task_id) - evicted = [] - with _env_lock: - for key in keys: - env = _active_environments.pop(key, None) - _last_activity.pop(key, None) - if env is not None: - evicted.append(env) - for env in evicted: - try: - env.cleanup() - except Exception: - logger.debug("cleanup of degraded environment failed", exc_info=True) - - def check_terminal_requirements() -> bool: """Check if all requirements for the terminal tool are met.""" try: diff --git a/tools/terminal_tool_lifecycle.py b/tools/terminal_tool_lifecycle.py new file mode 100644 index 0000000000..b5874bf508 --- /dev/null +++ b/tools/terminal_tool_lifecycle.py @@ -0,0 +1,327 @@ +"""Sandbox lifecycle for the terminal tool: idle reaping, teardown, manual/atexit cleanup, and the lazy ensure_task_env bring-up. The env cache dicts and locks stay in tools.terminal_tool (tests patch them there) and are read through it at call time. + +Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there, +so ``tools.terminal_tool.`` keeps resolving (and monkeypatching) as before. +""" + +import logging +import inspect +import shutil +import threading +import time +from pathlib import Path +from typing import Any, Dict, Optional +from tools.environments.singularity import _get_scratch_dir +from tools.terminal_tool_backends import ( + _container_config_from_config, + _ssh_config_from_config, +) + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.terminal_tool") + + +# Advisory disk-usage check; cached so the recursive scan doesn't run on +# every command (a result up to 5 minutes stale is harmless). +_disk_usage_cache: dict = {"timestamp": 0.0, "result": False} + + +_DISK_USAGE_CACHE_TTL = 300.0 # seconds + + +def _check_disk_usage_warning(): + """True when hermes scratch dirs exceed the warning threshold (cached, advisory).""" + from tools.terminal_tool import DISK_USAGE_WARNING_THRESHOLD_GB + import time as _time_mod + now = _time_mod.monotonic() + if now - _disk_usage_cache["timestamp"] < _DISK_USAGE_CACHE_TTL: + return _disk_usage_cache["result"] + try: + scratch_dir = _get_scratch_dir() + total_bytes = 0 + import glob + for path in glob.glob(str(scratch_dir / "hermes-*")): + for f in Path(path).rglob('*'): + if f.is_file(): + try: + total_bytes += f.stat().st_size + except OSError as e: + logger.debug("Could not stat file %s: %s", f, e) + total_gb = total_bytes / (1024 ** 3) + exceeded = total_gb > DISK_USAGE_WARNING_THRESHOLD_GB + if exceeded: + logger.warning("Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().", + total_gb, DISK_USAGE_WARNING_THRESHOLD_GB) + _disk_usage_cache["timestamp"] = _time_mod.monotonic() + _disk_usage_cache["result"] = exceeded + return exceeded + except Exception as e: + logger.debug("Disk usage warning check failed: %s", e, exc_info=True) + # Don't update cache on error so the next call retries. + return False + + +def _create_configured_env( + config: Dict[str, Any], env_type: str, *, image: str, cwd: str, timeout: int, + task_id: str, host_cwd: Optional[str], local_config: Optional[dict] = None, +): + """``_create_environment`` with the ssh/container kwargs shaped from *config* + (shared by the terminal tool and the lazy :func:`ensure_task_env` bring-up).""" + from tools.terminal_tool import _create_environment, _is_container_backend + return _create_environment( + env_type=env_type, image=image, cwd=cwd, timeout=timeout, + ssh_config=_ssh_config_from_config(config) if env_type == "ssh" else None, + container_config=( + _container_config_from_config(config) if _is_container_backend(env_type) else None + ), + local_config=local_config, task_id=task_id, 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. + + ``force_remove`` is forwarded to ``cleanup()`` only when given and the + backend's signature accepts it (DockerEnvironment; others don't). A + 404/"not found" error means the sandbox is already gone — logged at info. + """ + try: + if hasattr(env, 'cleanup'): + if force_remove is not None and "force_remove" in inspect.signature(env.cleanup).parameters: + env.cleanup(force_remove=force_remove) + else: + env.cleanup() + elif hasattr(env, 'stop'): + env.stop() + elif hasattr(env, 'terminate'): + env.terminate() + logger.info(done_msg, task_id) + except Exception as e: + error_str = str(e) + if "404" in error_str or "not found" in error_str.lower(): + logger.info("Environment for task %s already cleaned up", task_id) + else: + logger.warning("Error cleaning up environment for task %s: %s", task_id, e) + + +def _clear_file_ops_cache(task_id: str) -> None: + """Invalidate the file_ops cache entry so ShellFileOperations can't reference a dead sandbox.""" + try: + from tools.file_tools import clear_file_ops_cache + clear_file_ops_cache(task_id) + except ImportError: + pass + + +def _cleanup_inactive_envs(lifetime_seconds: int = 300): + """Clean up environments that have been inactive for longer than lifetime_seconds.""" + from tools.terminal_tool import ( + _active_environments, _creation_locks, _creation_locks_lock, _env_lock, + _last_activity, + ) + current_time = time.time() + + # Sandboxes with active background processes stay alive (refresh activity). + try: + from tools.process_registry import process_registry + for task_id in list(_last_activity.keys()): + if process_registry.has_active_processes(task_id): + _last_activity[task_id] = current_time + except ImportError: + pass + + # Phase 1: unregister stale entries under the lock. Do NOT call + # env.cleanup() inside the lock — Modal/Docker teardown can block 10-15s + # and would stall every concurrent terminal/file tool call. + envs_to_stop = [] # list of (task_id, env) pairs + + with _env_lock: + for task_id, last_time in list(_last_activity.items()): + if current_time - last_time > lifetime_seconds: + env = _active_environments.pop(task_id, None) + _last_activity.pop(task_id, None) + if env is not None: + envs_to_stop.append((task_id, env)) + + with _creation_locks_lock: + for task_id, _ in envs_to_stop: + _creation_locks.pop(task_id, None) + + # Phase 2: stop the sandboxes outside the lock. + for task_id, env in envs_to_stop: + _clear_file_ops_cache(task_id) + _teardown_env(env, task_id) + + +def get_active_env(task_id: str): + """Return the active BaseEnvironment for *task_id*, or None.""" + from tools.terminal_tool import _active_environments, _env_lock, _resolve_container_task_id + lookup = _resolve_container_task_id(task_id) + with _env_lock: + return _active_environments.get(lookup) or _active_environments.get(task_id) + + +def ensure_task_env(task_id: Optional[str] = None): + """Lazily create and cache the sandbox env for *task_id* if none is active. + + Lets non-terminal callers (``tools.image_source`` reading container-only + paths) bring the sandbox up on demand with the same machinery as the + terminal tool. No-op on local. Returns the env, or ``None`` when local or + when creation fails (best-effort; the caller's fail-closed path stays intact). + """ + from tools.terminal_tool import ( + _active_environments, _creation_locks, _creation_locks_lock, _env_lock, + _get_env_config, _last_activity, _resolve_container_task_id, + _resolve_task_host_cwd, _select_image, _start_cleanup_thread, get_active_env, + resolve_task_overrides, + ) + config = _get_env_config() + env_type = config["env_type"] + if env_type == "local": + return None + + effective_task_id = _resolve_container_task_id(task_id) + + existing = get_active_env(effective_task_id) + if existing is not None: + with _env_lock: + _last_activity[effective_task_id] = time.time() + return existing + + overrides = resolve_task_overrides(task_id) + image = _select_image(env_type, overrides, config) + + _start_cleanup_thread() + + with _creation_locks_lock: + task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock()) + + with task_lock: + existing = get_active_env(effective_task_id) + if existing is not None: + return existing + try: + new_env = _create_configured_env( + config, env_type, image=image, cwd=config["cwd"], + timeout=config["timeout"], task_id=effective_task_id, + host_cwd=_resolve_task_host_cwd(config, task_id), + ) + except Exception as exc: # noqa: BLE001 — best-effort bring-up + logger.warning( + "Lazy %s environment init failed for task %s: %s", + env_type, effective_task_id[:8], exc, + ) + return None + + with _env_lock: + _active_environments[effective_task_id] = new_env + _last_activity[effective_task_id] = time.time() + logger.info( + "%s environment lazily initialized for task %s", + env_type, effective_task_id[:8], + ) + return new_env + + +def is_persistent_env(task_id: str) -> bool: + """True if *task_id*'s active env persists across turns. + + The agent loop skips per-turn teardown for these (persistent docker, + daytona, modal, …); non-persistent backends are torn down at end of turn + to prevent leakage, and the idle reaper handles the rest. Session-scoped + docker containers count as persistent HERE: their lifetime is the session + (removed by ``AIAgent.close()`` → ``cleanup_vm`` and the idle reaper). + """ + from tools.terminal_tool import get_active_env + env = get_active_env(task_id) + if env is None: + return False + if getattr(env, "_session_scoped", False): + return True + return bool(getattr(env, "_persistent", False)) + + +def cleanup_all_environments(): + """Clean up ALL active environments. Use with caution.""" + from tools.terminal_tool import _active_environments, cleanup_vm + task_ids = list(_active_environments.keys()) + cleaned = 0 + + for task_id in task_ids: + try: + cleanup_vm(task_id) + cleaned += 1 + except Exception as e: + logger.error("Error cleaning %s: %s", task_id, e, exc_info=True) + + # Also clean any orphaned directories + scratch_dir = _get_scratch_dir() + import glob + for path in glob.glob(str(scratch_dir / "hermes-*")): + try: + shutil.rmtree(path, ignore_errors=True) + logger.info("Removed orphaned: %s", path) + except OSError as e: + logger.debug("Failed to remove orphaned path %s: %s", path, e) + + if cleaned > 0: + logger.info("Cleaned %d environments", cleaned) + return cleaned + + +def cleanup_vm(task_id: str, *, force_remove: bool = False): + """Manually clean up a specific environment by task_id. + + *force_remove* is forwarded to backends that accept it (currently only + ``DockerEnvironment``). Default False matches session-lifecycle semantics: + callers (``AIAgent.close()`` on TUI/gateway session teardown, the per-turn + cleanup of non-persistent envs) must honor the user's persist-mode + preference — stopping the container here would break the "ONE long-lived + container shared across sessions" contract. Pass ``force_remove=True`` + only for user-initiated teardown. The idle reaper calls ``env.cleanup()`` + directly, so persist-mode idle envs are likewise no-op'd; only the orphan + reaper at next startup reclaims them. + """ + from tools.terminal_tool import ( + _active_environments, _creation_locks, _creation_locks_lock, _env_lock, + _last_activity, + ) + # Unregister under the lock; run the (slow) cleanup outside it. + with _env_lock: + env = _active_environments.pop(task_id, None) + _last_activity.pop(task_id, None) + + with _creation_locks_lock: + _creation_locks.pop(task_id, None) + + _clear_file_ops_cache(task_id) + + if env is None: + return + _teardown_env( + env, task_id, force_remove=force_remove, + done_msg="Manually cleaned up environment for task: %s", + ) + + +def _evict_environment_for_task(task_id: Optional[str]) -> None: + """Drop any cached env for *task_id* (and its collapsed key) after an + infrastructure failure, so later calls don't reuse a dead connection.""" + from tools.terminal_tool import ( + _active_environments, _env_lock, _last_activity, _resolve_container_task_id, + ) + keys = {_resolve_container_task_id(task_id)} + if task_id: + keys.add(task_id) + evicted = [] + with _env_lock: + for key in keys: + env = _active_environments.pop(key, None) + _last_activity.pop(key, None) + if env is not None: + evicted.append(env) + for env in evicted: + try: + env.cleanup() + except Exception: + logger.debug("cleanup of degraded environment failed", exc_info=True) From 88f97462ff5e02098edc796e8746478d98a9d618 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:49:10 -0700 Subject: [PATCH 05/10] refactor(skills_hub): extract install/uninstall/update operations to skills_hub_install --- tools/skills_hub.py | 331 ++-------------------------------- tools/skills_hub_install.py | 350 ++++++++++++++++++++++++++++++++++++ 2 files changed, 363 insertions(+), 318 deletions(-) create mode 100644 tools/skills_hub_install.py diff --git a/tools/skills_hub.py b/tools/skills_hub.py index 4ff650a05a..cde0aaa0c7 100644 --- a/tools/skills_hub.py +++ b/tools/skills_hub.py @@ -10,10 +10,8 @@ re-exported here so ``from tools.skills_hub import X`` keeps working. Used by hermes_cli/skills_hub.py for CLI commands and the /skills slash command. """ -import hashlib import json import logging -import shutil import time from datetime import datetime, timezone from pathlib import Path @@ -23,8 +21,6 @@ from urllib.parse import urljoin import httpx from hermes_constants import get_hermes_home -from agent.skill_utils import is_excluded_skill_path -from tools.skills_guard import ScanResult, content_hash from tools.url_safety import is_safe_url from tools.website_policy import check_website_access from tools.skills_hub_models import ( # noqa: F401 (re-exported public API) @@ -44,6 +40,19 @@ from tools.skills_hub_sources import ( # noqa: F401 WellKnownSkillSource, UrlSource, LobeHubSource, BrowseShSource, ) from tools.skills_hub_official import OptionalSkillSource, HermesIndexSource # noqa: F401 +from tools.skills_hub_install import ( # noqa: F401 (re-exported; tests patch tools.skills_hub.) + _SOURCE_ID_ALIASES, + _category_skill_dirs, + _check_install_target, + _is_path_redirect, + _resolve_lock_install_path, + _source_matches, + bundle_content_hash, + check_for_skill_updates, + install_from_quarantine, + quarantine_bundle, + uninstall_skill, +) logger = logging.getLogger(__name__) @@ -127,37 +136,6 @@ _REDIRECT_STATUS_CODES = {301, 302, 303, 307, 308} _MAX_SKILL_FETCH_REDIRECTS = 5 -def _is_path_redirect(path: Path) -> bool: - """True when ``path`` is a symlink or (on Windows) a directory junction — - either lets a writer in ``skills/`` redirect a later ``rmtree`` outside it. - ``is_junction`` only exists on Python 3.12+ Windows; gate with ``hasattr``.""" - return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction()) - - -def _resolve_lock_install_path(install_path: str, skill_name: str) -> Path: - """Resolve a lock-file install path without allowing escapes from ``SKILLS_DIR``. - - Walks component-by-component refusing symlink/junction redirects (which - ``Path.resolve`` would silently follow), then rejects both escape-out and - ``resolved == SKILLS_DIR`` — an empty/``"."`` install_path resolves to the - skills root and ``rmtree`` there would wipe every installed skill. - """ - normalized = _normalize_lock_install_path(install_path, skill_name) - skills_dir = _skills_dir() - skills_root = skills_dir.resolve() - - target = skills_dir - for part in normalized.split("/"): - target = target / part - if _is_path_redirect(target): - raise ValueError(f"Unsafe install path: {install_path}") - - target = target.resolve() - if target == skills_root or not target.is_relative_to(skills_root): - raise ValueError(f"Unsafe install path: {install_path}") - return target - - def _ssrf_safe_http_get(url: str, *, timeout: int = 20) -> httpx.Response: """Fetch one URL with connect-time SSRF validation and no automatic redirects.""" from tools.url_safety import create_ssrf_safe_client @@ -402,289 +380,6 @@ def ensure_hub_dirs() -> None: path.write_text(initial, encoding="utf-8") -def quarantine_bundle(bundle: SkillBundle) -> Path: - """Write a skill bundle to the quarantine directory for scanning.""" - ensure_hub_dirs() - skill_name = _validate_skill_name(bundle.name) - # Validate every path before touching disk so a bad member aborts cleanly. - validated_files = [ - (_validate_bundle_rel_path(rel_path), file_content) - for rel_path, file_content in bundle.files.items() - ] - - dest = _quarantine_dir() / skill_name - if dest.exists(): - shutil.rmtree(dest) - dest.mkdir(parents=True) - - for rel_path, file_content in validated_files: - file_dest = dest.joinpath(*rel_path.split("/")) - file_dest.parent.mkdir(parents=True, exist_ok=True) - if isinstance(file_content, bytes): - file_dest.write_bytes(file_content) - else: - file_dest.write_text(file_content, encoding="utf-8") - - return dest - - -def _category_skill_dirs(directory: Path) -> List[str]: - """Names of non-hidden child dirs holding at least one active SKILL.md - anywhere below (nested layouts like ``mlops/training/`` count). - - Vendored/cache/progressive-disclosure paths are pruned via - :func:`is_excluded_skill_path` so a lone ``node_modules`` or - ``references/pkg/SKILL.md`` does not make the directory a category. - Shared with ``hermes_cli.skills_hub._existing_categories``. - """ - skill_dirs: List[str] = [] - for entry in directory.iterdir(): - if not entry.is_dir() or entry.name.startswith("."): - continue - if any( - not is_excluded_skill_path(skill_md.relative_to(directory), root=directory) - for skill_md in entry.rglob("SKILL.md") - ): - skill_dirs.append(entry.name) - return skill_dirs - - -def _check_install_target(install_dir: Path) -> None: - """Raise ValueError when installing at ``install_dir`` would destroy other skills. - - - Nesting inside an existing skill dir (``--category ``) - would make a later update/uninstall of the outer skill rmtree the inner one. - - A stray regular file at the target: rmtree would raise NotADirectoryError. - - A category bucket (dir without SKILL.md that holds other skills) must never - be silently wiped; a dir that directly contains SKILL.md is an existing - install and stays overwritable (hub installs are lock-guarded in do_install). - """ - skills_root = _skills_dir().resolve() - ancestor = install_dir.parent - while ancestor != skills_root and ancestor.is_relative_to(skills_root): - if (ancestor / "SKILL.md").is_file(): - raise ValueError( - f"Refusing to install into '{ancestor.name}': it is an " - f"existing skill directory, not a category. Choose a " - f"different category." - ) - ancestor = ancestor.parent - - if not install_dir.exists(): - return - if not install_dir.is_dir(): - raise ValueError( - f"Refusing to install: '{install_dir.name}' already exists " - f"and is not a directory. Remove it or choose a different " - f"skill name." - ) - if not (install_dir / "SKILL.md").exists(): - skill_dirs_in = _category_skill_dirs(install_dir) - if skill_dirs_in: - raise ValueError( - f"Refusing to overwrite category directory '{install_dir}' " - f"which contains {len(skill_dirs_in)} skill(s): " - f"{', '.join(sorted(skill_dirs_in))}. " - f"Use a different --name or install into a subcategory." - ) - - -def install_from_quarantine( - quarantine_path: Path, - skill_name: str, - category: str, - bundle: SkillBundle, - scan_result: ScanResult, - scan_provenance: Optional[Dict[str, Any]] = None, -) -> Path: - """Move a scanned skill from quarantine into the skills directory.""" - safe_skill_name = _validate_skill_name(skill_name) - safe_category = _validate_install_parent_path(category) if category else "" - quarantine_resolved = quarantine_path.resolve() - if not quarantine_resolved.is_relative_to(_quarantine_dir().resolve()): - raise ValueError(f"Unsafe quarantine path: {quarantine_path}") - - install_rel_path = f"{safe_category}/{safe_skill_name}" if safe_category else safe_skill_name - # Same validator the uninstaller uses, so a lock entry can never point at a - # symlink-redirected target. - install_dir = _resolve_lock_install_path(install_rel_path, safe_skill_name) - _check_install_target(install_dir) - if install_dir.exists(): - shutil.rmtree(install_dir) - - skill_md = quarantine_path / "SKILL.md" - if skill_md.exists(): - try: - skill_size = skill_md.stat().st_size - if skill_size > 100_000: - logger.warning( - "Skill '%s' has a large SKILL.md (%s chars). " - "Large skills consume significant context when loaded. " - "Consider asking the author to split it into smaller files.", - safe_skill_name, - f"{skill_size:,}", - ) - except OSError: - pass - - # A symlink in the bundle would copy its target into skills/ and leak it - # to the agent on the next skill_view. - for entry in quarantine_path.rglob("*"): - if not _is_path_redirect(entry): - continue - try: - rel = entry.relative_to(quarantine_resolved) - except ValueError: - rel = entry - raise ValueError( - f"Installed skill contains symlinks, which is not allowed: {rel}" - ) - - install_dir.parent.mkdir(parents=True, exist_ok=True) - shutil.move(str(quarantine_path), str(install_dir)) - - installed_hash = content_hash(install_dir) - HubLockFile().record_install( - name=safe_skill_name, - source=bundle.source, - identifier=bundle.identifier, - trust_level=bundle.trust_level, - scan_verdict=scan_result.verdict, - skill_hash=installed_hash, - install_path=install_dir.resolve().relative_to(_skills_dir().resolve()).as_posix(), - files=list(bundle.files.keys()), - metadata=bundle.metadata, - scan_provenance=scan_provenance or getattr(scan_result, "scan_provenance", None), - ) - - append_audit_log( - "INSTALL", safe_skill_name, bundle.source, - bundle.trust_level, scan_result.verdict, - installed_hash, - ) - - try: - from tools.skill_usage import record_installed - - record_installed(safe_skill_name) - except Exception: - logger.debug( - "Unable to record skill install lifecycle for %s", - safe_skill_name, - exc_info=True, - ) - - return install_dir - - -def uninstall_skill(skill_name: str) -> Tuple[bool, str]: - """Remove a hub-installed skill. Refuses to remove builtins.""" - lock = HubLockFile() - entry = lock.get_installed(skill_name) - if not entry: - return False, f"'{skill_name}' is not a hub-installed skill (may be a builtin)" - - # The destructive boundary: whatever reaches rmtree MUST be inside - # SKILLS_DIR and MUST NOT be SKILLS_DIR itself (see _resolve_lock_install_path). - try: - install_path = _resolve_lock_install_path(entry.get("install_path", ""), skill_name) - except ValueError as exc: - return False, f"Refusing to uninstall '{skill_name}': {exc}" - - if install_path.exists(): - shutil.rmtree(install_path) - - lock.record_uninstall(skill_name) - append_audit_log("UNINSTALL", skill_name, entry["source"], entry["trust_level"], "n/a", "user_request") - - return True, f"Uninstalled '{skill_name}' from {entry['install_path']}" - - -def bundle_content_hash(bundle: SkillBundle) -> str: - """Deterministic hash of an in-memory bundle. - - MUST stay symmetric with ``tools.skills_guard.content_hash`` (same skill - from disk), which keys files by POSIX relative path. Windows bundle keys - carry backslashes, which changed both bytes and sort order and made every - skill report ``update_available`` forever — normalize before hashing. The - path is hashed too so swapping contents between two files changes the hash. - """ - h = hashlib.sha256() - normalized = { - rel_path.replace("\\", "/"): content - for rel_path, content in bundle.files.items() - } - for rel_path in sorted(normalized): - h.update(rel_path.encode("utf-8")) - h.update(b"\x00") - content = normalized[rel_path] - h.update(content if isinstance(content, bytes) else content.encode("utf-8")) - return f"sha256:{h.hexdigest()[:16]}" - - -_SOURCE_ID_ALIASES = {"skills.sh": "skills-sh"} - - -def _source_matches(source: SkillSource, source_name: str) -> bool: - return source.source_id() == _SOURCE_ID_ALIASES.get(source_name, source_name) - - -def check_for_skill_updates( - name: Optional[str] = None, - *, - lock: Optional[HubLockFile] = None, - sources: Optional[List[SkillSource]] = None, - auth: Optional[GitHubAuth] = None, -) -> List[dict]: - """Check installed hub skills for upstream changes. - - Each entry is fetched ONLY from adapters matching its recorded source. - Falling back to all sources let a same-named skill in a different registry - satisfy the fetch and silently reassign provenance (names are not - namespaced across registries), so a missing adapter reports "unavailable". - """ - lock = lock or HubLockFile() - installed = lock.list_installed() - if name: - installed = [entry for entry in installed if entry.get("name") == name] - - if sources is None: - sources = create_source_router(auth=auth) - - results: List[dict] = [] - for entry in installed: - identifier = entry.get("identifier", "") - source_name = entry.get("source", "") - row = {"name": entry.get("name", ""), "identifier": identifier, "source": source_name} - - bundle = None - for src in sources: - if not _source_matches(src, source_name): - continue - try: - bundle = src.fetch(identifier) - except Exception: - bundle = None - if bundle: - break - - if not bundle: - results.append({**row, "status": "unavailable"}) - continue - - current_hash = entry.get("content_hash", "") - latest_hash = bundle_content_hash(bundle) - results.append({ - **row, - "status": "up_to_date" if current_hash == latest_hash else "update_available", - "current_hash": current_hash, - "latest_hash": latest_hash, - "bundle": bundle, - }) - - return results - - # --------------------------------------------------------------------------- # Hermes centralized index (data source for HermesIndexSource) # --------------------------------------------------------------------------- diff --git a/tools/skills_hub_install.py b/tools/skills_hub_install.py new file mode 100644 index 0000000000..f750ea3260 --- /dev/null +++ b/tools/skills_hub_install.py @@ -0,0 +1,350 @@ +"""Skills Hub install/uninstall/update operations: quarantine staging, install-target safety (symlink/junction, category-bucket and nested-skill checks), lock-file-backed uninstall, bundle hashing and upstream update checks. + +Split out of ``tools/skills_hub.py``; every public/patched name is re-imported there, +so ``tools.skills_hub.`` keeps resolving (and monkeypatching) as before. +""" + +from __future__ import annotations + +import logging +import hashlib +import shutil +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple +from agent.skill_utils import is_excluded_skill_path +from tools.skills_guard import ScanResult, content_hash +from tools.skills_hub_github import GitHubAuth +from tools.skills_hub_models import ( + SkillBundle, + SkillSource, + _normalize_lock_install_path, + _validate_bundle_rel_path, + _validate_install_parent_path, + _validate_skill_name, +) + +if TYPE_CHECKING: # origin class; runtime use is via the lazy origin import + from tools.skills_hub import HubLockFile + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.skills_hub") + + +def _is_path_redirect(path: Path) -> bool: + """True when ``path`` is a symlink or (on Windows) a directory junction — + either lets a writer in ``skills/`` redirect a later ``rmtree`` outside it. + ``is_junction`` only exists on Python 3.12+ Windows; gate with ``hasattr``.""" + return path.is_symlink() or (hasattr(path, "is_junction") and path.is_junction()) + + +def _resolve_lock_install_path(install_path: str, skill_name: str) -> Path: + """Resolve a lock-file install path without allowing escapes from ``SKILLS_DIR``. + + Walks component-by-component refusing symlink/junction redirects (which + ``Path.resolve`` would silently follow), then rejects both escape-out and + ``resolved == SKILLS_DIR`` — an empty/``"."`` install_path resolves to the + skills root and ``rmtree`` there would wipe every installed skill. + """ + from tools.skills_hub import _skills_dir + normalized = _normalize_lock_install_path(install_path, skill_name) + skills_dir = _skills_dir() + skills_root = skills_dir.resolve() + + target = skills_dir + for part in normalized.split("/"): + target = target / part + if _is_path_redirect(target): + raise ValueError(f"Unsafe install path: {install_path}") + + target = target.resolve() + if target == skills_root or not target.is_relative_to(skills_root): + raise ValueError(f"Unsafe install path: {install_path}") + return target + + +def quarantine_bundle(bundle: SkillBundle) -> Path: + """Write a skill bundle to the quarantine directory for scanning.""" + from tools.skills_hub import _quarantine_dir, ensure_hub_dirs + ensure_hub_dirs() + skill_name = _validate_skill_name(bundle.name) + # Validate every path before touching disk so a bad member aborts cleanly. + validated_files = [ + (_validate_bundle_rel_path(rel_path), file_content) + for rel_path, file_content in bundle.files.items() + ] + + dest = _quarantine_dir() / skill_name + if dest.exists(): + shutil.rmtree(dest) + dest.mkdir(parents=True) + + for rel_path, file_content in validated_files: + file_dest = dest.joinpath(*rel_path.split("/")) + file_dest.parent.mkdir(parents=True, exist_ok=True) + if isinstance(file_content, bytes): + file_dest.write_bytes(file_content) + else: + file_dest.write_text(file_content, encoding="utf-8") + + return dest + + +def _category_skill_dirs(directory: Path) -> List[str]: + """Names of non-hidden child dirs holding at least one active SKILL.md + anywhere below (nested layouts like ``mlops/training/`` count). + + Vendored/cache/progressive-disclosure paths are pruned via + :func:`is_excluded_skill_path` so a lone ``node_modules`` or + ``references/pkg/SKILL.md`` does not make the directory a category. + Shared with ``hermes_cli.skills_hub._existing_categories``. + """ + skill_dirs: List[str] = [] + for entry in directory.iterdir(): + if not entry.is_dir() or entry.name.startswith("."): + continue + if any( + not is_excluded_skill_path(skill_md.relative_to(directory), root=directory) + for skill_md in entry.rglob("SKILL.md") + ): + skill_dirs.append(entry.name) + return skill_dirs + + +def _check_install_target(install_dir: Path) -> None: + """Raise ValueError when installing at ``install_dir`` would destroy other skills. + + - Nesting inside an existing skill dir (``--category ``) + would make a later update/uninstall of the outer skill rmtree the inner one. + - A stray regular file at the target: rmtree would raise NotADirectoryError. + - A category bucket (dir without SKILL.md that holds other skills) must never + be silently wiped; a dir that directly contains SKILL.md is an existing + install and stays overwritable (hub installs are lock-guarded in do_install). + """ + from tools.skills_hub import _skills_dir + skills_root = _skills_dir().resolve() + ancestor = install_dir.parent + while ancestor != skills_root and ancestor.is_relative_to(skills_root): + if (ancestor / "SKILL.md").is_file(): + raise ValueError( + f"Refusing to install into '{ancestor.name}': it is an " + f"existing skill directory, not a category. Choose a " + f"different category." + ) + ancestor = ancestor.parent + + if not install_dir.exists(): + return + if not install_dir.is_dir(): + raise ValueError( + f"Refusing to install: '{install_dir.name}' already exists " + f"and is not a directory. Remove it or choose a different " + f"skill name." + ) + if not (install_dir / "SKILL.md").exists(): + skill_dirs_in = _category_skill_dirs(install_dir) + if skill_dirs_in: + raise ValueError( + f"Refusing to overwrite category directory '{install_dir}' " + f"which contains {len(skill_dirs_in)} skill(s): " + f"{', '.join(sorted(skill_dirs_in))}. " + f"Use a different --name or install into a subcategory." + ) + + +def install_from_quarantine( + quarantine_path: Path, + skill_name: str, + category: str, + bundle: SkillBundle, + scan_result: ScanResult, + scan_provenance: Optional[Dict[str, Any]] = None, +) -> Path: + """Move a scanned skill from quarantine into the skills directory.""" + from tools.skills_hub import HubLockFile, _quarantine_dir, _skills_dir, append_audit_log + safe_skill_name = _validate_skill_name(skill_name) + safe_category = _validate_install_parent_path(category) if category else "" + quarantine_resolved = quarantine_path.resolve() + if not quarantine_resolved.is_relative_to(_quarantine_dir().resolve()): + raise ValueError(f"Unsafe quarantine path: {quarantine_path}") + + install_rel_path = f"{safe_category}/{safe_skill_name}" if safe_category else safe_skill_name + # Same validator the uninstaller uses, so a lock entry can never point at a + # symlink-redirected target. + install_dir = _resolve_lock_install_path(install_rel_path, safe_skill_name) + _check_install_target(install_dir) + if install_dir.exists(): + shutil.rmtree(install_dir) + + skill_md = quarantine_path / "SKILL.md" + if skill_md.exists(): + try: + skill_size = skill_md.stat().st_size + if skill_size > 100_000: + logger.warning( + "Skill '%s' has a large SKILL.md (%s chars). " + "Large skills consume significant context when loaded. " + "Consider asking the author to split it into smaller files.", + safe_skill_name, + f"{skill_size:,}", + ) + except OSError: + pass + + # A symlink in the bundle would copy its target into skills/ and leak it + # to the agent on the next skill_view. + for entry in quarantine_path.rglob("*"): + if not _is_path_redirect(entry): + continue + try: + rel = entry.relative_to(quarantine_resolved) + except ValueError: + rel = entry + raise ValueError( + f"Installed skill contains symlinks, which is not allowed: {rel}" + ) + + install_dir.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(quarantine_path), str(install_dir)) + + installed_hash = content_hash(install_dir) + HubLockFile().record_install( + name=safe_skill_name, + source=bundle.source, + identifier=bundle.identifier, + trust_level=bundle.trust_level, + scan_verdict=scan_result.verdict, + skill_hash=installed_hash, + install_path=install_dir.resolve().relative_to(_skills_dir().resolve()).as_posix(), + files=list(bundle.files.keys()), + metadata=bundle.metadata, + scan_provenance=scan_provenance or getattr(scan_result, "scan_provenance", None), + ) + + append_audit_log( + "INSTALL", safe_skill_name, bundle.source, + bundle.trust_level, scan_result.verdict, + installed_hash, + ) + + try: + from tools.skill_usage import record_installed + + record_installed(safe_skill_name) + except Exception: + logger.debug( + "Unable to record skill install lifecycle for %s", + safe_skill_name, + exc_info=True, + ) + + return install_dir + + +def uninstall_skill(skill_name: str) -> Tuple[bool, str]: + """Remove a hub-installed skill. Refuses to remove builtins.""" + from tools.skills_hub import HubLockFile, append_audit_log + lock = HubLockFile() + entry = lock.get_installed(skill_name) + if not entry: + return False, f"'{skill_name}' is not a hub-installed skill (may be a builtin)" + + # The destructive boundary: whatever reaches rmtree MUST be inside + # SKILLS_DIR and MUST NOT be SKILLS_DIR itself (see _resolve_lock_install_path). + try: + install_path = _resolve_lock_install_path(entry.get("install_path", ""), skill_name) + except ValueError as exc: + return False, f"Refusing to uninstall '{skill_name}': {exc}" + + if install_path.exists(): + shutil.rmtree(install_path) + + lock.record_uninstall(skill_name) + append_audit_log("UNINSTALL", skill_name, entry["source"], entry["trust_level"], "n/a", "user_request") + + return True, f"Uninstalled '{skill_name}' from {entry['install_path']}" + + +def bundle_content_hash(bundle: SkillBundle) -> str: + """Deterministic hash of an in-memory bundle. + + MUST stay symmetric with ``tools.skills_guard.content_hash`` (same skill + from disk), which keys files by POSIX relative path. Windows bundle keys + carry backslashes, which changed both bytes and sort order and made every + skill report ``update_available`` forever — normalize before hashing. The + path is hashed too so swapping contents between two files changes the hash. + """ + h = hashlib.sha256() + normalized = { + rel_path.replace("\\", "/"): content + for rel_path, content in bundle.files.items() + } + for rel_path in sorted(normalized): + h.update(rel_path.encode("utf-8")) + h.update(b"\x00") + content = normalized[rel_path] + h.update(content if isinstance(content, bytes) else content.encode("utf-8")) + return f"sha256:{h.hexdigest()[:16]}" + + +_SOURCE_ID_ALIASES = {"skills.sh": "skills-sh"} + + +def _source_matches(source: SkillSource, source_name: str) -> bool: + return source.source_id() == _SOURCE_ID_ALIASES.get(source_name, source_name) + + +def check_for_skill_updates( + name: Optional[str] = None, + *, + lock: Optional[HubLockFile] = None, + sources: Optional[List[SkillSource]] = None, + auth: Optional[GitHubAuth] = None, +) -> List[dict]: + """Check installed hub skills for upstream changes. + + Each entry is fetched ONLY from adapters matching its recorded source. + Falling back to all sources let a same-named skill in a different registry + satisfy the fetch and silently reassign provenance (names are not + namespaced across registries), so a missing adapter reports "unavailable". + """ + from tools.skills_hub import HubLockFile, create_source_router + lock = lock or HubLockFile() + installed = lock.list_installed() + if name: + installed = [entry for entry in installed if entry.get("name") == name] + + if sources is None: + sources = create_source_router(auth=auth) + + results: List[dict] = [] + for entry in installed: + identifier = entry.get("identifier", "") + source_name = entry.get("source", "") + row = {"name": entry.get("name", ""), "identifier": identifier, "source": source_name} + + bundle = None + for src in sources: + if not _source_matches(src, source_name): + continue + try: + bundle = src.fetch(identifier) + except Exception: + bundle = None + if bundle: + break + + if not bundle: + results.append({**row, "status": "unavailable"}) + continue + + current_hash = entry.get("content_hash", "") + latest_hash = bundle_content_hash(bundle) + results.append({ + **row, + "status": "up_to_date" if current_hash == latest_hash else "update_available", + "current_hash": current_hash, + "latest_hash": latest_hash, + "bundle": bundle, + }) + + return results From 208e5b23129701599102ffee3825b9274cca260f Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:53:18 -0700 Subject: [PATCH 06/10] refactor(skills_hub): table-driven hub path resolvers; extract index fetch + source router + parallel search to skills_hub_search --- tools/skills_hub.py | 264 ++++--------------------------------- tools/skills_hub_search.py | 238 +++++++++++++++++++++++++++++++++ 2 files changed, 267 insertions(+), 235 deletions(-) create mode 100644 tools/skills_hub_search.py diff --git a/tools/skills_hub.py b/tools/skills_hub.py index cde0aaa0c7..9a6d07806e 100644 --- a/tools/skills_hub.py +++ b/tools/skills_hub.py @@ -15,7 +15,7 @@ import logging import time from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional from urllib.parse import urljoin import httpx @@ -40,6 +40,19 @@ from tools.skills_hub_sources import ( # noqa: F401 WellKnownSkillSource, UrlSource, LobeHubSource, BrowseShSource, ) from tools.skills_hub_official import OptionalSkillSource, HermesIndexSource # noqa: F401 +from tools.skills_hub_search import ( # noqa: F401 (re-exported; tests patch tools.skills_hub.) + HERMES_INDEX_TTL, + HERMES_INDEX_URL, + _API_SOURCE_IDS, + _hermes_index_cache_file, + _load_hermes_index, + _load_stale_index_cache, + _search_one_source, + _select_active_sources, + create_source_router, + parallel_search_sources, + unified_search, +) from tools.skills_hub_install import ( # noqa: F401 (re-exported; tests patch tools.skills_hub.) _SOURCE_ID_ALIASES, _category_skill_dirs, @@ -68,44 +81,27 @@ logger = logging.getLogger(__name__) INDEX_CACHE_TTL = 3600 # 1 hour -def _path(name: str, default): - """A test-injected real module attribute (patch.object/monkeypatch on - SKILLS_DIR etc.) wins over live resolution.""" - forced = globals().get(name) - return Path(forced) if forced is not None else default() +def _path_resolver(name: str, default): + """Resolver for a hub path: a test-injected real module attribute + (patch.object/monkeypatch on SKILLS_DIR etc.) wins over live resolution.""" + def resolve() -> Path: + forced = globals().get(name) + return Path(forced) if forced is not None else default() + resolve.__name__ = f"_{name.lower()}" + return resolve def _hermes_home() -> Path: return get_hermes_home() -def _skills_dir() -> Path: - return _path("SKILLS_DIR", lambda: _hermes_home() / "skills") - - -def _hub_dir() -> Path: - return _path("HUB_DIR", lambda: _skills_dir() / ".hub") - - -def _lock_file() -> Path: - return _path("LOCK_FILE", lambda: _hub_dir() / "lock.json") - - -def _quarantine_dir() -> Path: - return _path("QUARANTINE_DIR", lambda: _hub_dir() / "quarantine") - - -def _audit_log() -> Path: - return _path("AUDIT_LOG", lambda: _hub_dir() / "audit.log") - - -def _taps_file() -> Path: - return _path("TAPS_FILE", lambda: _hub_dir() / "taps.json") - - -def _index_cache_dir() -> Path: - return _path("INDEX_CACHE_DIR", lambda: _hub_dir() / "index-cache") - +_skills_dir = _path_resolver("SKILLS_DIR", lambda: _hermes_home() / "skills") +_hub_dir = _path_resolver("HUB_DIR", lambda: _skills_dir() / ".hub") +_lock_file = _path_resolver("LOCK_FILE", lambda: _hub_dir() / "lock.json") +_quarantine_dir = _path_resolver("QUARANTINE_DIR", lambda: _hub_dir() / "quarantine") +_audit_log = _path_resolver("AUDIT_LOG", lambda: _hub_dir() / "audit.log") +_taps_file = _path_resolver("TAPS_FILE", lambda: _hub_dir() / "taps.json") +_index_cache_dir = _path_resolver("INDEX_CACHE_DIR", lambda: _hub_dir() / "index-cache") _DYNAMIC_PATH_RESOLVERS = { "HERMES_HOME": _hermes_home, @@ -384,210 +380,8 @@ def ensure_hub_dirs() -> None: # Hermes centralized index (data source for HermesIndexSource) # --------------------------------------------------------------------------- -HERMES_INDEX_URL = "https://hermes-agent.nousresearch.com/docs/api/skills-index.json" -HERMES_INDEX_TTL = 6 * 3600 # 6 hours - - -def _hermes_index_cache_file() -> Path: - return _index_cache_dir() / "hermes-index.json" - - -def _load_hermes_index() -> Optional[dict]: - """Fetch the centralized skills index (docs site, rebuilt daily), cached - locally for HERMES_INDEX_TTL; on any failure serve the stale cache. - - Brotli is deliberately NOT negotiated: the index is tens of MB and httpx's - streaming Brotli decoder (brotlicffi, pinned for Discord attachments) raises - DecodingError on payloads this size — which surfaced as a silently empty - Skills Hub. gzip/deflate first; the identity retry covers proxies that - ignore the header and return Brotli anyway. - """ - cache_file = _hermes_index_cache_file() - cached = _read_json_if_fresh(cache_file, HERMES_INDEX_TTL) - if cached is not None: - return cached - - data = None - for accept_encoding in ("gzip, deflate", "identity"): - try: - resp = httpx.get( - HERMES_INDEX_URL, - timeout=15, - follow_redirects=True, - headers={"Accept-Encoding": accept_encoding}, - ) - if resp.status_code != 200: - logger.debug("Hermes index fetch returned %d", resp.status_code) - return _load_stale_index_cache() - data = resp.json() - break - except httpx.DecodingError as e: - logger.debug( - "Hermes index decode failed (Accept-Encoding=%s): %s", - accept_encoding, - e, - ) - continue - except (httpx.HTTPError, json.JSONDecodeError) as e: - logger.debug("Hermes index fetch failed: %s", e) - return _load_stale_index_cache() - - if not isinstance(data, dict) or "skills" not in data: - return _load_stale_index_cache() - - try: - cache_file.parent.mkdir(parents=True, exist_ok=True) - cache_file.write_text(json.dumps(data), encoding="utf-8") - except OSError: - pass - - return data - - -def _load_stale_index_cache() -> Optional[dict]: - """Fall back to the cache regardless of age when the network fetch fails.""" - return _read_json_if_fresh(_hermes_index_cache_file(), float("inf")) - # --------------------------------------------------------------------------- # Source router + parallel search # --------------------------------------------------------------------------- -# External API sources the centralized index already covers; skipped when the -# index is available and no source filter is active (~70 GitHub calls/search -# for unauthenticated users otherwise). -_API_SOURCE_IDS = frozenset({"github", "skills-sh", "clawhub", "lobehub", "well-known"}) - - -def create_source_router(auth: Optional[GitHubAuth] = None) -> List[SkillSource]: - """All configured source adapters, in priority order.""" - if auth is None: - auth = GitHubAuth() - - return [ - OptionalSkillSource(auth=auth), # official optional skills (highest priority) - HermesIndexSource(auth=auth), # centralized index (search + resolved install paths) - SkillsShSource(auth=auth), - WellKnownSkillSource(), - UrlSource(), # direct HTTP(S) URL to a SKILL.md - GitHubSource(auth=auth, extra_taps=TapsManager().list_taps()), - ClawHubSource(), - LobeHubSource(), - BrowseShSource(), # browse.sh site-specific browser skills - ] - - -def _search_one_source( - src: SkillSource, query: str, limit: int -) -> Tuple[str, List[SkillMeta]]: - """Search a single source. Runs in a thread for parallelism.""" - try: - return src.source_id(), src.search(query, limit=limit) - except Exception as e: - logger.debug("Search failed for %s: %s", src.source_id(), e) - return src.source_id(), [] - - -def _select_active_sources(sources: List[SkillSource], source_filter: str) -> List[SkillSource]: - """Sources to query for ``source_filter``. - - A provider filter (nvidia/openai/...) is not a source id — the data lives - in the index/github source under ``extra.provider`` — so it selects like - "all"; the narrowing happens later on the merged results. "official" is - always included alongside an explicit source filter. - """ - effective = "all" if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES else source_filter - index_available = effective == "all" and any( - src.source_id() == "hermes-index" and getattr(src, "is_available", False) - for src in sources - ) - active: List[SkillSource] = [] - for src in sources: - sid = src.source_id() - if effective != "all" and sid != effective and sid != "official": - continue - if index_available and sid in _API_SOURCE_IDS: - continue - active.append(src) - return active - - -def parallel_search_sources( - sources: List[SkillSource], - query: str = "", - per_source_limits: Optional[Dict[str, int]] = None, - source_filter: str = "all", - overall_timeout: float = 30, - on_source_done: Optional[Any] = None, -) -> Tuple[List[SkillMeta], Dict[str, int], List[str]]: - """Search all sources in parallel with an overall timeout. - - Returns ``(all_results, source_counts, timed_out_ids)``. *on_source_done* - is an optional ``(source_id, count) -> None`` progress callback. - """ - from concurrent.futures import as_completed - - per_source_limits = per_source_limits or {} - active = _select_active_sources(sources, source_filter) - - all_results: List[SkillMeta] = [] - source_counts: Dict[str, int] = {} - timed_out_ids: List[str] = [] - - if not active: - return all_results, source_counts, timed_out_ids - - # Not a ``with`` block: its shutdown(wait=True) would block on a slow source - # (ClawHub) for minutes and defeat ``overall_timeout``. Daemon workers so an - # abandoned source cannot block interpreter exit either. - from tools.daemon_pool import DaemonThreadPoolExecutor - pool = DaemonThreadPoolExecutor(max_workers=min(len(active), 8)) - futures = { - pool.submit(_search_one_source, src, query, per_source_limits.get(src.source_id(), 50)): src.source_id() - for src in active - } - - try: - try: - for fut in as_completed(futures, timeout=overall_timeout): - try: - sid, results = fut.result(timeout=0) - source_counts[sid] = len(results) - all_results.extend(results) - if on_source_done: - on_source_done(sid, len(results)) - except Exception: - pass - except TimeoutError: - timed_out_ids = [futures[f] for f in futures if not f.done()] - if timed_out_ids: - logger.debug( - "Skills browse timed out waiting for: %s", - ", ".join(timed_out_ids), - ) - finally: - pool.shutdown(wait=False, cancel_futures=True) - - return all_results, source_counts, timed_out_ids - - -def unified_search(query: str, sources: List[SkillSource], - source_filter: str = "all", limit: int = 10) -> List[SkillMeta]: - """Search all sources (in parallel) and merge results.""" - all_results, _, _ = parallel_search_sources( - sources, - query=query, - source_filter=source_filter, - overall_timeout=30, - ) - - # Provider filters target ``extra.provider`` on the merged set, not a source id. - if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES: - all_results = _filter_results_by_provider(all_results, source_filter) - - deduped = _dedupe_by_trust(all_results) - # Stable-sort by trust before truncating so the limit cut never drops a - # builtin/official entry because a high-volume community source finished - # first; insertion order is preserved within each rank. - deduped.sort(key=lambda r: -TRUST_RANK.get(r.trust_level, 0)) - return deduped[:limit] diff --git a/tools/skills_hub_search.py b/tools/skills_hub_search.py new file mode 100644 index 0000000000..78bec5406f --- /dev/null +++ b/tools/skills_hub_search.py @@ -0,0 +1,238 @@ +"""Skills Hub discovery: the centralized Hermes index fetch (cached, stale-fallback), the source router, and parallel/unified search across source adapters. + +Split out of ``tools/skills_hub.py``; every public/patched name is re-imported there, +so ``tools.skills_hub.`` keeps resolving (and monkeypatching) as before. +""" + +from __future__ import annotations + +import logging +import httpx +import json +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple +from tools.skills_hub_github import _PROVIDER_FILTER_VALUES +from tools.skills_hub_models import SkillMeta, SkillSource, TRUST_RANK, _dedupe_by_trust +from tools.skills_hub_skillssh import SkillsShSource +from tools.skills_hub_sources import LobeHubSource, WellKnownSkillSource + +if TYPE_CHECKING: # runtime use resolves through the origin (test patch target) + from tools.skills_hub_github import GitHubAuth + +# Log-record parity with the origin module. +logger = logging.getLogger("tools.skills_hub") + + +HERMES_INDEX_URL = "https://hermes-agent.nousresearch.com/docs/api/skills-index.json" + + +HERMES_INDEX_TTL = 6 * 3600 # 6 hours + + +def _hermes_index_cache_file() -> Path: + from tools.skills_hub import _index_cache_dir + return _index_cache_dir() / "hermes-index.json" + + +def _load_hermes_index() -> Optional[dict]: + """Fetch the centralized skills index (docs site, rebuilt daily), cached + locally for HERMES_INDEX_TTL; on any failure serve the stale cache. + + Brotli is deliberately NOT negotiated: the index is tens of MB and httpx's + streaming Brotli decoder (brotlicffi, pinned for Discord attachments) raises + DecodingError on payloads this size — which surfaced as a silently empty + Skills Hub. gzip/deflate first; the identity retry covers proxies that + ignore the header and return Brotli anyway. + """ + from tools.skills_hub import _hermes_index_cache_file, _read_json_if_fresh + cache_file = _hermes_index_cache_file() + cached = _read_json_if_fresh(cache_file, HERMES_INDEX_TTL) + if cached is not None: + return cached + + data = None + for accept_encoding in ("gzip, deflate", "identity"): + try: + resp = httpx.get( + HERMES_INDEX_URL, + timeout=15, + follow_redirects=True, + headers={"Accept-Encoding": accept_encoding}, + ) + if resp.status_code != 200: + logger.debug("Hermes index fetch returned %d", resp.status_code) + return _load_stale_index_cache() + data = resp.json() + break + except httpx.DecodingError as e: + logger.debug( + "Hermes index decode failed (Accept-Encoding=%s): %s", + accept_encoding, + e, + ) + continue + except (httpx.HTTPError, json.JSONDecodeError) as e: + logger.debug("Hermes index fetch failed: %s", e) + return _load_stale_index_cache() + + if not isinstance(data, dict) or "skills" not in data: + return _load_stale_index_cache() + + try: + cache_file.parent.mkdir(parents=True, exist_ok=True) + cache_file.write_text(json.dumps(data), encoding="utf-8") + except OSError: + pass + + return data + + +def _load_stale_index_cache() -> Optional[dict]: + """Fall back to the cache regardless of age when the network fetch fails.""" + from tools.skills_hub import _hermes_index_cache_file, _read_json_if_fresh + return _read_json_if_fresh(_hermes_index_cache_file(), float("inf")) + + +# External API sources the centralized index already covers; skipped when the +# index is available and no source filter is active (~70 GitHub calls/search +# for unauthenticated users otherwise). +_API_SOURCE_IDS = frozenset({"github", "skills-sh", "clawhub", "lobehub", "well-known"}) + + +def create_source_router(auth: Optional[GitHubAuth] = None) -> List[SkillSource]: + """All configured source adapters, in priority order.""" + from tools.skills_hub import ( # adapters resolve via origin: tests patch them there + BrowseShSource, ClawHubSource, GitHubAuth, GitHubSource, HermesIndexSource, + OptionalSkillSource, TapsManager, UrlSource, + ) + if auth is None: + auth = GitHubAuth() + + return [ + OptionalSkillSource(auth=auth), # official optional skills (highest priority) + HermesIndexSource(auth=auth), # centralized index (search + resolved install paths) + SkillsShSource(auth=auth), + WellKnownSkillSource(), + UrlSource(), # direct HTTP(S) URL to a SKILL.md + GitHubSource(auth=auth, extra_taps=TapsManager().list_taps()), + ClawHubSource(), + LobeHubSource(), + BrowseShSource(), # browse.sh site-specific browser skills + ] + + +def _search_one_source( + src: SkillSource, query: str, limit: int +) -> Tuple[str, List[SkillMeta]]: + """Search a single source. Runs in a thread for parallelism.""" + try: + return src.source_id(), src.search(query, limit=limit) + except Exception as e: + logger.debug("Search failed for %s: %s", src.source_id(), e) + return src.source_id(), [] + + +def _select_active_sources(sources: List[SkillSource], source_filter: str) -> List[SkillSource]: + """Sources to query for ``source_filter``. + + A provider filter (nvidia/openai/...) is not a source id — the data lives + in the index/github source under ``extra.provider`` — so it selects like + "all"; the narrowing happens later on the merged results. "official" is + always included alongside an explicit source filter. + """ + effective = "all" if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES else source_filter + index_available = effective == "all" and any( + src.source_id() == "hermes-index" and getattr(src, "is_available", False) + for src in sources + ) + active: List[SkillSource] = [] + for src in sources: + sid = src.source_id() + if effective != "all" and sid != effective and sid != "official": + continue + if index_available and sid in _API_SOURCE_IDS: + continue + active.append(src) + return active + + +def parallel_search_sources( + sources: List[SkillSource], + query: str = "", + per_source_limits: Optional[Dict[str, int]] = None, + source_filter: str = "all", + overall_timeout: float = 30, + on_source_done: Optional[Any] = None, +) -> Tuple[List[SkillMeta], Dict[str, int], List[str]]: + """Search all sources in parallel with an overall timeout. + + Returns ``(all_results, source_counts, timed_out_ids)``. *on_source_done* + is an optional ``(source_id, count) -> None`` progress callback. + """ + from concurrent.futures import as_completed + + per_source_limits = per_source_limits or {} + active = _select_active_sources(sources, source_filter) + + all_results: List[SkillMeta] = [] + source_counts: Dict[str, int] = {} + timed_out_ids: List[str] = [] + + if not active: + return all_results, source_counts, timed_out_ids + + # Not a ``with`` block: its shutdown(wait=True) would block on a slow source + # (ClawHub) for minutes and defeat ``overall_timeout``. Daemon workers so an + # abandoned source cannot block interpreter exit either. + from tools.daemon_pool import DaemonThreadPoolExecutor + pool = DaemonThreadPoolExecutor(max_workers=min(len(active), 8)) + futures = { + pool.submit(_search_one_source, src, query, per_source_limits.get(src.source_id(), 50)): src.source_id() + for src in active + } + + try: + try: + for fut in as_completed(futures, timeout=overall_timeout): + try: + sid, results = fut.result(timeout=0) + source_counts[sid] = len(results) + all_results.extend(results) + if on_source_done: + on_source_done(sid, len(results)) + except Exception: + pass + except TimeoutError: + timed_out_ids = [futures[f] for f in futures if not f.done()] + if timed_out_ids: + logger.debug( + "Skills browse timed out waiting for: %s", + ", ".join(timed_out_ids), + ) + finally: + pool.shutdown(wait=False, cancel_futures=True) + + return all_results, source_counts, timed_out_ids + + +def unified_search(query: str, sources: List[SkillSource], + source_filter: str = "all", limit: int = 10) -> List[SkillMeta]: + """Search all sources (in parallel) and merge results.""" + from tools.skills_hub import _filter_results_by_provider, parallel_search_sources + all_results, _, _ = parallel_search_sources( + sources, + query=query, + source_filter=source_filter, + overall_timeout=30, + ) + + # Provider filters target ``extra.provider`` on the merged set, not a source id. + if source_filter.strip().lower() in _PROVIDER_FILTER_VALUES: + all_results = _filter_results_by_provider(all_results, source_filter) + + deduped = _dedupe_by_trust(all_results) + # Stable-sort by trust before truncating so the limit cut never drops a + # builtin/official entry because a high-volume community source finished + # first; insertion order is preserved within each rank. + deduped.sort(key=lambda r: -TRUST_RANK.get(r.trust_level, 0)) + return deduped[:limit] From 428dcfd3a60bd6a51f9e52cf36914a0f436611cb Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:54:15 -0700 Subject: [PATCH 07/10] refactor(terminal): lift pre-exec block sequence into _pre_exec_block --- tools/terminal_tool.py | 46 +++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index 7cb7a6d63a..b12d0bf8d4 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -1224,6 +1224,34 @@ def _run_foreground( ) +def _pre_exec_block( + command: str, *, env: Any, env_type: str, cwd: str, + workdir: Optional[str], session_key: str, +) -> Optional[str]: + """Finished blocked-result JSON when the command must not run, else None. + + Order matters: gateway lifecycle first (protects the running gateway), + then the dangerous-workdir check, then the self-repo guard (local only). + """ + blocked = gateway_lifecycle_block( + command=command, env=env, env_type=env_type, cwd=cwd, + workdir=workdir, session_key=session_key, + ) + if blocked: + return blocked + if workdir: + workdir_error = _validate_workdir(workdir) + if workdir_error: + logger.warning("Blocked dangerous workdir: %s (command: %s)", + workdir[:200], _safe_command_preview(command)) + return _error_json(workdir_error, status="blocked") + if env_type == "local": + return self_repo_block( + command=command, cwd=cwd, workdir=workdir, session_key=session_key, + ) or None + return None + + def terminal_tool( command: str, background: bool = False, @@ -1269,27 +1297,13 @@ def terminal_tool( session_key = get_current_session_key(default="") or (task_id or "") - blocked = gateway_lifecycle_block( - command=command, env=env, env_type=env_type, cwd=cwd, + blocked = _pre_exec_block( + command, env=env, env_type=env_type, cwd=cwd, workdir=workdir, session_key=session_key, ) if blocked: return blocked - if workdir: - workdir_error = _validate_workdir(workdir) - if workdir_error: - logger.warning("Blocked dangerous workdir: %s (command: %s)", - workdir[:200], _safe_command_preview(command)) - return _error_json(workdir_error, status="blocked") - - if env_type == "local": - blocked = self_repo_block( - command=command, cwd=cwd, workdir=workdir, session_key=session_key, - ) - if blocked: - return blocked - # Pre-exec security checks (tirith + dangerous command detection); # force=True means the user already confirmed. verdict = _run_approval_guards(command, env_type, plan.config, force=force) From a8f3dc4946f3699959fecb0a27de8617b0713be3 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:54:47 -0700 Subject: [PATCH 08/10] refactor(termhub): derive ensure_hub_dirs seeds from state-file EMPTY shapes; module docstrings name the split companions --- tools/skills_hub.py | 14 ++++++++------ tools/terminal_tool.py | 10 +++++++--- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/tools/skills_hub.py b/tools/skills_hub.py index 9a6d07806e..e3cce82aee 100644 --- a/tools/skills_hub.py +++ b/tools/skills_hub.py @@ -2,10 +2,12 @@ """ Skills Hub — hub state management and the public facade for the source adapters. -Library module (not an agent tool). Owns the hub paths, index cache, lock file, -taps, audit log, quarantine/install/uninstall, update checks, and the source -router; the adapters live in the ``tools.skills_hub_*`` siblings and are -re-exported here so ``from tools.skills_hub import X`` keeps working. +Library module (not an agent tool). Owns the hub paths, guarded HTTP, index +cache, lock file, taps and audit log. Install/uninstall/update live in +``skills_hub_install``, the index fetch/source router/search in +``skills_hub_search``, and the adapters in the other ``tools.skills_hub_*`` +siblings; all are re-exported here so ``from tools.skills_hub import X`` keeps +working (and stays the test patch target). Used by hermes_cli/skills_hub.py for CLI commands and the /skills slash command. """ @@ -368,9 +370,9 @@ def ensure_hub_dirs() -> None: _quarantine_dir().mkdir(exist_ok=True) _index_cache_dir().mkdir(exist_ok=True) for path, initial in ( - (_lock_file(), '{"version": 1, "installed": {}}\n'), + (_lock_file(), json.dumps(HubLockFile.EMPTY) + "\n"), (_audit_log(), ""), - (_taps_file(), '{"taps": []}\n'), + (_taps_file(), json.dumps(TapsManager.EMPTY) + "\n"), ): if not path.exists(): path.write_text(initial, encoding="utf-8") diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index b12d0bf8d4..f23e54150f 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -9,9 +9,13 @@ Cloud-sandbox persistent filesystems preserve working state across sandbox recreation but do NOT guarantee the same live sandbox or long-running processes survive cleanup, idle reaping, or Hermes exit. -Companion modules: ``terminal_tool_guards`` (pre-exec blocks), -``terminal_tool_background`` (background spawn), ``terminal_tool_result`` -(foreground result post-processing). +Companion modules (all re-exported here, so ``tools.terminal_tool.`` +stays the import/patch target): ``terminal_tool_config`` (TERMINAL_* reads), +``terminal_tool_backends`` (env builders + requirement checkers), +``terminal_tool_lifecycle`` (reaper/teardown/ensure_task_env), +``terminal_tool_sudo`` (sudo password + shell rewrites), ``terminal_tool_guards`` +(pre-exec blocks), ``terminal_tool_background`` (background spawn), +``terminal_tool_result`` (foreground result post-processing). """ import json From d320d5f74152e5ecbe7c8b283938f0c9d4471c78 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 15:59:18 -0700 Subject: [PATCH 09/10] refactor(termhub): compact re-export blocks and wrap companion-module docstrings --- tools/skills_hub.py | 37 +++-------- tools/skills_hub_install.py | 4 +- tools/skills_hub_search.py | 6 +- tools/terminal_tool.py | 104 ++++++++----------------------- tools/terminal_tool_backends.py | 7 ++- tools/terminal_tool_config.py | 5 +- tools/terminal_tool_lifecycle.py | 6 +- tools/terminal_tool_sudo.py | 6 +- 8 files changed, 56 insertions(+), 119 deletions(-) diff --git a/tools/skills_hub.py b/tools/skills_hub.py index e3cce82aee..1bb60a3e40 100644 --- a/tools/skills_hub.py +++ b/tools/skills_hub.py @@ -26,11 +26,10 @@ from hermes_constants import get_hermes_home from tools.url_safety import is_safe_url from tools.website_policy import check_website_access from tools.skills_hub_models import ( # noqa: F401 (re-exported public API) - SkillMeta, SkillBundle, SkillSource, source_url_for_bundle, - _referenced_support_paths, _normalize_bundle_path, _validate_skill_name, - _validate_install_parent_path, _normalize_lock_install_path, - _validate_bundle_rel_path, _skill_meta_to_dict, _parse_frontmatter, - _dedupe_by_trust, TRUST_RANK, + SkillMeta, SkillBundle, SkillSource, source_url_for_bundle, _referenced_support_paths, + _normalize_bundle_path, _validate_skill_name, _validate_install_parent_path, + _normalize_lock_install_path, _validate_bundle_rel_path, _skill_meta_to_dict, + _parse_frontmatter, _dedupe_by_trust, TRUST_RANK, ) from tools.skills_hub_github import ( # noqa: F401 GITHUB_TAP_PROVIDERS, github_provider_for, _PROVIDER_FILTER_VALUES, @@ -43,30 +42,14 @@ from tools.skills_hub_sources import ( # noqa: F401 ) from tools.skills_hub_official import OptionalSkillSource, HermesIndexSource # noqa: F401 from tools.skills_hub_search import ( # noqa: F401 (re-exported; tests patch tools.skills_hub.) - HERMES_INDEX_TTL, - HERMES_INDEX_URL, - _API_SOURCE_IDS, - _hermes_index_cache_file, - _load_hermes_index, - _load_stale_index_cache, - _search_one_source, - _select_active_sources, - create_source_router, - parallel_search_sources, - unified_search, + HERMES_INDEX_TTL, HERMES_INDEX_URL, _API_SOURCE_IDS, _hermes_index_cache_file, + _load_hermes_index, _load_stale_index_cache, _search_one_source, _select_active_sources, + create_source_router, parallel_search_sources, unified_search, ) from tools.skills_hub_install import ( # noqa: F401 (re-exported; tests patch tools.skills_hub.) - _SOURCE_ID_ALIASES, - _category_skill_dirs, - _check_install_target, - _is_path_redirect, - _resolve_lock_install_path, - _source_matches, - bundle_content_hash, - check_for_skill_updates, - install_from_quarantine, - quarantine_bundle, - uninstall_skill, + _SOURCE_ID_ALIASES, _category_skill_dirs, _check_install_target, _is_path_redirect, + _resolve_lock_install_path, _source_matches, bundle_content_hash, check_for_skill_updates, + install_from_quarantine, quarantine_bundle, uninstall_skill, ) logger = logging.getLogger(__name__) diff --git a/tools/skills_hub_install.py b/tools/skills_hub_install.py index f750ea3260..de878170e0 100644 --- a/tools/skills_hub_install.py +++ b/tools/skills_hub_install.py @@ -1,4 +1,6 @@ -"""Skills Hub install/uninstall/update operations: quarantine staging, install-target safety (symlink/junction, category-bucket and nested-skill checks), lock-file-backed uninstall, bundle hashing and upstream update checks. +"""Skills Hub install/uninstall/update operations: quarantine staging, install- +target safety (symlink/junction, category-bucket and nested-skill checks), +lock-file-backed uninstall, bundle hashing and upstream update checks. Split out of ``tools/skills_hub.py``; every public/patched name is re-imported there, so ``tools.skills_hub.`` keeps resolving (and monkeypatching) as before. diff --git a/tools/skills_hub_search.py b/tools/skills_hub_search.py index 78bec5406f..ac8f12c1ee 100644 --- a/tools/skills_hub_search.py +++ b/tools/skills_hub_search.py @@ -1,4 +1,6 @@ -"""Skills Hub discovery: the centralized Hermes index fetch (cached, stale-fallback), the source router, and parallel/unified search across source adapters. +"""Skills Hub discovery: the centralized Hermes index fetch (cached, stale- +fallback), the source router, and parallel/unified search across source +adapters. Split out of ``tools/skills_hub.py``; every public/patched name is re-imported there, so ``tools.skills_hub.`` keeps resolving (and monkeypatching) as before. @@ -22,10 +24,8 @@ if TYPE_CHECKING: # runtime use resolves through the origin (test patch target) # Log-record parity with the origin module. logger = logging.getLogger("tools.skills_hub") - HERMES_INDEX_URL = "https://hermes-agent.nousresearch.com/docs/api/skills-index.json" - HERMES_INDEX_TTL = 6 * 3600 # 6 hours diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py index f23e54150f..425f86e906 100644 --- a/tools/terminal_tool.py +++ b/tools/terminal_tool.py @@ -45,79 +45,34 @@ def _redact_terminal_error_text(value: Any) -> str: from tools.interrupt import is_interrupted, _interrupt_event # noqa: F401 — re-exported from tools.registry import tool_error from tools.terminal_tool_lifecycle import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.) - _DISK_USAGE_CACHE_TTL, - _check_disk_usage_warning, - _cleanup_inactive_envs, - _clear_file_ops_cache, - _create_configured_env, - _disk_usage_cache, - _evict_environment_for_task, - _teardown_env, - cleanup_all_environments, - cleanup_vm, - ensure_task_env, - get_active_env, - is_persistent_env, + _DISK_USAGE_CACHE_TTL, _check_disk_usage_warning, _cleanup_inactive_envs, + _clear_file_ops_cache, _create_configured_env, _disk_usage_cache, + _evict_environment_for_task, _teardown_env, cleanup_all_environments, cleanup_vm, + ensure_task_env, get_active_env, is_persistent_env, ) from tools.terminal_tool_config import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.) - _CONTAINER_BACKENDS, - _HOST_CWD_PREFIXES, - _get_plugin_env_provider, - _is_container_backend, - _is_unusable_container_cwd, - _parse_env_var, - _plugin_env_flag, - _safe_getcwd, - _tenv, + _CONTAINER_BACKENDS, _HOST_CWD_PREFIXES, _get_plugin_env_provider, _is_container_backend, + _is_unusable_container_cwd, _parse_env_var, _plugin_env_flag, _safe_getcwd, _tenv, _tenv_bool, ) from tools.terminal_tool_backends import ( # noqa: F401 (re-exported; tests patch tools.terminal_tool.) - _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, + _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.) - _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, + _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.tool_backend_helpers import ( # noqa: F401 (managed_nous_tools_enabled: test patch target) @@ -848,23 +803,14 @@ def _command_requires_pipe_stdin(command: str) -> bool: from tools.terminal_tool_guards import ( # noqa: F401 — re-exported (tests, plugins) - _LONG_LIVED_FOREGROUND_PATTERNS, - _SHELL_LEVEL_BACKGROUND_RE, - _WORKDIR_SAFE_ASCII_CHARS, - _foreground_background_guidance, - _is_safe_workdir_char, - _looks_like_help_or_version_command, - _safe_command_preview, - _strip_quotes, - _validate_workdir, - gateway_lifecycle_block, - self_repo_block, + _LONG_LIVED_FOREGROUND_PATTERNS, _SHELL_LEVEL_BACKGROUND_RE, _WORKDIR_SAFE_ASCII_CHARS, + _foreground_background_guidance, _is_safe_workdir_char, + _looks_like_help_or_version_command, _safe_command_preview, _strip_quotes, + _validate_workdir, gateway_lifecycle_block, self_repo_block, ) from tools.terminal_tool_background import spawn_background_process from tools.terminal_tool_result import ( # noqa: F401 — re-exported (tests) - _SIGNAL_EXIT_NOTES, - _interpret_exit_code, - _interpret_signal_exit, + _SIGNAL_EXIT_NOTES, _interpret_exit_code, _interpret_signal_exit, finalize_foreground_result, ) diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.py index 1412b0d2d3..29432e5793 100644 --- a/tools/terminal_tool_backends.py +++ b/tools/terminal_tool_backends.py @@ -1,4 +1,7 @@ -"""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. +"""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.`` keeps resolving (and monkeypatching) as before. @@ -28,10 +31,8 @@ from tools.tool_backend_helpers import ( # 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") diff --git a/tools/terminal_tool_config.py b/tools/terminal_tool_config.py index 5e3e21bdf2..da39e7a193 100644 --- a/tools/terminal_tool_config.py +++ b/tools/terminal_tool_config.py @@ -1,4 +1,6 @@ -"""Terminal backend configuration: scope-aware TERMINAL_* reads, env-var parsing, container-cwd sanity checks, plugin-backend classification and the resolved config dict (_get_env_config). +"""Terminal backend configuration: scope-aware TERMINAL_* reads, env-var parsing, +container-cwd sanity checks, plugin-backend classification and the resolved +config dict (_get_env_config). Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there, so ``tools.terminal_tool.`` keeps resolving (and monkeypatching) as before. @@ -43,7 +45,6 @@ def _safe_getcwd() -> str: # dirs and Windows drive paths as they leak toward a Linux ``-w`` flag). _HOST_CWD_PREFIXES = ("/Users/", "/home/", "C:\\", "C:/") - _CONTAINER_BACKENDS = frozenset({"docker", "singularity", "modal", "daytona", "vercel_sandbox"}) diff --git a/tools/terminal_tool_lifecycle.py b/tools/terminal_tool_lifecycle.py index b5874bf508..6ff876084f 100644 --- a/tools/terminal_tool_lifecycle.py +++ b/tools/terminal_tool_lifecycle.py @@ -1,4 +1,7 @@ -"""Sandbox lifecycle for the terminal tool: idle reaping, teardown, manual/atexit cleanup, and the lazy ensure_task_env bring-up. The env cache dicts and locks stay in tools.terminal_tool (tests patch them there) and are read through it at call time. +"""Sandbox lifecycle for the terminal tool: idle reaping, teardown, manual/atexit +cleanup, and the lazy ensure_task_env bring-up. The env cache dicts and locks +stay in tools.terminal_tool (tests patch them there) and are read through it +at call time. Split out of ``tools/terminal_tool.py``; every public/patched name is re-imported there, so ``tools.terminal_tool.`` keeps resolving (and monkeypatching) as before. @@ -25,7 +28,6 @@ logger = logging.getLogger("tools.terminal_tool") # every command (a result up to 5 minutes stale is harmless). _disk_usage_cache: dict = {"timestamp": 0.0, "result": False} - _DISK_USAGE_CACHE_TTL = 300.0 # seconds diff --git a/tools/terminal_tool_sudo.py b/tools/terminal_tool_sudo.py index 786a94a403..ef09118a9b 100644 --- a/tools/terminal_tool_sudo.py +++ b/tools/terminal_tool_sudo.py @@ -1,4 +1,7 @@ -"""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. +"""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.`` keeps resolving (and monkeypatching) as before. @@ -23,7 +26,6 @@ logger = logging.getLogger("tools.terminal_tool") # 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() From f3810c4b97b8d2d4a4cc6e11ea64027a820fbaf8 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:07:36 -0700 Subject: [PATCH 10/10] refactor(skills_hub): keep ensure_hub_dirs seed literals (tests stub HubLockFile with a lambda) --- tools/skills_hub.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/skills_hub.py b/tools/skills_hub.py index 1bb60a3e40..224e3b6d81 100644 --- a/tools/skills_hub.py +++ b/tools/skills_hub.py @@ -353,9 +353,9 @@ def ensure_hub_dirs() -> None: _quarantine_dir().mkdir(exist_ok=True) _index_cache_dir().mkdir(exist_ok=True) for path, initial in ( - (_lock_file(), json.dumps(HubLockFile.EMPTY) + "\n"), + (_lock_file(), '{"version": 1, "installed": {}}\n'), (_audit_log(), ""), - (_taps_file(), json.dumps(TapsManager.EMPTY) + "\n"), + (_taps_file(), '{"taps": []}\n'), ): if not path.exists(): path.write_text(initial, encoding="utf-8")