The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools/terminal): split terminal_tool god method into helpers; dispatch tables; compact env probe/passthrough/daemon pool
Tekniumd4ded6750374
diff --git a/tools/close_terminal_tool.py b/tools/close_terminal_tool.pyindex 4ae8088fbd6..56bb2a102df 100644--- a/tools/close_terminal_tool.py+++ b/tools/close_terminal_tool.py@@ -1,15 +1,11 @@#!/usr/bin/env python3"""Close a read-only agent terminal tab in the Hermes desktop GUI.-Each ``terminal(background=true)`` process is mirrored as a read-only tab in the-desktop's terminal pane. This tool lets the agent drop a tab it no longer needs-to show — WITHOUT killing the process (use ``process(action='kill')`` for that).-The output keeps buffering and the user can reopen the tab from the status stack.--It routes through the process registry's ``on_close`` sink, which the desktop-gateway wires to emit a ``terminal.close`` event the renderer handles. Like-``read_terminal`` it lives in the ``desktop_ui`` toolset, which the GUI gateway-enables only for desktop-sourced sessions, so it never appears outside the GUI.+Each ``terminal(background=true)`` process is mirrored as a read-only tab; this+drops the tab WITHOUT killing the process (output keeps buffering, the user can+reopen it from the status stack). Routes through the process registry's+``on_close`` sink, which the desktop gateway wires to a ``terminal.close`` event.+Lives in the ``desktop_ui`` toolset, enabled only for desktop-sourced sessions."""import jsondiff --git a/tools/daemon_pool.py b/tools/daemon_pool.pyindex 33e99c5143a..7f45de11311 100644--- a/tools/daemon_pool.py+++ b/tools/daemon_pool.py@@ -1,35 +1,29 @@"""Shared daemon-thread ThreadPoolExecutor.-Stdlib ``ThreadPoolExecutor`` workers are non-daemon AND are registered in+Stdlib ``ThreadPoolExecutor`` workers are non-daemon AND registered in``concurrent.futures.thread._threads_queues``, whose atexit hook(``_python_exit``) joins every worker unconditionally — even after``shutdown(wait=False)``. A single wedged worker (tool blocked on network-I/O, hung provider daemon, stuck subagent) therefore blocks interpreter-exit forever. This is the root cause of multi-minute CLI exits on long-sessions: every abandoned concurrent-tool batch leaves workers that the-exit hook insists on joining.+I/O, hung provider daemon, stuck subagent) therefore blocks interpreter exit+forever; this is the root cause of multi-minute CLI exits on long sessions.``DaemonThreadPoolExecutor`` spawns daemon workers and skips the-``_threads_queues`` registration, so:-- - ``_python_exit`` never joins them, and- - the interpreter's non-daemon thread join at shutdown skips them.+``_threads_queues`` registration, so ``_python_exit`` never joins them and+the interpreter's non-daemon thread join at shutdown skips them.Semantics are otherwise identical (initializer/initargs, work queue,idle-thread reuse), plus context propagation: ``submit`` snapshots the-submitting context with ``copy_context()`` and runs each work item inside-it. Stdlib ``ThreadPoolExecutor`` only does this from Python 3.14; on the-3.11-3.13 runtimes Hermes ships, a bare pool worker starts with an EMPTY-Context and silently drops contextvar-based state (profile secret scope,-HERMES_HOME override) — under the multiplexed gateway a credential read in-such a worker fails closed with ``UnscopedSecretError``. Propagating by-default makes every consumer safe even when it forgets-``propagate_context_to_thread``. Use it for any pool whose work is-best-effort or independently interruptible and must never hold the process open:-concurrent tool execution, background memory sync, catalog fan-out,-subagent timeout wrappers. Do NOT use it for work that must complete-before exit (durable writes) — those belong on foreground threads with-explicit bounded joins.+submitting context with ``copy_context()`` and runs each work item inside it.+Stdlib only does this from Python 3.14; on 3.11-3.13 a bare pool worker+starts with an EMPTY Context and silently drops contextvar state (profile+secret scope, HERMES_HOME override) — under the multiplexed gateway a+credential read in such a worker fails closed with ``UnscopedSecretError``.++Use it for any pool whose work is best-effort or independently interruptible+and must never hold the process open (concurrent tool execution, background+memory sync, catalog fan-out, subagent timeout wrappers). Do NOT use it for+work that must complete before exit (durable writes) — those belong on+foreground threads with explicit bounded joins."""from __future__ import annotations@@ -49,14 +43,9 @@ class DaemonThreadPoolExecutor(ThreadPoolExecutor):def submit(self, fn, /, *args, **kwargs):"""Submit a callable, propagating the caller's contextvars.- Python 3.14's ``ThreadPoolExecutor`` snapshots the submitting- context with ``copy_context()`` and runs each work item inside it;- 3.11-3.13 (the runtimes Hermes ships) do not, so a pool worker- starts with an empty Context and loses the multiplexed profile- secret scope / HERMES_HOME override. Do it here unconditionally so- the daemon pool behaves identically on every runtime; on 3.14+ the- inner ``ctx.run`` re-applies the same immutable context and is a- no-op.+ Done unconditionally so the pool behaves identically on every+ runtime; on 3.14+ (which already propagates) the inner ``ctx.run``+ re-applies the same immutable context and is a no-op."""ctx = copy_context()diff --git a/tools/env_passthrough.py b/tools/env_passthrough.pyindex 5c7a4c10469..0c921c84cff 100644--- a/tools/env_passthrough.py+++ b/tools/env_passthrough.py@@ -1,22 +1,16 @@"""Environment variable passthrough registry.-Skills that declare ``required_environment_variables`` in their frontmatter-need those vars available in sandboxed execution environments (execute_code,-terminal). By default both sandboxes strip secrets from the child process-environment for security. This module provides a session-scoped allowlist-so skill-declared vars (and user-configured overrides) pass through.--Two sources feed the allowlist:--1. **Skill declarations** — when a skill is loaded via ``skill_view``, its- ``required_environment_variables`` are registered here automatically.-2. **User config** — ``terminal.env_passthrough`` in config.yaml lets users- explicitly allowlist vars for non-skill use cases.--Both ``code_execution_tool.py`` and ``tools/environments/local.py`` consult-:func:`is_env_passthrough` before stripping a variable.-When profile multiplexing is active, their forwarded values are resolved-through the current profile's secret scope rather than the process environment.+Skills that declare ``required_environment_variables`` need those vars in+sandboxed execution environments (execute_code, terminal), which strip secrets+from the child process environment by default. This module is the+session-scoped allowlist, fed by two sources: skill declarations (registered+automatically by ``skill_view``) and ``terminal.env_passthrough`` in+config.yaml.++``code_execution_tool.py`` and ``tools/environments/local.py`` consult+:func:`is_env_passthrough` before stripping a variable. When profile+multiplexing is active, forwarded values are resolved through the current+profile's secret scope rather than the process environment."""from __future__ import annotations@@ -28,8 +22,8 @@ from hermes_cli.config import cfg_getlogger = logging.getLogger(__name__)-# Session-scoped set of env var names that should pass through to sandboxes.-# Backed by ContextVar to prevent cross-session data bleed in the gateway pipeline.+# Session-scoped allowlist; ContextVar-backed to prevent cross-session bleed+# in the gateway pipeline._allowed_env_vars_var: ContextVar[set[str]] = ContextVar("_allowed_env_vars")@@ -48,24 +42,19 @@ _config_passthrough: frozenset[str] | None = Nonedef _is_hermes_provider_credential(name: str) -> bool:- """True if ``name`` is a Hermes-managed provider credential (API key,- token, or similar) per ``_HERMES_PROVIDER_ENV_BLOCKLIST``.+ """True if ``name`` is a Hermes-managed provider credential per+ ``_HERMES_PROVIDER_ENV_BLOCKLIST`` (or a dynamic Hermes-internal secret).- Skill-declared ``required_environment_variables`` frontmatter must- not be able to override this list — that was the bypass in- GHSA-rhgp-j443-p4rf where a malicious skill registered- ``ANTHROPIC_TOKEN`` / ``OPENAI_API_KEY`` as passthrough and received- the credential in the ``execute_code`` child process, defeating the- sandbox's scrubbing guarantee.-- Non-Hermes API keys (TENOR_API_KEY, NOTION_TOKEN, etc.) are NOT- in the blocklist and remain legitimately registerable — skills that- wrap third-party APIs still work.+ Skill-declared ``required_environment_variables`` must not override this+ list — that was the GHSA-rhgp-j443-p4rf bypass, where a malicious skill+ registered ``OPENAI_API_KEY`` as passthrough and received it in the+ ``execute_code`` child, defeating the sandbox's scrubbing guarantee.+ Non-Hermes API keys (TENOR_API_KEY, NOTION_TOKEN, …) are not in the+ blocklist and remain registerable.Fail closed: if the authoritative blocklist cannot be imported (partial- install, import-time error, etc.) we treat the name as a protected- provider credential and refuse passthrough, rather than fall open and- let a skill tunnel a Hermes credential into the execute_code child.+ install, import-time error), treat the name as protected and refuse+ passthrough rather than fall open."""try:from tools.environments.local import (@@ -81,30 +70,22 @@ def _is_hermes_provider_credential(name: str) -> bool:)return True# Dynamically-generated Hermes-internal secrets (AUXILIARY_*_API_KEY /- # _BASE_URL side-LLM credentials, GATEWAY_RELAY_* relay-auth) are provider- # credentials the static blocklist can't enumerate — they're injected per- # task/relay at gateway startup. A skill must not be able to register them- # as passthrough and tunnel them into an execute_code / terminal child.+ # _BASE_URL, GATEWAY_RELAY_*) are injected per task/relay at gateway+ # startup, so the static blocklist can't enumerate them.if _is_hermes_internal_secret(name):return Truereturn name in _HERMES_PROVIDER_ENV_BLOCKLISTdef register_env_passthrough(var_names: Iterable[str]) -> None:- """Register environment variable names as allowed in sandboxed environments.-- Typically called when a skill declares ``required_environment_variables``.-- Variables that are Hermes-managed provider credentials (from- ``_HERMES_PROVIDER_ENV_BLOCKLIST``) are rejected here to preserve- the ``execute_code`` sandbox's credential-scrubbing guarantee per- GHSA-rhgp-j443-p4rf. A skill that needs to talk to a Hermes-managed- provider should do so via the agent's main-process tools (web_search,- web_extract, etc.) where the credential remains safely in the main- process.-- Non-Hermes third-party API keys (TENOR_API_KEY, NOTION_TOKEN, etc.)- pass through normally — they were never in the sandbox scrub list.+ """Register env var names as allowed in sandboxed environments (typically+ from a skill's ``required_environment_variables``).++ Hermes-managed provider credentials are rejected to preserve the+ ``execute_code`` sandbox's credential-scrubbing guarantee+ (GHSA-rhgp-j443-p4rf); a skill needing a Hermes-managed provider should+ use the main-process tools (web_search, web_extract, …) where the+ credential stays in the main process. Third-party keys pass normally."""for name in var_names:name = name.strip()@@ -139,11 +120,9 @@ def _load_config_passthrough() -> frozenset[str]:if not isinstance(item, str) or not item.strip():continuename = item.strip()- # Mirror the skill-path filter in register_env_passthrough:- # Hermes-managed provider credentials must not be passed- # through to execute_code / terminal children, regardless of- # whether the request came from a skill or from config.yaml.- # See GHSA-rhgp-j443-p4rf.+ # Same filter as register_env_passthrough: provider credentials+ # must not reach sandbox children whether the request came from+ # a skill or from config.yaml (GHSA-rhgp-j443-p4rf).if _is_hermes_provider_credential(name):logger.warning("env passthrough: refusing to register Hermes "@@ -164,11 +143,7 @@ def _load_config_passthrough() -> frozenset[str]:def is_env_passthrough(var_name: str) -> bool:- """Check whether *var_name* is allowed to pass through to sandboxes.-- Returns ``True`` if the variable was registered by a skill or listed in- the user's ``tools.env_passthrough`` config.- """+ """True if *var_name* was registered by a skill or listed in config."""if var_name in _get_allowed():return Truereturn var_name in _load_config_passthrough()@@ -189,11 +164,10 @@ def resolve_passthrough_value(secret scopes existed (typically a snapshot of ``os.environ`` or thecurrent profile's ``.env``). An active multiplex scope is authoritative:a missing key returns ``None`` and never falls back to the process-global- environment. An unscoped read while multiplexing is active raises the+ environment; an unscoped read while multiplexing is active raises thefail-closed ``UnscopedSecretError`` from :mod:`agent.secret_scope`.-- Outside multiplexing, an installed scope keeps the existing overlay- semantics and an unscoped caller keeps its already-resolved fallback.+ Outside multiplexing, an installed scope keeps the overlay semantics and+ an unscoped caller keeps its already-resolved fallback."""from agent.secret_scope import (_is_global_env,@@ -204,7 +178,7 @@ def resolve_passthrough_value(# Global terminal/runtime settings are not profile secrets. ``fallback``# is already the caller's effective value (including an explicit per-call- # override), so preserve it instead of replacing it with the process-wide+ # override), so preserve it rather than replacing it with the process-wide# value while a multiplex scope is active.if _is_global_env(name) and fallback is not None:return fallbackdiff --git a/tools/env_probe.py b/tools/env_probe.pyindex d1eaf08c12d..fe1065c32d4 100644--- a/tools/env_probe.py+++ b/tools/env_probe.py@@ -1,28 +1,14 @@"""Local-environment toolchain probe for the system prompt.-When the terminal backend is local (the agent's tools run on the same-machine as Hermes itself), we surface a single deterministic line about-Python tooling state so models don't have to discover it by hitting-walls. Common failure modes this addresses:--* Hermes ships under one Python (e.g. 3.11 in a bundled venv) while the- user's login shell has a different one (e.g. 3.12 system). ``pip``- resolved from PATH may not match ``python3 -m pip``.-* The bundled-venv Python has no pip module installed → ``python3 -m- pip`` returns ``No module named pip``.-* The system Python is PEP-668 externally-managed → naive- ``pip install`` fails with ``error: externally-managed-environment``.--The probe is cheap (a handful of subprocess calls, ~50ms total),-cached for the lifetime of the process, and emits **at most one-short line** when something non-default is detected. When the-environment looks normal (python3+pip both present and matched, no-PEP 668), it emits nothing — no token cost.--Remote terminal backends (docker, modal, ssh, …) are skipped: the-host's Python state is irrelevant when tools run inside a sandbox.-The sandbox has its own existing probe (``_probe_remote_backend``)-in ``agent/prompt_builder.py``.+When the terminal backend is local, surface one deterministic line about+Python tooling state (python3/python versions, missing pip module, pip bound+to a different Python than ``python3``, PEP 668 externally-managed) so models+don't discover it by hitting walls. The probe is cheap (~50ms), cached for+the process lifetime, and emits nothing when the environment is clean.++Remote terminal backends (docker, modal, ssh, …) are skipped: the host's+Python state is irrelevant when tools run inside a sandbox, which has its own+probe (``_probe_remote_backend`` in ``agent/prompt_builder.py``).Toggle via ``agent.environment_probe`` in config.yaml (default True)."""@@ -30,7 +16,6 @@ Toggle via ``agent.environment_probe`` in config.yaml (default True).from __future__ import annotationsimport logging-import osimport shutilimport subprocessimport tempfile@@ -41,17 +26,12 @@ from hermes_cli._subprocess_compat import windows_hide_flagslogger = logging.getLogger(__name__)-# Module-level cache. The probe result is deterministic for the-# lifetime of the process — Python install state doesn't change-# mid-session in any way that would matter for the system prompt.-#-# Concurrency model (#67964): the probe runs in exactly ONE background-# worker thread; ``_PROBE_DONE`` signals completion. Callers never-# execute the probe themselves and never wait unboundedly — they block-# at most ``_PROBE_WAIT_TIMEOUT`` seconds on the event and then fail-# open with "". This guarantees a stuck probe (e.g. a Windows pipe-# wedged open by an orphaned pip descendant) can degrade at most the-# probe line itself, never system-prompt construction.+# Concurrency model: the probe runs in exactly ONE background worker thread;+# ``_PROBE_DONE`` signals completion. Callers never execute the probe+# themselves and block at most ``_PROBE_WAIT_TIMEOUT`` seconds on the event+# before failing open with "" — a stuck probe (e.g. a Windows pipe wedged open+# by an orphaned pip descendant) can degrade only the probe line, never+# system-prompt construction._CACHE_LOCK = threading.Lock()_CACHED_LINE: Optional[str] = None # None = not probed yet; "" = probed, nothing to say._PROBE_DONE = threading.Event()@@ -60,18 +40,15 @@ _PROBE_THREAD: Optional[threading.Thread] = None# before a test reset) can't publish its result into the fresh generation._PROBE_GEN = 0-# Upper bound a prompt build will wait for the probe. Generous vs the-# ~0.5s healthy runtime (6 subprocesses × 3s timeout ≈ 18s pathological-# worst case), but finite: prompt construction must always proceed.+# Upper bound a prompt build will wait for the probe. Generous vs the ~0.5s+# healthy runtime, but finite: prompt construction must always proceed._PROBE_WAIT_TIMEOUT = 10.0-# Once one caller has burned the full wait and given up, later callers-# stop paying it too — they just peek at the event. If the stuck worker-# ever finishes, the published line resumes appearing in new prompts.+# Once one caller has burned the full wait, later callers only peek at the+# event. If the stuck worker ever finishes, the line resumes appearing._WAIT_ALREADY_TIMED_OUT = False-# Remote backends — keep in sync with agent/prompt_builder.py:_REMOTE_TERMINAL_BACKENDS.-# Duplicated rather than imported to avoid a circular import (prompt_builder-# imports nothing from tools).+# Keep in sync with agent/prompt_builder.py:_REMOTE_TERMINAL_BACKENDS.+# Duplicated rather than imported to avoid a circular import._REMOTE_BACKENDS = frozenset({"docker", "singularity", "modal", "daytona", "ssh", "managed_modal","vercel_sandbox",@@ -95,19 +72,15 @@ def _run(cmd: list[str], timeout: float = 3.0) -> tuple[int, str, str]:Failures (binary missing, timeout, OSError) return (-1, "", "<reason>").- Output is captured through temporary files rather than ``capture_output``- pipes so ``timeout`` bounds the *whole* call — even on native Windows. A- console-script launcher (e.g. ``pip.exe``) can spawn a descendant that- inherits the captured stdout/stderr handles and outlives its parent. With- OS pipes, the reader threads inside ``subprocess.communicate()`` then block- until that descendant closes the write end — which the timeout does *not*- cover, because killing the direct child leaves the grandchild holding the- pipe. A whole warm probe could hang for ~28 min this way while holding- ``_CACHE_LOCK``, wedging every new session's system-prompt build.-- Temp files have no reader threads, so ``wait()`` only ever waits on the- direct child; a lingering grandchild holding the handle can't block us, and- the probe genuinely fails open on timeout.+ Output is captured through temp files rather than pipes so ``timeout``+ bounds the *whole* call, even on native Windows: a console-script launcher+ (e.g. ``pip.exe``) can spawn a descendant that inherits the captured+ handles and outlives its parent. With OS pipes, ``communicate()``'s reader+ threads block until that grandchild closes the write end — which the+ timeout does not cover, since killing the direct child leaves the+ grandchild holding the pipe (a warm probe could hang ~28 min holding+ ``_CACHE_LOCK``). Temp files have no reader threads, so ``wait()`` only+ waits on the direct child and the probe genuinely fails open on timeout."""try:with tempfile.TemporaryFile() as out_f, tempfile.TemporaryFile() as err_f:@@ -119,10 +92,9 @@ def _run(cmd: list[str], timeout: float = 3.0) -> tuple[int, str, str]:timeout=timeout,check=False,stdin=subprocess.DEVNULL,- # CREATE_NO_WINDOW (0 on POSIX): the probe runs in- # windowless processes (pythonw gateway / kanban workers)- # where a console child would otherwise flash a visible- # window per probe — ~5 flashes at every worker startup.+ # CREATE_NO_WINDOW (0 on POSIX): windowless hosts (pythonw+ # gateway / kanban workers) would otherwise flash a console+ # window per probe subprocess.creationflags=windows_hide_flags(),)except subprocess.TimeoutExpired:@@ -143,9 +115,7 @@ def _python_version_of(binary: str) -> Optional[str]:if not shutil.which(binary):return Nonerc, out, err = _run([binary, "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}')"])- if rc == 0 and out:- return out- return None+ return out if rc == 0 and out else Nonedef _has_pip_module(binary: str) -> bool:@@ -157,11 +127,8 @@ def _has_pip_module(binary: str) -> bool:def _detect_pep668(binary: str) -> bool:- """True when ``<binary>``'s install location is PEP-668 externally-managed.-- Looks for ``EXTERNALLY-MANAGED`` next to the stdlib (the marker file- Debian/Ubuntu drop in to gate naive ``pip install``).- """+ """True when ``<binary>`` is PEP-668 externally-managed (``EXTERNALLY-MANAGED``+ marker next to the stdlib, as Debian/Ubuntu ship)."""if not shutil.which(binary):return Falsecode = (@@ -177,24 +144,16 @@ def _detect_pep668(binary: str) -> bool:def _pip_python_version() -> Optional[str]:"""If ``pip`` is on PATH, return the Python version it's bound to.- ``pip --version`` output looks like::-- pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12)-- Returns the parenthesised version (e.g. ``"3.12"``) or None.+ Parses the trailing ``(python X.Y)`` of ``pip --version`` output, e.g.+ ``pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12)`` → ``"3.12"``."""if not shutil.which("pip"):return Nonerc, out, _err = _run(["pip", "--version"])if rc != 0 or not out:return None- # Parse trailing "(python X.Y)".if "(python " in out and out.endswith(")"):- try:- tail = out.rsplit("(python ", 1)[1]- return tail[:-1].strip()- except (IndexError, AttributeError):- return None+ return out.rsplit("(python ", 1)[1][:-1].strip()return None@@ -210,28 +169,20 @@ def _resolve_terminal_backend() -> str:def _build_probe_line() -> str:- """Build the one-liner. Returns "" when nothing notable is detected.-- Emit only when SOMETHING is off — the goal is to save the model from- hitting an avoidable wall, not to narrate a healthy environment.- """+ """Build the one-liner. Returns "" when nothing notable is detected —+ the goal is to save the model from an avoidable wall, not narrate a+ healthy environment."""py3_ver = _python_version_of("python3")py_ver = _python_version_of("python") # for systems with a `python` aliaspy3_has_pip = _has_pip_module("python3") if py3_ver else Falsepip_bound_to = _pip_python_version()py3_pep668 = _detect_pep668("python3") if py3_ver else False# Bare which() is correct here, unlike Hermes's own uv call sites: this- # reports the environment *the model will see* in the terminal tool, and- # what the model can type is exactly what is on that subshell's PATH.- # local.py puts the Hermes-managed $HERMES_HOME/bin there, so a managed-only- # install answers yes — without that, claiming uv the model cannot invoke- # would be worse than claiming none.+ # reports the environment *the model will see* in the terminal tool, whose+ # PATH (via local.py) includes the Hermes-managed $HERMES_HOME/bin.+ # Claiming uv the model cannot invoke would be worse than claiming none.has_uv = shutil.which("uv") is not None- # If python3 exists, has pip, has uv (or no PEP 668), and there's no- # version mismatch between `pip` and `python3` → environment is- # clean enough to stay silent. The model can discover details by- # running commands if it cares.mismatch = bool(pip_bound_to and py3_ver and not py3_ver.startswith(pip_bound_to))silent_conditions = (py3_ver is not None@@ -242,8 +193,7 @@ def _build_probe_line() -> str:if silent_conditions:return ""- # Build a compact factual summary. Keep it ONE line so it doesn't- # dominate the prompt; the model is good at parsing dense info.+ # Compact factual summary; ONE line so it doesn't dominate the prompt.bits: list[str] = []if py3_ver:py3_bit = f"python3={py3_ver}"@@ -256,21 +206,17 @@ def _build_probe_line() -> str:if py_ver and py_ver != py3_ver:bits.append(f"python={py_ver}")elif not py_ver and py3_ver:- # Common on Debian/Ubuntu — call it out so the model doesn't- # type `python` and hit "command not found".+ # Common on Debian/Ubuntu — stop the model typing `python`.bits.append("python=missing (use python3)")if pip_bound_to:if mismatch:bits.append(f"pip→python{pip_bound_to} (mismatch)")elif not py3_has_pip:- # pip exists but `python3 -m pip` doesn't — the script- # works but the module path doesn't.+ # pip script works but `python3 -m pip` doesn't.bits.append(f"pip→python{pip_bound_to}")- elif py3_has_pip:- # `pip` not on PATH but `python3 -m pip` works.- pass- else:+ elif not py3_has_pip:+ # (when `pip` is off PATH but `python3 -m pip` works, say nothing)bits.append("pip=missing")if py3_pep668:@@ -279,41 +225,28 @@ def _build_probe_line() -> str:if has_uv:bits.append("uv=installed")- if not bits:- return ""-return "Python toolchain: " + ", ".join(bits) + "."def get_environment_probe_line(*, force_refresh: bool = False) -> str:"""Return the cached probe line (building it on first call).- Returns "" when the environment is clean — the system prompt- assembler should drop the section in that case rather than- emit an empty heading.-- The probe itself always runs in a single background worker thread;- this function waits on its completion event for at most- ``_PROBE_WAIT_TIMEOUT`` seconds and then fails open with "". A- wedged probe subprocess (#67964) therefore can never block- system-prompt construction — at worst the toolchain line is absent- from prompts built while the probe is stuck.+ Returns "" when the environment is clean — the system prompt assembler+ should drop the section rather than emit an empty heading. The probe runs+ in a single background worker; this waits at most ``_PROBE_WAIT_TIMEOUT``+ seconds on its completion event and then fails open with "", so a wedged+ probe subprocess can never block system-prompt construction.``force_refresh`` is for tests; real callers should never need it."""- global _CACHED_LINE, _PROBE_THREAD, _PROBE_GEN, _WAIT_ALREADY_TIMED_OUT+ global _WAIT_ALREADY_TIMED_OUTif force_refresh:- with _CACHE_LOCK:- _CACHED_LINE = None- _PROBE_DONE.clear()- _PROBE_THREAD = None- _PROBE_GEN += 1- _WAIT_ALREADY_TIMED_OUT = False+ _reset_cache_for_tests()# Resolve the backend HERE, in the caller's context: under gateway# multiplexing the routed profile's backend lives in the per-turn terminal- # scope, which the bare probe worker thread does not inherit (#68559). A- # remote backend answers "" without consulting the cache — the cached line+ # scope, which the bare probe worker thread does not inherit. A remote+ # backend answers "" without consulting the cache — the cached line# describes the HOST toolchain, not where that profile's tools run.backend = _resolve_terminal_backend()if backend in _REMOTE_BACKENDS or _plugin_backend_is_remote(backend):@@ -325,9 +258,8 @@ def get_environment_probe_line(*, force_refresh: bool = False) -> str:_ensure_probe_started()wait_timeout = 0.05 if _WAIT_ALREADY_TIMED_OUT else _PROBE_WAIT_TIMEOUTif not _PROBE_DONE.wait(timeout=wait_timeout):- # Probe stuck or pathologically slow. The line is a nice-to-have;- # blocking prompt construction is an outage. Fail open — if the- # worker eventually finishes, sessions started later get the line.+ # Probe stuck or pathologically slow: the line is a nice-to-have,+ # blocking prompt construction is an outage. Fail open.if not _WAIT_ALREADY_TIMED_OUT:_WAIT_ALREADY_TIMED_OUT = Truelogger.warning(@@ -372,15 +304,11 @@ def _ensure_probe_started() -> None:def warm_environment_probe_async() -> None:- """Kick off the probe in a background thread so the first- system-prompt build doesn't pay the ~0.5s of subprocess calls- (python3/pip/PEP-668 version checks) on the time-to-first-token- critical path.-- Idempotent and fail-safe. The prompt-build call to- ``get_environment_probe_line`` waits (bounded) on the same worker's- completion event instead of recomputing. Called from agent init- (all platforms); safe to call from anywhere.+ """Start the probe in the background so the first system-prompt build+ doesn't pay the ~0.5s of subprocess calls on the time-to-first-token path.++ Idempotent and fail-safe; ``get_environment_probe_line`` waits (bounded)+ on the same worker instead of recomputing. Called from agent init."""_ensure_probe_started()diff --git a/tools/interpreter_shutdown.py b/tools/interpreter_shutdown.pyindex 2092ebb2448..df00316e591 100644--- a/tools/interpreter_shutdown.py+++ b/tools/interpreter_shutdown.py@@ -1,18 +1,13 @@"""Shared interpreter-shutdown detection.-Single home for the "is the Python interpreter finalizing?" predicate used-by every subsystem whose background threads can outlive process teardown-(cron delivery, concurrent tool submission, the conversation loop's retry-path, background review forks).--Once finalization starts, ``concurrent.futures`` refuses new work with-``RuntimeError: cannot schedule new futures after interpreter shutdown`` and-asyncio's default executor is gone — *any* further attempt to schedule work-(an API retry, a thread-pool submit, ``asyncio.run``) is doomed and only-produces noise: stray ``❌`` prints after the TUI exited, tracebacks in-``errors.log``, and futile retry loops that burn iterations against a dying-process (#55924, #58720, and the CLI-exit retry spam this module was-extracted for).+Single home for the "is the Python interpreter finalizing?" predicate used by+every subsystem whose background threads can outlive process teardown (cron+delivery, concurrent tool submission, the conversation loop's retry path,+background review forks). Once finalization starts, ``concurrent.futures``+refuses new work and asyncio's default executor is gone — any further attempt+to schedule work (an API retry, a pool submit, ``asyncio.run``) is doomed and+only produces noise: stray ``❌`` prints after the TUI exited, tracebacks in+``errors.log``, and futile retry loops against a dying process.CPython emits two message variants depending on the failing site:@@ -22,15 +17,10 @@ CPython emits two message variants depending on the failing site:- ``cannot schedule new futures after shutdown`` — a plain``ThreadPoolExecutor`` whose ``shutdown()`` ran.-The common short prefix catches both. Matching the second variant is safe+The common short prefix catches both. Matching the second variant is safefor shutdown detection at every current call site: the pools involved areeither module-global daemons or ``with``-scoped locals that cannot be shutdown mid-use by anything except interpreter finalization.--Historically this predicate existed at three sites, each fixed-independently as its own incident — ``cron/scheduler.py`` (#55924/#58720),-``agent/tool_executor.py``, and nothing at all in the conversation loop's-outer retry handler (the CLI-exit spam). One predicate, all sites."""from __future__ import annotationsdiff --git a/tools/interrupt.py b/tools/interrupt.pyindex aaa4b1081d4..f0d012643d0 100644--- a/tools/interrupt.py+++ b/tools/interrupt.py@@ -1,12 +1,10 @@"""Per-thread interrupt signaling for all tools.-Provides thread-scoped interrupt tracking so that interrupting one agent-session does not kill tools running in other sessions. This is critical-in the gateway where multiple agents run concurrently in the same process.--The agent stores its execution thread ID at the start of run_conversation()-and passes it to set_interrupt()/clear_interrupt(). Tools call-is_interrupted() which checks the CURRENT thread — no argument needed.+Thread-scoped interrupt tracking so that interrupting one agent session does+not kill tools running in other sessions — critical in the gateway where+multiple agents run concurrently in one process. The agent stores its+execution thread ID at the start of run_conversation() and passes it to+set_interrupt(); tools call is_interrupted(), which checks the CURRENT thread.Usage in tools:from tools.interrupt import is_interrupted@@ -21,19 +19,17 @@ import threadinglogger = logging.getLogger(__name__)# Opt-in debug tracing — pairs with HERMES_DEBUG_INTERRUPT in-# tools/environments/base.py. Enables per-call logging of set/check so the-# caller thread, target thread, and current state are visible when-# diagnosing "interrupt signaled but tool never saw it" reports.+# tools/environments/base.py. Logs caller thread, target thread, and current+# state per set/check for "interrupt signaled but tool never saw it" reports._DEBUG_INTERRUPT = bool(os.getenv("HERMES_DEBUG_INTERRUPT"))if _DEBUG_INTERRUPT:- # AIAgent's quiet_mode path forces `tools` logger to ERROR on CLI startup.- # Force our own logger back to INFO so the trace is visible in agent.log.+ # AIAgent's quiet_mode path forces the `tools` logger to ERROR on CLI+ # startup; force ours back to INFO so the trace is visible in agent.log.logger.setLevel(logging.INFO)-# Set of thread idents that have been interrupted, plus an optional-# user-safe cause for each signal. The cause deliberately does not contain an-# incoming user's message text.+# Interrupted thread idents, plus an optional user-safe cause per signal. The+# cause deliberately never contains an incoming user's message text._interrupted_threads: set[int] = set()_interrupt_reasons: dict[int, str] = {}_lock = threading.Lock()@@ -45,14 +41,9 @@ def set_interrupt(*,reason: str | None = None,) -> None:- """Set or clear interrupt for a specific thread.-- Args:- active: True to signal interrupt, False to clear it.- thread_id: Target thread ident. When None, targets the- current thread (backward compat for CLI/tests).- reason: Optional user-safe cause for the interrupt.- """+ """Set (``active=True``) or clear the interrupt for *thread_id*, defaulting+ to the current thread (backward compat for CLI/tests). ``reason`` is an+ optional user-safe cause."""tid = thread_id if thread_id is not None else threading.current_thread().identwith _lock:if active:@@ -74,20 +65,16 @@ def set_interrupt(def is_interrupted() -> bool:- """Check if an interrupt has been requested for the current thread.-- Safe to call from any thread — each thread only sees its own- interrupt state.- """+ """Check if an interrupt has been requested for the current thread."""return is_thread_interrupted(threading.current_thread().ident)def is_thread_interrupted(thread_id: int | None) -> bool:- """Check whether *thread_id* has an interrupt bit set.+ """Check whether *thread_id* has an interrupt bit set (``None`` never is).Used when a wait is moved onto a deadline worker (``run_bounded_sync``)so ``/stop`` targeting the original tool-worker tid still kills the- subprocess (#94285). ``None`` is never interrupted.+ subprocess."""if thread_id is None:return False@@ -114,16 +101,14 @@ def clear_current_thread_interrupt() -> None:the executor's poll loop. Call this directly, never via the_interrupt_event proxy (its .clear() binds to whatever thread runs it)."""- set_interrupt(False) # thread_id=None -> current thread (see set_interrupt)+ set_interrupt(False) # thread_id=None -> current thread# ----------------------------------------------------------------------------# Backward-compatible _interrupt_event proxy+# Backward-compatible _interrupt_event proxy: legacy call sites+# (code_execution_tool, process_registry, tests) import it and call+# .is_set() / .set() / .clear(); the shim maps those to the per-thread API.# ----------------------------------------------------------------------------# Some legacy call sites (code_execution_tool, process_registry, tests)-# import _interrupt_event directly and call .is_set() / .set() / .clear().-# This shim maps those calls to the per-thread functions above so existing-# code keeps working while the underlying mechanism is thread-scoped.class _ThreadAwareEventProxy:"""Drop-in proxy that maps threading.Event methods to per-thread state."""diff --git a/tools/read_terminal_tool.py b/tools/read_terminal_tool.pyindex 5cd47a572ac..5fad29f0aa4 100644--- a/tools/read_terminal_tool.py+++ b/tools/read_terminal_tool.py@@ -1,14 +1,10 @@#!/usr/bin/env python3"""Read the in-app terminal pane in the Hermes desktop GUI.-The embedded terminal's buffer lives in the desktop renderer (xterm.js), so this-tool round-trips through the gateway's blocking-prompt bridge — the same one-`clarify` uses: tui_gateway emits ``terminal.read.request``, the renderer answers-with ``terminal.read.respond``. This module is just schema + a thin dispatcher-over the platform-injected callback.--Lives in the ``desktop_ui`` toolset, which the GUI gateway enables only for-desktop-sourced sessions.+The buffer lives in the desktop renderer (xterm.js), so this round-trips through+the gateway's blocking-prompt bridge (as `clarify` does): tui_gateway emits+``terminal.read.request``, the renderer answers ``terminal.read.respond``. Lives+in the ``desktop_ui`` toolset, enabled only for desktop-sourced sessions."""import jsondiff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex 4b16c7f0bd4..d4987d5d4ca 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -1,51 +1,33 @@#!/usr/bin/env python3-"""-Terminal Tool Module--A terminal tool that executes commands in local, Docker, Modal, SSH,-Singularity, Daytona, and Vercel Sandbox environments. Supports local-execution, containerized backends, and cloud sandboxes, including managed-Modal mode.--Environment Selection (via TERMINAL_ENV environment variable):-- "local": Execute directly on the host machine (default, fastest)-- "docker": Execute in Docker containers (isolated, requires Docker)-- "modal": Execute in Modal cloud sandboxes (direct Modal or managed gateway)-- "vercel_sandbox": Execute in Vercel Sandbox cloud sandboxes--Features:-- Multiple execution backends (local, docker, modal, vercel_sandbox)-- Background task support-- VM/container lifecycle management-- Automatic cleanup after inactivity--Cloud sandbox note:-- Persistent filesystems preserve working state across sandbox recreation-- Persistent filesystems do NOT guarantee the same live sandbox or long-running processes survive cleanup, idle reaping, or Hermes exit--Usage:- from terminal_tool import terminal_tool-- # Execute a simple command- result = terminal_tool("ls -la")-- # Execute in background- result = terminal_tool("python server.py", background=True)+"""Terminal tool: run shell commands in the configured backend.++Backends (``TERMINAL_ENV``): local (default), docker, singularity, modal+(direct or managed gateway), daytona, vercel_sandbox, ssh, plus+plugin-registered backends. Handles background processes, sandbox lifecycle+(per-task cache, idle reaper, atexit teardown) and sudo password plumbing.+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)."""import importlib.util+import inspectimport jsonimport loggingimport osimport platformimport re-import shlex-import stat+import sysimport timeimport threadingimport atexitimport shutilimport subprocess+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Optional, Dict, Any, List@@ -61,24 +43,11 @@ def _redact_terminal_error_text(value: Any) -> str:return redact_sensitive_text("" if value is None else str(value), force=True)-# ----------------------------------------------------------------------------# Global interrupt event: set by the agent when a user interrupt arrives.-# The terminal tool polls this during command execution so it can kill-# long-running subprocesses immediately instead of blocking until timeout.-# ---------------------------------------------------------------------------+# Interrupt event set by the agent on user interrupt; executors poll it to+# kill long-running subprocesses instead of blocking until timeout.from tools.interrupt import is_interrupted, _interrupt_event # noqa: F401 — re-exportedfrom tools.registry import tool_error-from tools.shell_heredoc import strip_inert_heredoc_bodies# display_hermes_home imported lazily at call site (stale-module safety during hermes update)-----# =============================================================================-# Custom Singularity Environment with more space-# =============================================================================--# Singularity helpers (scratch dir, SIF cache) now live in tools/environments/singularity.pyfrom tools.environments.singularity import _get_scratch_dirfrom tools.tool_backend_helpers import (coerce_modal_mode,@@ -95,11 +64,8 @@ def _safe_parse_import_env(converter,type_label: str,):- """Parse module-level numeric env vars without breaking import.-- Terminal tool is imported by CLI, ACP, tests, and tool discovery. A single- malformed env var must not make the whole module unloadable at import time.- """+ """Parse a module-level numeric env var; a malformed value must never make+ the module unloadable at import time (CLI, ACP, tests, tool discovery)."""raw = os.getenv(name)if raw is None or raw == "":return default@@ -197,28 +163,20 @@ def _check_vercel_sandbox_requirements(config: dict[str, Any]) -> bool:return False-# Cache for disk usage warning to avoid full rglob scan on every call.-# The check is advisory-only — staleness for up to 5 minutes is acceptable.+# 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 # secondsdef _check_disk_usage_warning():- """Check if total disk usage exceeds warning threshold.-- Result is cached for :data:`_DISK_USAGE_CACHE_TTL` seconds (default:- 5 minutes) to avoid an expensive recursive filesystem scan on every- terminal command. The check is advisory-only so a stale result is- harmless.- """+ """True when hermes scratch dirs exceed the warning threshold (cached, advisory)."""import time as _time_modnow = _time_mod.monotonic()if now - _disk_usage_cache["timestamp"] < _DISK_USAGE_CACHE_TTL:return _disk_usage_cache["result"]try:scratch_dir = _get_scratch_dir()-- # Get total size of hermes directoriestotal_bytes = 0import globfor path in glob.glob(str(scratch_dir / "hermes-*")):@@ -228,9 +186,7 @@ def _check_disk_usage_warning():total_bytes += f.stat().st_sizeexcept 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_GBif exceeded:logger.warning("Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().",@@ -244,27 +200,16 @@ def _check_disk_usage_warning():return False-# Interactive sudo password cache.-#-# Scope the cache to the active session when a session key is available, then-# fall back to callback identity (ACP / CLI interactive callbacks), then the-# current thread. This prevents one interactive session from reusing another-# session's cached sudo password inside the same long-lived process.+# 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()-# Optional UI callbacks for interactive prompts. When set, these are called-# instead of the default /dev/tty or input() readers. The CLI registers these-# so prompts route through prompt_toolkit's event loop.-# Callback slots used by the approval prompt and sudo password prompt-# routines. Stored in thread-local state so overlapping ACP sessions —-# each running in its own ThreadPoolExecutor thread — don't stomp on-# each other's callbacks. See GHSA-qg5c-hvr5-hjgr.-#-# CLI mode is single-threaded, so each thread (the only one) holds its-# own callback exactly like before. Gateway mode resolves approvals via-# the per-session queue in tools.approval, not through these callbacks,-# so it's unaffected.+# 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+# resolves approvals via the per-session queue in tools.approval instead._callback_tls = threading.local()@@ -273,13 +218,8 @@ def _get_sudo_password_callback():def _current_session_key() -> str:- """Return the active gateway/WebUI session key, or "" outside sessions.-- Single lookup point for the ``HERMES_SESSION_KEY`` ContextVar with the- os.environ fallback that ``get_session_env()`` applies for CLI, cron, and- test processes. Callers scope per-session caches by prefixing the value- with ``"session:"`` so two sessions never share a cache slot.- """+ """Active gateway/WebUI session key, or "" outside sessions (ContextVar with+ the ``get_session_env`` os.environ fallback for CLI/cron/tests)."""from gateway.session_context import get_session_envreturn get_session_env("HERMES_SESSION_KEY", "")@@ -290,21 +230,12 @@ def _get_approval_callback():def set_sudo_password_callback(cb):- """Register a callback for sudo password prompts (used by CLI).-- Per-thread scope — ACP sessions that run concurrently in a- ThreadPoolExecutor each have their own callback slot.- """+ """Register the CLI's sudo password prompt callback (per-thread slot)."""_callback_tls.sudo_password = cbdef set_approval_callback(cb):- """Register a callback for dangerous command approval prompts.-- Per-thread scope — ACP sessions that run concurrently in a- ThreadPoolExecutor each have their own callback slot. See- GHSA-qg5c-hvr5-hjgr.- """+ """Register the dangerous-command approval prompt callback (per-thread slot)."""_callback_tls.approval = cb@@ -343,18 +274,10 @@ def _set_cached_sudo_password(password: str) -> None:def _reset_cached_sudo_passwords() -> None:- """Clear all cached sudo passwords.-- Internal helper for tests and process teardown paths.- """+ """Clear all cached sudo passwords (tests / process teardown)."""with _sudo_password_cache_lock:_sudo_password_cache.clear()-# =============================================================================-# Dangerous Command Approval System-# =============================================================================--# Dangerous command detection + approval now consolidated in tools/approval.pyfrom tools.approval import (check_all_command_guards as _check_all_guards_impl,)@@ -389,59 +312,17 @@ def _check_all_guards(command: str, env_type: str,has_host_access=has_host_access)-# Allowlist: characters that can legitimately appear in directory paths.-# Covers Unicode letters/digits, path separators, Windows drive/UNC separators,-# tilde, dot, hyphen, underscore, space, plus, at, equals, and comma. Shell-# metacharacters remain rejected. This intentionally fixes the old ASCII-only-# guard that blocked perfectly normal workdirs such as Chinese Obsidian vault-# paths while preserving the injection boundary around command execution-# (the cwd is additionally shlex-quoted before it reaches the shell; this-# allowlist is defense-in-depth).-_WORKDIR_SAFE_ASCII_CHARS = frozenset('/\\:_-.~ +@=,')---def _is_safe_workdir_char(ch: str) -> bool:- if not ch:- return False- # Reject control characters (including newlines/tabs) and NUL bytes before- # considering Unicode categories.- if ord(ch) < 32 or ord(ch) == 127:- return False- return ch.isalnum() or ch in _WORKDIR_SAFE_ASCII_CHARS---def _validate_workdir(workdir: str) -> str | None:- """Reject workdir values that don't look like a filesystem path.-- Uses an allowlist of safe characters rather than a deny-list, so novel- shell metacharacters can't slip through.-- Returns None if safe, or an error message string if dangerous.- """- if not workdir:- return None- for ch in workdir:- if not _is_safe_workdir_char(ch):- return (- f"Blocked: workdir contains disallowed character {repr(ch)}. "- "Use a simple filesystem path without shell metacharacters."- )- return Nonedef _in_delegated_child_context() -> bool:- """Return True while running inside a delegate_task child.-- Subagents execute on worker threads of the parent process, so they- inherit process-wide interactivity signals (``HERMES_INTERACTIVE=1`` set- by the CLI at startup) that do NOT mean *this* execution context can- reach the user. A child that passes the interactive gate with no sudo- callback falls through to the raw ``/dev/tty`` prompt — printed mid-TUI- from a background thread, racing siblings for the tty, and blocking the- child for the full timeout. Children must always behave as headless for- sudo prompting. The ContextVar is set by ``delegated_child_context()``- around every child run and propagates through ``contextvars.copy_context``- onto the executor thread.+ """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@@ -452,19 +333,14 @@ def _in_delegated_child_context() -> bool:def _handle_sudo_failure(output: str, env_type: str) -> str:- """- Check for sudo failure and add helpful message for headless contexts- (messaging gateway sessions and delegate_task subagents).-- Returns enhanced output if sudo failed in such a context, else original.- """+ """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-- # Check for sudo failure indicators+sudo_failures = ["sudo: a password is required","sudo: no tty present",@@ -523,28 +399,15 @@ def _invalidate_cached_sudo_on_auth_failure(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``."""- Prompt user for sudo password with timeout.-- Returns the password if entered, or empty string if:- - User presses Enter without input (skip)- - Timeout expires (45s default)- - Any error occurs-- Only works in interactive mode (HERMES_INTERACTIVE=1).- If a _sudo_password_callback is registered (by the CLI), delegates to it- so the prompt integrates with prompt_toolkit's UI. Otherwise reads- directly from /dev/tty with echo disabled.- """- import sys-- # Use the registered callback when available (prompt_toolkit-compatible)_sudo_cb = _get_sudo_password_callback()if _sudo_cb is not None:try:- # Blocked on a human typing their password: exclude from tool- # deadlines (#85125 2e). Local import avoids any import-layering- # surprises; tools.terminal_tool already imports tools.approval.from tools.approval import human_wait_windowwith human_wait_window():return _sudo_cb() or ""@@ -618,9 +481,6 @@ def _prompt_for_sudo_password(timeout_seconds: int = 45) -> str:password_thread = threading.Thread(target=read_password_thread, daemon=True)password_thread.start()- # Blocked on a human typing their password: exclude from tool- # deadlines on both executor paths (#85125 2e). Local import avoids- # any import-layering surprises.from tools.approval import human_wait_windowwith human_wait_window():password_thread.join(timeout=timeout_seconds)@@ -656,16 +516,6 @@ def _prompt_for_sudo_password(timeout_seconds: int = 45) -> str:if "HERMES_SPINNER_PAUSE" in os.environ:del os.environ["HERMES_SPINNER_PAUSE"]-def _safe_command_preview(command: Any, limit: int = 200) -> str:- """Return a log-safe preview for possibly-invalid command values."""- if command is None:- return "<None>"- if isinstance(command, str):- return command[:limit]- try:- return repr(command)[:limit]- except Exception:- return f"<{type(command).__name__}>"def _looks_like_env_assignment(token: str) -> bool:"""Return True when *token* is a leading shell environment assignment."""@@ -714,7 +564,11 @@ def _read_shell_token(command: str, start: int) -> tuple[str, int]:def _rewrite_real_sudo_invocations(command: str) -> tuple[str, int]:"""Rewrite only real unquoted sudo command words, not plain text mentions.- Returns the rewritten command and the number of sudo invocations rewritten.+ 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@@ -741,7 +595,7 @@ def _rewrite_real_sudo_invocations(command: str) -> tuple[str, int]:i = comment_endcontinue- if command.startswith("&&", i) or command.startswith("||", i) or command.startswith(";;", i):+ if command.startswith(("&&", "||", ";;"), i):out.append(command[i:i + 2])i += 2command_start = True@@ -766,78 +620,23 @@ def _rewrite_real_sudo_invocations(command: str) -> tuple[str, int]:else:out.append(token)- if command_start and _looks_like_env_assignment(token):- command_start = True- else:- command_start = False+ command_start = bool(command_start and _looks_like_env_assignment(token))i = next_ireturn "".join(out), sudo_countdef _count_real_sudo_invocations(command: str) -> int:- """Return how many real sudo command words appear in *command*.-- Lightweight scan that reuses the same tokeniser as- ``_rewrite_real_sudo_invocations`` but skips the string-building, so it- is cheap to call from the result-processing path.- """- count = 0- i = 0- n = len(command)- command_start = True-- while i < n:- ch = command[i]-- if ch.isspace():- if ch == "\n":- command_start = True- i += 1- continue-- if ch == "#" and command_start:- comment_end = command.find("\n", i)- if comment_end == -1:- break- i = comment_end- continue-- if command.startswith("&&", i) or command.startswith("||", i) or command.startswith(";;", i):- i += 2- command_start = True- continue-- if ch in ";|&(":- i += 1- command_start = True- continue-- if ch == ")":- i += 1- command_start = False- continue-- token, next_i = _read_shell_token(command, i)- if command_start and token == "sudo":- count += 1-- if command_start and _looks_like_env_assignment(token):- command_start = True- else:- command_start = False- i = next_i-- return count+ """Return how many real sudo command words appear in *command*."""+ return _rewrite_real_sudo_invocations(command)[1]def _sudo_nopasswd_works() -> bool:- """Return True when local sudo currently works without prompting.+ """True when local sudo currently works without prompting.- Only probes for the `local` terminal backend; Docker/SSH/Modal/etc. must- not inherit the host's sudo state. Re-probes every call (no process-level- cache) so an expired sudo timestamp cannot make a later command silently- block waiting for a password.+ 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":@@ -860,25 +659,16 @@ def _sudo_nopasswd_works() -> bool:def _rewrite_compound_background(command: str) -> str:"""Wrap `A && B &` (or `A || B &`) to `A && { B & }` at depth 0.- Bash parses ``A && B &`` with `&&` tighter than `&`, so it forks a- subshell for the whole `A && B` compound and backgrounds it. Inside- the subshell, `B` runs foreground, so the subshell waits for `B` to- finish. When `B` is a long-running process (`python3 -m http.server`,- `yes > /dev/null`, anything that doesn't naturally exit), the subshell- never exits. It leaks as a process stuck in ``wait4`` forever — and- on the way, its open stdout pipe can prevent the terminal tool from- returning promptly.-- Rewriting the tail to `A && { B & }` preserves `&&`'s error semantics- (skip B if A fails) while replacing the subshell with a brace group.- The brace group runs in the current shell (no fork), backgrounds B as- a simple command (bash doesn't wait for it in non-interactive mode),- and exits immediately. B runs as a normal backgrounded child, orphaned- when the parent shell exits.-- Handles redirects (``&>``, ``2>&1``) and skips content inside quoted- strings and parenthesised subshells. Leaves simple ``cmd &`` alone —- that construct doesn't have the subshell-wait bug.+ 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@@ -1023,40 +813,19 @@ def _rewrite_compound_background(command: str) -> str:def _transform_sudo_command(command: str | None) -> tuple[str | None, str | None]:- """- Transform sudo commands to use -S flag if SUDO_PASSWORD is available.-- This is a shared helper used by all execution environments to provide- consistent sudo handling across local, SSH, and container environments.-- Returns:- (transformed_command, sudo_stdin) where:- - transformed_command has every bare ``sudo`` replaced with- ``sudo -S -p ''`` so sudo reads its password from stdin.- - sudo_stdin is the password string with a trailing newline that the- caller must prepend to the process's stdin stream. sudo -S reads- exactly one line (the password) and passes the rest of stdin to the- child command, so prepending is safe even when the caller also has- its own stdin_data to pipe.- - If no password is available, sudo_stdin is None and the command is- returned unchanged so it fails gracefully with- "sudo: a password is required".-- Callers that drive a subprocess directly (local, ssh, docker, singularity)- should prepend sudo_stdin to their stdin_data and pass the merged bytes to- Popen's stdin pipe.-- Callers that cannot pipe subprocess stdin (modal, daytona,- vercel_sandbox) must embed the password in the command string- themselves; see their execute() methods for how they handle the- non-None sudo_stdin case.-- If SUDO_PASSWORD is not set and an interactive UI is available- (HERMES_INTERACTIVE=1 or a registered sudo password callback):- Prompts user for password with 45s timeout, caches for session.-- If SUDO_PASSWORD is not set and NOT interactive:- Command runs as-is (fails gracefully with "sudo: a password is required").+ """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@@ -1064,9 +833,8 @@ def _transform_sudo_command(command: str | None) -> tuple[str | None, str | Noneif sudo_count == 0:return command, None- # Scope-aware read (Slack pattern): under multiplex the process env may- # hold another profile's SUDO_PASSWORD, so honor the installed scope's- # verdict; unscoped callers keep the legacy os.environ read.+ # 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@@ -1083,23 +851,16 @@ def _transform_sudo_command(command: str | None) -> tuple[str | None, str | Noneelse _get_cached_sudo_password())- # Local hosts with sudoers NOPASSWD should not be forced through the- # interactive Hermes password prompt or the sudo -S password-pipe path.- # Scoped to the local terminal backend so Docker/SSH/Modal/etc. can't- # inherit host sudo state. Re-probes every call (no process-lifetime- # cache) so an expired sudo timestamp doesn't make a later command block- # silently without Hermes prompting.+ # 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, Nonehas_sudo_prompt_callback = _get_sudo_password_callback() is not None- # delegate_task children inherit the parent's process-wide- # HERMES_INTERACTIVE=1 (and, on a recycled worker thread, potentially a- # stale thread-local callback), but there is no user on the other side of- # this execution context: prompting from a subagent thread fights the- # parent's TUI for /dev/tty and blocks the child for the full timeout.- # Children always behave as headless — configured SUDO_PASSWORD, the- # session cache, and the NOPASSWD probe above all still work.+ # 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()@@ -1117,7 +878,6 @@ def _transform_sudo_command(command: str | None) -> tuple[str | None, str | Nonereturn command, None-# Environment classes now live in tools/environments/from tools.environments.base import EnvironmentConnectionErrorfrom tools.environments.local import LocalEnvironment as _LocalEnvironmentfrom tools.environments.singularity import SingularityEnvironment as _SingularityEnvironment@@ -1126,7 +886,6 @@ from tools.environments.docker import DockerEnvironment as _DockerEnvironmentfrom tools.environments.modal import ModalEnvironment as _ModalEnvironmentfrom tools.environments.managed_modal import ManagedModalEnvironment as _ManagedModalEnvironmentfrom tools.managed_tool_gateway import is_managed_tool_gateway_ready-import sys# Tool description for LLM@@ -1141,7 +900,7 @@ Working directory: use 'workdir' for per-command cwd; when a command changes thePTY: pty=true + background=true for interactive CLIs (they hang without a terminal); drive them with process(action="write"/"submit"). Local backend only."""-# Global state for environment lifecycle management+# Environment lifecycle state._active_environments: Dict[str, Any] = {}_last_activity: Dict[str, float] = {}_env_lock = threading.Lock()@@ -1150,9 +909,7 @@ _creation_locks_lock = threading.Lock() # Protects _creation_locks dict itself_cleanup_thread = None_cleanup_running = False-# Once-per-process guard for the docker orphan reaper (issue #20561).-# Set when _maybe_reap_docker_orphans first runs; concurrent _create_environment-# calls for parallel subagents won't re-trigger the sweep.+# Once-per-process guard for the docker orphan reaper._docker_orphan_reaper_ran = False_docker_orphan_reaper_lock = threading.Lock()@@ -1160,40 +917,27 @@ _docker_orphan_reaper_lock = threading.Lock()def _maybe_reap_docker_orphans(container_config: Dict[str, Any]) -> None:"""Run the docker orphan reaper once per process, if enabled.- Sweeps long-Exited containers labeled ``hermes-agent=1`` for the current- profile that match the issue #20561 leak class — containers left behind- by Hermes processes that exited without firing ``atexit`` (SIGKILL,- OOM, terminal-window-close). The reaper is conservative by default:- only Exited containers older than ``2 × lifetime_seconds`` and scoped to- the current profile.-- Gates:-- * ``terminal.docker_orphan_reaper: false`` disables it entirely (the- operator opted out — usually because they're running multiple- Hermes processes in the same profile and don't trust the- conservative defaults).- * ``_docker_orphan_reaper_ran`` flag — sweep runs once per Python- interpreter, not on every subagent / RL-rollout / parallel- ``terminal()`` call.+ Sweeps Exited containers labeled ``hermes-agent=1`` for the current+ profile — leftovers of Hermes processes that died without firing+ ``atexit`` (SIGKILL, OOM, closed terminal). Conservative: only containers+ older than ``2 × lifetime_seconds``, profile-scoped. Gates:+ ``terminal.docker_orphan_reaper: false`` (operator opt-out, e.g. several+ Hermes processes sharing a profile) and the once-per-interpreter flag so+ parallel subagent / RL-rollout calls don't re-sweep."""global _docker_orphan_reaper_ranif not container_config.get("docker_orphan_reaper", True):return- # Cheap double-checked-locking: read without the lock, take the lock- # only on first run, recheck inside.- if _docker_orphan_reaper_ran:+ if _docker_orphan_reaper_ran: # double-checked lockingreturnwith _docker_orphan_reaper_lock:if _docker_orphan_reaper_ran:return_docker_orphan_reaper_ran = True- # 2 × lifetime_seconds gives sibling Hermes processes a generous grace- # window. Floor at 60s so an operator with TERMINAL_LIFETIME_SECONDS=0- # doesn't get an instant-reap that races their own setup.- # ``container_config`` only carries container_* keys, so read- # lifetime_seconds from the env var the rest of the module uses.+ # 2 × lifetime gives sibling processes a grace window; floor at 60s so+ # TERMINAL_LIFETIME_SECONDS=0 can't instant-reap a sibling's own setup.+ # container_config only carries container_* keys, so read the env var.try:lifetime = int(_tenv("TERMINAL_LIFETIME_SECONDS", "300"))except (TypeError, ValueError):@@ -1220,43 +964,25 @@ def _maybe_reap_docker_orphans(container_config: Dict[str, Any]) -> None:logger.debug("Docker orphan reaper raised: %s", e)-# Per-task environment overrides registry.-# Allows environments (e.g., TerminalBench2Env) to specify a custom Docker/Modal-# image for a specific task_id BEFORE the agent loop starts. When the terminal or-# file tools create a new sandbox for that task_id, they check this registry first-# and fall back to the TERMINAL_MODAL_IMAGE (etc.) env var if no override is set.-#-# This is never exposed to the model -- only infrastructure code calls it.-# Thread-safe because each task_id is unique per rollout.+# Per-task environment overrides (never exposed to the model). RL/benchmark+# envs and ACP register a custom image / cwd for a task_id BEFORE the agent+# loop; sandbox creation consults this first, then the TERMINAL_* env vars._task_env_overrides: Dict[str, Dict[str, Any]] = {}-# ── Per-session cwd records (cwd rearchitecture, step 1) ────────────────────-#-# The durable source of truth for "which directory is THIS session working-# in". Keyed by the raw session/task key (NOT the collapsed container id):-# the terminal env is shared across sessions, so any cwd state stored on the-# env is a global mutable timeshared between sessions — the root cause of the-# wrong-worktree bug class (env.cwd_owner stamping, _last_known_cwd, and the-# ownership ladder in file_tools are all patches over that misplacement).-#-# Step 1 (this change): dual-write only. Every site that learns a session's-# live cwd (post-command tracking, cwd-override registration) also records it-# here. Readers still use the legacy env.cwd ladder. Later steps flip-# file_tools and _resolve_command_cwd to read this store, then delete the-# env-side tracking + ownership guards.+# Per-session cwd records: the durable source of truth for "which directory+# is THIS session in". Keyed by the raw session/task key, NOT the collapsed+# container id — the env is shared across sessions, so cwd state stored on+# it is a global mutable timeshared between sessions (the wrong-worktree bug+# class). Written after every completed command and on cwd-override+# registration; readers resolve against it before any env-side cwd._session_cwd: Dict[str, str] = {}_session_cwd_lock = threading.Lock()def record_session_cwd(session_key: Optional[str], cwd: Optional[str]) -> None:- """Record *cwd* as the working directory of *session_key*.-- Called wherever a session's live cwd becomes known: after a terminal- command completes (the env's post-command tracking has just parsed the- resulting cwd) and when a surface registers a workspace cwd override.- Empty/None session keys collapse to ``"default"`` (single-session CLI).- Non-string / empty cwds are ignored.- """+ """Record *cwd* as *session_key*'s working directory (after a completed+ command, or on workspace-override registration). None/empty keys collapse+ to ``"default"``; non-string / empty cwds are ignored."""if not isinstance(cwd, str) or not cwd.strip():returnkey = str(session_key or "default")@@ -1266,12 +992,8 @@ def record_session_cwd(session_key: Optional[str], cwd: Optional[str]) -> None:def get_session_cwd(session_key: Optional[str]) -> Optional[str]:- """Return the recorded working directory for *session_key*, if any.-- No fallback chain here on purpose: callers decide what an absent record- means (config default, TERMINAL_CWD seed, process cwd). ``None``/empty- keys read the ``"default"`` record.- """+ """Recorded cwd for *session_key*, or None. No fallback chain on purpose:+ callers decide what an absent record means. None/empty keys read ``"default"``."""key = str(session_key or "default")with _session_cwd_lock:return _session_cwd.get(key)@@ -1284,38 +1006,23 @@ def clear_session_cwd(session_key: str) -> None:def register_task_env_overrides(task_id: str, overrides: Dict[str, Any]):- """- Register environment overrides for a specific task/rollout.-- Called by Atropos environments before the agent loop to configure- per-task sandbox settings (e.g., a custom Dockerfile for the Modal image).-- Supported override keys:- - modal_image: str -- Path to Dockerfile or Docker Hub image name- - docker_image: str -- Docker image name- - cwd: str -- Working directory inside the sandbox-- Args:- task_id: The rollout's unique task identifier- overrides: Dict of config keys to override+ """Register per-task sandbox overrides (``docker_image``/``modal_image``/+ ``singularity_image``/``daytona_image``, ``env_type``, ``cwd``) before the+ agent loop runs.++ A ``cwd`` override takes effect immediately: it becomes the session's+ recorded cwd (until a ``cd`` changes it) and any live env's cwd is updated+ too, so env-side seeding stays consistent (ACP switching project root+ mid-session via ``session/load``)."""_task_env_overrides[task_id] = overrides- # If a live environment already exists for this task, a freshly registered- # ``cwd`` override (e.g. the ACP client switching the editor's project root- # mid-session via ``session/load`` / ``session/resume``) must take effect- # immediately. The session record is what commands resolve against;- # the live env's cwd is also updated so env-side seeding stays consistent.new_cwd = overrides.get("cwd")if isinstance(new_cwd, str) and new_cwd.strip():- # A registered workspace cwd IS the session's working directory until- # a `cd` changes it.record_session_cwd(task_id, new_cwd)- # The live env is cached under the raw task_id for per-session surfaces- # (ACP/gateway/dashboard) and under the collapsed container id for- # isolation-keyed rollouts. Try the raw id first, then the container id,- # so a CWD-only override (which collapses to "default") still finds and- # updates the originating session's env.+ # Live env may be cached under the raw task_id (per-session surfaces)+ # or the collapsed container id (isolation-keyed rollouts); try both so+ # a CWD-only override (which collapses to "default") still finds it.container_id = _resolve_container_task_id(task_id)with _env_lock:env = _active_environments.get(task_id) or _active_environments.get(container_id)@@ -1324,34 +1031,24 @@ def register_task_env_overrides(task_id: str, overrides: Dict[str, Any]):def clear_task_env_overrides(task_id: str):- """- Clear environment overrides for a task after rollout completes.-- Called during cleanup to avoid stale entries accumulating.- """+ """Drop a task's overrides, cwd record and container alias (rollout cleanup)."""_task_env_overrides.pop(task_id, None)clear_session_cwd(task_id)with _container_alias_lock:_container_aliases.pop(task_id, None)-# Subagent → parent container aliasing. delegate_task children get their own-# task_id (file-state tracking, TUI events) but must share the PARENT-# session's container — one bash, one /workspace, one set of installed-# packages. With per-session container isolation active (docker +-# container_persistent: false), the collapse-to-"default" shortcut no longer-# provides that sharing, so the spawn site registers an explicit alias.+# Subagent → parent container aliasing. delegate_task children have their own+# task_id but must share the PARENT's container; under per-session isolation+# the collapse-to-"default" shortcut no longer provides that, so the spawn+# site registers an explicit alias._container_aliases: Dict[str, str] = {}_container_alias_lock = threading.Lock()def register_container_alias(child_task_id: str, parent_task_id: Optional[str]) -> None:- """Make *child_task_id* resolve to *parent_task_id*'s container.-- Called by ``delegate_task`` at child spawn so subagents share the parent- session's sandbox under per-session container isolation. A missing/empty- parent id aliases the child to ``"default"`` (top-level CLI parent).- """+ """Make *child_task_id* resolve to *parent_task_id*'s container (called at+ delegate_task spawn). A missing parent id aliases to ``"default"``."""if not child_task_id:returnwith _container_alias_lock:@@ -1372,16 +1069,11 @@ def _resolve_container_alias(task_id: str) -> str:def _session_isolation_enabled() -> bool:"""True when non-persistent sandboxes get per-session identities.- ``container_persistent: false`` is a statement that state must not- survive or be shared across sessions, so sharing one sandbox across- sessions contradicts it (#82731). Backends whose non-persistent mode is- session-scoped:-- - ``docker`` — per-session containers (the original fix).- - plugin backends that declare ``session_isolated_when_nonpersistent``- (e.g. sandboxes resumed *by name*, where a shared deterministic name- under non-persistent mode would let two independent ephemeral runs- attach one live VM and delete it out from under each other).+ ``container_persistent: false`` means state must not survive or be shared+ across sessions, so one shared sandbox contradicts it. Applies to docker+ and to plugin backends declaring ``session_isolated_when_nonpersistent``+ (e.g. sandboxes resumed by name, where a shared deterministic name would+ let two ephemeral runs attach one VM and delete it under each other)."""_ensure_terminal_env_bridged()env_type = _tenv("TERMINAL_ENV", "local")@@ -1389,16 +1081,12 @@ def _session_isolation_enabled() -> bool:env_type, "session_isolated_when_nonpersistent"):return False- return _tenv("TERMINAL_CONTAINER_PERSISTENT", "true").lower() not in {"true", "1", "yes"}+ return not _tenv_bool("TERMINAL_CONTAINER_PERSISTENT", "true")def _docker_session_isolation_enabled() -> bool:- """Docker-specific view of :func:`_session_isolation_enabled`.-- Kept separate because several docker-only paths (workspace mount- selection, session-scoped container teardown) key off it; those must- not fire for other backends.- """+ """Docker-only view of :func:`_session_isolation_enabled` — the workspace+ mount and session-scoped teardown paths must not fire for other backends."""if _tenv("TERMINAL_ENV", "local") != "docker":return Falsereturn _session_isolation_enabled()@@ -1407,31 +1095,22 @@ def _docker_session_isolation_enabled() -> bool:def _docker_persistent_profile_scoped() -> bool:"""True when the persistent Docker container is shared per PROFILE.- The product contract for ``TERMINAL_ENV=docker`` +- ``container_persistent: true`` is ONE long-lived container per Hermes- profile, shared by every session of that profile (CLI, gateway chats,- WebUI). Commit a270c4ade added a session-key fallback to- :func:`_resolve_container_task_id` to stop cross-profile SSH environment- reuse, but the fallback wasn't backend-gated, so persistent Docker- silently fragmented into one container per gateway session (#93950 was- downstream damage from that). This predicate gates the resolver back to- profile scoping for exactly this backend/mode; SSH and other backends- keep the session-scoped cache key that fixed the original leak.+ Contract for docker + ``container_persistent: true``: ONE long-lived+ container per profile, shared by every session (CLI, gateway, WebUI).+ The session-key fallback in :func:`_resolve_container_task_id` exists to+ stop cross-profile SSH reuse; ungated it fragmented persistent Docker+ into one container per gateway session, so this predicate restores+ profile scoping for exactly this backend/mode."""_ensure_terminal_env_bridged()if _tenv("TERMINAL_ENV", "local") != "docker":return False- return _tenv("TERMINAL_CONTAINER_PERSISTENT", "true").lower() in {"true", "1", "yes"}+ return _tenv_bool("TERMINAL_CONTAINER_PERSISTENT", "true")def _current_session_profile() -> str:- """Return the active session's Hermes profile name, or "" when unset.-- Same lookup discipline as :func:`_current_session_key`: the ContextVar- (bound per message by the gateway, per session by the WebUI streaming- layer) with the ``get_session_env`` os.environ fallback for CLI, cron,- and test processes.- """+ """Active session's Hermes profile name, or "" (same lookup discipline as+ :func:`_current_session_key`)."""from gateway.session_context import get_session_envreturn get_session_env("HERMES_SESSION_PROFILE", "")@@ -1444,77 +1123,44 @@ _ISOLATION_OVERRIDE_KEYS = frozenset({def _has_isolation_overrides(task_id: Optional[str]) -> bool:- """True when *task_id* registered backend-image/env_type overrides.-- The single owner of the "is this an RL/benchmark-style isolated rollout"- predicate — shared by container-key resolution and container creation so- the two can't drift.- """+ """True when *task_id* registered image/env_type overrides — the single+ "isolated RL/benchmark rollout" predicate shared by key resolution and+ container creation so the two can't drift."""if not task_id or task_id not in _task_env_overrides:return Falsereturn bool(set(_task_env_overrides[task_id].keys()) & _ISOLATION_OVERRIDE_KEYS)def _resolve_container_task_id(task_id: Optional[str]) -> str:- """- Map a tool-call ``task_id`` to the container/sandbox key used by- ``_active_environments``.-- The top-level agent passes ``task_id=None`` and lands on ``"default"``.- ``delegate_task`` children pass their own subagent ID so that- file-state tracking, the active-subagents registry, and TUI events stay- distinct per child -- but we deliberately collapse that ID back to- ``"default"`` here so subagents share the parent's long-lived container- (one bash, one /workspace, one set of installed packages).-- Exception: RL / benchmark environments (TerminalBench2, HermesSweEnv, ...)- call ``register_task_env_overrides(task_id, {...})`` to request a- per-task Docker/Modal image. When an override is registered for a- task_id, we honour it by returning the task_id unchanged -- those- rollouts need their own isolated sandbox, which is the whole point of- the override.-- CWD-only overrides (registered by the ACP adapter for workspace- tracking) are *not* isolation signals — they should not cause each- session to spin up its own container. Only overrides containing- backend-specific image keys or ``env_type`` trigger isolation.-- Per-session container isolation (docker + ``container_persistent:- false``): each session's task_id is its own container key, so a fresh- chat gets a fresh sandbox with only ITS mounts — a previous session's- workspace can no longer appear in a new session's container.- ``delegate_task`` children keep sharing the parent's container via the- alias registry (``register_container_alias``).+ """Map a tool-call ``task_id`` to the ``_active_environments`` key.++ Order matters — earlier branches are authoritative where they apply:++ 1. Task ids with image/``env_type`` overrides (RL/benchmark rollouts) key+ their own sandbox. CWD-only overrides (ACP workspace tracking) are NOT+ isolation signals.+ 2. Per-session isolation (docker + ``container_persistent: false``): each+ session's task_id is its own key, so a fresh chat gets a fresh sandbox+ with only ITS mounts; delegate_task children follow the alias registry+ to the parent's container.+ 3. With a session key present (WebUI per-session, gateway per-message):+ persistent Docker is PROFILE-scoped (``shared:<key>`` opt-in, else+ ``profile:<name>``, with the default profile staying literally+ ``"default"`` so CLI and default-profile gateway sessions share ONE+ container); other backends key ``session:<key>`` so switching profiles+ can't reuse another profile's SSHEnvironment on the wrong host.+ 4. No session key (CLI): ``shared:<key>`` when opted in — or a CLI run of+ a keyed profile would split from its gateway sessions — else+ ``"default"``, which subagent ids collapse onto so they share the+ parent's long-lived container."""if task_id and _has_isolation_overrides(task_id):return task_idif task_id and _session_isolation_enabled():return _resolve_container_alias(task_id)- # Per-session isolation: when a session key is present (the WebUI streaming- # layer sets it per-session, the gateway per-message via contextvars), scope- # the container to it so switching profiles can't reuse a previous profile's- # SSHEnvironment and silently run commands on the wrong remote host. Subagents- # inherit the same session key, so they still collapse onto the parent's- # container (the #16177 shared-container intent). CLI mode has no session key- # and falls through to "default", behaviour unchanged. See commit e00f940a9.- #- # This runs *after* the isolation-override and docker/container_persistent- # branches above: those paths already key containers per task_id, so they- # stay authoritative where they apply and this only covers the cases that- # would otherwise collapse to the shared "default" key (notably SSH).session_key = _current_session_key()if session_key:- # Persistent Docker is PROFILE-scoped by contract: one long-lived- # container shared by every session of the profile. Key it by profile- # (not session) so gateway chats, CLI, and WebUI all land in the same- # container and sandbox. The bare "profile:default" key stays literally- # "default" so CLI mode (no session key at all) and gateway sessions of- # the default profile share the SAME container — CLI's historical key- # IS the default profile's container.if _docker_persistent_profile_scoped():- # Explicit opt-in: trusted profiles configuring the same- # terminal.docker_shared_container_key share ONE container/cache- # slot (and sandbox dir) regardless of profile name (#84671).shared = _tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip()if shared:return f"shared:{shared}"@@ -1523,10 +1169,6 @@ def _resolve_container_task_id(task_id: Optional[str]) -> str:return "default"return f"profile:{profile}"return f"session:{session_key}"- # CLI/no-session path: honour the shared-container opt-in here too, or a- # CLI run of a keyed profile would land in "default" while its gateway- # sessions land in "shared:<key>" — splitting the very container the- # setting exists to unify.if _docker_persistent_profile_scoped():shared = _tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip()if shared:@@ -1539,12 +1181,10 @@ def resolve_task_overrides(task_id: Optional[str]) -> Dict[str, Any]:``register_task_env_overrides`` writes under the *raw* task/session id, buta CWD-only override collapses (:func:`_resolve_container_task_id`) to the- shared ``"default"`` container so per-session surfaces (ACP/gateway/- dashboard) don't each spin up their own sandbox. Callers that need the- override (terminal command setup, file-tool cwd resolution) must therefore- read the raw id FIRST and only fall back to the collapsed container id, or- the originating session's override is silently dropped. This is the single- source of that lookup so the terminal and file layers can't drift apart.+ shared ``"default"`` container. Callers must therefore read the raw id+ FIRST and only fall back to the collapsed container id, or the originating+ session's override is silently dropped. Single source of that lookup so+ the terminal and file layers can't drift apart."""raw = task_id or "default"return (@@ -1554,25 +1194,52 @@ def resolve_task_overrides(task_id: Optional[str]) -> Dict[str, Any]:)+# Backends that take an image, keyed to the override/config key carrying it.+_IMAGE_KEY_BY_BACKEND = {+ "docker": "docker_image",+ "singularity": "singularity_image",+ "modal": "modal_image",+ "daytona": "daytona_image",+}+++def _select_image(env_type: str, overrides: Dict[str, Any], config: Dict[str, Any]) -> str:+ """Image for *env_type*: per-task override first, then config; "" for imageless backends."""+ key = _IMAGE_KEY_BY_BACKEND.get(env_type)+ if key is None:+ return ""+ return overrides.get(key) or config[key]+++def _lookup_active_env(effective_task_id: str, task_id: Optional[str]):+ """Return the cached env for the collapsed id, else for the raw task_id, else None.++ Caller holds ``_env_lock``. Per-session surfaces (ACP/gateway/dashboard)+ with a CWD-only override collapse to ``"default"`` for container sharing,+ yet an env may already be cached under the originating task_id; honor it+ instead of spawning a duplicate. Refreshes ``_last_activity`` on a hit.+ """+ if effective_task_id in _active_environments:+ key = effective_task_id+ elif task_id and task_id in _active_environments:+ key = task_id+ else:+ return None+ _last_activity[key] = time.time()+ return _active_environments[key]++def _resolve_task_host_cwd(config: Dict[str, Any], task_id: Optional[str]) -> Optional[str]:"""Host directory to bind-mount at ``/workspace`` for *task_id*'s container.- The single owner of the cwd-mount policy, shared by every environment- creation site (terminal tool, file tools, execute_code, lazy bring-up):-- * Shared-container mode (the default): the process-global- ``TERMINAL_CWD``-derived ``config["host_cwd"]`` — unchanged legacy- behavior, ONE container whose mount tracks the configured workspace.- * Per-session isolation mode (docker + ``container_persistent: false``):- only the SESSION's own registered workspace may mount. The process- env var is a launch artifact — the TUI/desktop workspace picker writes- ``os.environ["TERMINAL_CWD"]`` and it outlives the session that set it,- so deriving a fresh session's mount from it leaks the previous- session's directory into a chat that never attached one. Overrides- tagged ``cwd_source: "process"`` (gateway fallback to the global env- var) are likewise refused as mount sources; only a workspace the user- actually attached to THIS session (``cwd_source: "session"`` or an- untagged override from ACP/RL surfaces) mounts.+ Single owner of the cwd-mount policy for every creation site. Shared-+ container mode: the ``TERMINAL_CWD``-derived ``config["host_cwd"]``.+ Per-session isolation (docker + ``container_persistent: false``): only+ the SESSION's own registered workspace may mount — the process env var is+ a launch artifact that outlives the session that set it, so deriving a+ fresh session's mount from it would leak the previous session's directory.+ Overrides tagged ``cwd_source: "process"`` are refused for the same reason;+ ``cwd_source: "session"`` or untagged (ACP/RL) overrides mount."""if config.get("env_type") != "docker":return None@@ -1598,18 +1265,12 @@ def _resolve_task_host_cwd(config: Dict[str, Any], task_id: Optional[str]) -> Opreturn candidate-# Configuration from environment variables-def _parse_env_var(name: str, default: str, converter: Any = int, type_label: str = "integer"):- """Parse an environment variable with *converter*, raising a clear error on bad values.-- Without this wrapper, a single malformed env var (e.g. TERMINAL_TIMEOUT=5m)- causes an unhandled ValueError that kills every terminal command.- """+ """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_"):- # Scope-aware: under gateway multiplexing the active profile's- # per-turn scope overrides the process env.raw = _tenv(name, default)try:return converter(raw)@@ -1621,40 +1282,26 @@ def _parse_env_var(name: str, default: str, converter: Any = int, type_label: stdef _safe_getcwd() -> str:- """Return the current working directory, tolerating a deleted or- permission-restricted CWD.-- ``os.getcwd()`` raises FileNotFoundError when the process's working- directory has been removed out from under it (e.g. a scratch workspace- that was cleaned up mid-session). On macOS with TCC (Transparency,- Consent, and Control), it raises PermissionError (EPERM) when the CWD- is under a protected location (~/Documents, ~/Desktop, ~/Downloads)- and the calling process lacks Full Disk Access. Fall back to- TERMINAL_CWD, then the user's home directory, so terminal setup never- crashes on a stale or TCC-blocked CWD.- """+ """``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("~")-# Path prefixes that identify a *host* working directory which cannot exist-# inside a container sandbox. Covers POSIX user dirs and Windows drive paths-# (``C:\Users\...`` / ``C:/Users/...``) — the latter is how a Windows host's-# cwd looks when it leaks toward a Linux container's ``-w`` flag.+# 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 attribute for a plugin-registered terminal backend.-- Fail-soft: returns *default* when the registry is unavailable, the- backend is unknown, or the provider attribute raises — a misbehaving- plugin must degrade, never take the terminal tool down.- """+ """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 defaulttry:@@ -1666,11 +1313,7 @@ def _plugin_env_flag(env_type: str, attr: str, default=False):def _is_container_backend(env_type: str) -> bool:- """True when *env_type* behaves like a container/sandbox backend.-- Built-in container backends via ``_CONTAINER_BACKENDS``; plugin-registered- backends via their declarative ``is_container`` flag.- """+ """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")@@ -1687,71 +1330,51 @@ def _get_plugin_env_provider(env_type: str):def _is_unusable_container_cwd(cwd: str) -> bool:- """Return True if *cwd* is a host/relative path that won't work as the- working directory inside a container sandbox.-- A container's cwd must be an absolute path that exists *inside* the- sandbox (e.g. ``/workspace`` or ``/root``). A host path (``/home/user``,- ``C:\\Users\\me``) or a relative path (``.``, ``src/``) is meaningless to- ``docker run -w`` and makes the container fail to start (exit 125).- """+ """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- if any(cwd.startswith(p) for p in _HOST_CWD_PREFIXES):- return True- # Relative paths (".", "src/") can't be a container workdir either. Windows- # drive paths are absolute on Windows but os.path.isabs() is False on a- # POSIX host, so they're already caught by the prefix check above.- if not os.path.isabs(cwd):- return True- 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 read in this module must go through this helper:- under gateway multiplexing the active profile's terminal config arrives- via a per-turn scope (``tools.terminal_scope``), and a raw ``os.getenv``- would read whatever profile's config a previous turn pinned into the- process env (the cross-profile backend leak fixed here).- """+ """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_envreturn terminal_env(name, default)-# One-shot guard for the config-fallback bridge below. Purely an-# optimization: after the first attempt either TERMINAL_ENV is set (bridge-# succeeded — merged config always carries terminal.backend) or the import-# failed and retrying every call would be wasted work.+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 = Falsedef _ensure_terminal_env_bridged() -> None:"""Backfill TERMINAL_* env vars from config.yaml when no launcher did.- terminal_tool reads ALL terminal settings from os.environ (TERMINAL_*).- The CLI (cli.py ``env_mappings``), the gateway (gateway/run.py- ``_terminal_env_map``), and TUI/dashboard PTY launches- (``apply_terminal_config_to_env``) bridge ``terminal.*`` config into env- vars at startup — but processes that skip all of those paths (``hermes- serve`` / the Desktop app backend's in-process agents, the desktop cron- ticker, ACP) used to silently fall back to the local backend even when- config.yaml selects ``terminal.backend: docker``, running commands on the- host the user intended to sandbox (#63141, #54449, #61115, #65696).-- Explicit terminal config keys win: when config.yaml has a ``terminal``- section, each key present there overrides its matching env value (which may- be stale from ``hermes setup``). Environment values for omitted terminal- keys are preserved. When no terminal section exists, exported/.env values- keep working unchanged.-- A per-turn terminal scope (multiplexed gateway / profile-scoped cron)- suppresses this bridge entirely: the scope holds the active profile's- authoritative values and reads fall through ``_tenv`` — writing them into- the process-global ``os.environ`` would re-create the first-writer-wins- cross-profile leak the scope exists to fix.+ The CLI, gateway and TUI/dashboard PTY launches bridge ``terminal.*`` into+ env vars at startup; processes that skip those paths (``hermes serve``,+ Desktop in-process agents, desktop cron ticker, ACP) would otherwise fall+ back to the local backend even when config selects docker, running+ commands on the host the user meant to sandbox.++ Explicit keys in config.yaml's ``terminal`` section override matching+ env values (which may be stale from ``hermes setup``); env values for+ omitted keys are preserved. Without a terminal section, an existing+ TERMINAL_ENV selection is kept and defaults are backfilled only when none+ is set. A per-turn terminal scope suppresses the bridge entirely: writing+ the scope's values into the process-global env would re-create the+ first-writer-wins cross-profile leak the scope exists to fix."""from tools.terminal_scope import get_terminal_scope@@ -1764,42 +1387,29 @@ def _ensure_terminal_env_bridged() -> None:try:from hermes_cli.config import apply_terminal_config_to_env, read_raw_config- # If config.yaml has an explicit terminal section, bridge with- # override enabled. The helper only overrides env vars for keys present- # in that raw section; merged defaults remain backfill-only. Without a- # terminal section, preserve an existing TERMINAL_ENV selection or- # backfill defaults when no selection exists.raw_config = read_raw_config()- has_terminal_section = isinstance(raw_config.get("terminal"), dict)-- if has_terminal_section:- # Explicit terminal keys in config.yaml win over matching env values.+ if isinstance(raw_config.get("terminal"), dict):apply_terminal_config_to_env(env=None, override=True)elif "TERMINAL_ENV" not in os.environ:- # No terminal section in config.yaml, TERMINAL_ENV not set —- # backfill from config defaultsapply_terminal_config_to_env(env=None, override=False)except Exception:- # Never let a config problem take the terminal tool down — the- # historical local default still applies.+ # Never let a config problem take the terminal tool down.logger.debug("terminal config → env fallback bridge failed", exc_info=True)def _get_env_config() -> Dict[str, Any]:- """Get terminal environment configuration from environment variables."""- # Default image with Python and Node.js for maximum compatibility+ """Resolve the terminal configuration dict from TERMINAL_* env vars."""default_image = "nikolaik/python-nodejs:python3.11-nodejs20"_ensure_terminal_env_bridged()env_type = _tenv("TERMINAL_ENV", "local")-- mount_docker_cwd = _tenv("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").lower() in {"true", "1", "yes"}++ mount_docker_cwd = _tenv_bool("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false")container_backend = _is_container_backend(env_type)docker_backend = env_type == "docker"- # Docker/container-only env vars may be bridged from config.yaml even when- # the active backend is local/ssh. Do not parse their JSON/numeric payloads- # until a backend that can consume them is selected; a stale or invalid- # Docker value should not make local terminal/execute_code unusable.+ # Container/docker-only payloads are parsed only when such a backend is+ # selected: a stale or invalid Docker value bridged from config.yaml must+ # not make local terminal/execute_code unusable.if container_backend:container_cpu = _parse_env_var("TERMINAL_CONTAINER_CPU", "1", float, "number")container_memory = _parse_env_var("TERMINAL_CONTAINER_MEMORY", "5120")@@ -1822,9 +1432,6 @@ def _get_env_config() -> Dict[str, Any]:docker_extra_args = []docker_shm_size = "1g"- # Default cwd: local uses the host's current directory, ssh uses the- # remote home, Vercel uses its documented workspace root, and everything- # else starts in the backend's default root-like cwd.if env_type == "local":default_cwd = _safe_getcwd()elif env_type == "ssh":@@ -1834,10 +1441,9 @@ def _get_env_config() -> Dict[str, Any]:else:default_cwd = "/root"- # Read TERMINAL_CWD but sanity-check it for container backends.- # If Docker cwd passthrough is explicitly enabled, remap the host path to- # /workspace and track the original host path separately. Otherwise keep the- # normal sandbox behavior and discard host paths.+ # TERMINAL_CWD, sanity-checked for container backends: with Docker cwd+ # passthrough the host path is remapped to /workspace and tracked as+ # host_cwd; otherwise host paths are discarded.cwd = _tenv("TERMINAL_CWD", default_cwd)from hermes_cli.config import _is_ssh_remote_tilde_cwdif cwd and not _is_ssh_remote_tilde_cwd(env_type, cwd):@@ -1852,8 +1458,7 @@ def _get_env_config() -> Dict[str, Any]:):host_cwd = candidatecwd = "/workspace"- elif _is_container_backend(env_type) and cwd:- # Host paths and relative paths that won't work inside containers+ elif container_backend and cwd:if _is_unusable_container_cwd(cwd) and cwd != default_cwd:logger.info("Ignoring TERMINAL_CWD=%r for %s backend ""(host/relative path won't work in sandbox). Using %r instead.",@@ -1880,44 +1485,29 @@ def _get_env_config() -> Dict[str, Any]:"ssh_port": _parse_env_var("TERMINAL_SSH_PORT", "22"),"ssh_key": _tenv("TERMINAL_SSH_KEY", ""),# Persistent shell: SSH defaults to the config-level persistent_shell- # setting (true by default for non-local backends); local is always opt-in.- # Per-backend env vars override if explicitly set.- "ssh_persistent": _tenv(- "TERMINAL_SSH_PERSISTENT",- _tenv("TERMINAL_PERSISTENT_SHELL", "true"),- ).lower() in {"true", "1", "yes"},- "local_persistent": _tenv("TERMINAL_LOCAL_PERSISTENT", "false").lower() in {"true", "1", "yes"},- # Container resource config (applies to docker, singularity, modal,- # daytona, and vercel_sandbox -- ignored for local/ssh)+ # setting; local is always opt-in. Per-backend env vars override.+ "ssh_persistent": _tenv_bool(+ "TERMINAL_SSH_PERSISTENT", _tenv("TERMINAL_PERSISTENT_SHELL", "true"),+ ),+ "local_persistent": _tenv_bool("TERMINAL_LOCAL_PERSISTENT", "false"),+ # Container resources (MB); ignored for local/ssh."container_cpu": container_cpu,- "container_memory": container_memory, # MB (default 5GB)- "container_disk": container_disk, # MB (default 50GB)- "container_persistent": _tenv("TERMINAL_CONTAINER_PERSISTENT", "true").lower() in {"true", "1", "yes"},+ "container_memory": container_memory,+ "container_disk": container_disk,+ "container_persistent": _tenv_bool("TERMINAL_CONTAINER_PERSISTENT", "true"),"docker_volumes": docker_volumes,"docker_env": docker_env,- "docker_run_as_host_user": _tenv("TERMINAL_DOCKER_RUN_AS_HOST_USER", "false").lower() in {"true", "1", "yes"},- "docker_network": _tenv("TERMINAL_DOCKER_NETWORK", "true").lower() in {"true", "1", "yes"},+ "docker_run_as_host_user": _tenv_bool("TERMINAL_DOCKER_RUN_AS_HOST_USER", "false"),+ "docker_network": _tenv_bool("TERMINAL_DOCKER_NETWORK", "true"),"docker_extra_args": docker_extra_args,"docker_shm_size": docker_shm_size,- # Cross-process container reuse (issue #20561). The docs claim- # "ONE long-lived container shared across sessions" — this toggle- # makes that real by probing for a labeled container at startup and- # attaching to it instead of always starting a fresh one. Set to- # ``false`` for hard per-process isolation (no reuse, container is- # removed on exit).- "docker_persist_across_processes": _tenv(- "TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSES", "true"- ).lower() in {"true", "1", "yes"},+ # Cross-process reuse: attach to a labeled container at startup+ # instead of starting fresh; false = per-process isolation.+ "docker_persist_across_processes": _tenv_bool("TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSES", "true"),"docker_shared_container_key": _tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip(),- # Startup orphan reaper for hermes-tagged containers left behind by- # crashed / SIGKILL'd previous processes that bypassed atexit.- # Conservative: only sweeps Exited containers older than 2× the- # idle-reap window AND scoped to the current profile. Issue #20561.- "docker_orphan_reaper": _tenv(- "TERMINAL_DOCKER_ORPHAN_REAPER", "true"- ).lower() in {"true", "1", "yes"},+ "docker_orphan_reaper": _tenv_bool("TERMINAL_DOCKER_ORPHAN_REAPER", "true"),}@@ -1931,12 +1521,8 @@ def _get_modal_backend_state(modal_mode: object | None) -> Dict[str, Any]:def _ssh_config_from_config(config: Dict[str, Any]) -> dict:- """Build the ``ssh_config`` dict passed to :func:`_create_environment`.-- Shared by the terminal tool's own get-or-create path and the lazy- :func:`ensure_task_env` bring-up so both derive SSH connection settings- from the resolved config identically.- """+ """``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", ""),@@ -1947,11 +1533,8 @@ def _ssh_config_from_config(config: Dict[str, Any]) -> dict:def _container_config_from_config(config: Dict[str, Any]) -> dict:- """Build the ``container_config`` dict passed to :func:`_create_environment`.-- Shared by the terminal tool's own get-or-create path and the lazy- :func:`ensure_task_env` bring-up (see :func:`_ssh_config_from_config`).- """+ """``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),@@ -1973,281 +1556,288 @@ def _container_config_from_config(config: Dict[str, Any]) -> dict:}-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 for sandboxed command execution.-- Args:- env_type: One of "local", "docker", "singularity", "modal",- "daytona", "vercel_sandbox", "ssh"- image: Docker/Singularity/Modal image name (ignored for local/ssh/vercel)- cwd: Working directory- timeout: Default command timeout- ssh_config: SSH connection config (for env_type="ssh")- container_config: Resource config for container backends (cpu, memory, disk, persistent)- task_id: Task identifier for environment reuse and snapshot keying- host_cwd: Optional host working directory to bind into Docker when explicitly enabled-- Returns:- Environment instance with execute() method- """- cc = container_config or {}- cpu = cc.get("container_cpu", 1)- memory = cc.get("container_memory", 5120)- disk = cc.get("container_disk", 51200)- persistent = cc.get("container_persistent", True)- volumes = cc.get("docker_volumes", [])- docker_forward_env = cc.get("docker_forward_env", [])- docker_env = cc.get("docker_env", {})- docker_extra_args = cc.get("docker_extra_args", [])- docker_network = cc.get("docker_network", 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),+ }- if env_type == "local":- return _LocalEnvironment(cwd=cwd, timeout=timeout)-- elif env_type == "docker":- # One-shot orphan reaper: clean up labeled containers left behind by- # prior Hermes processes that hit SIGKILL / OOM / a closed terminal- # before the atexit cleanup hook could run. Gated to once per- # process so concurrent _create_environment calls (parallel- # subagents, RL benchmarks) don't run the reaper N times.- # Disable via ``terminal.docker_orphan_reaper: false`` (issue #20561).- _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 instead of leaving a- # running container behind for every chat ever opened. 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,- cpu=cpu, memory=memory, disk=disk,- persistent_filesystem=persistent, task_id=task_id,- volumes=volumes,- host_cwd=host_cwd,- auto_mount_cwd=cc.get("docker_mount_cwd_to_workspace", False),- forward_env=docker_forward_env,- env=docker_env,- run_as_host_user=cc.get("docker_run_as_host_user", False),- network=docker_network,- extra_args=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 setattr: test doubles for- # _DockerEnvironment may not accept attributes.- if session_scoped:- try:- docker_env_obj._session_scoped = True- except AttributeError:- pass- return docker_env_obj-- elif env_type == "singularity":- return _SingularityEnvironment(++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,- cpu=cpu, memory=memory, disk=disk,+ modal_sandbox_kwargs=sandbox_kwargs,persistent_filesystem=persistent, task_id=task_id,)-- elif env_type == "modal":- sandbox_kwargs = {}- if cpu > 0:- sandbox_kwargs["cpu"] = cpu- if memory > 0:- sandbox_kwargs["memory"] = memory- if disk > 0:- try:- import inspect, modal- if "ephemeral_disk" in inspect.signature(modal.Sandbox.create).parameters:- sandbox_kwargs["ephemeral_disk"] = 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["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",)- 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."+ + " 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",)- raise ValueError(message)+ )+ 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,- )-- elif env_type == "daytona":- # Lazy import so daytona SDK is only required when backend is selected.- from tools.environments.daytona import DaytonaEnvironment as _DaytonaEnvironment- return _DaytonaEnvironment(- image=image, cwd=cwd, timeout=timeout,- cpu=int(cpu), memory=memory, disk=disk,- persistent_filesystem=persistent, task_id=task_id,- )+ return _ModalEnvironment(+ image=image, cwd=cwd, timeout=timeout,+ modal_sandbox_kwargs=sandbox_kwargs,+ persistent_filesystem=persistent, task_id=task_id,+ )- elif env_type == "vercel_sandbox":- from tools.environments.vercel_sandbox import (- VercelSandboxEnvironment as _VercelSandboxEnvironment,- )- return _VercelSandboxEnvironment(- runtime=cc.get("vercel_runtime") or None,- cwd=cwd,- timeout=timeout,- cpu=cpu,- memory=memory,- disk=disk,- persistent_filesystem=persistent,- task_id=task_id,- )- elif env_type == "ssh":- 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_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)- else:- 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}"- )+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 _cleanup_inactive_envs(lifetime_seconds: int = 300):- """Clean up environments that have been inactive for longer than lifetime_seconds."""- current_time = time.time()+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,+ )+- # Check the process registry -- skip cleanup for sandboxes with active- # background processes (their _last_activity gets refreshed to keep them alive).+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_objtry:- 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 # Keep sandbox alive- except ImportError:- pass+ from agent.terminal_env_registry import plugin_backend_names- # Phase 1: collect stale entries and remove them from tracking dicts while- # holding the lock. Do NOT call env.cleanup() inside the lock -- Modal and- # Docker teardown can block for 10-15s, which would stall every concurrent- # terminal/file tool call waiting on _env_lock.- envs_to_stop = [] # list of (task_id, env) pairs+ 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}"+ )- 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))- # Also purge per-task creation locks for cleaned-up tasks- with _creation_locks_lock:- for task_id, _ in envs_to_stop:- _creation_locks.pop(task_id, None)+# 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,+}- # Phase 2: stop the actual sandboxes OUTSIDE the lock so other tool calls- # are not blocked while Modal/Docker sandboxes shut down.- for task_id, env in envs_to_stop:- # Invalidate stale file_ops cache entry (Bug fix: prevents- # ShellFileOperations from referencing a dead sandbox)- try:- from tools.file_tools import clear_file_ops_cache- clear_file_ops_cache(task_id)- except ImportError:- pass- try:- if hasattr(env, 'cleanup'):- env.cleanup()- elif hasattr(env, 'stop'):- env.stop()- elif hasattr(env, 'terminate'):- env.terminate()+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,+ )- logger.info("Cleaned up inactive environment for task: %s", 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)+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:- logger.warning("Error cleaning up environment for task %s: %s", task_id, e)+ 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():@@ -2297,17 +1887,10 @@ def get_active_env(task_id: str):def ensure_task_env(task_id: Optional[str] = None):"""Lazily create and cache the sandbox env for *task_id* if none is active.- :func:`terminal_tool` creates the environment on the first terminal command,- but nothing else did — so under a non-local backend (ssh, docker, …) a- session whose first action is ``vision_analyze`` on a container-only path hit- "no active sandbox session" because the SSH/Docker handshake never ran- (issue #62825). vision reads such paths inside the sandbox (see- ``tools.image_source``), so it calls this to bring the env up on demand,- reusing the same creation machinery as the terminal tool.-- No-op on the local backend (images are read host-side). Returns the env- instance, or ``None`` when local or when creation fails (best-effort: a- failure leaves the caller's fail-closed error path intact).+ 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"]@@ -2316,7 +1899,6 @@ def ensure_task_env(task_id: Optional[str] = None):effective_task_id = _resolve_container_task_id(task_id)- # Fast path: already active — mirror terminal_tool and refresh activity.existing = get_active_env(effective_task_id)if existing is not None:with _env_lock:@@ -2324,21 +1906,10 @@ def ensure_task_env(task_id: Optional[str] = None):return existingoverrides = resolve_task_overrides(task_id)- if env_type == "docker":- image = overrides.get("docker_image") or config["docker_image"]- elif env_type == "singularity":- image = overrides.get("singularity_image") or config["singularity_image"]- elif env_type == "modal":- image = overrides.get("modal_image") or config["modal_image"]- elif env_type == "daytona":- image = overrides.get("daytona_image") or config["daytona_image"]- else:- image = ""+ image = _select_image(env_type, overrides, config)_start_cleanup_thread()- # Per-task creation lock so a concurrent terminal_tool call and this helper- # don't each spawn a sandbox for the same task.with _creation_locks_lock:task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock())@@ -2379,20 +1950,13 @@ def ensure_task_env(task_id: Optional[str] = None):def is_persistent_env(task_id: str) -> bool:- """Return True if the active environment for task_id is configured for- cross-turn persistence (``persistent_filesystem=True``).-- Used by the agent loop to skip per-turn teardown for backends whose whole- point is to survive between turns (docker with ``container_persistent``,- daytona, modal, etc.). Non-persistent backends (e.g. Morph) still get torn- down at end-of-turn to prevent leakage. The idle reaper- (``_cleanup_inactive_envs``) handles persistent envs once they exceed- ``terminal.lifetime_seconds``.-- Session-scoped docker containers (per-session isolation mode) also count- as persistent HERE: their lifetime is the SESSION, not the turn — they- are removed by ``AIAgent.close()`` → ``cleanup_vm`` at session teardown- and by the idle reaper, not per-turn.+ """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:@@ -2434,86 +1998,46 @@ def cleanup_all_environments():def cleanup_vm(task_id: str, *, force_remove: bool = False):"""Manually clean up a specific environment by task_id.- *force_remove* (default False) is forwarded to backends that accept it- — currently only ``DockerEnvironment``. The default of False matches- session-lifecycle semantics: this function is called from- ``AIAgent.close()`` (TUI session close, gateway session teardown) and the- per-turn cleanup branch for non-persistent envs, both of which should- honor the user's persist-mode preference. Stopping the container here- would defeat the "ONE long-lived container shared across sessions"- contract — exactly the bug Ben reported when the container was killed- on every TUI session close.-- Pass ``force_remove=True`` for actual user-initiated teardown- (e.g. ``/reset``-style flows that haven't been wired yet, or future- "destroy my sandbox" commands).-- The idle reaper passes the env through ``env.cleanup()`` directly (not- via this function), so persist-mode idle envs are similarly no-op'd —- only the orphan reaper at next startup reclaims them.+ *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."""- # Remove from tracking dicts while holding the lock, but defer the- # actual (potentially slow) env.cleanup() call to outside the lock- # so other tool calls aren't blocked.- env = None+ # 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)- # Clean up per-task creation lockwith _creation_locks_lock:_creation_locks.pop(task_id, None)- # Invalidate stale file_ops cache entry- try:- from tools.file_tools import clear_file_ops_cache- clear_file_ops_cache(task_id)- except ImportError:- pass+ _clear_file_ops_cache(task_id)if env is None:return-- try:- if hasattr(env, 'cleanup'):- # Pass force_remove only if the env's cleanup() accepts it- # (DockerEnvironment after issue #20561; other backends don't).- import inspect- sig = inspect.signature(env.cleanup)- if "force_remove" in sig.parameters:- env.cleanup(force_remove=force_remove)- else:- env.cleanup()- elif hasattr(env, 'stop'):- env.stop()- elif hasattr(env, 'terminate'):- env.terminate()-- logger.info("Manually cleaned up environment for task: %s", 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)+ _teardown_env(+ env, task_id, force_remove=force_remove,+ done_msg="Manually cleaned up environment for task: %s",+ )def _atexit_cleanup():- """Stop cleanup thread and shut down all remaining sandboxes on exit."""+ """Stop the cleanup thread and shut down all remaining sandboxes on exit."""_stop_cleanup_thread()if _active_environments:count = len(_active_environments)logger.info("Shutting down %d remaining sandbox(es)...", count)- # Snapshot the env objects BEFORE cleanup_all_environments empties- # the dict; we need them to wait on docker cleanup threads after the- # registry has been cleared.+ # Snapshot BEFORE cleanup_all_environments empties the dict, then+ # block briefly so docker stop/rm completes before the interpreter+ # exits — otherwise daemon cleanup threads die mid-`docker stop` and+ # Exited containers pile up on the host.envs_to_wait = list(_active_environments.values())cleanup_all_environments()- # Block briefly so docker stop/rm actually completes before the- # interpreter exits. Issue #20561 — without this join, the daemon- # cleanup threads were getting torn down mid-`docker stop`, leaving- # Exited containers piled up on the host.for env in envs_to_wait:wait_fn = getattr(env, "wait_for_cleanup", None)if wait_fn is None:@@ -2526,156 +2050,12 @@ def _atexit_cleanup():atexit.register(_atexit_cleanup)-# =============================================================================-# Exit Code Context for Common CLI Tools-# =============================================================================-# Many Unix commands use non-zero exit codes for informational purposes, not-# to indicate failure. The model sees a raw exit_code=1 from `grep` and-# wastes a turn investigating something that just means "no matches".-# This lookup adds a human-readable note so the agent can move on.--# Signal-death notes for the lethal signals seen in practice. Keyed by-# signum; used for both the ``-signum`` (subprocess) and ``128+signum``-# (shell) encodings. Curated rather than exhaustive so we never mislabel a-# legitimate application exit code (e.g. 130/SIGINT is handled by the-# executor's interrupt-marker path and excluded here).-_SIGNAL_EXIT_NOTES: dict[int, str] = {- 3: "SIGQUIT (quit from keyboard)",- 4: "SIGILL (illegal instruction — corrupt binary or wrong architecture)",- 6: "SIGABRT (abort — assertion failure, fatal runtime error, or glibc abort)",- 7: "SIGBUS (bus error — misaligned or unmapped memory access)",- 8: "SIGFPE (fatal arithmetic error, e.g. integer division by zero)",- 9: "SIGKILL — often the kernel OOM killer on memory exhaustion, "- "or an explicit kill -9",- 11: "SIGSEGV (segmentation fault — the program crashed)",- 13: "SIGPIPE (wrote to a closed pipe — e.g. output piped to a reader that exited)",- 15: "SIGTERM (terminated — kill/timeout or shutdown requested it to stop)",- 24: "SIGXCPU (CPU time limit exceeded)",- 25: "SIGXFSZ (file size limit exceeded)",-}---def _interpret_signal_exit(exit_code: int) -> str | None:- """Map signal-termination exit codes to a human-readable note.-- Returns None when ``exit_code`` does not look like a signal death.- Negative codes are Python ``subprocess`` semantics (definite); codes in- the 128+signum band are the shell convention (very likely but not- guaranteed, so those notes hedge with "usually").- """- if exit_code < 0:- signum = -exit_code- if signum == 2: # SIGINT — executor's interrupt-marker path owns it- return None- note = _SIGNAL_EXIT_NOTES.get(signum)- if note:- return f"Command terminated by signal {signum}: {note}"- try:- import signal as _signal- name = _signal.Signals(signum).name- except (ValueError, ImportError):- name = f"signal {signum}"- return f"Command terminated by {name} (signal {signum})"-- if exit_code > 128:- signum = exit_code - 128- note = _SIGNAL_EXIT_NOTES.get(signum)- if note:- return (- f"Exit code {exit_code} usually means the command was "- f"terminated by signal {signum}: {note}"- )-- return None---def _interpret_exit_code(command: str, exit_code: int) -> str | None:- """Return a human-readable note when a non-zero exit code is non-erroneous.-- Returns None when the exit code is 0 or genuinely signals an error.- The note is appended to the tool result so the model doesn't waste- turns investigating expected exit codes.- """- if exit_code == 0:- return None-- # Signal terminations (ported from Kilo-Org/kilocode#12698, adapted to- # Python semantics). Two shapes reach the model:- # * negative codes — subprocess.Popen reports a signal-killed process- # as ``-signum`` (definite signal death), and- # * 128+signum — the conventional shell encoding when bash reports a- # signal-killed child (heuristic: a program *can* ``exit 139``, so- # these notes say "usually").- # Without a note the model sees a bare ``exit_code=-9`` or ``137`` and- # burns turns re-running or mis-diagnosing (137 = OOM kill is the big- # one). 130/SIGINT is deliberately absent: the executor has bespoke- # interrupt-marker handling for rc=130.- signal_note = _interpret_signal_exit(exit_code)- if signal_note is not None:- return signal_note-- # Extract the last command in a pipeline/chain — that determines the- # exit code. Handles `cmd1 && cmd2`, `cmd1 | cmd2`, `cmd1; cmd2`.- # Deliberately simple: split on shell operators and take the last piece.- segments = re.split(r'\s*(?:\|\||&&|[|;])\s*', command)- last_segment = (segments[-1] if segments else command).strip()-- # Get base command name (first word), stripping env var assignments- # like VAR=val cmd ...- words = last_segment.split()- base_cmd = ""- for w in words:- if "=" in w and not w.startswith("-"):- continue # skip VAR=val- base_cmd = w.split("/")[-1] # handle /usr/bin/grep -> grep- break-- if not base_cmd:- return None-- # Command-specific semantics- semantics: dict[str, dict[int, str]] = {- # grep/rg/ag/ack: 1=no matches found (normal), 2+=real error- "grep": {1: "No matches found (not an error)"},- "egrep": {1: "No matches found (not an error)"},- "fgrep": {1: "No matches found (not an error)"},- "rg": {1: "No matches found (not an error)"},- "ag": {1: "No matches found (not an error)"},- "ack": {1: "No matches found (not an error)"},- # diff: 1=files differ (expected), 2+=real error- "diff": {1: "Files differ (expected, not an error)"},- "colordiff": {1: "Files differ (expected, not an error)"},- # find: 1=some dirs inaccessible but results may still be valid- "find": {1: "Some directories were inaccessible (partial results may still be valid)"},- # test/[: 1=condition is false (expected)- "test": {1: "Condition evaluated to false (expected, not an error)"},- "[": {1: "Condition evaluated to false (expected, not an error)"},- # curl: common non-error codes- "curl": {- 6: "Could not resolve host",- 7: "Failed to connect to host",- 22: "HTTP response code indicated error (e.g. 404, 500)",- 28: "Operation timed out",- },- # git: 1 is context-dependent but often normal (e.g. git diff with changes)- "git": {1: "Non-zero exit (often normal — e.g. 'git diff' returns 1 when files differ)"},- }-- cmd_semantics = semantics.get(base_cmd)- if cmd_semantics and exit_code in cmd_semantics:- return cmd_semantics[exit_code]-- return Nonedef _command_requires_pipe_stdin(command: str) -> bool:- """Return True when PTY mode would break stdin-driven commands.-- Some CLIs change behavior when stdin is a TTY. In particular,- `gh auth login --with-token` expects the token to arrive via piped stdin and- waits for EOF; when we launch it under a PTY, `process.submit()` only sends a- newline, so the command appears to hang forever with no visible progress.- """+ """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+ `process.submit()` only sends a newline, so it hangs forever."""normalized = " ".join(command.lower().split())return (normalized.startswith("gh auth login")@@ -2683,118 +2063,38 @@ def _command_requires_pipe_stdin(command: str) -> bool:)-_SHELL_LEVEL_BACKGROUND_RE = re.compile(- r"(?:^|[;&|]\s*|&&\s*|\|\|\s*|\$\(\s*)(?:nohup|disown|setsid)\b", re.IGNORECASE | re.MULTILINE+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,)-_INLINE_BACKGROUND_AMP_RE = re.compile(r"\s&\s")-_TRAILING_BACKGROUND_AMP_RE = re.compile(r"\s&\s*(?:#.*)?$")---def _strip_quotes(command: str) -> str:- """Remove single- and double-quoted content so regex checks don't match inside strings.-- This prevents false positives when keywords like 'nohup' or 'setsid' appear- in commit messages, Python -c code, echo arguments, or PR body text.- Also strips backtick-quoted content and provably-inert heredoc body text.- """- # Mask inert heredoc bodies FIRST (before quote-stripping — a heredoc- # delimiter may be quoted, e.g. <<'EOF', and the body commonly contains- # characters like '&' that are literal payload, not shell operators).- # strip_inert_heredoc_bodies is deliberately conservative: it masks a body- # only when the delimiter is quoted (no expansion), terminated, on a- # simple opener, and fed to a known non-shell consumer — anything- # ambiguous stays visible so a real background operator can't hide behind- # a fake or executable heredoc.- result = strip_inert_heredoc_bodies(command)- # Remove single-quoted strings (no escaping inside single quotes in shell)- result = re.sub(r"'[^']*'", "''", result)- # Remove double-quoted strings (handle escaped quotes)- result = re.sub(r'"(?:[^"\\]|\\.)*"', '""', result)- # Remove backtick-quoted strings- result = re.sub(r"`[^`]*`", "``", result)- return result---_LONG_LIVED_FOREGROUND_PATTERNS = (- re.compile(r"\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|watch)\b", re.IGNORECASE),- re.compile(r"\bdocker\s+compose\s+up\b", re.IGNORECASE),- re.compile(r"\bnext\s+dev\b", re.IGNORECASE),- re.compile(r"\bvite(?:\s|$)", re.IGNORECASE),- re.compile(r"\bnodemon\b", re.IGNORECASE),- re.compile(r"\buvicorn\b", re.IGNORECASE),- re.compile(r"\bgunicorn\b", re.IGNORECASE),- re.compile(r"\bpython(?:3)?\s+-m\s+http\.server\b", re.IGNORECASE),+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,+ finalize_foreground_result,)-def _looks_like_help_or_version_command(command: str) -> bool:- """Return True for informational invocations that should never be blocked."""- normalized = " ".join(command.lower().split())- return (- " --help" in normalized- or normalized.endswith(" -h")- or " --version" in normalized- or normalized.endswith(" -v")- )---def _foreground_background_guidance(command: str) -> str | None:- """Suggest background mode when a foreground command looks long-lived.-- Prevents workflows that start a server/watch process and then stall before- follow-up checks or test commands run.- """- if _looks_like_help_or_version_command(command):- return None-- # Strip quoted content so keywords inside strings/arguments don't trigger- # false positives (e.g., git commit -m "... setsid ...", python3 -c "os.setsid").- unquoted = _strip_quotes(command)-- if _SHELL_LEVEL_BACKGROUND_RE.search(unquoted):- return (- "Foreground command uses shell-level background wrappers (nohup/disown/setsid). "- "Re-send WITHOUT the wrapper as terminal(command=\"<cmd>\", background=true, "- "notify_on_complete=true) so Hermes tracks the process, then run readiness "- "checks and tests in separate commands."- )-- if _INLINE_BACKGROUND_AMP_RE.search(unquoted) or _TRAILING_BACKGROUND_AMP_RE.search(unquoted):- return (- "Foreground command uses '&' backgrounding. Re-send WITHOUT the '&' as "- "terminal(command=\"<cmd>\", background=true) — add notify_on_complete=true "- "for bounded jobs — then run health checks and tests in follow-up terminal calls."- )-- for pattern in _LONG_LIVED_FOREGROUND_PATTERNS:- if pattern.search(unquoted):- return (- "This foreground command appears to start a long-lived server/watch process. "- "Run it with background=true, verify readiness (health endpoint/log signal), "- "then execute tests in a separate command."- )-- return None--def _resolve_notification_flag_conflict(*,notify_on_complete: bool,watch_patterns,background: bool,) -> tuple:- """Decide what to do when both notify_on_complete and watch_patterns are set.-- These flags produce duplicate, delayed notifications when combined — one- notification per watch-pattern match AND one on process exit, with async- delivery that can spam the user long after the process ends. When both are- set, we drop watch_patterns in favor of notify_on_complete (the more useful- "let me know when it's done" signal) and return a human-readable note.-- Returns:- (watch_patterns_to_use, conflict_note). conflict_note is "" when there- is no conflict.- """+ """Resolve notify_on_complete + watch_patterns both set: drop watch_patterns+ (combined they produce duplicate async notifications — one per match plus+ one on exit — that can spam the user long after the process ends).+ Returns ``(watch_patterns_to_use, conflict_note)``; note is "" without conflict."""if background and notify_on_complete and watch_patterns:note = ("watch_patterns ignored because notify_on_complete=True; "@@ -2811,21 +2111,14 @@ def _resolve_command_cwd(session_key: Optional[str] = None,env_type: Optional[str] = None,) -> str:- """Return the cwd for a command. Explicit ``workdir=`` overrides everything.-- Otherwise the session's own cwd RECORD (``get_session_cwd``) wins — it is- written after every completed command for this session, so it IS the- session's ``cd`` state, with no shared-env ambiguity: another session's- ``cd`` lands in another record and can't affect us. A session with no- record yet (first command) runs in ``default_cwd`` (config/override cwd),- which is also what seeds a fresh environment.-- ``env_type`` makes the record container-aware: on container backends a- recorded HOST path (a desktop/TUI surface registering its host workspace- via ``register_task_env_overrides`` → ``record_session_cwd``) is unusable- inside the sandbox — the shell prefixes every command with ``cd <host- path>`` and fails with exit 126. Same guard class as the env-creation- sanitizers (#50636, #54447); this is the per-command sibling site.+ """cwd for a command: explicit ``workdir`` > the session's own cwd record >+ ``default_cwd``.++ The record is written after every completed command of THIS session, so+ it is the session's ``cd`` state with no shared-env ambiguity. On+ container backends a recorded HOST path (a desktop/TUI surface registering+ its workspace) is unusable in the sandbox — ``cd <host path>`` fails with+ exit 126 — so it is discarded in favor of ``default_cwd``."""if workdir:return workdir@@ -2844,6 +2137,86 @@ def _resolve_command_cwd(return recorded or default_cwd+@dataclass+class _ApprovalVerdict:+ """Outcome of the pre-exec guard pass.++ ``blocked_json`` is the finished tool result when the command may not run+ (denied, or pending gateway approval). ``approved_run`` is True when the+ user explicitly approved (or pre-confirmed via ``force``); it drives the+ clean-interrupt-slate clear before ``env.execute`` so an approved command+ can't be SIGINT-killed by a bit that landed during the approval-wait.+ """+ blocked_json: Optional[str] = None+ note: Optional[str] = None+ approved_run: bool = False+++def _run_approval_guards(command: str, env_type: str, config: Dict[str, Any], *, force: bool) -> _ApprovalVerdict:+ """Run tirith + dangerous-command guards; ``force`` skips them entirely."""+ if force:+ return _ApprovalVerdict(approved_run=True)+ approval = _check_all_guards(+ command, env_type,+ has_host_access=_docker_has_host_access(config),+ )+ 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))+ 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))+ 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.",+ )+ return _ApprovalVerdict()+++def _fatal_error_json(e: BaseException) -> str:+ """Log the traceback and return the redacted error+traceback envelope.++ Exception text can embed the failing command line (and any secrets inline+ in it), so both fields are force-redacted before reaching the model.+ """+ import traceback+ tb_str = traceback.format_exc()+ logger.error("terminal_tool exception:\n%s", tb_str)+ return json.dumps({+ "output": "",+ "exit_code": -1,+ "error": _redact_terminal_error_text(f"Failed to execute command: {e}"),+ "traceback": _redact_terminal_error_text(tb_str),+ "status": "error"+ }, ensure_ascii=False)++def terminal_tool(command: str,background: bool = False,@@ -2857,36 +2230,18 @@ def terminal_tool(watch_patterns: Optional[List[str]] = None,_host_local: bool = False,) -> str:- """- Execute a command in the configured terminal environment.-- Args:- command: The command to execute- background: Whether to run in background (default: False)- timeout: Command timeout in seconds (default: from config)- task_id: Unique identifier for environment isolation (optional)- session_id: Conversation/session identifier for durable observability- force: If True, skip dangerous command check (use after user confirms)- workdir: Working directory for this command (optional, uses session cwd if not set)- pty: If True, use pseudo-terminal for interactive CLI tools (local backend only)- notify_on_complete: If True and background=True, you'll be notified exactly once when the process exits. The right choice for almost every long task. MUTUALLY EXCLUSIVE with watch_patterns.- watch_patterns: List of strings to watch for in background output. HARD rate limit: 1 notification per 15s per process. After 3 strike windows in a row — or after a small lifetime cap of delivered matches, however cleanly spaced — watch_patterns is disabled and the session is auto-promoted to notify_on_complete. Use ONLY for rare, one-shot mid-process signals on long-lived processes (server readiness, migration-done markers). NEVER use in loops/batch jobs — error patterns there will hit the strike limit and get disabled. MUTUALLY EXCLUSIVE with notify_on_complete — set one, not both.-- Returns:- str: JSON string with output, exit_code, and error fields-- Examples:- # Execute a simple command- >>> result = terminal_tool(command="ls -la /tmp")-- # Run a background task- >>> result = terminal_tool(command="python server.py", background=True)-- # With custom timeout- >>> result = terminal_tool(command="long_task.sh", timeout=300)-- # Force run after user confirmation- # Note: force parameter is internal only, not exposed to model API+ """Execute *command* in the configured terminal environment; returns a JSON string.++ ``force`` (internal, not in the model schema) skips the dangerous-command+ check after the user confirmed. ``workdir`` is per-command and never+ recorded as the session cwd. ``pty`` applies to the local backend only.+ ``notify_on_complete`` and ``watch_patterns`` are mutually exclusive+ background-only flags: on conflict watch_patterns is dropped. watch_patterns+ is hard rate-limited (1 notification / 15s / process) and auto-disabled+ after repeated strikes or a lifetime cap, promoting to notify_on_complete —+ use it only for rare one-shot signals on long-lived processes.+ ``_host_local`` forces the local backend for Hermes-owned control-plane+ children (kept in a separate env cache from the configured backend)."""try:if not isinstance(command, str):@@ -2901,68 +2256,36 @@ def terminal_tool("status": "error",}, ensure_ascii=False)- # Get configurationconfig = _get_env_config()env_type = "local" if _host_local else config["env_type"]- # Fail closed under a refusal scope (#68559): the routed profile's- # terminal policy could not be resolved, so executing with the launch- # process's ambient policy is forbidden — refuse with a typed,- # model-actionable error instead.+ # 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_refusalenforce_no_refusal()- # Use task_id for environment isolation. By default all subagent- # task_ids collapse back to "default" so the top-level agent and- # every delegate_task child share one container; only task_ids with- # a registered env override (RL benchmarks) get isolated sandboxes.effective_task_id = _resolve_container_task_id(task_id)if _host_local:- # Hermes-owned control-plane children must run beside the current- # interpreter, never inside the model's configured Docker/SSH/etc.- # Keep their environment cache separate from the configured backend.+ # 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}"- # Check per-task overrides (set by environments like TerminalBench2Env)- # before falling back to global env var config. ``resolve_task_overrides``- # reads the raw task id first then the collapsed container id, so a- # CWD-only override (which collapses ``effective_task_id`` to- # ``"default"``) is still found under its originating session id while- # isolation-keyed RL/benchmark overrides keep resolving as before.+ # 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)-- # Select image based on env type, with per-task override support- if env_type == "docker":- image = overrides.get("docker_image") or config["docker_image"]- elif env_type == "singularity":- image = overrides.get("singularity_image") or config["singularity_image"]- elif env_type == "modal":- image = overrides.get("modal_image") or config["modal_image"]- elif env_type == "daytona":- image = overrides.get("daytona_image") or config["daytona_image"]- else:- image = ""+ image = _select_image(env_type, overrides, config)cwd = overrides.get("cwd") or get_session_cwd(task_id) or config["cwd"]- # Session-scoped mount resolution (single owner: _resolve_task_host_cwd).- # Under per-session isolation a fresh session must not inherit the- # process-global TERMINAL_CWD mount left behind by a previous session.host_cwd = _resolve_task_host_cwd(config, task_id)- # A per-task cwd override (registered by the gateway/TUI for workspace- # tracking, or by RL/benchmark envs) wins over config["cwd"] — but- # config["cwd"] was already sanitized for container backends in- # _get_env_config() while the override is raw. On a container backend a- # raw host path (e.g. a Windows desktop session's C:\Users\<user>, or a- # POSIX /home/<user>) reaches `docker run -w <host-path>` and the- # container fails to start (exit 125). Re-apply the same host/relative- # path guard to the *resolved* cwd so the override can't bypass it.- # When the host path IS this session's mounted workspace, remap it to- # /workspace (where the mount lands) instead of discarding it.- # Valid in-container override paths (RL/benchmark sandboxes that set- # cwd to /workspace, /root, etc.) are absolute non-host paths and pass- # through untouched.+ # 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:@@ -2972,21 +2295,15 @@ def terminal_tool(cwd, env_type, remapped,)cwd = remapped- default_timeout = config["timeout"]-- # Validate an explicit timeout before it flows into deadline math.- # ``timeout or default`` silently turns 0 into the default (0 can't mean- # "no timeout" here), and a negative value is truthy so it would sail- # through to ``deadline = now + timeout`` and fire an immediate,- # nonsensical "-Ns" timeout. Reject non-positive values outright.+ # 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 default_timeout+ effective_timeout = timeout or config["timeout"]- # Reject foreground commands where the model explicitly requests- # a timeout above FOREGROUND_MAX_TIMEOUT — nudge it toward background.if not background and timeout and timeout > FOREGROUND_MAX_TIMEOUT:return tool_error(f"Foreground timeout {timeout}s exceeds the maximum of "@@ -2994,8 +2311,6 @@ def terminal_tool(f"notify_on_complete=true for long-running commands.")- # Guardrail: long-lived server/watch commands should run as managed- # background sessions, not foreground shell hacks.if not background:guidance = _foreground_background_guidance(command)if guidance:@@ -3006,75 +2321,41 @@ def terminal_tool("status": "error",}, ensure_ascii=False)- # Start cleanup thread_start_cleanup_thread()- # Get or create environment.- # Use a per-task creation lock so concurrent tool calls for the same- # task_id wait for the first one to finish creating the sandbox,- # instead of each creating their own (wasting Modal resources).- env: Any = None+ # 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:- # Prefer the collapsed container id, but fall back to an env cached- # under the raw task_id. Per-session surfaces (ACP/gateway/dashboard)- # with a CWD-only override collapse to "default" for container- # sharing, yet an env may already be cached under the originating- # task_id; honor it instead of spawning a duplicate.- _existing_key = (- effective_task_id if effective_task_id in _active_environments- else (task_id if task_id and task_id in _active_environments else None)- )- if _existing_key is not None:- _last_activity[_existing_key] = time.time()- env = _active_environments[_existing_key]- needs_creation = False- else:- needs_creation = True+ env: Any = _lookup_active_env(effective_task_id, task_id)- if needs_creation:- # Per-task lock: only one thread creates the sandbox, others wait+ if env is None:with _creation_locks_lock:- if effective_task_id not in _creation_locks:- _creation_locks[effective_task_id] = threading.Lock()- task_lock = _creation_locks[effective_task_id]+ task_lock = _creation_locks.setdefault(effective_task_id, threading.Lock())with task_lock:- # Double-check after acquiring the per-task lockwith _env_lock:- _existing_key = (- effective_task_id if effective_task_id in _active_environments- else (task_id if task_id and task_id in _active_environments else None)- )- if _existing_key is not None:- _last_activity[_existing_key] = time.time()- env = _active_environments[_existing_key]- needs_creation = False+ env = _lookup_active_env(effective_task_id, task_id)- if needs_creation:+ 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:- 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- if env_type == "local":- local_config = {- "persistent": config.get("local_persistent", False),- }-new_env = _create_environment(env_type=env_type,image=image,cwd=cwd,timeout=effective_timeout,- ssh_config=ssh_config,- container_config=container_config,- local_config=local_config,+ 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,)@@ -3096,133 +2377,20 @@ def terminal_tool(assert env is not None # all creation failure paths return above- # The session key that drives cwd records: get_current_session_key()'s- # contextvar doesn't cross tool-worker threads, so fall back to the raw- # task_id (which IS the session_key for the top-level agent) — a- # stable, thread-safe anchor.+ # 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+ # session_key) as a stable anchor.from tools.approval import get_current_session_keysession_key = get_current_session_key(default="") or (task_id or "")- # Hard-block: gateway lifecycle commands (systemctl/launchctl/hermes- # restart|stop|uninstall targeting hermes-gateway) must never run inside the- # gateway process itself. The restart would SIGTERM the gateway, which- # kills this very subprocess before it can complete — the service may- # never restart. This mirrors the `hermes gateway restart` guard in- # hermes_cli/gateway.py and the cron-path guard in hermes_cli/cron.py,- # but applies unconditionally (force=True cannot help here).- # Gate on the SUPERVISED-gateway probe, not the raw _HERMES_GATEWAY- # marker: gateway.run sets it at import time, so it leaks into every- # process that merely imports gateway.run (hermes serve --isolated,- # CLI, web server) which are NOT the gateway and must be able to- # restart it. A plain foreground `hermes gateway run` (env set, PID- # owned, no supervisor) now also PASSES this guard: intentional and- # harmless, since without a supervisor there is no KeepAlive to turn a- # self-restart into a respawn loop.- from tools.process_registry import _is_supervised_gateway_process-- if _is_supervised_gateway_process():- from cron.lifecycle_guard import (- _MAX_REFERENCED_SCRIPT_BYTES,- contains_gateway_lifecycle_command_or_referenced_script,- contains_launchctl_submit_command,- )- if contains_launchctl_submit_command(command):- return json.dumps({- "output": "",- "exit_code": 1,- "error": (- "Blocked: launchctl submit/bootstrap registers a persistent "- "KeepAlive job and is unsafe from inside the gateway process. "- "Use Hermes cron for one-shot delayed work, or install an "- "explicit LaunchAgent from a separate shell."- ),- "status": "error",- }, ensure_ascii=False)- guard_cwd_base = get_session_cwd(session_key)- if guard_cwd_base is None:- guard_cwd_base = getattr(env, "cwd", None) or cwd- guard_cwd = _resolve_command_cwd(- workdir=workdir,- default_cwd=guard_cwd_base,- session_key=session_key,- env_type=env_type,- )-- def _read_script_in_env(script_path: str) -> Optional[str]:- """Best-effort script read; uses env.execute only when local read fails.-- For local backends the script path is on the host filesystem. For- SSH/Modal/Daytona the same path is remote; the local read misses, so we- fall back to a bounded ``env.execute('head -c ... < path')`` read.- """- if env is None:- return None- try:- local_path = Path(script_path).expanduser()- if not local_path.is_absolute():- local_path = Path(guard_cwd) / local_path- if local_path.is_file():- metadata = local_path.stat()- if stat.S_ISREG(metadata.st_mode) and metadata.st_size <= _MAX_REFERENCED_SCRIPT_BYTES:- data = local_path.read_bytes()- if len(data) <= _MAX_REFERENCED_SCRIPT_BYTES:- if b"\x00" in data:- # Binary (ELF/Mach-O/PE), not a shell script:- # feeding its decoded bytes back into the guard- # tokenizes machine code into bogus NUL-bearing- # paths and crashes the scanner (#77703). Mirror- # lifecycle_guard._read_referenced_script and- # treat it as nothing to scan.- return None- return data.decode("utf-8", errors="replace")- except Exception:- pass- # Remote / sandboxed backend: read via the environment's shell.- # Bound the read at the source with `head -c` so an oversized- # file (e.g. a 166MB ELF invoked by absolute path) never- # crosses the wire — `cat` of such a binary previously pinned- # the gateway's tool thread on a superlinear shlex scan for- # 30+ minutes. One byte over the guard's budget is enough for- # lifecycle_guard's sanitizer to fail the oversized case- # closed, mirroring the local-read semantics. The `< path`- # redirect keeps leading-dash paths out of argv (same form as- # tools/image_source.py).- try:- result = env.execute(- f"head -c {_MAX_REFERENCED_SCRIPT_BYTES + 1} "- f"< {shlex.quote(script_path)}"- )- if result.get("returncode", -1) == 0:- output = result.get("output", "")- if output and "\x00" in output:- # Binary content from a remote read: skip for the- # same reason as the local branch above (#77703).- return None- return output- except Exception:- pass- return None-- if contains_gateway_lifecycle_command_or_referenced_script(- command,- cwd=guard_cwd,- read_remote_script=_read_script_in_env,- ):- return json.dumps({- "output": "",- "exit_code": 1,- "error": (- "Blocked: command or referenced script cannot restart, stop, or "- "uninstall the gateway from inside the gateway process. The gateway would "- "kill this command before it could complete (SIGTERM propagates "- "to child processes). Run `hermes gateway restart` from a "- "separate shell outside the running gateway."- ),- "status": "error",- }, ensure_ascii=False)+ blocked = gateway_lifecycle_block(+ command=command, env=env, env_type=env_type, cwd=cwd,+ workdir=workdir, session_key=session_key,+ )+ if blocked:+ return blocked- # Validate before the source guard resolves an explicit workdir.if workdir:workdir_error = _validate_workdir(workdir)if workdir_error:@@ -3235,88 +2403,20 @@ def terminal_tool("status": "blocked"}, ensure_ascii=False)- # Windows-only: NTFS locks loaded module files, so rewriting the local- # checkout backing this interpreter can corrupt the running process.- # POSIX keeps old inodes alive for open handles, so the guard is off- # there. Remote backends cannot reach that checkout.if env_type == "local":- from tools.self_repo_guard import (- detect_self_repo_git_mutation,- guard_active,+ blocked = self_repo_block(+ command=command, cwd=cwd, workdir=workdir, session_key=session_key,)+ if blocked:+ return blocked- guard_cwd = _resolve_command_cwd(- workdir=workdir,- default_cwd=cwd,- session_key=session_key,- )- _self_repo_hit, _self_repo_msg = (- detect_self_repo_git_mutation(command, guard_cwd)- if guard_active()- else (False, None)- )- if _self_repo_hit:- logger.warning(- "Blocked self-repo git mutation (command: %s)",- _safe_command_preview(command),- )- return json.dumps({- "output": "",- "exit_code": 1,- "error": _self_repo_msg,- "status": "blocked",- }, ensure_ascii=False)+ # 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)+ if verdict.blocked_json:+ return verdict.blocked_json+ approval_note = verdict.note- # Pre-exec security checks (tirith + dangerous command detection)- # Skip check if force=True (user has confirmed they want to run it)- approval_note = None- # True when the user explicitly approved this run (or pre-confirmed via- # force). Drives the clean-interrupt-slate clear before env.execute so- # an approved command can't be SIGINT-killed by a bit that landed during- # the approval-wait (see clear_current_thread_interrupt).- _approved_run = bool(force)- if not force:- approval = _check_all_guards(- command, env_type,- has_host_access=_docker_has_host_access(config),- )- if not approval["approved"]:- # Check if this is an approval_required (gateway ask mode)- if approval.get("status") == "pending_approval":- return 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)- # Command was blocked- desc = approval.get("description", "command flagged")- fallback_msg = (- f"Command denied: {desc}. "- "Use the approval prompt to allow it, or rephrase the command."- )- return json.dumps({- "output": "",- "exit_code": -1,- "error": approval.get("message", fallback_msg),- "status": "blocked"- }, ensure_ascii=False)- # Track whether approval was explicitly granted by the user- if approval.get("user_approved"):- desc = approval.get("description", "flagged as dangerous")- approval_note = f"Command required approval ({desc}) and was approved by the user."- _approved_run = True- elif approval.get("smart_approved"):- desc = approval.get("description", "flagged as dangerous")- approval_note = f"Command was flagged ({desc}) and auto-approved by smart approval."-- # Prepare command for executionpty_disabled_reason = Noneeffective_pty = ptyif pty and _command_requires_pipe_stdin(command):@@ -3328,602 +2428,107 @@ def terminal_tool("EOF.")- # The session key is already computed above the gateway guard.if background:- # Spawn a tracked background process via the process registry.- # For local backends: uses subprocess.Popen with output buffering.- # For non-local backends: runs inside the sandbox via env.execute().- from tools.process_registry import process_registry-- effective_cwd = _resolve_command_cwd(- workdir=workdir,- default_cwd=cwd,- session_key=session_key,+ return spawn_background_process(+ command=command,+ env=env,env_type=env_type,+ effective_task_id=effective_task_id,+ task_id=task_id,+ session_key=session_key,+ workdir=workdir,+ cwd=cwd,+ effective_pty=effective_pty,+ notify_on_complete=notify_on_complete,+ watch_patterns=watch_patterns,+ approval_note=approval_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:- if env_type == "local":- proc_session = process_registry.spawn_local(- command=command,- cwd=effective_cwd,- task_id=effective_task_id,- owner_task_id=task_id or effective_task_id,- session_key=session_key,- env_vars=env.env if hasattr(env, 'env') else None,- use_pty=effective_pty,- )- else:- proc_session = process_registry.spawn_via_env(- env=env,- command=command,- cwd=effective_cwd,- task_id=effective_task_id,- owner_task_id=task_id or effective_task_id,- session_key=session_key,- )-- result_data = {- "output": "Background process started",- "session_id": proc_session.id,- "pid": proc_session.pid,- "exit_code": 0,- "error": None,- }- # Background spawns detached and returns exit_code 0 immediately;- # it never inline-polls is_interrupted(), so the stale-bit kill- # cannot occur here and this note never co-occurs with rc=130.- if approval_note:- result_data["approval"] = approval_note- if pty_disabled_reason:- result_data["pty_note"] = pty_disabled_reason-- # Nudge: background=True without notify_on_complete=True OR- # watch_patterns is a silent process. The agent has NO way to- # learn it finished short of calling process(action="poll"/"wait")- # explicitly. That's correct only for genuine long-lived- # processes that never exit (servers, watchers). For every- # bounded task (tests, builds, CI pollers, deploys, batch- # jobs) the agent almost certainly wanted notification and- # forgot the flag. May 2026 PR #31231 incident: bg CI poller- # ran fine, exited green, agent never noticed — user had to- # surface the result. Cheap nudge here costs ~one read for- # server cases (false positive) and prevents silent- # blindness for bounded-task cases (false negative).- if background and not notify_on_complete and not watch_patterns:- result_data["hint"] = (- "background=true without notify_on_complete=true means "- "this process runs SILENTLY — you will not be told when "- "it exits. If this is a bounded task (test suite, build, "- "CI poller, deploy, anything with a defined end), you "- "almost certainly wanted notify_on_complete=true so the "- "system pings you on exit. Re-launch with "- "notify_on_complete=true, or call process(action='poll') "- "/ process(action='wait') yourself to learn the outcome. "- "Only ignore this hint for genuine long-lived processes "- "that never exit (servers, watchers, daemons)."- )-- # Nudge: homebrewed CI watcher built from `gh pr view`- # `--json statusCheckRollup` or `gh pr checks` piped through- # `jq` is the #1 cause of silent CI-watcher failures in- # hermes-agent dev work. May 2026 PRs that surfaced this- # exact failure mode: #31329, #31448, #31695, #31709, #31745,- # #32264, #33131. Failure modes seen:- # * `gh pr view --json statusCheckRollup --jq ...` with- # `from_entries` choking on null `conclusion` keys, loop- # silently exits with empty status, never terminates.- # * `for i in $(seq 1 60); do ... 2>&1` block-buffered stdout- # never flushed to background-process capture; SIGTERM- # cuts the buffer before flush; `process(action='log')`- # returns total_lines=0 forever.- # * conclusion vs. status field confusion: filtering for- # `PENDING` in `.conclusion` while in-progress checks have- # empty conclusion → poller declares all-green while 18/23- # checks still IN_PROGRESS.- # * grepping for TTY-only banners ("All checks were- # successful") that never appear when stdout is piped.- # The canonical patterns in the green-ci-policy skill avoid- # every one of these — drive the loop off exit codes or on- # tab-separated `awk -F"\t" "$2==\"pending\""` (column 2).- # The detector here is deliberately narrow: it flags the- # statusCheckRollup JSON-API path and the `gh pr checks` +- # jq combination, but NOT the canonical column-2 awk- # poller (which uses awk on tabs, not as a generic- # stdout parser). When we detect the homebrew shape, point- # the agent at the canonical snippet rather than letting- # it ship another broken poller.- if background and command:- _gh = ("gh pr view" in command or "gh pr checks" in command)- _has_jq = (- " jq " in command or "| jq" in command or "$(jq" in command- )- _bad_shape = (- # The JSON-API anti-pattern. Even without jq, going- # through `--json statusCheckRollup` + parsing puts- # you in conclusion-vs-status field hell.- "statusCheckRollup" in command- # gh pr checks piped to jq is also wrong — `gh pr- # checks` doesn't emit JSON, so any `| jq` here is- # confused intent. The canonical column-2 poller- # uses awk-on-tabs, not jq.- or (_gh and _has_jq)- )- if _bad_shape:- existing = result_data.get("hint", "")- canonical_hint = (- "This looks like a homebrewed CI poller built from "- "`gh pr view --json statusCheckRollup` and/or "- "`gh pr checks | jq`. That shape has burned us "- "repeatedly in hermes-agent dev work (PRs #31329, "- "#31448, #31695, #31709, #31745, #32264, #33131) — "- "stdout buffering kills output capture, jq null-key "- "edge cases silently exit the loop, conclusion-vs-"- "status field confusion exits early with bogus "- "all-green verdicts, TTY-only summary banners "- "never appear when piped. Use the canonical "- "snippets in the green-ci-policy skill instead: "- "the exit-code-driven `gh pr checks $PR >/dev/null` "- "(rc 0 = green, 8 = pending, else fail) for "- "exit-on-first-fail behavior, or the column-2 "- "awk-on-tabs poller "- "(`awk -F\"\\t\" \"$2==\\\"pending\\\"\"`) for "- "sharded matrices. Load skill_view("- "name='github/hermes-agent-dev', "- "file_path='references/green-ci-policy.md') for "- "the verbatim snippets. If you must roll a custom "- "loop with rich structured output, write each tick "- "to a known file (`tee -a /tmp/ci.log`) and rely "- "on `process(action='log')` to read THAT file — "- "do not rely on background-process stdout capture "- "for line-buffered shell loops."- )- result_data["hint"] = (- existing + "\n\n" + canonical_hint if existing- else canonical_hint- )-- # Populate routing metadata on the session so that- # watch-pattern and completion notifications can be- # routed back to the correct chat/thread.- if background and (notify_on_complete or watch_patterns):- from gateway.session_context import (- async_delivery_supported as _async_ok,- get_session_env as _gse,- )-- # Finite sessions (stateless HTTP requests and one-shot- # Kanban workers) cannot route a completion back to the- # agent after the turn/process ends. Refuse the promise:- # drop the flags and tell the agent to poll.- if not _async_ok():- notify_on_complete = False- watch_patterns = None- result_data["notify_on_complete"] = False- result_data["notify_unsupported"] = (- "notify_on_complete / watch_patterns are not available in "- "this session — it cannot receive an async completion after "- "the turn ends (a one-shot runner such as `hermes -z`, a "- "cron job, a Kanban worker, or a stateless HTTP endpoint). "- "The process is "- "running in the background; retrieve its result with "- "process(action='poll') or process(action='wait')."- )- logger.info(- "background proc %s: async delivery unsupported on this "- "session; notify_on_complete/watch_patterns disabled",- proc_session.id,- )- else:- _gw_platform = _gse("HERMES_SESSION_PLATFORM", "")- if _gw_platform:- _gw_chat_id = _gse("HERMES_SESSION_CHAT_ID", "")- _gw_thread_id = _gse("HERMES_SESSION_THREAD_ID", "")- _gw_user_id = _gse("HERMES_SESSION_USER_ID", "")- _gw_user_name = _gse("HERMES_SESSION_USER_NAME", "")- _gw_message_id = _gse("HERMES_SESSION_MESSAGE_ID", "")- proc_session.watcher_platform = _gw_platform- proc_session.watcher_chat_id = _gw_chat_id- proc_session.watcher_user_id = _gw_user_id- proc_session.watcher_user_name = _gw_user_name- proc_session.watcher_thread_id = _gw_thread_id- proc_session.watcher_message_id = _gw_message_id- # Stamp the spawning conversation's session-db id- # so the gateway's completion pre-flight- # (_classify_completion_target) can drop the- # notification when the user closes this session- # (/new) before the process finishes, instead of- # injecting it into the chat's NEW session.- proc_session.parent_session_id = _gse(- "HERMES_SESSION_ID", ""- )-- # Mutual exclusion: if both notify_on_complete and watch_patterns- # are set, drop watch_patterns. The combination produces duplicate- # notifications (one per match + one on exit) that deliver- # asynchronously and can spam the user long after the process ends.- # notify_on_complete is the more useful signal for "let me know- # when the task finishes"; watch_patterns should be reserved for- # standalone mid-process signals on long-lived processes.- watch_patterns, conflict_note = _resolve_notification_flag_conflict(- notify_on_complete=bool(notify_on_complete),- watch_patterns=watch_patterns,- background=bool(background),+ 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,)- if conflict_note:- logger.warning("background proc %s: %s", proc_session.id, conflict_note)- result_data["watch_patterns_ignored"] = conflict_note-- # Mark for agent notification on completion- if notify_on_complete and background:- proc_session.notify_on_complete = True- result_data["notify_on_complete"] = True-- # In gateway mode, auto-register a fast watcher so the- # gateway can detect completion and trigger a new agent- # turn. CLI mode uses the completion_queue directly.- if proc_session.watcher_platform:- proc_session.watcher_interval = 5- process_registry.pending_watchers.append({- "session_id": proc_session.id,- "check_interval": 5,- "session_key": session_key,- "platform": proc_session.watcher_platform,- "chat_id": proc_session.watcher_chat_id,- "user_id": proc_session.watcher_user_id,- "user_name": proc_session.watcher_user_name,- "thread_id": proc_session.watcher_thread_id,- "message_id": proc_session.watcher_message_id,- "notify_on_complete": True,- "parent_session_id": proc_session.parent_session_id,- })-- # Set watch patterns for output monitoring- if watch_patterns and background:- proc_session.watch_patterns = list(watch_patterns)- result_data["watch_patterns"] = proc_session.watch_patterns-- return json.dumps(result_data, ensure_ascii=False)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"Failed to start background process: {e}"+ f"Command execution failed: {type(e).__name__}: {e}")}, ensure_ascii=False)- else:- # Run foreground command with retry logic- 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 on this thread during the- # approval-wait so it can't SIGINT the just-approved run. Do NOT- # re-clear inside the loop -- a genuine interrupt arriving during the- # backoff sleep between retries must survive and abort the command- # (caught by the next attempt's _wait_for_process poll loop -> 130).- if _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,- )- execute_kwargs = {- "timeout": effective_timeout,- "cwd": command_cwd,- # Foreground model-facing output: cap retention while- # streaming (head/tail window) so a verbose command- # can't OOM the gateway before truncation (#64435).- # Internal env.execute() consumers (file ops cat- # reads, RPC reads) intentionally stay unbounded.- "bounded_capture": True,- }- result = env.execute(command, **execute_kwargs)- 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)-- # Got a result- break- # Dual-write (cwd rearch step 1): the env's post-command tracking- # (marker parse / local sync) has just updated env.cwd with the- # directory this command finished in. That cwd belongs to THIS- # session — record it under the session key so the durable record- # never depends on the shared env surviving or on who drives the- # env next.- #- # BUT: a per-command ``workdir`` override is transient by contract- # (docstring: "Working directory for this command"). Recording it- # would hijack the session's durable cwd for every later command- # that doesn't pass ``workdir``. Skip the dual-write in that case.- #- # AND only when the command actually reported its cwd. The marker- # is printed after the command returns, so an interrupted / killed- # / timed-out command emits none and env.cwd still holds whatever- # the last command to FINISH left there — on a shared env, that is- # another session's directory. Recording it silently re-homes this- # session into a directory the user never opened.- observed_cwd = None- if (result or {}).get("cwd_observed"):- # New/current environments return the CWD observed by THIS- # command. The env field is shared mutable compatibility state- # and may already belong to a concurrent command. Keep the- # fallback for third-party providers that only implement the- # older cwd_observed + env.cwd contract.- observed_cwd = (result or {}).get("cwd") or getattr(env, "cwd", None)- if not workdir and observed_cwd:- record_session_cwd(session_key, observed_cwd)-- # Extract output- output = result.get("output", "")- returncode = result.get("returncode", 0)- # Spill metadata from the bounded collector: present only when- # output overflowed the capture window (see _wait_for_process).- spill_total_chars = result.get("output_total_chars")- spill_file_path = result.get("full_output_path")-- # Add helpful message for sudo failures in messaging context- output = _handle_sudo_failure(output, env_type)-- sudo_auth_failed = _sudo_wrong_password_failure(output)- sudo_cache_cleared = _invalidate_cached_sudo_on_auth_failure(- command, output- )- if sudo_cache_cleared:- has_sudo_prompt_callback = _get_sudo_password_callback() is not None- can_reprompt = (- has_sudo_prompt_callback or env_var_enabled("HERMES_INTERACTIVE")- ) and not _in_delegated_child_context()- if can_reprompt:- output += (- "\n\n⚠️ Sudo authentication failed — cached password "- "cleared. You will be prompted again on the next sudo "- "command."- )+ break- # Foreground terminal output canonicalization seam: process capture- # is already bounded by BaseEnvironment before sudo checks and hooks- # run. Plugins may replace that bounded string; replacements are- # still subject to the final output limit below.- # The hook is fail-open, and the first valid string return wins.- try:- from hermes_cli.lifecycle import invoke_hook- hook_results = invoke_hook(- "transform_terminal_output",- command=command,- output=output,- returncode=returncode,- task_id=effective_task_id or "",- env_type=env_type,- )- for hook_result in hook_results:- if isinstance(hook_result, str):- output = hook_result- break- except Exception:- pass-- # Truncate output if too long, keeping both head and tail- from tools.tool_output_limits import get_max_bytes- MAX_OUTPUT_CHARS = get_max_bytes()- if len(output) > MAX_OUTPUT_CHARS:- head_chars = int(MAX_OUTPUT_CHARS * 0.4) # 40% head (error messages often appear early)- tail_chars = MAX_OUTPUT_CHARS - head_chars # 60% tail (most recent/relevant output)- omitted = len(output) - head_chars - tail_chars- truncated_notice = (- f"\n\n... [OUTPUT TRUNCATED - {omitted} chars omitted "- f"out of {len(output)} total] ...\n\n"- )- output = output[:head_chars] + truncated_notice + output[-tail_chars:]-- # Strip ANSI escape sequences so the model never sees terminal- # formatting — prevents it from copying escapes into file writes.- from tools.ansi_strip import strip_ansi- output = strip_ansi(output)-- # Redact secrets from command output. For source/config dumps- # (MAX_TOKENS=100, "apiKey": "x" fixtures, postgresql:// f-string- # templates) the ENV/JSON/template passes are skipped to avoid- # false positives (code_file=True). But for env-dump commands- # (env/printenv/set/export/declare) the output IS a KEY=value- # credential dump, so redact_terminal_output runs the ENV pass- # (code_file=False) to mask opaque tokens with no vendor prefix.- # Real prefixes, auth headers, JWTs, private keys are masked in- # both modes. See issue #43025.- from agent.redact import redact_terminal_output- output = redact_terminal_output(output.strip(), command) if output else ""-- # Interpret non-zero exit codes that aren't real errors- # (e.g. grep=1 means "no matches", diff=1 means "files differ")- exit_note = _interpret_exit_code(command, returncode)-- # Output-pattern failure hints: map well-known error shapes- # (command-not-found, ModuleNotFoundError, gh field drift,- # merge conflicts, ...) to one short recovery hint so the model- # fixes the root cause on the next call instead of spending- # turns on re-diagnosis. See tools/terminal_hints.py.- failure_hint = None- if returncode != 0 and not exit_note:- try:- from tools.terminal_hints import annotate_failure- failure_hint = annotate_failure(command, returncode, output)- except Exception:- failure_hint = None- elif returncode == 0:- # Masked-success backstop: `cargo build | tail -20` returns- # tail's exit 0 even when the build failed (bash reports the- # last pipeline command's status; same for `cmd || echo ...`).- # When the command shape can mask an upstream failure AND the- # output carries strong failure indicators, warn the model so- # exit_code 0 isn't read as a success signal. Advisory only —- # the exit code itself is never modified.- try:- from tools.terminal_hints import annotate_masked_success- failure_hint = annotate_masked_success(command, output)- except Exception:- failure_hint = None-- result_dict = {- "output": output,- "exit_code": returncode,- "error": None,- }- # cwd echo: when the command changed the session's working- # directory (cd, pushd, ...), tell the model where it ended up.- # Production mining shows 60% of terminal calls carry a- # defensive 'cd X && ' prefix because the model can't see cwd- # state; echoing it on change removes the guesswork (pattern- # borrowed from crush's <cwd> injection).- #- # Gated on the same observation flag as the record above: without- # it, an interrupted command echoes the shared env's leftover cwd- # and tells the model it moved to a directory another session- # opened.- try:- post_cwd = observed_cwd- if post_cwd and command_cwd and os.path.realpath(str(post_cwd)) != os.path.realpath(str(command_cwd)):- result_dict["cwd"] = str(post_cwd)- except Exception:- pass- # Truncation metadata (codex/opencode/goose pattern): report the- # pre-truncation size and a spill-file handle so the model can- # retrieve the omitted middle with read_file/search_files instead- # of re-running the command. The spill was written raw by the- # collector; redact it here with the same pass as the visible- # output so no secret persists unmasked on disk.- if spill_file_path:- try:- _sp = Path(spill_file_path)- raw_spill = _sp.read_text(encoding="utf-8", errors="replace")- from tools.spill_safety import write_text_exclusive-- # Rewrite in place via lstat-checked unlink + exclusive- # create so the redacted copy can't be diverted through a- # symlink planted between the collector's write and now.- write_text_exclusive(- _sp,- redact_terminal_output(strip_ansi(raw_spill), command),- private=True,- overwrite=True,- errors="replace",- )- result_dict["output_total_chars"] = spill_total_chars- result_dict["full_output_path"] = spill_file_path- result_dict["truncation_note"] = (- "Output exceeded the capture window (head+tail shown). "- f"Full output ({spill_total_chars:,} chars) saved to "- f"{spill_file_path} — search it with search_files or page it "- "with read_file instead of re-running the command."- )- except Exception:- logger.debug("spill redaction failed; dropping spill handle", exc_info=True)- try:- Path(spill_file_path).unlink()- except OSError:- pass- try:- from agent.verification_evidence import record_terminal_result-- evidence = record_terminal_result(- command=command,- cwd=command_cwd,- session_id=session_id or task_id or effective_task_id or "default",- exit_code=returncode,- output=output,- )- if evidence:- result_dict["verification_evidence"] = {- "status": evidence.get("status"),- "kind": evidence.get("kind"),- "scope": evidence.get("scope"),- "canonical_command": evidence.get("canonical_command"),- }- except Exception:- logger.debug("verification evidence recording failed", exc_info=True)- if approval_note:- # Treat rc=130 as an interrupt only when the executor's marker is- # present. A command can legitimately exit 130 on its own- # (e.g. `bash -c 'exit 130'`); _wait_for_process returns the- # child's natural returncode there with no marker, and that must- # NOT be relabelled as a user interrupt in the audit note.- if returncode == 130 and "[Command interrupted]" in output:- # Approved command was interrupted mid-run by a genuine Stop.- # Keep the audit trail but never imply success: the bare- # "...approved by the user." note must not co-occur with the- # interrupt exit code (satisfies the 3-part-signature DONE).- result_dict["approval"] = approval_note.rstrip(".") + ", then interrupted."- else:- result_dict["approval"] = approval_note- if exit_note:- result_dict["exit_code_meaning"] = exit_note- if failure_hint:- result_dict["hint"] = failure_hint- if sudo_auth_failed:- result_dict["sudo_auth_failed"] = True- if sudo_cache_cleared:- result_dict["sudo_cache_cleared"] = True-- return json.dumps(result_dict, ensure_ascii=False)+ 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,+ )except EnvironmentConnectionError as e:- # Infrastructure/connection-class failure (SSH host down, Docker- # daemon unreachable) — distinct from a command failing with a- # nonzero exit code. Config gate ``terminal.degraded_mode``:- # warn (default) — return a structured degraded result the model- # can act on (reason + retry hint, no traceback).- # fail — preserve the historical error+traceback result.+ # Infrastructure failure (SSH host down, Docker daemon unreachable),+ # distinct from a nonzero exit. ``terminal.degraded_mode``: warn+ # (default) returns a structured degraded result with a retry hint;+ # fail preserves the historical error+traceback result.degraded_mode = _tenv("TERMINAL_DEGRADED_MODE", "warn").strip().lower()if degraded_mode == "fail":- import traceback- tb_str = traceback.format_exc()- logger.error("terminal_tool exception:\n%s", tb_str)- # Exception text can embed the failing command line (and any- # secrets inline in it) — redact before returning to the model.- return json.dumps({- "output": "",- "exit_code": -1,- "error": _redact_terminal_error_text(f"Failed to execute command: {e}"),- "traceback": _redact_terminal_error_text(tb_str),- "status": "error"- }, ensure_ascii=False)+ return _fatal_error_json(e)logger.warning("terminal backend degraded: %s", e.reason)- # Never keep a possibly-broken backend cached: evict it so the next- # call re-creates the environment from scratch and simply works once- # the backend is reachable again.+ # Evict the possibly-broken backend so the next call re-creates it.try:_evict_environment_for_task(task_id)except Exception:@@ -3938,27 +2543,12 @@ def terminal_tool(}, ensure_ascii=False)except Exception as e:- import traceback- tb_str = traceback.format_exc()- logger.error("terminal_tool exception:\n%s", tb_str)- # Exception text can embed the failing command line (and any- # secrets inline in it) — redact before returning to the model.- return json.dumps({- "output": "",- "exit_code": -1,- "error": _redact_terminal_error_text(f"Failed to execute command: {e}"),- "traceback": _redact_terminal_error_text(tb_str),- "status": "error"- }, ensure_ascii=False)+ return _fatal_error_json(e)def _evict_environment_for_task(task_id: Optional[str]) -> None:- """Drop any cached environment for *task_id* (and its collapsed key).-- Used when a backend reports an infrastructure failure: keeping the dead- env cached would make every subsequent call fail against a stale- connection, defeating automatic recovery.- """+ """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)@@ -3976,173 +2566,137 @@ def _evict_environment_for_task(task_id: Optional[str]) -> None: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:- config = _get_env_config()- env_type = config["env_type"]+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- if env_type == "local":- return True- elif env_type == "docker":- 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-- elif env_type == "singularity":- 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_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+- elif env_type == "ssh":- if not config.get("ssh_host") or not config.get("ssh_user"):+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(- "SSH backend selected but TERMINAL_SSH_HOST and TERMINAL_SSH_USER "- "are not both set. Configure both or switch TERMINAL_ENV to 'local'."+ "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.")- return False- return True+ 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- elif env_type == "modal":- 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- 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- return True- elif env_type == "vercel_sandbox":- return _check_vercel_sandbox_requirements(config)+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- elif env_type == "daytona":- 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- else:- 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+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:+ config = _get_env_config()+ checker = _REQUIREMENT_CHECKERS.get(config["env_type"], _check_plugin_requirements)+ return checker(config)except Exception as e:logger.error("Terminal requirements check failed: %s", e, exc_info=True)return False-if __name__ == "__main__":- # Simple test when run directly- print("Terminal Tool Module")- print("=" * 50)-- config = _get_env_config()- print("\nCurrent Configuration:")- print(f" Environment type: {config['env_type']}")- print(f" Docker image: {config['docker_image']}")- print(f" Modal image: {config['modal_image']}")- print(f" Working directory: {config['cwd']}")- print(f" Default timeout: {config['timeout']}s")- print(f" Lifetime: {config['lifetime_seconds']}s")-- if not check_terminal_requirements():- print("\n❌ Requirements not met. Please check the messages above.")- sys.exit(1)-- print("\n✅ All requirements met!")- print("\nAvailable Tool:")- print(" - terminal_tool: Execute commands in sandboxed environments")-- print("\nUsage Examples:")- print(" # Execute a command")- print(" result = terminal_tool(command='ls -la')")- print(" ")- print(" # Run a background task")- print(" result = terminal_tool(command='python server.py', background=True)")-- print("\nEnvironment Variables:")- default_img = "nikolaik/python-nodejs:python3.11-nodejs20"- print(- " TERMINAL_ENV: "- f"{_tenv('TERMINAL_ENV', 'local')} "- "(local/docker/singularity/modal/daytona/vercel_sandbox/ssh)"- )- print(f" TERMINAL_DOCKER_IMAGE: {_tenv('TERMINAL_DOCKER_IMAGE', default_img)}")- print(f" TERMINAL_SINGULARITY_IMAGE: {_tenv('TERMINAL_SINGULARITY_IMAGE', f'docker://{default_img}')}")- print(f" TERMINAL_MODAL_IMAGE: {_tenv('TERMINAL_MODAL_IMAGE', default_img)}")- print(f" TERMINAL_DAYTONA_IMAGE: {_tenv('TERMINAL_DAYTONA_IMAGE', default_img)}")- print(f" TERMINAL_CWD: {_tenv('TERMINAL_CWD', _safe_getcwd())}")- from hermes_constants import display_hermes_home as _dhh- print(f" TERMINAL_SANDBOX_DIR: {_tenv('TERMINAL_SANDBOX_DIR', f'{_dhh()}/sandboxes')}")- print(f" TERMINAL_TIMEOUT: {_tenv('TERMINAL_TIMEOUT', '60')}")- print(f" TERMINAL_LIFETIME_SECONDS: {_tenv('TERMINAL_LIFETIME_SECONDS', '300')}")---# ----------------------------------------------------------------------------# Registry-# ---------------------------------------------------------------------------from tools.registry import registryTERMINAL_SCHEMA = {@@ -4191,25 +2745,21 @@ TERMINAL_SCHEMA = {def _handle_terminal(args, **kw):- # Mirror of execute_code's misplaced-argument recovery: models sometimes- # send execute_code's ``code`` argument here. Without this, the call- # falls through to command=None and fails with "Invalid command:- # expected string, got NoneType" — naming neither the stray argument- # nor the right tool.+ # Models sometimes send execute_code's ``code`` here; name the stray+ # argument and the right tool instead of failing on command=None.if "command" not in args and "code" in args:return tool_error("terminal received a 'code' parameter, but it requires a shell ""command in 'command'. Use execute_code(code=...) for Python; ""for shell, retry as terminal(command=...).")- # `notify` is the advertised interface: true → notify_on_complete,- # ['pat', ...] → watch_patterns. The legacy args remain accepted- # (old transcripts, internal callers); explicit `notify` wins.+ # `notify` is the advertised interface (true → notify_on_complete,+ # [...] → watch_patterns); the legacy args stay accepted, explicit+ # `notify` wins. Background-only modifiers on a foreground call fail+ # with the corrected call instead of being silently ignored.notify = args.get("notify")notify_on_complete = args.get("notify_on_complete", False)watch_patterns = args.get("watch_patterns")- # Background-only modifiers on a foreground call were silently ignored;- # fail with the corrected call instead (poka-yoke, no schema cost).if not args.get("background", False):if notify or watch_patterns or notify_on_complete:return tool_error(@@ -4258,3 +2808,4 @@ registry.register(emoji="💻",max_result_size_chars=100_000,)+diff --git a/tools/terminal_tool_background.py b/tools/terminal_tool_background.pynew file mode 100644index 00000000000..71c81fa52a1--- /dev/null+++ b/tools/terminal_tool_background.py@@ -0,0 +1,244 @@+"""Background-process launch path of the terminal tool.++``terminal(background=true)`` spawns a tracked process through the process+registry (Popen for the local backend, ``env.execute`` inside the sandbox+otherwise), stamps gateway routing metadata for completion / watch-pattern+notifications, and returns the JSON result. Split out of+tools/terminal_tool.py; lazy ``from tools.terminal_tool import ...`` keeps+the origin module's monkeypatch points authoritative.+"""++import json+import logging+from typing import Any, List, Optional++logger = logging.getLogger("tools.terminal_tool")++# A silent background process (no notify_on_complete / watch_patterns) is right+# only for servers/watchers; for bounded tasks the agent almost always wanted a+# notification and forgot the flag, so nudge it (cheap false positive).+_SILENT_BACKGROUND_HINT = (+ "background=true without notify_on_complete=true means "+ "this process runs SILENTLY — you will not be told when "+ "it exits. If this is a bounded task (test suite, build, "+ "CI poller, deploy, anything with a defined end), you "+ "almost certainly wanted notify_on_complete=true so the "+ "system pings you on exit. Re-launch with "+ "notify_on_complete=true, or call process(action='poll') "+ "/ process(action='wait') yourself to learn the outcome. "+ "Only ignore this hint for genuine long-lived processes "+ "that never exit (servers, watchers, daemons)."+)++# Homebrewed CI pollers built on `gh pr view --json statusCheckRollup` or+# `gh pr checks | jq` fail silently in known ways (block-buffered stdout never+# reaches capture, jq null-key edge cases exit the loop, conclusion-vs-status+# confusion declares all-green early, TTY-only banners never appear piped).+# Detector is deliberately narrow: the canonical column-2 awk poller is fine.+_HOMEBREW_CI_POLLER_HINT = (+ "This looks like a homebrewed CI poller built from "+ "`gh pr view --json statusCheckRollup` and/or "+ "`gh pr checks | jq`. That shape has burned us "+ "repeatedly in hermes-agent dev work (PRs #31329, "+ "#31448, #31695, #31709, #31745, #32264, #33131) — "+ "stdout buffering kills output capture, jq null-key "+ "edge cases silently exit the loop, conclusion-vs-"+ "status field confusion exits early with bogus "+ "all-green verdicts, TTY-only summary banners "+ "never appear when piped. Use the canonical "+ "snippets in the green-ci-policy skill instead: "+ "the exit-code-driven `gh pr checks $PR >/dev/null` "+ "(rc 0 = green, 8 = pending, else fail) for "+ "exit-on-first-fail behavior, or the column-2 "+ "awk-on-tabs poller "+ "(`awk -F\"\\t\" \"$2==\\\"pending\\\"\"`) for "+ "sharded matrices. Load skill_view("+ "name='github/hermes-agent-dev', "+ "file_path='references/green-ci-policy.md') for "+ "the verbatim snippets. If you must roll a custom "+ "loop with rich structured output, write each tick "+ "to a known file (`tee -a /tmp/ci.log`) and rely "+ "on `process(action='log')` to read THAT file — "+ "do not rely on background-process stdout capture "+ "for line-buffered shell loops."++)++_ASYNC_UNSUPPORTED_NOTE = (+ "notify_on_complete / watch_patterns are not available in "+ "this session — it cannot receive an async completion after "+ "the turn ends (a one-shot runner such as `hermes -z`, a "+ "cron job, a Kanban worker, or a stateless HTTP endpoint). "+ "The process is "+ "running in the background; retrieve its result with "+ "process(action='poll') or process(action='wait')."+)+++def _looks_like_homebrew_ci_poller(command: str) -> bool:+ has_gh = "gh pr view" in command or "gh pr checks" in command+ has_jq = " jq " in command or "| jq" in command or "$(jq" in command+ # `gh pr checks` doesn't emit JSON, so piping it to jq is confused intent.+ return "statusCheckRollup" in command or (has_gh and has_jq)+++def _stamp_gateway_routing(proc_session, get_session_env) -> None:+ """Copy the spawning chat's routing metadata onto the process session so+ completion / watch notifications reach the right chat/thread."""+ platform = get_session_env("HERMES_SESSION_PLATFORM", "")+ if not platform:+ return+ proc_session.watcher_platform = platform+ proc_session.watcher_chat_id = get_session_env("HERMES_SESSION_CHAT_ID", "")+ proc_session.watcher_user_id = get_session_env("HERMES_SESSION_USER_ID", "")+ proc_session.watcher_user_name = get_session_env("HERMES_SESSION_USER_NAME", "")+ proc_session.watcher_thread_id = get_session_env("HERMES_SESSION_THREAD_ID", "")+ proc_session.watcher_message_id = get_session_env("HERMES_SESSION_MESSAGE_ID", "")+ # The spawning conversation's session-db id lets the gateway's completion+ # pre-flight drop the notification if the user closed this session (/new)+ # before the process finished, instead of injecting it into the NEW one.+ proc_session.parent_session_id = get_session_env("HERMES_SESSION_ID", "")+++def spawn_background_process(+ *,+ command: str,+ env: Any,+ env_type: str,+ effective_task_id: str,+ task_id: Optional[str],+ session_key: str,+ workdir: Optional[str],+ cwd: str,+ effective_pty: bool,+ notify_on_complete: bool,+ watch_patterns: Optional[List[str]],+ approval_note: Optional[str],+ pty_disabled_reason: Optional[str],+) -> str:+ """Spawn *command* as a tracked background process and return the JSON result.++ Never inline-polls ``is_interrupted()``: the spawn detaches and returns+ exit_code 0 immediately, so the stale-interrupt kill cannot occur here.+ """+ from tools.process_registry import process_registry+ from tools.terminal_tool import (+ _redact_terminal_error_text,+ _resolve_command_cwd,+ _resolve_notification_flag_conflict,+ )++ effective_cwd = _resolve_command_cwd(+ workdir=workdir,+ default_cwd=cwd,+ session_key=session_key,+ env_type=env_type,+ )+ try:+ if env_type == "local":+ proc_session = process_registry.spawn_local(+ command=command,+ cwd=effective_cwd,+ task_id=effective_task_id,+ owner_task_id=task_id or effective_task_id,+ session_key=session_key,+ env_vars=env.env if hasattr(env, 'env') else None,+ use_pty=effective_pty,+ )+ else:+ proc_session = process_registry.spawn_via_env(+ env=env,+ command=command,+ cwd=effective_cwd,+ task_id=effective_task_id,+ owner_task_id=task_id or effective_task_id,+ session_key=session_key,+ )++ result_data = {+ "output": "Background process started",+ "session_id": proc_session.id,+ "pid": proc_session.pid,+ "exit_code": 0,+ "error": None,+ }+ if approval_note:+ result_data["approval"] = approval_note+ if pty_disabled_reason:+ result_data["pty_note"] = pty_disabled_reason++ if not notify_on_complete and not watch_patterns:+ result_data["hint"] = _SILENT_BACKGROUND_HINT++ if command and _looks_like_homebrew_ci_poller(command):+ existing = result_data.get("hint", "")+ result_data["hint"] = (+ existing + "\n\n" + _HOMEBREW_CI_POLLER_HINT if existing+ else _HOMEBREW_CI_POLLER_HINT+ )++ if notify_on_complete or watch_patterns:+ from gateway.session_context import (+ async_delivery_supported as _async_ok,+ get_session_env as _gse,+ )++ # Finite sessions (stateless HTTP, one-shot Kanban workers) can't+ # route a completion back after the turn ends: drop the flags+ # and tell the agent to poll.+ if not _async_ok():+ notify_on_complete = False+ watch_patterns = None+ result_data["notify_on_complete"] = False+ result_data["notify_unsupported"] = _ASYNC_UNSUPPORTED_NOTE+ logger.info(+ "background proc %s: async delivery unsupported on this "+ "session; notify_on_complete/watch_patterns disabled",+ proc_session.id,+ )+ else:+ _stamp_gateway_routing(proc_session, _gse)++ watch_patterns, conflict_note = _resolve_notification_flag_conflict(+ notify_on_complete=bool(notify_on_complete),+ watch_patterns=watch_patterns,+ background=True,+ )+ if conflict_note:+ logger.warning("background proc %s: %s", proc_session.id, conflict_note)+ result_data["watch_patterns_ignored"] = conflict_note++ if notify_on_complete:+ proc_session.notify_on_complete = True+ result_data["notify_on_complete"] = True+ # Gateway mode: register a fast watcher so completion triggers a+ # new agent turn (CLI mode uses the completion_queue directly).+ if proc_session.watcher_platform:+ proc_session.watcher_interval = 5+ process_registry.pending_watchers.append({+ "session_id": proc_session.id,+ "check_interval": 5,+ "session_key": session_key,+ "platform": proc_session.watcher_platform,+ "chat_id": proc_session.watcher_chat_id,+ "user_id": proc_session.watcher_user_id,+ "user_name": proc_session.watcher_user_name,+ "thread_id": proc_session.watcher_thread_id,+ "message_id": proc_session.watcher_message_id,+ "notify_on_complete": True,+ "parent_session_id": proc_session.parent_session_id,+ })++ if watch_patterns:+ proc_session.watch_patterns = list(watch_patterns)+ result_data["watch_patterns"] = proc_session.watch_patterns++ return json.dumps(result_data, ensure_ascii=False)+ except Exception as e:+ return json.dumps({+ "output": "",+ "exit_code": -1,+ "error": _redact_terminal_error_text(+ f"Failed to start background process: {e}"+ )+ }, ensure_ascii=False)diff --git a/tools/terminal_tool_guards.py b/tools/terminal_tool_guards.pynew file mode 100644index 00000000000..d7cc2dba829--- /dev/null+++ b/tools/terminal_tool_guards.py@@ -0,0 +1,296 @@+"""Pre-execution guards for the terminal tool.++Pure functions that decide whether a command may run at all: workdir+validation, the foreground long-lived/background-operator guidance, the+supervised-gateway lifecycle block, and the Windows self-repo git guard.+Each ``*_block`` helper returns a finished JSON error string, or None when+the command may proceed. Split out of tools/terminal_tool.py; the origin+module re-imports every public helper so ``tools.terminal_tool.<name>``+keeps resolving.+"""++import json+import logging+import re+import shlex+import stat+from pathlib import Path+from typing import Any, Optional++from tools.shell_heredoc import strip_inert_heredoc_bodies++logger = logging.getLogger("tools.terminal_tool")+++# Workdir allowlist: Unicode alnum plus path/drive/UNC separators and common+# punctuation; shell metacharacters stay rejected. Unicode is allowed on+# purpose (e.g. CJK vault paths). Defense-in-depth — the cwd is also+# shlex-quoted before reaching the shell.+_WORKDIR_SAFE_ASCII_CHARS = frozenset('/\\:_-.~ +@=,')+++def _is_safe_workdir_char(ch: str) -> bool:+ if not ch or ord(ch) < 32 or ord(ch) == 127: # control chars / NUL+ return False+ return ch.isalnum() or ch in _WORKDIR_SAFE_ASCII_CHARS+++def _validate_workdir(workdir: str) -> str | None:+ """Error message if *workdir* has a disallowed character, else None.+ Allowlist rather than deny-list so novel metacharacters can't slip through."""+ if not workdir:+ return None+ for ch in workdir:+ if not _is_safe_workdir_char(ch):+ return (+ f"Blocked: workdir contains disallowed character {repr(ch)}. "+ "Use a simple filesystem path without shell metacharacters."+ )+ return None+++def _safe_command_preview(command: Any, limit: int = 200) -> str:+ """Return a log-safe preview for possibly-invalid command values."""+ if command is None:+ return "<None>"+ if isinstance(command, str):+ return command[:limit]+ try:+ return repr(command)[:limit]+ except Exception:+ return f"<{type(command).__name__}>"+++_SHELL_LEVEL_BACKGROUND_RE = re.compile(+ r"(?:^|[;&|]\s*|&&\s*|\|\|\s*|\$\(\s*)(?:nohup|disown|setsid)\b", re.IGNORECASE | re.MULTILINE+)+_INLINE_BACKGROUND_AMP_RE = re.compile(r"\s&\s")+_TRAILING_BACKGROUND_AMP_RE = re.compile(r"\s&\s*(?:#.*)?$")+++def _strip_quotes(command: str) -> str:+ """Blank quoted / backtick content and provably-inert heredoc bodies so+ regex checks can't match keywords (nohup, setsid, '&') inside strings.++ Heredocs are masked FIRST: their delimiter may itself be quoted+ (``<<'EOF'``). ``strip_inert_heredoc_bodies`` is conservative — only a+ quoted, terminated delimiter on a simple opener fed to a known non-shell+ consumer is masked, so a real background operator can't hide in one.+ """+ result = strip_inert_heredoc_bodies(command)+ result = re.sub(r"'[^']*'", "''", result)+ result = re.sub(r'"(?:[^"\\]|\\.)*"', '""', result)+ result = re.sub(r"`[^`]*`", "``", result)+ return result+++_LONG_LIVED_FOREGROUND_PATTERNS = (+ re.compile(r"\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|watch)\b", re.IGNORECASE),+ re.compile(r"\bdocker\s+compose\s+up\b", re.IGNORECASE),+ re.compile(r"\bnext\s+dev\b", re.IGNORECASE),+ re.compile(r"\bvite(?:\s|$)", re.IGNORECASE),+ re.compile(r"\bnodemon\b", re.IGNORECASE),+ re.compile(r"\buvicorn\b", re.IGNORECASE),+ re.compile(r"\bgunicorn\b", re.IGNORECASE),+ re.compile(r"\bpython(?:3)?\s+-m\s+http\.server\b", re.IGNORECASE),+)+++def _looks_like_help_or_version_command(command: str) -> bool:+ """Return True for informational invocations that should never be blocked."""+ normalized = " ".join(command.lower().split())+ return (+ " --help" in normalized+ or normalized.endswith(" -h")+ or " --version" in normalized+ or normalized.endswith(" -v")+ )+++def _foreground_background_guidance(command: str) -> str | None:+ """Guidance text when a foreground command looks long-lived or uses shell+ backgrounding (it should be a managed background session), else None."""+ if _looks_like_help_or_version_command(command):+ return None++ unquoted = _strip_quotes(command)++ if _SHELL_LEVEL_BACKGROUND_RE.search(unquoted):+ return (+ "Foreground command uses shell-level background wrappers (nohup/disown/setsid). "+ "Re-send WITHOUT the wrapper as terminal(command=\"<cmd>\", background=true, "+ "notify_on_complete=true) so Hermes tracks the process, then run readiness "+ "checks and tests in separate commands."+ )++ if _INLINE_BACKGROUND_AMP_RE.search(unquoted) or _TRAILING_BACKGROUND_AMP_RE.search(unquoted):+ return (+ "Foreground command uses '&' backgrounding. Re-send WITHOUT the '&' as "+ "terminal(command=\"<cmd>\", background=true) — add notify_on_complete=true "+ "for bounded jobs — then run health checks and tests in follow-up terminal calls."+ )++ for pattern in _LONG_LIVED_FOREGROUND_PATTERNS:+ if pattern.search(unquoted):+ return (+ "This foreground command appears to start a long-lived server/watch process. "+ "Run it with background=true, verify readiness (health endpoint/log signal), "+ "then execute tests in a separate command."+ )++ return None+++def gateway_lifecycle_block(+ *,+ command: str,+ env: Any,+ env_type: str,+ cwd: str,+ workdir: Optional[str],+ session_key: str,+) -> Optional[str]:+ """Refuse gateway lifecycle commands issued from inside the supervised gateway.++ ``systemctl``/``launchctl``/``hermes gateway restart|stop|uninstall``+ targeting hermes-gateway would SIGTERM the gateway — and this very+ subprocess — before completing, so the service may never come back.+ Applies unconditionally (``force=True`` cannot bypass it). Gated on the+ SUPERVISED-gateway probe, not the raw ``_HERMES_GATEWAY`` marker: that+ marker leaks into every process that merely imports gateway.run (hermes+ serve, CLI, web server), which must still be able to restart the gateway;+ an unsupervised foreground ``hermes gateway run`` has no KeepAlive to turn+ a self-restart into a respawn loop, so it passes too.+ Returns the JSON error string when blocked, else None.+ """+ from tools.process_registry import _is_supervised_gateway_process+ from tools.terminal_tool import _resolve_command_cwd, get_session_cwd++ if not _is_supervised_gateway_process():+ return None+ from cron.lifecycle_guard import (+ _MAX_REFERENCED_SCRIPT_BYTES,+ contains_gateway_lifecycle_command_or_referenced_script,+ contains_launchctl_submit_command,+ )+ if contains_launchctl_submit_command(command):+ return json.dumps({+ "output": "",+ "exit_code": 1,+ "error": (+ "Blocked: launchctl submit/bootstrap registers a persistent "+ "KeepAlive job and is unsafe from inside the gateway process. "+ "Use Hermes cron for one-shot delayed work, or install an "+ "explicit LaunchAgent from a separate shell."+ ),+ "status": "error",+ }, ensure_ascii=False)+ guard_cwd_base = get_session_cwd(session_key)+ if guard_cwd_base is None:+ guard_cwd_base = getattr(env, "cwd", None) or cwd+ guard_cwd = _resolve_command_cwd(+ workdir=workdir,+ default_cwd=guard_cwd_base,+ session_key=session_key,+ env_type=env_type,+ )++ def _read_script_in_env(script_path: str) -> Optional[str]:+ """Best-effort script read: host filesystem first, then a bounded+ ``env.execute('head -c ... < path')`` for remote backends."""+ if env is None:+ return None+ try:+ local_path = Path(script_path).expanduser()+ if not local_path.is_absolute():+ local_path = Path(guard_cwd) / local_path+ if local_path.is_file():+ metadata = local_path.stat()+ if stat.S_ISREG(metadata.st_mode) and metadata.st_size <= _MAX_REFERENCED_SCRIPT_BYTES:+ data = local_path.read_bytes()+ if len(data) <= _MAX_REFERENCED_SCRIPT_BYTES:+ if b"\x00" in data:+ # Binary, not a script: feeding it to the guard+ # tokenizes machine code into bogus paths and+ # crashes the scanner. Nothing to scan.+ return None+ return data.decode("utf-8", errors="replace")+ except Exception:+ pass+ # Remote backend: bound the read at the source with `head -c` so an+ # oversized binary never crosses the wire (an unbounded `cat` once+ # pinned the gateway's tool thread for 30+ min on a shlex scan). One+ # byte over budget is enough for lifecycle_guard to fail closed. The+ # `< path` redirect keeps leading-dash paths out of argv.+ try:+ result = env.execute(+ f"head -c {_MAX_REFERENCED_SCRIPT_BYTES + 1} "+ f"< {shlex.quote(script_path)}"+ )+ if result.get("returncode", -1) == 0:+ output = result.get("output", "")+ if output and "\x00" in output: # binary, see above+ return None+ return output+ except Exception:+ pass+ return None++ if contains_gateway_lifecycle_command_or_referenced_script(+ command,+ cwd=guard_cwd,+ read_remote_script=_read_script_in_env,+ ):+ return json.dumps({+ "output": "",+ "exit_code": 1,+ "error": (+ "Blocked: command or referenced script cannot restart, stop, or "+ "uninstall the gateway from inside the gateway process. The gateway would "+ "kill this command before it could complete (SIGTERM propagates "+ "to child processes). Run `hermes gateway restart` from a "+ "separate shell outside the running gateway."+ ),+ "status": "error",+ }, ensure_ascii=False)+ return None+++def self_repo_block(+ *,+ command: str,+ cwd: str,+ workdir: Optional[str],+ session_key: str,+) -> Optional[str]:+ """Windows-only guard against git-mutating the checkout backing this interpreter.++ NTFS locks loaded module files, so rewriting the live checkout can corrupt+ the running process; POSIX keeps old inodes alive for open handles, so the+ guard is off there (``guard_active``). Local backend only — remote+ backends cannot reach that checkout. Returns the JSON error string when+ blocked, else None.+ """+ from tools.self_repo_guard import detect_self_repo_git_mutation, guard_active+ from tools.terminal_tool import _resolve_command_cwd++ if not guard_active():+ return None+ guard_cwd = _resolve_command_cwd(+ workdir=workdir,+ default_cwd=cwd,+ session_key=session_key,+ )+ hit, msg = detect_self_repo_git_mutation(command, guard_cwd)+ if not hit:+ return None+ logger.warning(+ "Blocked self-repo git mutation (command: %s)",+ _safe_command_preview(command),+ )+ return json.dumps({+ "output": "",+ "exit_code": 1,+ "error": msg,+ "status": "blocked",+ }, ensure_ascii=False)diff --git a/tools/terminal_tool_result.py b/tools/terminal_tool_result.pynew file mode 100644index 00000000000..8f653881ee3--- /dev/null+++ b/tools/terminal_tool_result.py@@ -0,0 +1,328 @@+"""Foreground result post-processing for the terminal tool.++Everything that happens between ``env.execute`` returning and the JSON+result leaving the tool: session-cwd dual-write, sudo failure handling,+output transform hook, truncation, ANSI strip, redaction, exit-code notes+and failure hints, spill-file redaction, verification evidence. Also owns+the exit-code interpretation tables. Split out of tools/terminal_tool.py;+lazy ``from tools.terminal_tool import ...`` keeps the origin module's+monkeypatch points authoritative.+"""++import json+import logging+import os+import re+from pathlib import Path+from typing import Any, Optional++logger = logging.getLogger("tools.terminal_tool")+++# Signal-death notes keyed by signum, used for both ``-signum`` (subprocess)+# and ``128+signum`` (shell) encodings. Curated, not exhaustive, so a+# legitimate application exit code is never mislabeled; 130/SIGINT is owned+# by the executor's interrupt-marker path and excluded.+_SIGNAL_EXIT_NOTES: dict[int, str] = {+ 3: "SIGQUIT (quit from keyboard)",+ 4: "SIGILL (illegal instruction — corrupt binary or wrong architecture)",+ 6: "SIGABRT (abort — assertion failure, fatal runtime error, or glibc abort)",+ 7: "SIGBUS (bus error — misaligned or unmapped memory access)",+ 8: "SIGFPE (fatal arithmetic error, e.g. integer division by zero)",+ 9: "SIGKILL — often the kernel OOM killer on memory exhaustion, "+ "or an explicit kill -9",+ 11: "SIGSEGV (segmentation fault — the program crashed)",+ 13: "SIGPIPE (wrote to a closed pipe — e.g. output piped to a reader that exited)",+ 15: "SIGTERM (terminated — kill/timeout or shutdown requested it to stop)",+ 24: "SIGXCPU (CPU time limit exceeded)",+ 25: "SIGXFSZ (file size limit exceeded)",+}+++def _interpret_signal_exit(exit_code: int) -> str | None:+ """Note for a signal-termination exit code, or None. Negative codes are+ definite (subprocess semantics); 128+signum is the shell convention and a+ program *can* exit 139 itself, so those notes hedge with "usually"."""+ if exit_code < 0:+ signum = -exit_code+ if signum == 2: # SIGINT — executor's interrupt-marker path owns it+ return None+ note = _SIGNAL_EXIT_NOTES.get(signum)+ if note:+ return f"Command terminated by signal {signum}: {note}"+ try:+ import signal as _signal+ name = _signal.Signals(signum).name+ except (ValueError, ImportError):+ name = f"signal {signum}"+ return f"Command terminated by {name} (signal {signum})"++ if exit_code > 128:+ signum = exit_code - 128+ note = _SIGNAL_EXIT_NOTES.get(signum)+ if note:+ return (+ f"Exit code {exit_code} usually means the command was "+ f"terminated by signal {signum}: {note}"+ )++ return None+++_NO_MATCH = "No matches found (not an error)"+_FILES_DIFFER = "Files differ (expected, not an error)"+_COND_FALSE = "Condition evaluated to false (expected, not an error)"++# Informational non-zero exit codes per base command.+_EXIT_CODE_SEMANTICS: dict[str, dict[int, str]] = {+ "grep": {1: _NO_MATCH},+ "egrep": {1: _NO_MATCH},+ "fgrep": {1: _NO_MATCH},+ "rg": {1: _NO_MATCH},+ "ag": {1: _NO_MATCH},+ "ack": {1: _NO_MATCH},+ "diff": {1: _FILES_DIFFER},+ "colordiff": {1: _FILES_DIFFER},+ "find": {1: "Some directories were inaccessible (partial results may still be valid)"},+ "test": {1: _COND_FALSE},+ "[": {1: _COND_FALSE},+ "curl": {+ 6: "Could not resolve host",+ 7: "Failed to connect to host",+ 22: "HTTP response code indicated error (e.g. 404, 500)",+ 28: "Operation timed out",+ },+ "git": {1: "Non-zero exit (often normal — e.g. 'git diff' returns 1 when files differ)"},+}+++def _interpret_exit_code(command: str, exit_code: int) -> str | None:+ """Note for a non-zero exit code that is informational rather than an+ error (grep=1 "no matches", diff=1 "files differ", signal deaths), so the+ model doesn't burn turns investigating it. None when 0 or a real error.+ """+ if exit_code == 0:+ return None++ signal_note = _interpret_signal_exit(exit_code)+ if signal_note is not None:+ return signal_note++ # The last command of a pipeline/chain determines the exit code.+ segments = re.split(r'\s*(?:\|\||&&|[|;])\s*', command)+ last_segment = (segments[-1] if segments else command).strip()++ # Base command name: first word that isn't a VAR=val assignment, basename'd.+ base_cmd = ""+ for w in last_segment.split():+ if "=" in w and not w.startswith("-"):+ continue+ base_cmd = w.split("/")[-1]+ break++ return _EXIT_CODE_SEMANTICS.get(base_cmd, {}).get(exit_code)+++def finalize_foreground_result(+ *,+ command: str,+ result: dict,+ env: Any,+ env_type: str,+ effective_task_id: str,+ task_id: Optional[str],+ session_id: Optional[str],+ session_key: str,+ workdir: Optional[str],+ command_cwd: Optional[str],+ approval_note: Optional[str],+) -> str:+ """Turn a raw ``env.execute`` result into the tool's JSON result string."""+ from tools.terminal_tool import (+ _get_sudo_password_callback,+ _handle_sudo_failure,+ _in_delegated_child_context,+ _invalidate_cached_sudo_on_auth_failure,+ _sudo_wrong_password_failure,+ env_var_enabled,+ record_session_cwd,+ )++ # Record the cwd this command finished in as THIS session's durable cwd —+ # but only when the command actually reported it (an interrupted/killed+ # command emits no marker, and env.cwd then holds another session's+ # directory), and never for a transient per-command ``workdir``, which+ # would hijack the session cwd for every later command.+ observed_cwd = None+ if (result or {}).get("cwd_observed"):+ # Prefer the result's own cwd; env.cwd is shared mutable compat state+ # kept as fallback for third-party providers.+ observed_cwd = (result or {}).get("cwd") or getattr(env, "cwd", None)+ if not workdir and observed_cwd:+ record_session_cwd(session_key, observed_cwd)++ output = result.get("output", "")+ returncode = result.get("returncode", 0)+ # Spill metadata: present only when output overflowed the capture window.+ spill_total_chars = result.get("output_total_chars")+ spill_file_path = result.get("full_output_path")++ output = _handle_sudo_failure(output, env_type)++ sudo_auth_failed = _sudo_wrong_password_failure(output)+ sudo_cache_cleared = _invalidate_cached_sudo_on_auth_failure(+ command, output+ )+ if sudo_cache_cleared:+ has_sudo_prompt_callback = _get_sudo_password_callback() is not None+ can_reprompt = (+ has_sudo_prompt_callback or env_var_enabled("HERMES_INTERACTIVE")+ ) and not _in_delegated_child_context()+ if can_reprompt:+ output += (+ "\n\n⚠️ Sudo authentication failed — cached password "+ "cleared. You will be prompted again on the next sudo "+ "command."+ )++ # Plugin output-transform seam (fail-open; first string result wins).+ # Replacements are still subject to the output limit below.+ try:+ from hermes_cli.lifecycle import invoke_hook+ hook_results = invoke_hook(+ "transform_terminal_output",+ command=command,+ output=output,+ returncode=returncode,+ task_id=effective_task_id or "",+ env_type=env_type,+ )+ for hook_result in hook_results:+ if isinstance(hook_result, str):+ output = hook_result+ break+ except Exception:+ pass++ # Truncate keeping head (errors often appear early) and tail (most recent).+ from tools.tool_output_limits import get_max_bytes+ MAX_OUTPUT_CHARS = get_max_bytes()+ if len(output) > MAX_OUTPUT_CHARS:+ head_chars = int(MAX_OUTPUT_CHARS * 0.4)+ tail_chars = MAX_OUTPUT_CHARS - head_chars+ omitted = len(output) - head_chars - tail_chars+ truncated_notice = (+ f"\n\n... [OUTPUT TRUNCATED - {omitted} chars omitted "+ f"out of {len(output)} total] ...\n\n"+ )+ output = output[:head_chars] + truncated_notice + output[-tail_chars:]++ # Strip ANSI so the model never copies escapes into file writes.+ from tools.ansi_strip import strip_ansi+ output = strip_ansi(output)++ # Redact secrets; redact_terminal_output is command-aware (env-dump+ # commands get the KEY=value pass, source/config dumps skip it).+ from agent.redact import redact_terminal_output+ output = redact_terminal_output(output.strip(), command) if output else ""++ exit_note = _interpret_exit_code(command, returncode)++ # Recovery hints for well-known failure shapes (tools/terminal_hints.py);+ # on rc=0, warn when a pipeline tail / `|| echo` may mask an upstream+ # failure and the output carries strong failure indicators (advisory only).+ failure_hint = None+ if returncode != 0 and not exit_note:+ try:+ from tools.terminal_hints import annotate_failure+ failure_hint = annotate_failure(command, returncode, output)+ except Exception:+ failure_hint = None+ elif returncode == 0:+ try:+ from tools.terminal_hints import annotate_masked_success+ failure_hint = annotate_masked_success(command, output)+ except Exception:+ failure_hint = None++ result_dict = {+ "output": output,+ "exit_code": returncode,+ "error": None,+ }+ # cwd echo when the command changed directory (gated on the observation+ # flag above so an interrupted command can't echo another session's cwd).+ try:+ if observed_cwd and command_cwd and os.path.realpath(str(observed_cwd)) != os.path.realpath(str(command_cwd)):+ result_dict["cwd"] = str(observed_cwd)+ except Exception:+ pass+ # Spill handle so the model can read the omitted middle instead of+ # re-running. The collector wrote it raw; redact it with the same pass+ # so no secret persists unmasked on disk.+ if spill_file_path:+ try:+ _sp = Path(spill_file_path)+ raw_spill = _sp.read_text(encoding="utf-8", errors="replace")+ from tools.spill_safety import write_text_exclusive++ # lstat-checked unlink + exclusive create: the redacted copy can't+ # be diverted through a symlink planted since the collector's write.+ write_text_exclusive(+ _sp,+ redact_terminal_output(strip_ansi(raw_spill), command),+ private=True,+ overwrite=True,+ errors="replace",+ )+ result_dict["output_total_chars"] = spill_total_chars+ result_dict["full_output_path"] = spill_file_path+ result_dict["truncation_note"] = (+ "Output exceeded the capture window (head+tail shown). "+ f"Full output ({spill_total_chars:,} chars) saved to "+ f"{spill_file_path} — search it with search_files or page it "+ "with read_file instead of re-running the command."+ )+ except Exception:+ logger.debug("spill redaction failed; dropping spill handle", exc_info=True)+ try:+ Path(spill_file_path).unlink()+ except OSError:+ pass+ try:+ from agent.verification_evidence import record_terminal_result++ evidence = record_terminal_result(+ command=command,+ cwd=command_cwd,+ session_id=session_id or task_id or effective_task_id or "default",+ exit_code=returncode,+ output=output,+ )+ if evidence:+ result_dict["verification_evidence"] = {+ "status": evidence.get("status"),+ "kind": evidence.get("kind"),+ "scope": evidence.get("scope"),+ "canonical_command": evidence.get("canonical_command"),+ }+ except Exception:+ logger.debug("verification evidence recording failed", exc_info=True)+ if approval_note:+ # rc=130 is an interrupt only with the executor's marker — a command+ # can legitimately `exit 130` itself. An interrupted approved run keeps+ # the audit note but must never imply success.+ if returncode == 130 and "[Command interrupted]" in output:+ result_dict["approval"] = approval_note.rstrip(".") + ", then interrupted."+ else:+ result_dict["approval"] = approval_note+ if exit_note:+ result_dict["exit_code_meaning"] = exit_note+ if failure_hint:+ result_dict["hint"] = failure_hint+ if sudo_auth_failed:+ result_dict["sudo_auth_failed"] = True+ if sudo_cache_cleared:+ result_dict["sudo_cache_cleared"] = True++ return json.dumps(result_dict, ensure_ascii=False)