Skip to content

The agent that grows with you

refactor(tools/environments): split local/base into output/wait/session-env siblings; extract docker_egress + remote_common; dedupe remote backends; compact process_registry

Teknium3bbec90f23e0
diff --git a/tools/environments/base.py b/tools/environments/base.py
index c4acd344028..54cf4ede924 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -4,28 +4,50 @@ Unified spawn-per-call model: every command spawns a fresh ``bash -c`` process.
A session snapshot (env vars, functions, aliases) is captured once at init and
re-sourced before each command. CWD persists via in-band stdout markers (remote)
or a temp file (local).
+
+Cohesive pieces live in sibling modules and are re-exported here so
+``from tools.environments.base import X`` / ``patch("tools.environments.base.X")``
+keep working: ``base_output`` (collector, ProcessHandle, stdin/drain plumbing),
+``base_session_env`` (snapshot/wrapper shell scripting), ``base_wait`` (tracing).
"""
-import codecs
import json
import logging
import os
-import re
-import select
import shlex
-import subprocess
import threading
import time
import uuid
from abc import ABC, abstractmethod
-from collections import deque
from pathlib import Path
-from typing import IO, Callable, Iterable, Protocol
+from typing import Callable, Iterable
from hermes_constants import get_hermes_home
-from hermes_cli._subprocess_compat import windows_hide_flags
from tools.interrupt import is_interrupted, is_thread_interrupted
-from tools.environments.path_utils import (
+from tools.environments.base_output import ( # noqa: F401
+ ProcessHandle,
+ _BoundedOutputCollector,
+ _ThreadedProcessHandle,
+ _UNBOUNDED_CAPTURE_CHARS,
+ _finalize_wait_result,
+ _new_output_collector,
+ _pipe_stdin,
+ _popen_bash,
+ _start_drain_thread,
+)
+from tools.environments.base_session_env import ( # noqa: F401
+ _SHELL_ENV_NAME_RE,
+ _SNAP_TMP,
+ _SNAP_TMP_SUFFIX,
+ _SNAPSHOT_EXCLUDED_ENV_REGEX,
+ _cwd_marker,
+ _export_dump_excluding_session_vars,
+ _snapshot_bootstrap_script,
+ _split_cwd_marker,
+ _wrap_command_script,
+)
+from tools.environments.base_wait import _WaitTrace
+from tools.environments.path_utils import ( # noqa: F401
_SANDBOX_DIR_HASH_LEN,
_SANDBOX_DIR_MAX_LEN,
_SANDBOX_DIR_UNSAFE_RE,
@@ -34,51 +56,36 @@ from tools.environments.path_utils import (
logger = logging.getLogger(__name__)
-# Opt-in debug tracing for the interrupt/activity/poll machinery. Set
-# HERMES_DEBUG_INTERRUPT=1 to log loop entry/exit, periodic heartbeats, and
-# every is_interrupted() state change from _wait_for_process. Off by default
-# to avoid flooding production gateway logs.
+# Opt-in debug tracing for the interrupt/activity/poll machinery
+# (HERMES_DEBUG_INTERRUPT=1). Off by default to avoid flooding gateway logs.
_DEBUG_INTERRUPT = bool(os.getenv("HERMES_DEBUG_INTERRUPT"))
# Extra seconds the ``run_bounded_sync`` backstop waits past the inner
-# ``_wait_for_process`` deadline. The inner poll loop is what returns
-# partial output + returncode 124; this outer bound only exists for when
-# that loop itself never returns (family A of #94285: a blocked wait
-# that silently disables asyncio timers). Keep it small so a healthy
-# timeout still comes from the inner path.
+# ``_wait_for_process`` deadline. The inner poll loop returns partial output +
+# returncode 124; the outer bound only fires when that loop itself never
+# returns (a blocked wait that silently disables asyncio timers). Keep it
+# small so a healthy timeout still comes from the inner path.
_EXECUTE_WAIT_BOUND_GRACE_S = 2.0
if _DEBUG_INTERRUPT:
- # AIAgent's quiet_mode path (run_agent.py) forces the `tools` logger to
- # ERROR on CLI startup, which would silently swallow every trace we emit.
- # Force this module's own logger back to INFO so the trace is visible in
- # agent.log regardless of quiet-mode. Scoped to the opt-in case only.
+ # quiet_mode forces the `tools` logger to ERROR on CLI startup, which would
+ # swallow every trace; force this logger back to INFO in the opt-in case.
logger.setLevel(logging.INFO)
-# Thread-local activity callback. The agent sets this before a tool call so
+# Thread-local activity callback: the agent sets it before a tool call so
# long-running _wait_for_process loops can report liveness to the gateway.
_activity_callback_local = threading.local()
-# Sentinel capacity for full-fidelity capture (internal consumers). Large
-# enough that the collector never evicts in practice, keeping a single code
-# path for both bounded and unbounded modes.
-_UNBOUNDED_CAPTURE_CHARS = 2**63 - 1
-
-
class EnvironmentConnectionError(RuntimeError):
"""Infrastructure/connection-class failure of a terminal backend.
- Raised when the backend itself is unreachable (SSH host down, Docker
- daemon not running, remote file sync failing on a dead link) — never
- for a command that merely exited nonzero. Subclassing RuntimeError
- keeps every existing ``except RuntimeError`` catcher working.
-
- ``terminal_tool`` turns this into a structured ``status: "degraded"``
- tool result (config gate ``terminal.degraded_mode: warn|fail``) so the
- model gets an actionable reason + retry hint instead of a traceback.
- The failed backend is never cached, so a later call retries from
- scratch and simply works once the backend is reachable again.
+ Raised when the backend itself is unreachable (SSH host down, Docker daemon
+ not running, remote file sync failing on a dead link) — never for a command
+ that merely exited nonzero. Subclassing RuntimeError keeps every existing
+ ``except RuntimeError`` catcher working. ``terminal_tool`` turns this into a
+ structured ``status: "degraded"`` result (config ``terminal.degraded_mode``);
+ the failed backend is never cached, so a later call retries from scratch.
"""
def __init__(self, reason: str, *, retry_hint: str = ""):
@@ -92,165 +99,6 @@ class EnvironmentConnectionError(RuntimeError):
)
-class _BoundedOutputCollector:
- """Retain a bounded 40/60 head-tail window of streamed text.
-
- When ``spill_path`` is set, the collector also tees the FULL stream to
- that file once eviction begins (up to ``_SPILL_CAP_CHARS``), so a
- truncated foreground result is recoverable without re-running the
- command. Memory stays bounded either way — the spill is disk-only.
- """
-
- # Hard ceiling on spill file size. Beyond this the file stops growing
- # (marker appended); protects disk from pathological runaway output.
- _SPILL_CAP_CHARS = 5_000_000
-
- def __init__(self, max_chars: int, spill_path: "Path | None" = None):
- self.max_chars = max(1, int(max_chars))
- self._head_limit = int(self.max_chars * 0.4)
- self._tail_limit = self.max_chars - self._head_limit
- self._head: list[str] = []
- self._tail: deque[str] = deque()
- self._head_chars = 0
- self._tail_chars = 0
- self._total_chars = 0
- self._lock = threading.Lock()
- self._spill_path = spill_path
- self._spill_fh: IO[str] | None = None
- self._spill_chars = 0
- self._spill_capped = False
-
- def _maybe_spill(self, text: str) -> None:
- """Tee ``text`` to the spill file (opened lazily on first overflow)."""
- if self._spill_path is None or self._spill_capped:
- return
- try:
- if self._spill_fh is None:
- from tools.spill_safety import ensure_spill_dir, open_exclusive
-
- # Raw pre-redaction output: private perms + symlink-refusing
- # exclusive create (a planted link must fail the spill, never
- # redirect the write).
- ensure_spill_dir(self._spill_path.parent, private=True)
- self._spill_fh = open_exclusive(
- self._spill_path, private=True, errors="replace"
- )
- # Backfill everything retained so far so the file holds the
- # stream from byte 0, not just from the overflow point.
- backlog = "".join(self._head) + "".join(self._tail)
- self._spill_fh.write(backlog)
- self._spill_chars = len(backlog)
- budget = self._SPILL_CAP_CHARS - self._spill_chars
- if budget <= 0 or len(text) > budget:
- self._spill_fh.write(text[:max(0, budget)])
- self._spill_fh.write("\n... [spill capped at 5,000,000 chars] ...\n")
- self._spill_capped = True
- else:
- self._spill_fh.write(text)
- self._spill_chars += len(text)
- except OSError:
- # Disk trouble must never break command execution.
- self._spill_capped = True
-
- def close_spill(self) -> "str | None":
- """Close the spill file and return its path if it was used."""
- with self._lock:
- if self._spill_fh is None:
- return None
- try:
- self._spill_fh.close()
- except OSError:
- pass
- self._spill_fh = None
- return str(self._spill_path)
-
- @property
- def buffered_chars(self) -> int:
- with self._lock:
- return self._head_chars + self._tail_chars
-
- @property
- def total_chars(self) -> int:
- with self._lock:
- return self._total_chars
-
- def append(self, text: str) -> None:
- if not text:
- return
- with self._lock:
- text_len = len(text)
- # Spill tee: activates at the first overflow (backfilling what's
- # retained so far), then mirrors every subsequent chunk.
- if self._spill_path is not None and (
- self._spill_fh is not None
- or self._total_chars + text_len > self.max_chars
- ):
- self._maybe_spill(text)
- self._total_chars += text_len
- start = 0
-
- if self._head_chars < self._head_limit:
- take = min(self._head_limit - self._head_chars, text_len)
- if take:
- self._head.append(text[:take])
- self._head_chars += take
- start = take
-
- remaining = text_len - start
- if remaining <= 0 or self._tail_limit <= 0:
- return
- if remaining >= self._tail_limit:
- self._tail.clear()
- self._tail.append(text[-self._tail_limit :])
- self._tail_chars = self._tail_limit
- return
-
- chunk = text[start:]
- self._tail.append(chunk)
- self._tail_chars += len(chunk)
- while self._tail_chars > self._tail_limit:
- excess = self._tail_chars - self._tail_limit
- first = self._tail[0]
- if len(first) <= excess:
- self._tail.popleft()
- self._tail_chars -= len(first)
- else:
- self._tail[0] = first[excess:]
- self._tail_chars -= excess
-
- def render(self, *, suffix: str = "") -> str:
- """Render within ``max_chars``, preserving a required status suffix."""
- with self._lock:
- if len(suffix) >= self.max_chars:
- return suffix[-self.max_chars :]
-
- head = "".join(self._head)
- tail = "".join(self._tail)
- available = self.max_chars - len(suffix)
- if self._total_chars <= available:
- return head + tail + suffix
-
- notice = ""
- for _ in range(4):
- content_budget = max(0, available - len(notice))
- head_chars = int(content_budget * 0.4)
- tail_chars = content_budget - head_chars
- omitted = max(0, self._total_chars - head_chars - tail_chars)
- updated = (
- f"\n\n... [OUTPUT TRUNCATED - {omitted:,} chars omitted "
- f"out of {self._total_chars:,} total] ...\n\n"
- )
- if updated == notice:
- break
- notice = updated
-
- content_budget = max(0, available - len(notice))
- head_chars = int(content_budget * 0.4)
- tail_chars = content_budget - head_chars
- rendered_tail = tail[-tail_chars:] if tail_chars else ""
- return head[:head_chars] + notice[:available] + rendered_tail + suffix
-
-
def set_activity_callback(cb: Callable[[str], None] | None) -> None:
"""Register a callback that _wait_for_process fires periodically."""
_activity_callback_local.callback = cb
@@ -259,25 +107,18 @@ def set_activity_callback(cb: Callable[[str], None] | None) -> None:
def get_activity_callback() -> Callable[[str], None] | None:
"""Return the thread-local activity callback (see ``set_activity_callback``).
- Public accessor for callers outside this module that need to capture the
- calling thread's callback before handing work to another thread (the
- callback is thread-local, so a freshly spawned thread cannot read it
- back) — e.g. the manual cron-run heartbeat (#76502).
+ For callers that must capture the calling thread's callback before handing
+ work to another thread — a freshly spawned thread cannot read it back.
"""
return getattr(_activity_callback_local, "callback", None)
-def touch_activity_if_due(
- state: dict,
- label: str,
-) -> None:
+def touch_activity_if_due(state: dict, label: str) -> None:
"""Fire the activity callback at most once every ``state['interval']`` seconds.
- *state* must contain ``last_touch`` (monotonic timestamp) and ``start``
- (monotonic timestamp of the operation start). An optional ``interval``
- key overrides the default 10 s cadence.
-
- Swallows all exceptions so callers don't need their own try/except.
+ *state* must contain ``last_touch`` and ``start`` (monotonic timestamps);
+ optional ``interval`` overrides the default 10 s cadence. Swallows all
+ exceptions so callers don't need their own try/except.
"""
now = time.monotonic()
interval = state.get("interval", 10.0)
@@ -294,110 +135,14 @@ def touch_activity_if_due(
def get_sandbox_dir() -> Path:
- """Return the host-side root for all sandbox storage (Docker workspaces,
- Singularity overlays/SIF cache, etc.).
-
- Configurable via TERMINAL_SANDBOX_DIR. Defaults to {HERMES_HOME}/sandboxes/.
- """
+ """Host-side root for all sandbox storage (Docker workspaces, Singularity
+ overlays/SIF cache). ``TERMINAL_SANDBOX_DIR`` overrides ``{HERMES_HOME}/sandboxes``."""
custom = os.getenv("TERMINAL_SANDBOX_DIR")
- if custom:
- p = Path(custom)
- else:
- p = get_hermes_home() / "sandboxes"
+ p = Path(custom) if custom else get_hermes_home() / "sandboxes"
p.mkdir(parents=True, exist_ok=True)
return p
-# ---------------------------------------------------------------------------
-# Shared constants and utilities
-# ---------------------------------------------------------------------------
-
-
-def _pipe_stdin(proc: subprocess.Popen, data: str) -> None:
- """Write *data* to proc.stdin on a daemon thread to avoid pipe-buffer deadlocks.
-
- On Windows, text-mode stdin (``text=True`` / ``encoding="utf-8"``)
- translates ``\\n`` → ``\\r\\n`` as the data flows through the pipe —
- which corrupts every write_file / patch call because the bytes that
- land on disk include injected carriage returns. The file IS created,
- but every subsequent byte-count / content compare against the
- caller's ``\\n``-only string fails.
-
- Workaround: write through ``proc.stdin.buffer`` (the underlying byte
- buffer), encoding to UTF-8 ourselves. That bypasses Python's
- newline translation entirely on every platform. No behaviour change
- on POSIX — the byte sequence is identical to what text-mode would
- produce there.
-
- Encoding uses ``errors="surrogateescape"`` — the exact inverse of the
- surrogateescape decode, so original bytes are restored. For
- surrogate-free strings it is byte-identical to strict UTF-8.
- Surrogates outside the round-trip range U+DC80–U+DCFF raise and are
- recorded on ``proc._hermes_stdin_errors`` while stdin is still closed
- in ``finally`` so the child sees EOF instead of hanging;
- ``_wait_for_process`` reads the recorded error and surfaces it as
- ``stdin_error`` on the result.
- """
-
- errors: list[BaseException] = []
- proc._hermes_stdin_errors = errors
-
- def _write():
- if proc.stdin is None:
- errors.append(RuntimeError("process stdin unavailable"))
- return
- # Resolve the target BEFORE encoding: a failed encode must still
- # reach the finally-close, or the child hangs on EOF forever.
- target = getattr(proc.stdin, "buffer", proc.stdin)
- try:
- raw = data.encode("utf-8", "surrogateescape") if isinstance(data, str) else data
- written = target.write(raw)
- if written != len(raw):
- # Buffered writers normally complete or raise; a short write
- # is a real failure and must be surfaced, not swallowed.
- raise RuntimeError(f"short stdin write: {written} of {len(raw)} bytes")
- except (BrokenPipeError, OSError):
- pass # child closed stdin early — normal
- except Exception as exc:
- # Only reachable with surrogates outside the surrogateescape
- # round-trip range (e.g. a literal U+D800). Record it so
- # _wait_for_process can surface it instead of a silent false
- # success.
- errors.append(exc)
- finally:
- try:
- target.close()
- except Exception:
- pass
-
- thread = threading.Thread(target=_write, daemon=True)
- proc._hermes_stdin_thread = thread
- thread.start()
-
-
-def _popen_bash(
- cmd: list[str], stdin_data: str | None = None, **kwargs
-) -> subprocess.Popen:
- """Spawn a subprocess with standard stdout/stderr/stdin setup.
-
- If *stdin_data* is provided, writes it asynchronously via :func:`_pipe_stdin`.
- Backends with special Popen needs (e.g. local's ``preexec_fn``) can bypass
- this and call :func:`_pipe_stdin` directly.
- """
- kwargs.setdefault("creationflags", windows_hide_flags())
- proc = subprocess.Popen(
- cmd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- stdin=subprocess.PIPE if stdin_data is not None else subprocess.DEVNULL,
- text=True, encoding="utf-8", errors="replace",
- **kwargs,
- )
- if stdin_data is not None:
- _pipe_stdin(proc, stdin_data)
- return proc
-
-
def _load_json_store(path: Path) -> dict:
"""Load a JSON file as a dict, returning ``{}`` on any error."""
if path.exists():
@@ -423,186 +168,6 @@ def _file_mtime_key(host_path: str) -> tuple[float, int] | None:
return None
-# ---------------------------------------------------------------------------
-# ProcessHandle protocol
-# ---------------------------------------------------------------------------
-
-
-class ProcessHandle(Protocol):
- """Duck type that every backend's _run_bash() must return.
-
- subprocess.Popen satisfies this natively. SDK backends (Modal, Daytona)
- return _ThreadedProcessHandle which adapts their blocking calls.
- """
-
- def poll(self) -> int | None: ...
- def kill(self) -> None: ...
- def wait(self, timeout: float | None = None) -> int: ...
-
- @property
- def stdout(self) -> IO[str] | None: ...
-
- @property
- def returncode(self) -> int | None: ...
-
-
-class _ThreadedProcessHandle:
- """Adapter for SDK backends (Modal, Daytona) that have no real subprocess.
-
- Wraps a blocking ``exec_fn() -> (output_str, exit_code)`` in a background
- thread and exposes a ProcessHandle-compatible interface. An optional
- ``cancel_fn`` is invoked on ``kill()`` for backend-specific cancellation
- (e.g. Modal sandbox.terminate, Daytona sandbox.stop).
- """
-
- def __init__(
- self,
- exec_fn: Callable[[], tuple[str, int]],
- cancel_fn: Callable[[], None] | None = None,
- ):
- self._cancel_fn = cancel_fn
- self._done = threading.Event()
- self._returncode: int | None = None
- self._error: Exception | None = None
-
- # Pipe for stdout — drain thread in _wait_for_process reads the read end.
- read_fd, write_fd = os.pipe()
- self._stdout = os.fdopen(read_fd, "r", encoding="utf-8", errors="replace")
- self._write_fd = write_fd
-
- def _worker():
- try:
- output, exit_code = exec_fn()
- self._returncode = exit_code
- # Write output into the pipe so drain thread picks it up.
- try:
- os.write(self._write_fd, output.encode("utf-8", errors="replace"))
- except OSError:
- pass
- except Exception as exc:
- self._error = exc
- self._returncode = 1
- finally:
- try:
- os.close(self._write_fd)
- except OSError:
- pass
- self._done.set()
-
- t = threading.Thread(target=_worker, daemon=True)
- t.start()
-
- @property
- def stdout(self):
- return self._stdout
-
- @property
- def returncode(self) -> int | None:
- return self._returncode
-
- def poll(self) -> int | None:
- return self._returncode if self._done.is_set() else None
-
- def kill(self):
- if self._cancel_fn:
- try:
- self._cancel_fn()
- except Exception:
- pass
-
- def wait(self, timeout: float | None = None) -> int:
- self._done.wait(timeout=timeout)
- return self._returncode
-
-
-# ---------------------------------------------------------------------------
-# CWD marker for remote backends
-# ---------------------------------------------------------------------------
-
-
-def _cwd_marker(session_id: str) -> str:
- return f"__HERMES_CWD_{session_id}__"
-
-
-# Per-session variables that the gateway bridges freshly onto every command's
-# process environment (via tools/environments/local._inject_session_context_env,
-# reading gateway.session_context._VAR_MAP). They must NEVER be persisted into
-# the shared bash session snapshot: a single long-lived backend serves many
-# concurrent sessions (the messaging gateway, TUI, desktop/web dashboard all
-# collapse the terminal to one "default" environment), so ``export -p`` dumping
-# the FIRST session's HERMES_SESSION_ID into the snapshot makes every LATER
-# session ``source`` that stale value and see a FOREIGN session's identity —
-# overriding the correct per-command Popen env (issue: cross-session
-# HERMES_SESSION_ID leak via the shared snapshot). Stripping them from the
-# snapshot is safe because they are re-injected on every command; a snapshot
-# should only carry the user's own shell state (PATH, functions, exports they
-# set), not Hermes' per-turn session identity.
-#
-# Kept in sync with gateway.session_context._VAR_MAP: every bridged name starts
-# with one of these prefixes (or is HERMES_UI_SESSION_ID). Used by unit tests
-# as the Python-side contract for the exclusion set; the dump path unsets by
-# name/prefix instead of grepping declare lines (see below / issue #71296).
-_SNAPSHOT_EXCLUDED_ENV_REGEX = (
- "^declare -x (HERMES_SESSION_|HERMES_UI_SESSION_ID|HERMES_CRON_AUTO_DELIVER_|"
- "HERMES_CRON_SESSION|HERMES_BROWSER_CONTROL_)"
-)
-_SHELL_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
-
-
-def _export_dump_excluding_session_vars(
- tmp_path: str,
- excluded_names: Iterable[str] = (),
-) -> str:
- """Return a shell snippet that dumps ``export -p`` to *tmp_path* minus the
- per-session bridged vars (see ``_SNAPSHOT_EXCLUDED_ENV_REGEX``) and any
- additional names supplied by the caller.
-
- Unset the bridged vars in a subshell *before* ``export -p``. A line-based
- ``grep -vE`` filter is unsafe: bash 3.2 prints a value containing a newline
- as a multi-line ``declare -x NAME="…`` block, so only the opener matches the
- regex and continuation lines (e.g. ``curl … | bash #`` smuggled into a
- Matrix room/display name via ``HERMES_SESSION_CHAT_NAME``) land in the
- snapshot and execute on the next ``source`` (issue #71296). Unsetting first
- means ``export -p`` never emits those vars — including any continuation
- lines. ``|| true`` keeps the success contract for callers that chain on it.
-
- The dump MUST be wrapped in a brace group with the redirection applied to
- the group. *tmp_path* is typically a shell-variable expansion (a
- mktemp-allocated per-writer temp name); a redirection attached to a
- pipeline segment would expand it inside that segment's subshell,
- potentially inconsistently with the parent that expands the follow-up
- ``mv``. The brace-group redirect is expanded in the current shell,
- keeping both expansions consistent.
- """
- # ${!PREFIX*} is bash 3.2+ name-prefix expansion; empty matches are fine
- # because ``unset`` with only missing names is ignored under 2>/dev/null.
- # Quote caller-provided names so malformed configuration can never become
- # shell syntax. Valid environment names remain unquoted by shlex.quote().
- safe_names = {
- name for name in excluded_names
- if isinstance(name, str) and name
- }
- extra_unset = " ".join(shlex.quote(name) for name in sorted(safe_names))
- if extra_unset:
- extra_unset = f" {extra_unset}"
- return (
- "{ ( "
- "unset ${!HERMES_SESSION_*} ${!HERMES_CRON_AUTO_DELIVER_*} "
- "${!HERMES_BROWSER_CONTROL_*} "
- # AI_AGENT / HERMES_AGENT are per-command attribution markers
- # (re-exported by every _wrap_command with outer-harness-preserving
- # ${VAR:-default} semantics). Persisting them into the snapshot
- # would make the FIRST command's value override a later outer
- # harness value arriving via the process env, exactly like the
- # session-var leak this dump already guards against.
- "AI_AGENT HERMES_AGENT "
- f"HERMES_UI_SESSION_ID{extra_unset} 2>/dev/null; "
- "export -p; "
- ") || true; } "
- f"> {tmp_path}"
- )
-
-
# ---------------------------------------------------------------------------
# BaseEnvironment
# ---------------------------------------------------------------------------
@@ -621,26 +186,19 @@ class BaseEnvironment(ABC):
# True only when commands execute on the SAME host as the Hermes process
# (LocalEnvironment). Controller-host facts (sys.platform, Path.home())
- # only describe the execution target when this is True — remote/container
- # backends must not inherit controller-side platform behavior (e.g. the
- # macOS TCC search pruning in tools/file_operations.py).
+ # describe the execution target only when this is True.
is_local: bool = False
# Snapshot creation timeout (override for slow cold-starts).
_snapshot_timeout: int = 30
# Local and Docker override this because they resolve allowlisted values
- # through the active profile scope. Other backends keep their existing
- # snapshot semantics until they implement the same resolver contract.
+ # through the active profile scope; other backends keep plain snapshots.
_profile_scoped_passthrough: bool = False
def get_temp_dir(self) -> str:
- """Return the backend temp directory used for session artifacts.
-
- Most sandboxed backends use ``/tmp`` inside the target environment.
- LocalEnvironment overrides this on platforms like Termux where ``/tmp``
- may be missing and ``TMPDIR`` is the portable writable location.
- """
+ """Backend temp directory for session artifacts (``/tmp`` in sandboxes;
+ LocalEnvironment overrides for Termux where only ``TMPDIR`` is writable)."""
return "/tmp"
def __init__(self, cwd: str, timeout: int, env: dict = None):
@@ -655,9 +213,8 @@ class BaseEnvironment(ABC):
self._cwd_marker = _cwd_marker(self._session_id)
self._snapshot_ready = False
self._snapshot_passthrough_names: set[str] = set()
- # When True, login bash is unusable (e.g. broken Git-for-Windows
- # ``Directory \\drivers\\etc`` startup) so execute() must not fall
- # back to ``bash -l`` per command — use non-login ``bash -c`` instead.
+ # True when login bash is unusable (e.g. broken Git-for-Windows startup)
+ # so execute() must fall back to non-login ``bash -c``, not ``bash -l``.
self._prefer_nonlogin = False
# ------------------------------------------------------------------
@@ -672,11 +229,7 @@ class BaseEnvironment(ABC):
timeout: int = 120,
stdin_data: str | None = None,
) -> ProcessHandle:
- """Spawn a bash process to run *cmd_string*.
-
- Returns a ProcessHandle (subprocess.Popen or _ThreadedProcessHandle).
- Must be overridden by every backend.
- """
+ """Spawn a bash process to run *cmd_string*; every backend overrides this."""
raise NotImplementedError(f"{type(self).__name__} must implement _run_bash()")
@abstractmethod
@@ -693,12 +246,11 @@ class BaseEnvironment(ABC):
return ()
def _snapshot_excluded_passthrough_names(self) -> tuple[str, ...]:
- """Return profile-scoped names that must not persist in the snapshot.
+ """Profile-scoped names that must not persist in the snapshot.
- The set is monotonic for the environment lifetime. A skill/config
- allowlist can be cleared after a value was captured; retaining the
- exclusion prevents that old value from becoming visible to a later
- profile through the shared snapshot.
+ Monotonic for the environment lifetime: an allowlist can be cleared
+ after a value was captured, and retaining the exclusion keeps that old
+ value from leaking to a later profile through the shared snapshot.
"""
if not self._profile_scoped_passthrough:
return ()
@@ -723,80 +275,22 @@ class BaseEnvironment(ABC):
return tuple(sorted(self._snapshot_passthrough_names))
def init_session(self):
- """Capture login shell environment into a snapshot file.
+ """Capture the login shell environment into the snapshot file.
- Called once after backend construction. On success, sets
- ``_snapshot_ready = True`` so subsequent commands source the snapshot
- instead of running with ``bash -l``.
+ Called once after construction. On success ``_snapshot_ready`` is set so
+ commands source the snapshot instead of running under ``bash -l``. On
+ failure, fall back to ``bash -l`` per command — unless a non-login probe
+ shows login bash itself is dead, in which case prefer ``bash -c``.
"""
- # Full capture: env vars, functions, aliases, shell options.
- # Restore configured cwd after login shell profile scripts, which may
- # change the working directory (e.g. bashrc `cd ~`). Without this,
- # pwd -P captures the profile's directory, not terminal.cwd.
- # Route through ``_quote_cwd_for_cd`` (not a bare ``shlex.quote``) so
- # the Windows subclass override converts a native ``C:\Users\x`` cwd to
- # the Git-Bash ``/c/Users/x`` form the bootstrap ``cd`` can resolve.
- # Without this the snapshot bootstrap ``cd`` below fails on Windows and
- # ``pwd -P`` captures the login shell's directory, not ``terminal.cwd``.
- _quoted_cwd = self._quote_cwd_for_cd(self.cwd)
- # Quote snapshot / cwd-file paths via ``_quote_shell_path`` so the
- # LocalEnvironment override can rewrite ``C:/...`` (and mixed
- # ``/c/Users\\...``) to ``/c/...`` before quoting — bare drive paths
- # in the bootstrap script trip MSYS into the
- # ``Directory \\drivers\\etc does not exist`` failure class.
- # On POSIX this is plain ``shlex.quote``.
- _quoted_snap = self._quote_shell_path(self._snapshot_path)
- # Use atomic file replacement: assemble the snapshot in a temp file,
- # then mv it over the final path. This prevents concurrent source()
- # calls from reading a half-written snapshot when another terminal
- # command finishes and rewrites the env vars (issue #38249). `mv` is
- # atomic on POSIX when src and dest are on the same filesystem, so
- # source() either sees the old complete snapshot or the new complete
- # one — never a partial/truncated file.
- #
- # The temp name MUST be unique per concurrent writer. ``$$`` is the
- # bash PID, but in ``&``-launched subshells (how concurrent terminal
- # calls run) ``$$`` stays the *parent* shell's PID — so two concurrent
- # writers would pick the SAME temp name, clobber each other's temp
- # mid-write, and mv would then publish a torn file (the corruption is
- # only narrowed, not closed). ``$BASHPID`` would be unique per writer,
- # but macOS ships bash 3.2 which does NOT provide it — the name expands
- # empty there, so every writer shares one temp path and the race is
- # back. ``mktemp`` allocates a per-writer unique path portably across
- # bash versions. The template is shell-quoted (Windows/Git-Bash drive
- # letters, spaces) and the resulting path lives in a shell variable so
- # every later expansion is consistent.
- _snap_tmp_template = self._quote_shell_path(self._snapshot_path + ".tmp.XXXXXXXXXX")
- _snap_tmp = '"$__hermes_snap_tmp"'
- snapshot_excluded = self._snapshot_excluded_passthrough_names()
- bootstrap = (
- f"umask 077\n"
- f"__hermes_snap_tmp=$(mktemp {_snap_tmp_template}) || exit 1\n"
- f"{_export_dump_excluding_session_vars(_snap_tmp, snapshot_excluded)}\n"
- # Dump function definitions, filtering out private (``_``-prefixed)
- # helpers — mainly bash-completion internals (``_git``, ``_make``…)
- # — by NAME, not by line. A naive ``declare -f | grep -vE '^_[^_]'``
- # is line-based: it strips the function *header* line but leaves the
- # orphaned ``{ … }`` body behind, which corrupts the snapshot and
- # makes every sourced command fail (e.g. exit 127). Selecting the
- # wanted names with ``declare -F`` first, then dumping only those
- # whole definitions, preserves the filter's intent without ever
- # tearing a function body. The non-empty guard matters: bare
- # ``declare -f`` with no name args dumps ALL functions, so an empty
- # name list (only private funcs present) would otherwise leak the
- # very functions we meant to drop.
- f"__hermes_fns=$(declare -F | awk '{{print $3}}' | grep -vE '^_[^_]') || true\n"
- f"[ -n \"$__hermes_fns\" ] && declare -f $__hermes_fns "
- f">> {_snap_tmp} 2>/dev/null || true\n"
- f"alias -p >> {_snap_tmp}\n"
- f"echo 'shopt -s expand_aliases' >> {_snap_tmp}\n"
- f"echo 'set +e' >> {_snap_tmp}\n"
- f"echo 'set +u' >> {_snap_tmp}\n"
- # Publish atomically only if assembly succeeded; otherwise drop the
- # partial temp rather than leave it to be sourced or orphaned.
- f"mv -f {_snap_tmp} {_quoted_snap} || rm -f {_snap_tmp}\n"
- f"builtin cd -- {_quoted_cwd} 2>/dev/null || true\n"
- f"printf '\\n{self._cwd_marker}%s{self._cwd_marker}\\n' \"$(pwd -P)\"\n"
+ bootstrap = _snapshot_bootstrap_script(
+ # ``_quote_cwd_for_cd`` / ``_quote_shell_path`` (not bare shlex.quote)
+ # let the Windows subclass rewrite ``C:\\...`` to ``/c/...`` so the
+ # bootstrap ``cd`` resolves and MSYS doesn't choke on drive paths.
+ quoted_cwd=self._quote_cwd_for_cd(self.cwd),
+ quoted_snap=self._quote_shell_path(self._snapshot_path),
+ snap_tmp_template=self._quote_shell_path(self._snapshot_path + _SNAP_TMP_SUFFIX),
+ excluded_names=self._snapshot_excluded_passthrough_names(),
+ cwd_marker=self._cwd_marker,
)
try:
proc = self._run_bash(bootstrap, login=True, timeout=self._snapshot_timeout)
@@ -814,23 +308,8 @@ class BaseEnvironment(ABC):
)
except Exception as exc:
self._snapshot_ready = False
- # Default fallback is bash -l per command so PATH/nvm/etc still
- # load. If login itself is dead (classic Windows Git Bash
- # ``Directory \\drivers\\etc does not exist``), that fallback
- # would brick every tool — prefer non-login bash -c instead.
- detail = str(exc)
- prefer_nonlogin = False
- try:
- probe = self._run_bash("true", login=False, timeout=min(15, self._snapshot_timeout))
- probe_result = self._wait_for_process(probe, timeout=min(15, self._snapshot_timeout))
- prefer_nonlogin = int(probe_result.get("returncode") or 0) == 0
- if not prefer_nonlogin:
- detail = (probe_result.get("stdout") or detail).strip() or detail
- except Exception as probe_exc:
- detail = f"{detail}; non-login probe: {probe_exc}"
-
- self._prefer_nonlogin = prefer_nonlogin
- if prefer_nonlogin:
+ self._prefer_nonlogin, detail = self._probe_nonlogin_fallback(str(exc))
+ if self._prefer_nonlogin:
logger.warning(
"init_session failed (session=%s): %s — "
"login bash unusable; falling back to non-login bash -c",
@@ -845,13 +324,27 @@ class BaseEnvironment(ABC):
detail,
)
+ def _probe_nonlogin_fallback(self, detail: str) -> tuple[bool, str]:
+ """Run ``true`` under non-login bash; return ``(prefer_nonlogin, detail)``."""
+ probe_timeout = min(15, self._snapshot_timeout)
+ try:
+ probe = self._run_bash("true", login=False, timeout=probe_timeout)
+ probe_result = self._wait_for_process(probe, timeout=probe_timeout)
+ prefer_nonlogin = int(probe_result.get("returncode") or 0) == 0
+ if not prefer_nonlogin:
+ detail = (probe_result.get("stdout") or detail).strip() or detail
+ return prefer_nonlogin, detail
+ except Exception as probe_exc:
+ return False, f"{detail}; non-login probe: {probe_exc}"
+
# ------------------------------------------------------------------
# Command wrapping
# ------------------------------------------------------------------
@staticmethod
def _quote_cwd_for_cd(cwd: str) -> str:
- """Quote a ``cd`` target while preserving ``~`` expansion."""
+ """Quote a ``cd`` target while preserving ``~`` expansion (``~/...``
+ goes through ``$HOME`` so suffixes with spaces stay one word)."""
if cwd == "~":
return cwd
if cwd == "~/":
@@ -861,144 +354,26 @@ class BaseEnvironment(ABC):
return shlex.quote(cwd)
def _quote_shell_path(self, path: str) -> str:
- """Quote *path* for interpolation into a bash script.
-
- LocalEnvironment overrides this to rewrite native/mixed Windows
- paths to ``/c/...`` before quoting. Remote backends leave paths
- as-is (they already speak POSIX).
- """
+ """Quote *path* for a bash script. LocalEnvironment overrides this to
+ rewrite native/mixed Windows paths to ``/c/...``; remote backends are POSIX."""
return shlex.quote(path)
def _wrap_command(self, command: str, cwd: str) -> str:
"""Build the full bash script that sources snapshot, cd's, runs command,
- re-dumps env vars, and emits CWD markers."""
- escaped = command.replace("'", "'\\''")
-
- # Quote the snapshot path (see init_session — LocalEnvironment
- # rewrites ``C:/...`` to ``/c/...`` so MSYS doesn't mangle it).
- _quoted_snap = self._quote_shell_path(self._snapshot_path)
- # Use atomic file replacement for env snapshot updates (issue #38249).
- # Assemble into a per-writer-unique temp file, then mv to atomically
- # replace the snapshot so concurrent source() calls never read a
- # truncated/half-written file. ``mktemp`` is used instead of
- # ``$BASHPID``/``$$`` because macOS bash 3.2 lacks ``$BASHPID`` (it
- # expands empty, collapsing every writer onto one temp name) and ``$$``
- # is shared by ``&``-launched subshells. Template shell-quoted
- # (Windows/spaces); the allocated path lives in a shell variable.
- _snap_tmp_template = self._quote_shell_path(self._snapshot_path + ".tmp.XXXXXXXXXX")
- _snap_tmp = '"$__hermes_snap_tmp"'
-
- parts = []
- passthrough_names = self._snapshot_excluded_passthrough_names()
-
- # A shared snapshot may contain the previous profile's value. Save
- # the current process environment before sourcing it, then restore the
- # current profile's value (or unset the name) immediately afterwards.
- # Values stay in environment memory and never enter the shell command
- # string, so secrets are not exposed through process arguments/logs.
- saved_names: list[tuple[str, str, str]] = []
- for name in passthrough_names:
- marker = f"_HERMES_RUNTIME_PASSTHROUGH_{name}"
- present = f"{marker}_PRESENT"
- value = f"{marker}_VALUE"
- saved_names.append((name, present, value))
- parts.append(f"{present}=${{{name}+x}}")
- parts.append(f"{value}=${{{name}-}}")
-
- # Source snapshot (env vars from previous commands).
- # Redirect stdout to /dev/null: on macOS (bash 3.2 and certain
- # Homebrew bash builds) sourcing a file containing ``declare -x``
- # can emit the declarations to stdout, leaking ~60 lines of env
- # vars into every tool response (issue #15459). Linux bash is
- # silent here, but the redirect is harmless.
- if self._snapshot_ready:
- parts.append(
- f"source {_quoted_snap} >/dev/null 2>&1 || true"
- )
-
- for name, present, value in saved_names:
- parts.append(
- f'if [ "${present}" = x ]; then export {name}="${value}"; '
- f'else unset {name}; fi'
- )
- parts.append(f"unset {present} {value}")
-
- # Harness attribution: every tool subprocess advertises that it runs
- # under Hermes via the cross-agent ``AI_AGENT`` standard (read by e.g.
- # huggingface_hub's agent detection) plus the Hermes-specific
- # ``HERMES_AGENT`` marker. The value MUST equal our id in the public
- # agent-harness registry (``hermes-agent`` — see huggingface.js
- # ``agent-harnesses.ts``); standard-var matching is exact, so any other
- # value is reported as "unknown". Setting it here (rather than only in
- # the host process env) is what carries the marker into REMOTE backends
- # (Docker/SSH/Modal/Daytona/Singularity/Vercel), whose exec env is not
- # inherited from the Hermes process. ``${VAR:-default}`` semantics:
- # never clobber an outer harness value that arrived via the inherited
- # process env (Hermes running inside another agent's terminal).
- parts.append(
- 'export AI_AGENT="${AI_AGENT:-hermes-agent}" '
- 'HERMES_AGENT="${HERMES_AGENT:-true}"'
- )
-
- # Non-interactive pager defaults: git log/diff/branch and similar
- # pager-happy tools hang a captured (non-TTY writing to a pipe is
- # fine, but PTY mode IS a TTY) or PTY-backed command waiting for `q`.
- # GIT_PAGER=cat neutralizes git specifically; PAGER=cat catches the
- # long tail (man, systemctl, psql, ...). ${VAR:-default} semantics:
- # a user who exported their own pager in the session keeps it.
- parts.append(
- 'export GIT_PAGER="${GIT_PAGER:-cat}" PAGER="${PAGER:-cat}"'
+ re-dumps env vars, and emits CWD markers (see ``_wrap_command_script``)."""
+ return _wrap_command_script(
+ command,
+ quoted_cwd=self._quote_cwd_for_cd(cwd),
+ quoted_snap=self._quote_shell_path(self._snapshot_path),
+ snap_tmp_template=self._quote_shell_path(self._snapshot_path + _SNAP_TMP_SUFFIX),
+ passthrough_names=self._snapshot_excluded_passthrough_names(),
+ snapshot_ready=self._snapshot_ready,
+ cwd_marker=self._cwd_marker,
)
- # Preserve bare ``~`` expansion, but rewrite ``~/...`` through
- # ``$HOME`` so suffixes with spaces remain a single shell word.
- quoted_cwd = self._quote_cwd_for_cd(cwd)
- # ``--`` keeps hyphen-prefixed directory names from being parsed as options.
- parts.append(f"builtin cd -- {quoted_cwd} || exit 126")
-
- # Run the actual command
- parts.append(f"eval '{escaped}'")
- parts.append("__hermes_ec=$?")
- # Restrict Hermes metadata files without changing the user's command
- # umask. Snapshot files may contain env-carried secrets.
- parts.append("umask 077")
-
- # Re-dump env vars to snapshot (atomic replacement to avoid races).
- # Chain mv on the export succeeding so a failed/partial dump never
- # replaces a good snapshot; drop the temp on failure so it isn't
- # orphaned (cleaned up wholesale in LocalEnvironment.cleanup too).
- # NOTE: the temp path is allocated with mktemp into a shell variable
- # first — the redirection inside _export_dump_excluding_session_vars is
- # attached to a brace group so the variable expands in the same shell
- # that later expands the ``mv`` operand, keeping both consistent.
- if self._snapshot_ready:
- parts.append(
- f"__hermes_snap_tmp=$(mktemp {_snap_tmp_template}) && "
- f"{{ {_export_dump_excluding_session_vars(_snap_tmp, passthrough_names)} "
- f"&& mv -f {_snap_tmp} {_quoted_snap}; }} "
- f"2>/dev/null || rm -f {_snap_tmp} 2>/dev/null || true"
- )
-
- # Emit the CWD stdout marker; all backends (including local, since
- # PR #63255) parse it from output — no temp-file write needed.
- # Use a distinct line for the marker. The leading \n ensures
- # the marker starts on its own line even if the command doesn't
- # end with a newline (e.g. printf 'exact'). We'll strip this
- # injected newline in _extract_cwd_from_output.
- parts.append(
- f"printf '\\n{self._cwd_marker}%s{self._cwd_marker}\\n' \"$(pwd -P)\""
- )
- parts.append("exit $__hermes_ec")
-
- return "\n".join(parts)
-
- # ------------------------------------------------------------------
- # Stdin heredoc embedding (for SDK backends)
- # ------------------------------------------------------------------
-
@staticmethod
def _embed_stdin_heredoc(command: str, stdin_data: str) -> str:
- """Append stdin_data as a shell heredoc to the command string."""
+ """Append stdin_data as a shell heredoc to the command string (SDK backends)."""
delimiter = f"HERMES_STDIN_{uuid.uuid4().hex[:12]}"
return f"{command} << '{delimiter}'\n{stdin_data}\n{delimiter}"
@@ -1016,330 +391,78 @@ class BaseEnvironment(ABC):
) -> dict:
"""Poll-based wait with interrupt checking and stdout draining.
- Shared across all backends — not overridden.
-
- ``bounded_capture=True`` (foreground terminal-tool path only) retains
- at most ``tool_output.max_bytes`` of output in a head/tail window
- while draining, so a verbose subprocess cannot OOM the process
- (#64435). The default (False) preserves full-fidelity capture for
- internal consumers — file-operation ``cat`` reads feeding the patch
- engine, code-execution RPC reads, log reads — where truncation would
- corrupt data.
-
- Fires the ``activity_callback`` (if set on this instance) every 10s
- while the process is running so the gateway's inactivity timeout
- doesn't kill long-running commands.
-
- ``watch_interrupt_tid`` is the tool-worker thread that submitted this
- wait. ``execute()`` may move the wait onto a ``run_bounded_sync``
- worker; ``/stop`` still interrupts the original worker tid, so the
- poll loop must honor that bit as well as the current thread's.
-
- Also wraps the poll loop in a ``try/finally`` that guarantees we
- call ``self._kill_process(proc)`` if we exit via ``KeyboardInterrupt``
- or ``SystemExit``. Without this, the local backend (which spawns
- subprocesses with ``os.setsid`` into their own process group) leaves
- an orphan with ``PPID=1`` when python is shut down mid-tool — the
- ``sleep 300``-survives-30-min bug Physikal and I both hit.
+ Shared across all backends — not overridden. ``bounded_capture=True``
+ (foreground terminal-tool path only) retains at most
+ ``tool_output.max_bytes`` in a head/tail window so a verbose subprocess
+ cannot OOM the process; the default keeps full fidelity for internal
+ consumers (file-op ``cat`` reads, RPC reads) where truncation corrupts
+ data. Fires the activity callback every 10s so the gateway's
+ inactivity timeout doesn't kill long commands. ``watch_interrupt_tid``
+ is the tool-worker thread that submitted this wait: ``execute()`` may
+ move the wait onto a ``run_bounded_sync`` worker while ``/stop`` still
+ interrupts the original tid, so both bits are honored. A
+ ``KeyboardInterrupt``/``SystemExit`` mid-poll kills the process first —
+ the local backend spawns into its own process group (``os.setsid``), so
+ an unkilled child would be orphaned to PPID=1 and keep running.
"""
- if bounded_capture:
- try:
- from tools.tool_output_limits import get_max_bytes
-
- capture_limit = get_max_bytes()
- except Exception:
- capture_limit = 50_000
- else:
- # Full fidelity: effectively unbounded collector (single head
- # segment, no eviction) so behavior matches the historical
- # accumulate-everything semantics.
- capture_limit = _UNBOUNDED_CAPTURE_CHARS
- spill_path = None
- if bounded_capture:
- # Foreground terminal path: tee overflow to a spill file so a
- # truncated result is recoverable without re-running (the file
- # only gets created if output actually exceeds the cap).
- try:
- spill_dir = get_hermes_home() / "cache" / "terminal-output"
- spill_path = spill_dir / f"out-{int(time.time())}-{os.getpid()}-{id(proc) & 0xffff:x}.log"
- # Opportunistic cleanup of spills older than 7 days.
- if spill_dir.is_dir():
- cutoff = time.time() - 7 * 86400
- for old in spill_dir.glob("out-*.log"):
- try:
- if old.stat().st_mtime < cutoff:
- old.unlink()
- except OSError:
- pass
- except Exception:
- spill_path = None
- output = _BoundedOutputCollector(capture_limit, spill_path=spill_path)
-
- # Non-blocking drain via select().
- #
- # The old pattern — ``for line in proc.stdout`` — blocks on
- # ``readline()`` until the pipe reaches EOF. When the user's command
- # backgrounds a process (``cmd &``, ``setsid cmd & disown``, etc.),
- # that backgrounded grandchild inherits the write-end of our stdout
- # pipe via ``fork()``. Even after ``bash`` itself exits, the pipe
- # stays open because the grandchild still holds it — so the drain
- # thread never returns and the tool hangs for the full lifetime of
- # the grandchild (issue #8340: users reported indefinite hangs when
- # restarting uvicorn with ``setsid ... & disown``).
- #
- # The fix: select() with a short poll interval, and stop draining
- # shortly after ``bash`` exits even if the pipe hasn't EOF'd yet.
- # Any output the grandchild writes after that point goes to an
- # orphaned pipe (harmless — the kernel reaps it when our end closes).
- #
- # Decoding: we ``os.read()`` raw bytes in fixed-size chunks (4096)
- # so a single multibyte UTF-8 character can split across reads. An
- # incremental decoder buffers partial sequences across chunks, and
- # ``errors="replace"`` mirrors the baseline ``TextIOWrapper`` (which
- # was constructed with ``encoding="utf-8", errors="replace"`` on
- # ``Popen``) so binary or mis-encoded output is preserved with
- # U+FFFD substitution rather than clobbering the whole buffer.
- decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
-
- def _drain_iterable(stream):
- # Fallback path: ``stream`` is not backed by a real OS file
- # descriptor (no usable ``fileno()``). This covers in-memory
- # ProcessHandle adapters that expose stdout as a plain iterator of
- # already-collected output (the legacy ``for line in proc.stdout``
- # contract) rather than a live pipe. Iterate it to EOF. Without
- # this, the drain thread would raise an unhandled exception and die
- # silently, losing all of the process's output.
- try:
- for piece in stream:
- if piece is None:
- continue
- if isinstance(piece, bytes):
- output.append(decoder.decode(piece))
- else:
- output.append(str(piece))
- except Exception:
- pass
- finally:
- try:
- tail = decoder.decode(b"", final=True)
- if tail:
- output.append(tail)
- except Exception:
- pass
-
- def _drain():
- # Resolve a real OS file descriptor up front. Real subprocesses and
- # the SDK ``_ThreadedProcessHandle`` (os.pipe-backed) both return an
- # integer fd here. Mocks / iterator-style stdout streams either lack
- # ``fileno()`` entirely or return a non-integer — in that case fall
- # back to draining the stream as an iterable instead of crashing the
- # thread (issue: 'list_iterator' object has no attribute 'fileno').
- stream = proc.stdout
- if stream is None:
- return
- fileno = getattr(stream, "fileno", None)
- try:
- fd = fileno() if callable(fileno) else None
- except Exception:
- fd = None
- if not isinstance(fd, int) or fd < 0:
- _drain_iterable(stream)
- return
- # select.select does NOT work on pipe fds on Windows (only sockets).
- # Use blocking os.read in a daemon thread instead — safe because
- # EOF arrives promptly when bash exits.
- if os.name == "nt":
- try:
- while True:
- chunk = os.read(fd, 4096)
- if not chunk:
- break
- output.append(decoder.decode(chunk))
- except (ValueError, OSError):
- pass
- finally:
- try:
- tail = decoder.decode(b"", final=True)
- if tail:
- output.append(tail)
- except Exception:
- pass
- return
- idle_after_exit = 0
- try:
- while True:
- try:
- ready, _, _ = select.select([fd], [], [], 0.1)
- except (ValueError, OSError):
- break # fd already closed
- if ready:
- try:
- chunk = os.read(fd, 4096)
- except (ValueError, OSError):
- break
- if not chunk:
- break # true EOF — all writers closed
- output.append(decoder.decode(chunk))
- idle_after_exit = 0
- elif proc.poll() is not None:
- # bash is gone and the pipe was idle for ~100ms. Give
- # it two more cycles to catch any buffered tail, then
- # stop — otherwise we wait forever on a grandchild pipe.
- idle_after_exit += 1
- if idle_after_exit >= 3:
- break
- finally:
- # Flush any bytes buffered mid-sequence. With ``errors="replace"``
- # this emits U+FFFD for any final incomplete sequence rather than
- # raising.
- try:
- tail = decoder.decode(b"", final=True)
- if tail:
- output.append(tail)
- except Exception:
- pass
-
- drain_thread = threading.Thread(target=_drain, daemon=True)
- drain_thread.start()
+ output = _new_output_collector(proc, bounded_capture)
+ drain_thread = _start_drain_thread(proc, output)
deadline = time.monotonic() + timeout
_now = time.monotonic()
- _activity_state = {
- "last_touch": _now,
- "start": _now,
- }
-
- # --- Debug tracing (opt-in via HERMES_DEBUG_INTERRUPT=1) -------------
- # Captures loop entry/exit, interrupt state changes, and periodic
- # heartbeats so we can diagnose "agent never sees the interrupt"
- # reports without reproducing locally.
- _tid = threading.current_thread().ident
- _pid = getattr(proc, "pid", None)
- _iter_count = 0
- _last_heartbeat = _now
- _last_interrupt_state = False
- _cb_was_none = get_activity_callback() is None
- if _DEBUG_INTERRUPT:
- logger.info(
- "[interrupt-debug] _wait_for_process ENTER tid=%s pid=%s "
- "timeout=%ss activity_cb=%s initial_interrupt=%s",
- _tid, _pid, timeout,
- "set" if not _cb_was_none else "MISSING",
- is_interrupted(),
- )
+ _activity_state = {"last_touch": _now, "start": _now}
+ trace = _WaitTrace(proc, timeout, enabled=_DEBUG_INTERRUPT, logger=logger)
+ trace.enter()
+
+ def _kill_and_join():
+ self._kill_process(proc)
+ drain_thread.join(timeout=2)
try:
+ # Adaptive poll: start at 5ms so fast commands return in ~6ms, back
+ # off exponentially toward 200ms so long builds don't pay poll CPU.
_poll_sleep = 0.005
while proc.poll() is None:
- _iter_count += 1
+ trace.iterations += 1
if is_interrupted() or is_thread_interrupted(watch_interrupt_tid):
- if _DEBUG_INTERRUPT:
- logger.info(
- "[interrupt-debug] _wait_for_process INTERRUPT DETECTED "
- "tid=%s pid=%s iter=%d elapsed=%.1fs — killing process group",
- _tid, _pid, _iter_count, time.monotonic() - _activity_state["start"],
- )
- self._kill_process(proc)
- drain_thread.join(timeout=2)
+ trace.interrupted()
+ _kill_and_join()
return self._finalize_wait_result(
- output,
- output.render(suffix="\n[Command interrupted]"),
- 130,
+ output, output.render(suffix="\n[Command interrupted]"), 130
)
if time.monotonic() > deadline:
- if _DEBUG_INTERRUPT:
- logger.info(
- "[interrupt-debug] _wait_for_process TIMEOUT "
- "tid=%s pid=%s iter=%d timeout=%ss",
- _tid, _pid, _iter_count, timeout,
- )
- self._kill_process(proc)
- drain_thread.join(timeout=2)
+ trace.timed_out()
+ _kill_and_join()
timeout_msg = f"\n[Command timed out after {timeout}s]"
- return self._finalize_wait_result(
- output,
- output.render(suffix=timeout_msg).lstrip()
- if output.total_chars == 0
- else output.render(suffix=timeout_msg),
- 124,
- )
- # Periodic activity touch so the gateway knows we're alive
+ rendered = output.render(suffix=timeout_msg)
+ if output.total_chars == 0:
+ rendered = rendered.lstrip()
+ return self._finalize_wait_result(output, rendered, 124)
touch_activity_if_due(_activity_state, "terminal command running")
-
- # Heartbeat every ~30s: proves the loop is alive and reports
- # the activity-callback state (thread-local, can get clobbered
- # by nested tool calls or executor thread reuse).
- if _DEBUG_INTERRUPT and time.monotonic() - _last_heartbeat >= 30.0:
- _cb_now_none = get_activity_callback() is None
- logger.info(
- "[interrupt-debug] _wait_for_process HEARTBEAT "
- "tid=%s pid=%s iter=%d elapsed=%.0fs "
- "interrupt=%s activity_cb=%s%s",
- _tid, _pid, _iter_count,
- time.monotonic() - _activity_state["start"],
- is_interrupted(),
- "set" if not _cb_now_none else "MISSING",
- " (LOST during run)" if _cb_now_none and not _cb_was_none else "",
- )
- _last_heartbeat = time.monotonic()
- _cb_was_none = _cb_now_none
-
- # Adaptive poll: start at 5ms so fast commands (echo, pwd,
- # date, cat short files) return in ~6ms instead of being
- # stuck waiting for the next 200ms tick. Back off
- # exponentially toward 200ms so long-running commands
- # (builds, tests, sleeps) don't pay measurable CPU in the
- # poll loop. For an `echo` this saves ~195ms per tool call;
- # for a 10s build the steady-state poll rate is identical
- # to the old behavior.
+ trace.heartbeat()
time.sleep(_poll_sleep)
if _poll_sleep < 0.2:
_poll_sleep = min(_poll_sleep * 1.5, 0.2)
except (KeyboardInterrupt, SystemExit):
- # Signal arrived (SIGTERM/SIGHUP/SIGINT) or sys.exit() was called
- # while we were polling. The local backend spawns subprocesses
- # with os.setsid, which puts them in their own process group — so
- # if we let the interrupt propagate without killing the child,
- # python exits and the child is reparented to init (PPID=1) and
- # keeps running as an orphan. Killing the process group here
- # guarantees the tool's side effects stop when the agent stops.
- if _DEBUG_INTERRUPT:
- logger.info(
- "[interrupt-debug] _wait_for_process EXCEPTION_EXIT "
- "tid=%s pid=%s iter=%d elapsed=%.1fs — killing subprocess group before re-raise",
- _tid, _pid, _iter_count,
- time.monotonic() - _activity_state["start"],
- )
+ trace.exception_exit()
try:
- self._kill_process(proc)
- drain_thread.join(timeout=2)
+ _kill_and_join()
except Exception:
pass # cleanup is best-effort
raise
- # Drain thread now exits promptly after bash does (~300ms idle
- # check). A short join is enough; a long one would be a bug since
- # it means the non-blocking loop itself stopped cooperating.
+ # The drain thread exits promptly after bash does (~300ms idle check);
+ # a long join here would itself indicate a bug in the drain loop.
drain_thread.join(timeout=2)
-
try:
proc.stdout.close()
except Exception:
pass
+ trace.natural_exit(proc.returncode)
- if _DEBUG_INTERRUPT:
- logger.info(
- "[interrupt-debug] _wait_for_process EXIT (natural) "
- "tid=%s pid=%s iter=%d elapsed=%.1fs returncode=%s",
- _tid, _pid, _iter_count,
- time.monotonic() - _activity_state["start"],
- proc.returncode,
- )
-
- # Join the stdin writer thread before reading its error list: a child
- # that exits without reading stdin can otherwise race ahead of a
- # recorded encode failure, silently dropping it. The thread cannot
- # block long after child exit (write raises BrokenPipeError once the
- # pipe closes); the timeout is a pure safety net.
+ # Join the stdin writer before reading its error list: a child that
+ # exits without reading stdin can otherwise race ahead of a recorded
+ # encode failure. The timeout is a pure safety net (write raises
+ # BrokenPipeError once the pipe closes).
stdin_thread = getattr(proc, "_hermes_stdin_thread", None)
if stdin_thread is not None:
stdin_thread.join(timeout=5)
@@ -1352,16 +475,7 @@ class BaseEnvironment(ABC):
result["output"] = rendered + f"\n[stdin write failed: {err}]"
return result
- @staticmethod
- def _finalize_wait_result(collector: "_BoundedOutputCollector",
- rendered: str, returncode: int | None) -> dict:
- """Assemble a wait result, attaching spill metadata when overflow occurred."""
- result = {"output": rendered, "returncode": returncode}
- spill = collector.close_spill()
- if spill:
- result["output_total_chars"] = collector.total_chars
- result["full_output_path"] = spill
- return result
+ _finalize_wait_result = staticmethod(_finalize_wait_result)
def _kill_process(self, proc: ProcessHandle):
"""Terminate a process. Subclasses may override for process-group kill."""
@@ -1379,63 +493,33 @@ class BaseEnvironment(ABC):
self._extract_cwd_from_output(result)
def _extract_cwd_from_output(self, result: dict):
- """Parse the __HERMES_CWD_{session}__ marker from stdout output.
-
- Updates self.cwd and strips the marker from result["output"].
- Used by remote backends (Docker, SSH, Modal, Daytona, Singularity).
-
- Sets ``result["cwd_observed"]`` when the marker yielded a directory for
- THIS command. The wrapper prints the marker after the command returns,
- so a killed / timed-out command never emits one and ``self.cwd`` keeps
- whatever the previous command left there. That environment is shared by
- every session, so callers must not attribute an unobserved cwd to the
- session that ran this command (see terminal_tool's session-cwd record).
+ """Parse the ``__HERMES_CWD_{session}__`` marker from ``result["output"]``.
+
+ Updates ``self.cwd`` and strips the marker line. Sets
+ ``result["cwd_observed"]`` (and ``result["cwd"]``) only when THIS command
+ emitted a marker: the wrapper prints it after the command returns, so a
+ killed/timed-out command emits none and ``self.cwd`` keeps the previous
+ value. The environment is shared across sessions, so callers must not
+ attribute an unobserved cwd to this session, and concurrent callers
+ must read ``result["cwd"]`` rather than ``self.cwd``.
"""
- output = result.get("output", "")
- marker = self._cwd_marker
- last = output.rfind(marker)
- if last == -1:
+ split = _split_cwd_marker(result.get("output", ""), self._cwd_marker)
+ if split is None:
return
-
- # Find the opening marker before this closing one
- search_start = max(0, last - 4096) # CWD path won't be >4KB
- first = output.rfind(marker, search_start, last)
- if first == -1 or first == last:
- return
-
- cwd_path = output[first + len(marker) : last].strip()
+ cwd_path, cleaned = split
if cwd_path:
self.cwd = cwd_path
result["cwd_observed"] = True
- # Keep the observation on this command's result as well as on the
- # shared environment. Concurrent callers must not read self.cwd
- # after another command has already updated it.
result["cwd"] = cwd_path
-
- # Strip the marker line AND the \n we injected before it.
- # The wrapper emits: printf '\n__MARKER__%s__MARKER__\n'
- # So the output looks like: <cmd output>\n__MARKER__path__MARKER__\n
- # We want to remove everything from the injected \n onwards.
- line_start = output.rfind("\n", 0, first)
- if line_start == -1:
- line_start = first
- line_end = output.find("\n", last + len(marker))
- line_end = line_end + 1 if line_end != -1 else len(output)
-
- result["output"] = output[:line_start] + output[line_end:]
+ result["output"] = cleaned
# ------------------------------------------------------------------
# Hooks
# ------------------------------------------------------------------
def _before_execute(self) -> None:
- """Hook called before each command execution.
-
- Remote backends (SSH, Modal, Daytona) override this to trigger
- their FileSyncManager. Bind-mount backends (Docker, Singularity)
- and Local don't need file sync — the host filesystem is directly
- visible inside the container/process.
- """
+ """Hook before each command. Remote backends (SSH, Modal, Daytona)
+ trigger their FileSyncManager here; bind-mount backends and Local don't."""
pass
# ------------------------------------------------------------------
@@ -1454,54 +538,44 @@ class BaseEnvironment(ABC):
) -> dict:
"""Execute a command, return {"output": str, "returncode": int}.
- ``bounded_capture=True`` caps stdout/stderr retention at
- ``tool_output.max_bytes`` WHILE the stream is drained (head/tail
- window) instead of holding the full output in memory (#64435).
- It must only be set by callers whose output is destined for the
- model/tool payload (the foreground terminal tool). Internal
- full-fidelity consumers — file operations ``cat`` reads that feed
- the patch engine, code-execution RPC reads, log reads — MUST leave
- it False: truncating those corrupts data, not just display.
-
- The wait is bounded by ``agent.deadline.run_bounded_sync`` so a
- wedged poll loop cannot hang past ``timeout`` and silently disable
- every asyncio timer in the process (#94285).
+ ``bounded_capture=True`` caps retention at ``tool_output.max_bytes``
+ WHILE draining; only the foreground terminal tool may set it — internal
+ full-fidelity consumers (file-op ``cat`` reads feeding the patch
+ engine, RPC reads, log reads) MUST leave it False or data is corrupted.
+ The wait is bounded by ``agent.deadline.run_bounded_sync`` so a wedged
+ poll loop cannot hang past ``timeout`` and silently disable every
+ asyncio timer in the process.
"""
self._before_execute()
exec_command, sudo_stdin = self._prepare_command(command)
- # Guard against the `A && B &` subshell-wait trap by default.
- # Some callers (spawn_via_env) already produce shell-safe wrappers and
- # pass rewrite_compound_background=False.
+ # Guard against the `A && B &` subshell-wait trap by default; callers
+ # that already produce shell-safe wrappers (spawn_via_env) pass False.
if rewrite_compound_background:
from tools.terminal_tool import _rewrite_compound_background
exec_command = _rewrite_compound_background(exec_command)
effective_timeout = timeout or self.timeout
effective_cwd = cwd or self.cwd
- # Merge sudo stdin with caller stdin
- if sudo_stdin is not None and stdin_data is not None:
- effective_stdin = sudo_stdin + stdin_data
- elif sudo_stdin is not None:
- effective_stdin = sudo_stdin
+ # Merge sudo stdin with caller stdin.
+ if sudo_stdin is not None:
+ effective_stdin = sudo_stdin + (stdin_data or "")
else:
effective_stdin = stdin_data
- # Embed stdin as heredoc for backends that need it
if effective_stdin and self._stdin_mode == "heredoc":
exec_command = self._embed_stdin_heredoc(exec_command, effective_stdin)
effective_stdin = None
wrapped = self._wrap_command(exec_command, effective_cwd)
- # Use login shell if snapshot failed (so user's profile still loads),
- # unless login itself is broken — then non-login is the only path.
+ # Login shell if the snapshot failed (so the user's profile still
+ # loads), unless login itself is broken — then non-login is the only path.
login = not self._snapshot_ready and not self._prefer_nonlogin
parent_tid = threading.current_thread().ident
- # Activity callback is thread-local (see set_activity_callback). The
- # wait runs on the deadline worker, so copy it across or long
- # commands look idle to cron/gateway heartbeats.
+ # The activity callback is thread-local and the wait runs on the
+ # deadline worker, so copy it across or long commands look idle.
parent_activity_cb = get_activity_callback()
proc_holder: list = []
@@ -1522,43 +596,20 @@ class BaseEnvironment(ABC):
def _on_timeout() -> None:
if not proc_holder:
return
- spawned = proc_holder[0]
- try:
- self._kill_process(spawned)
- except Exception:
- logger.debug(
- "terminal wait-bound kill_process failed", exc_info=True
- )
- pid = getattr(spawned, "pid", None)
- if not pid:
- return
- try:
- from agent.deadline import kill_process_tree
-
- kill_process_tree(int(pid))
- except Exception:
- logger.debug(
- "terminal wait-bound kill_process_tree failed", exc_info=True
- )
-
- # Hard wall-clock backstop (#94285): ``_wait_for_process`` already
- # polls to ``effective_timeout``, but that loop runs on the tool
- # thread. If that thread is the event-loop thread — or the wait
- # itself never returns (Windows pipe/poll hang) — every asyncio
- # timer in the process is silently disabled, including the 420s
- # sequential-tool deadline and the cron inactivity monitor.
- # ``run_bounded_sync`` drives expiry from a daemon worker +
- # ``Event.wait`` so a blocked loop cannot disable it. Grace lets
- # the inner poll return the partial-output 124 path on a healthy
- # timeout; the outer bound only fires when that loop is wedged.
+ self._kill_spawned_tree(proc_holder[0])
+
+ # Hard wall-clock backstop: ``_wait_for_process`` polls to
+ # ``effective_timeout`` on the tool thread; if that is the event-loop
+ # thread, or the wait never returns (Windows pipe/poll hang), every
+ # asyncio timer is silently disabled. ``run_bounded_sync`` drives expiry
+ # from a daemon worker + ``Event.wait`` so a blocked loop cannot disable
+ # it; the grace lets the inner loop return the partial-output 124 path.
from agent.deadline import run_bounded_sync
try:
bound_s = float(effective_timeout) + _EXECUTE_WAIT_BOUND_GRACE_S
except (TypeError, ValueError):
- # Defensive: a non-numeric timeout must not silently disable the
- # backstop (that would recreate the unbounded wait this bound
- # exists to prevent). Fall back to the module's 120s wait default.
+ # A non-numeric timeout must not disable the backstop; use the 120s default.
bound_s = 120.0 + _EXECUTE_WAIT_BOUND_GRACE_S
try:
@@ -1581,6 +632,22 @@ class BaseEnvironment(ABC):
return result
+ def _kill_spawned_tree(self, spawned) -> None:
+ """Best-effort kill of a wedged spawned process and its tree (backstop path)."""
+ try:
+ self._kill_process(spawned)
+ except Exception:
+ logger.debug("terminal wait-bound kill_process failed", exc_info=True)
+ pid = getattr(spawned, "pid", None)
+ if not pid:
+ return
+ try:
+ from agent.deadline import kill_process_tree
+
+ kill_process_tree(int(pid))
+ except Exception:
+ logger.debug("terminal wait-bound kill_process_tree failed", exc_info=True)
+
# ------------------------------------------------------------------
# Shared helpers
# ------------------------------------------------------------------
diff --git a/tools/environments/base_output.py b/tools/environments/base_output.py
new file mode 100644
index 00000000000..8d71c1c6aed
--- /dev/null
+++ b/tools/environments/base_output.py
@@ -0,0 +1,478 @@
+"""Process-handle plumbing for ``tools.environments.base``.
+
+Bounded output capture (head/tail window + disk spill), the ``ProcessHandle``
+duck type, the SDK adapter ``_ThreadedProcessHandle``, stdin piping, and the
+stdout drain thread used by ``BaseEnvironment._wait_for_process``.
+"""
+
+import codecs
+import os
+import select
+import subprocess
+import threading
+import time
+from collections import deque
+from pathlib import Path
+from typing import IO, Callable, Protocol
+
+from hermes_constants import get_hermes_home
+from hermes_cli._subprocess_compat import windows_hide_flags
+
+# Sentinel capacity for full-fidelity capture: large enough that the collector
+# never evicts, so bounded and unbounded modes share one code path.
+_UNBOUNDED_CAPTURE_CHARS = 2**63 - 1
+
+_SPILL_MAX_AGE_S = 7 * 86400
+
+
+class _BoundedOutputCollector:
+ """Retain a bounded 40/60 head-tail window of streamed text.
+
+ When ``spill_path`` is set, the FULL stream is also teed to that file once
+ eviction begins (up to ``_SPILL_CAP_CHARS``) so a truncated foreground
+ result is recoverable without re-running. Memory stays bounded either way.
+ """
+
+ # Hard ceiling on spill file size; protects disk from runaway output.
+ _SPILL_CAP_CHARS = 5_000_000
+
+ def __init__(self, max_chars: int, spill_path: "Path | None" = None):
+ self.max_chars = max(1, int(max_chars))
+ self._head_limit = int(self.max_chars * 0.4)
+ self._tail_limit = self.max_chars - self._head_limit
+ self._head: list[str] = []
+ self._tail: deque[str] = deque()
+ self._head_chars = 0
+ self._tail_chars = 0
+ self._total_chars = 0
+ self._lock = threading.Lock()
+ self._spill_path = spill_path
+ self._spill_fh: IO[str] | None = None
+ self._spill_chars = 0
+ self._spill_capped = False
+
+ def _maybe_spill(self, text: str) -> None:
+ """Tee ``text`` to the spill file (opened lazily on first overflow)."""
+ if self._spill_path is None or self._spill_capped:
+ return
+ try:
+ if self._spill_fh is None:
+ from tools.spill_safety import ensure_spill_dir, open_exclusive
+
+ # Raw pre-redaction output: private perms + symlink-refusing
+ # exclusive create (a planted link must fail, never redirect).
+ ensure_spill_dir(self._spill_path.parent, private=True)
+ self._spill_fh = open_exclusive(
+ self._spill_path, private=True, errors="replace"
+ )
+ # Backfill what's retained so the file holds the stream from byte 0.
+ backlog = "".join(self._head) + "".join(self._tail)
+ self._spill_fh.write(backlog)
+ self._spill_chars = len(backlog)
+ budget = self._SPILL_CAP_CHARS - self._spill_chars
+ if budget <= 0 or len(text) > budget:
+ self._spill_fh.write(text[:max(0, budget)])
+ self._spill_fh.write("\n... [spill capped at 5,000,000 chars] ...\n")
+ self._spill_capped = True
+ else:
+ self._spill_fh.write(text)
+ self._spill_chars += len(text)
+ except OSError:
+ # Disk trouble must never break command execution.
+ self._spill_capped = True
+
+ def close_spill(self) -> "str | None":
+ """Close the spill file and return its path if it was used."""
+ with self._lock:
+ if self._spill_fh is None:
+ return None
+ try:
+ self._spill_fh.close()
+ except OSError:
+ pass
+ self._spill_fh = None
+ return str(self._spill_path)
+
+ @property
+ def buffered_chars(self) -> int:
+ with self._lock:
+ return self._head_chars + self._tail_chars
+
+ @property
+ def total_chars(self) -> int:
+ with self._lock:
+ return self._total_chars
+
+ def append(self, text: str) -> None:
+ if not text:
+ return
+ with self._lock:
+ text_len = len(text)
+ # Spill tee activates at the first overflow, then mirrors every chunk.
+ if self._spill_path is not None and (
+ self._spill_fh is not None
+ or self._total_chars + text_len > self.max_chars
+ ):
+ self._maybe_spill(text)
+ self._total_chars += text_len
+ start = 0
+
+ if self._head_chars < self._head_limit:
+ take = min(self._head_limit - self._head_chars, text_len)
+ if take:
+ self._head.append(text[:take])
+ self._head_chars += take
+ start = take
+
+ remaining = text_len - start
+ if remaining <= 0 or self._tail_limit <= 0:
+ return
+ if remaining >= self._tail_limit:
+ self._tail.clear()
+ self._tail.append(text[-self._tail_limit :])
+ self._tail_chars = self._tail_limit
+ return
+
+ chunk = text[start:]
+ self._tail.append(chunk)
+ self._tail_chars += len(chunk)
+ while self._tail_chars > self._tail_limit:
+ excess = self._tail_chars - self._tail_limit
+ first = self._tail[0]
+ if len(first) <= excess:
+ self._tail.popleft()
+ self._tail_chars -= len(first)
+ else:
+ self._tail[0] = first[excess:]
+ self._tail_chars -= excess
+
+ def render(self, *, suffix: str = "") -> str:
+ """Render within ``max_chars``, preserving a required status suffix."""
+ with self._lock:
+ if len(suffix) >= self.max_chars:
+ return suffix[-self.max_chars :]
+
+ head = "".join(self._head)
+ tail = "".join(self._tail)
+ available = self.max_chars - len(suffix)
+ if self._total_chars <= available:
+ return head + tail + suffix
+
+ # The notice length depends on the omitted count, which depends on
+ # the notice length; iterate to a fixed point (converges quickly).
+ notice = ""
+ for _ in range(4):
+ content_budget = max(0, available - len(notice))
+ head_chars = int(content_budget * 0.4)
+ tail_chars = content_budget - head_chars
+ omitted = max(0, self._total_chars - head_chars - tail_chars)
+ updated = (
+ f"\n\n... [OUTPUT TRUNCATED - {omitted:,} chars omitted "
+ f"out of {self._total_chars:,} total] ...\n\n"
+ )
+ if updated == notice:
+ break
+ notice = updated
+
+ content_budget = max(0, available - len(notice))
+ head_chars = int(content_budget * 0.4)
+ tail_chars = content_budget - head_chars
+ rendered_tail = tail[-tail_chars:] if tail_chars else ""
+ return head[:head_chars] + notice[:available] + rendered_tail + suffix
+
+
+def _new_output_collector(proc, bounded_capture: bool) -> _BoundedOutputCollector:
+ """Build the collector for one ``_wait_for_process`` call.
+
+ ``bounded_capture`` (foreground terminal path only) caps retention at
+ ``tool_output.max_bytes`` and tees overflow to a spill file under
+ ``$HERMES_HOME/cache/terminal-output`` (created only on actual overflow;
+ spills older than 7 days are pruned opportunistically). Otherwise the
+ collector is effectively unbounded so internal consumers (file-op ``cat``
+ reads, RPC reads) keep full-fidelity output.
+ """
+ if not bounded_capture:
+ return _BoundedOutputCollector(_UNBOUNDED_CAPTURE_CHARS)
+ try:
+ from tools.tool_output_limits import get_max_bytes
+
+ capture_limit = get_max_bytes()
+ except Exception:
+ capture_limit = 50_000
+ spill_path = None
+ try:
+ spill_dir = get_hermes_home() / "cache" / "terminal-output"
+ spill_path = spill_dir / f"out-{int(time.time())}-{os.getpid()}-{id(proc) & 0xffff:x}.log"
+ if spill_dir.is_dir():
+ cutoff = time.time() - _SPILL_MAX_AGE_S
+ for old in spill_dir.glob("out-*.log"):
+ try:
+ if old.stat().st_mtime < cutoff:
+ old.unlink()
+ except OSError:
+ pass
+ except Exception:
+ spill_path = None
+ return _BoundedOutputCollector(capture_limit, spill_path=spill_path)
+
+
+def _finalize_wait_result(
+ collector: _BoundedOutputCollector, rendered: str, returncode: int | None
+) -> dict:
+ """Assemble a wait result, attaching spill metadata when overflow occurred."""
+ result = {"output": rendered, "returncode": returncode}
+ spill = collector.close_spill()
+ if spill:
+ result["output_total_chars"] = collector.total_chars
+ result["full_output_path"] = spill
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Stdin / spawn helpers
+# ---------------------------------------------------------------------------
+
+
+def _pipe_stdin(proc: subprocess.Popen, data: str) -> None:
+ """Write *data* to proc.stdin on a daemon thread to avoid pipe-buffer deadlocks.
+
+ Writes go through ``proc.stdin.buffer`` as UTF-8 bytes we encode ourselves:
+ Windows text-mode stdin would translate ``\\n`` -> ``\\r\\n`` and corrupt
+ every write_file/patch payload (byte-identical on POSIX). Encoding uses
+ ``surrogateescape`` (exact inverse of the read-side decode). Surrogates
+ outside U+DC80-U+DCFF raise; the error is recorded on
+ ``proc._hermes_stdin_errors`` and stdin is still closed in ``finally`` so
+ the child sees EOF instead of hanging. ``_wait_for_process`` surfaces the
+ recorded error as ``stdin_error``.
+ """
+
+ errors: list[BaseException] = []
+ proc._hermes_stdin_errors = errors
+
+ def _write():
+ if proc.stdin is None:
+ errors.append(RuntimeError("process stdin unavailable"))
+ return
+ # Resolve the target BEFORE encoding: a failed encode must still
+ # reach the finally-close, or the child hangs on EOF forever.
+ target = getattr(proc.stdin, "buffer", proc.stdin)
+ try:
+ raw = data.encode("utf-8", "surrogateescape") if isinstance(data, str) else data
+ written = target.write(raw)
+ if written != len(raw):
+ # A short write from a buffered writer is a real failure.
+ raise RuntimeError(f"short stdin write: {written} of {len(raw)} bytes")
+ except (BrokenPipeError, OSError):
+ pass # child closed stdin early — normal
+ except Exception as exc:
+ # Only reachable with out-of-range surrogates (e.g. literal U+D800).
+ errors.append(exc)
+ finally:
+ try:
+ target.close()
+ except Exception:
+ pass
+
+ thread = threading.Thread(target=_write, daemon=True)
+ proc._hermes_stdin_thread = thread
+ thread.start()
+
+
+def _popen_bash(
+ cmd: list[str], stdin_data: str | None = None, **kwargs
+) -> subprocess.Popen:
+ """Spawn a subprocess with standard stdout/stderr/stdin setup.
+
+ If *stdin_data* is provided, writes it asynchronously via :func:`_pipe_stdin`.
+ Backends with special Popen needs (e.g. local's ``preexec_fn``) can bypass
+ this and call :func:`_pipe_stdin` directly.
+ """
+ kwargs.setdefault("creationflags", windows_hide_flags())
+ proc = subprocess.Popen(
+ cmd,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ stdin=subprocess.PIPE if stdin_data is not None else subprocess.DEVNULL,
+ text=True, encoding="utf-8", errors="replace",
+ **kwargs,
+ )
+ if stdin_data is not None:
+ _pipe_stdin(proc, stdin_data)
+ return proc
+
+
+# ---------------------------------------------------------------------------
+# ProcessHandle protocol
+# ---------------------------------------------------------------------------
+
+
+class ProcessHandle(Protocol):
+ """Duck type that every backend's _run_bash() must return.
+
+ subprocess.Popen satisfies this natively. SDK backends (Modal, Daytona)
+ return _ThreadedProcessHandle which adapts their blocking calls.
+ """
+
+ def poll(self) -> int | None: ...
+ def kill(self) -> None: ...
+ def wait(self, timeout: float | None = None) -> int: ...
+
+ @property
+ def stdout(self) -> IO[str] | None: ...
+
+ @property
+ def returncode(self) -> int | None: ...
+
+
+class _ThreadedProcessHandle:
+ """Adapter for SDK backends (Modal, Daytona) that have no real subprocess.
+
+ Wraps a blocking ``exec_fn() -> (output_str, exit_code)`` in a background
+ thread and exposes a ProcessHandle-compatible interface. An optional
+ ``cancel_fn`` is invoked on ``kill()`` for backend-specific cancellation
+ (e.g. Modal sandbox.terminate, Daytona sandbox.stop).
+ """
+
+ def __init__(
+ self,
+ exec_fn: Callable[[], tuple[str, int]],
+ cancel_fn: Callable[[], None] | None = None,
+ ):
+ self._cancel_fn = cancel_fn
+ self._done = threading.Event()
+ self._returncode: int | None = None
+ self._error: Exception | None = None
+
+ # Pipe for stdout — the drain thread in _wait_for_process reads the read end.
+ read_fd, write_fd = os.pipe()
+ self._stdout = os.fdopen(read_fd, "r", encoding="utf-8", errors="replace")
+ self._write_fd = write_fd
+
+ def _worker():
+ try:
+ output, exit_code = exec_fn()
+ self._returncode = exit_code
+ try:
+ os.write(self._write_fd, output.encode("utf-8", errors="replace"))
+ except OSError:
+ pass
+ except Exception as exc:
+ self._error = exc
+ self._returncode = 1
+ finally:
+ try:
+ os.close(self._write_fd)
+ except OSError:
+ pass
+ self._done.set()
+
+ t = threading.Thread(target=_worker, daemon=True)
+ t.start()
+
+ @property
+ def stdout(self):
+ return self._stdout
+
+ @property
+ def returncode(self) -> int | None:
+ return self._returncode
+
+ def poll(self) -> int | None:
+ return self._returncode if self._done.is_set() else None
+
+ def kill(self):
+ if self._cancel_fn:
+ try:
+ self._cancel_fn()
+ except Exception:
+ pass
+
+ def wait(self, timeout: float | None = None) -> int:
+ self._done.wait(timeout=timeout)
+ return self._returncode
+
+
+# ---------------------------------------------------------------------------
+# Stdout drain thread
+# ---------------------------------------------------------------------------
+
+
+def _drain_stdout(proc: ProcessHandle, output: _BoundedOutputCollector) -> None:
+ """Drain ``proc.stdout`` into *output* until EOF or shortly after exit.
+
+ ``for line in proc.stdout`` would block on ``readline()`` until EOF, and a
+ backgrounded grandchild (``cmd &``, ``setsid cmd & disown``) inherits the
+ pipe's write end — so the tool would hang for the grandchild's lifetime.
+ Instead we ``select()`` with a short poll and stop ~300ms after bash exits
+ even if the pipe has not EOF'd (later grandchild output goes to an orphaned
+ pipe, harmless). Raw 4096-byte ``os.read`` chunks can split a multibyte
+ UTF-8 sequence, so an incremental decoder with ``errors="replace"`` (same
+ as the Popen TextIOWrapper) buffers partial sequences across chunks.
+
+ Streams without a real integer ``fileno()`` (mocks, iterator-style stdout
+ from in-memory adapters) are iterated to EOF instead — otherwise the thread
+ would die silently and lose all output. ``select()`` does not work on pipe
+ fds on Windows, so a blocking ``os.read`` loop is used there (EOF arrives
+ promptly when bash exits).
+ """
+ stream = proc.stdout
+ if stream is None:
+ return
+ decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
+ fileno = getattr(stream, "fileno", None)
+ try:
+ fd = fileno() if callable(fileno) else None
+ except Exception:
+ fd = None
+ try:
+ if not isinstance(fd, int) or fd < 0:
+ for piece in stream:
+ if piece is not None:
+ output.append(decoder.decode(piece) if isinstance(piece, bytes) else str(piece))
+ elif os.name == "nt":
+ while chunk := os.read(fd, 4096):
+ output.append(decoder.decode(chunk))
+ else:
+ _drain_fd_select(proc, fd, output, decoder)
+ except Exception:
+ pass # closed fd / broken stream: keep what was captured
+ finally:
+ # With errors="replace" this emits U+FFFD for a final incomplete sequence.
+ try:
+ tail = decoder.decode(b"", final=True)
+ if tail:
+ output.append(tail)
+ except Exception:
+ pass
+
+
+def _drain_fd_select(proc, fd: int, output: _BoundedOutputCollector, decoder) -> None:
+ """POSIX drain: select() poll, stopping ~300ms after bash exits with the pipe idle."""
+ idle_after_exit = 0
+ while True:
+ try:
+ ready, _, _ = select.select([fd], [], [], 0.1)
+ except (ValueError, OSError):
+ return # fd already closed
+ if ready:
+ try:
+ chunk = os.read(fd, 4096)
+ except (ValueError, OSError):
+ return
+ if not chunk:
+ return # true EOF — all writers closed
+ output.append(decoder.decode(chunk))
+ idle_after_exit = 0
+ elif proc.poll() is not None:
+ # bash is gone and the pipe was idle ~100ms; allow two more cycles
+ # for a buffered tail, then stop (a grandchild may hold the pipe).
+ idle_after_exit += 1
+ if idle_after_exit >= 3:
+ return
+
+
+def _start_drain_thread(proc: ProcessHandle, output: _BoundedOutputCollector) -> threading.Thread:
+ """Start the daemon thread running :func:`_drain_stdout`."""
+ thread = threading.Thread(target=_drain_stdout, args=(proc, output), daemon=True)
+ thread.start()
+ return thread
diff --git a/tools/environments/base_session_env.py b/tools/environments/base_session_env.py
new file mode 100644
index 00000000000..24abb56c58f
--- /dev/null
+++ b/tools/environments/base_session_env.py
@@ -0,0 +1,212 @@
+"""Bash session-snapshot scripting for ``tools.environments.base``.
+
+Pure string builders: the CWD marker, the ``export -p`` dump that strips
+per-session vars, the ``init_session`` bootstrap, and the per-command wrapper.
+No module state lives here; ``BaseEnvironment`` supplies quoting hooks.
+"""
+
+import re
+import shlex
+from typing import Iterable
+
+# Bridged per-session vars (gateway.session_context._VAR_MAP) are injected fresh
+# onto every command's process env and must NEVER persist in the shared bash
+# snapshot: one long-lived backend serves many sessions, so a snapshot carrying
+# the FIRST session's HERMES_SESSION_ID would make every LATER session source a
+# foreign identity, overriding the correct per-command Popen env. Every bridged
+# name starts with one of these prefixes (or is HERMES_UI_SESSION_ID); unit
+# tests use this regex as the Python-side contract for the exclusion set.
+_SNAPSHOT_EXCLUDED_ENV_REGEX = (
+ "^declare -x (HERMES_SESSION_|HERMES_UI_SESSION_ID|HERMES_CRON_AUTO_DELIVER_|"
+ "HERMES_CRON_SESSION|HERMES_BROWSER_CONTROL_)"
+)
+_SHELL_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+
+# mktemp template suffix + the shell variable holding the allocated temp path.
+_SNAP_TMP_SUFFIX = ".tmp.XXXXXXXXXX"
+_SNAP_TMP = '"$__hermes_snap_tmp"'
+
+
+def _cwd_marker(session_id: str) -> str:
+ return f"__HERMES_CWD_{session_id}__"
+
+
+def _cwd_marker_printf(marker: str) -> str:
+ """Emit the CWD marker on its own line (leading ``\\n`` guards against a
+ command whose output lacks a trailing newline; ``_split_cwd_marker`` strips it)."""
+ return f"printf '\\n{marker}%s{marker}\\n' \"$(pwd -P)\""
+
+
+def _export_dump_excluding_session_vars(
+ tmp_path: str,
+ excluded_names: Iterable[str] = (),
+) -> str:
+ """Shell snippet dumping ``export -p`` to *tmp_path* minus the per-session
+ bridged vars (see ``_SNAPSHOT_EXCLUDED_ENV_REGEX``) and *excluded_names*.
+
+ The vars are ``unset`` in a subshell BEFORE ``export -p``. A line-based
+ ``grep -vE`` filter is unsafe: bash 3.2 prints a value containing a newline
+ as a multi-line ``declare -x`` block, so continuation lines (attacker text
+ smuggled via e.g. HERMES_SESSION_CHAT_NAME) would survive into the snapshot
+ and execute on the next ``source``. ``|| true`` keeps the success contract.
+
+ The dump is a brace group with the redirection on the group: *tmp_path* is
+ usually a shell-variable expansion, and a redirect attached to a pipeline
+ segment would expand it inside that segment's subshell, inconsistently with
+ the parent that expands the follow-up ``mv``.
+ """
+ # ${!PREFIX*} is bash 3.2+ name-prefix expansion; empty matches are ignored
+ # under 2>/dev/null. Caller names are quoted so malformed config can never
+ # become shell syntax (valid names stay unquoted by shlex.quote()).
+ safe_names = {name for name in excluded_names if isinstance(name, str) and name}
+ extra_unset = " ".join(shlex.quote(name) for name in sorted(safe_names))
+ if extra_unset:
+ extra_unset = f" {extra_unset}"
+ return (
+ "{ ( "
+ "unset ${!HERMES_SESSION_*} ${!HERMES_CRON_AUTO_DELIVER_*} "
+ "${!HERMES_BROWSER_CONTROL_*} "
+ # AI_AGENT / HERMES_AGENT are per-command attribution markers re-exported
+ # by every wrapper with ${VAR:-default} semantics; persisting them would
+ # let the FIRST command's value override a later outer-harness value.
+ "AI_AGENT HERMES_AGENT "
+ f"HERMES_UI_SESSION_ID{extra_unset} 2>/dev/null; "
+ "export -p; "
+ ") || true; } "
+ f"> {tmp_path}"
+ )
+
+
+def _snapshot_bootstrap_script(
+ *,
+ quoted_cwd: str,
+ quoted_snap: str,
+ snap_tmp_template: str,
+ excluded_names: Iterable[str],
+ cwd_marker: str,
+) -> str:
+ """Login-shell bootstrap that captures env/functions/aliases into the snapshot.
+
+ Atomic publish: assemble in a ``mktemp`` file, then ``mv`` over the final
+ path so a concurrent ``source`` never reads a half-written snapshot. The
+ temp name must be unique per concurrent writer: ``$$`` is the parent PID in
+ ``&``-launched subshells and macOS bash 3.2 lacks ``$BASHPID``, so only
+ ``mktemp`` is portable. Functions are filtered by NAME via ``declare -F``
+ (a line-based ``declare -f | grep -v`` strips the header and leaves an
+ orphaned body that breaks every sourced command); the non-empty guard
+ matters because bare ``declare -f`` dumps ALL functions. The trailing
+ ``cd`` restores the configured cwd after profile scripts (e.g. ``cd ~``)
+ so ``pwd -P`` reports terminal.cwd, not the profile's directory.
+ """
+ return (
+ "umask 077\n"
+ f"__hermes_snap_tmp=$(mktemp {snap_tmp_template}) || exit 1\n"
+ f"{_export_dump_excluding_session_vars(_SNAP_TMP, excluded_names)}\n"
+ "__hermes_fns=$(declare -F | awk '{print $3}' | grep -vE '^_[^_]') || true\n"
+ f"[ -n \"$__hermes_fns\" ] && declare -f $__hermes_fns >> {_SNAP_TMP} 2>/dev/null || true\n"
+ f"alias -p >> {_SNAP_TMP}\n"
+ f"echo 'shopt -s expand_aliases' >> {_SNAP_TMP}\n"
+ f"echo 'set +e' >> {_SNAP_TMP}\n"
+ f"echo 'set +u' >> {_SNAP_TMP}\n"
+ # Publish only if assembly succeeded; otherwise drop the partial temp.
+ f"mv -f {_SNAP_TMP} {quoted_snap} || rm -f {_SNAP_TMP}\n"
+ f"builtin cd -- {quoted_cwd} 2>/dev/null || true\n"
+ f"{_cwd_marker_printf(cwd_marker)}\n"
+ )
+
+
+def _passthrough_save_restore(names: Iterable[str]) -> tuple[list[str], list[str]]:
+ """Shell lines that save profile-scoped passthrough vars before the snapshot
+ is sourced and restore (or unset) them afterwards.
+
+ A shared snapshot may hold the previous profile's value. Values stay in
+ environment memory and never enter the command string, so secrets are not
+ exposed through process arguments or logs.
+ """
+ save: list[str] = []
+ restore: list[str] = []
+ for name in names:
+ marker = f"_HERMES_RUNTIME_PASSTHROUGH_{name}"
+ present, value = f"{marker}_PRESENT", f"{marker}_VALUE"
+ save.append(f"{present}=${{{name}+x}}")
+ save.append(f"{value}=${{{name}-}}")
+ restore.append(
+ f'if [ "${present}" = x ]; then export {name}="${value}"; '
+ f'else unset {name}; fi'
+ )
+ restore.append(f"unset {present} {value}")
+ return save, restore
+
+
+def _wrap_command_script(
+ command: str,
+ *,
+ quoted_cwd: str,
+ quoted_snap: str,
+ snap_tmp_template: str,
+ passthrough_names: Iterable[str],
+ snapshot_ready: bool,
+ cwd_marker: str,
+) -> str:
+ """Per-command bash script: source snapshot, cd, run, re-dump env, emit CWD marker.
+
+ ``source`` stdout goes to /dev/null because macOS bash 3.2 / some Homebrew
+ builds echo ``declare -x`` lines when sourcing. AI_AGENT/HERMES_AGENT
+ advertise the harness to remote backends (whose env is not inherited from
+ the Hermes process); ``${VAR:-default}`` never clobbers an outer harness.
+ GIT_PAGER/PAGER=cat stop pager-happy tools hanging a PTY-backed command.
+ The env re-dump uses the same mktemp+mv atomic publish as the bootstrap and
+ chains ``mv`` on the dump succeeding so a failed dump never replaces a good
+ snapshot. ``umask 077`` is applied after the user's command so snapshot
+ files (which may carry secrets) are private without changing the command's
+ umask.
+ """
+ escaped = command.replace("'", "'\\''")
+ save, restore = _passthrough_save_restore(passthrough_names)
+ parts = list(save)
+ if snapshot_ready:
+ parts.append(f"source {quoted_snap} >/dev/null 2>&1 || true")
+ parts.extend(restore)
+ parts.append(
+ 'export AI_AGENT="${AI_AGENT:-hermes-agent}" '
+ 'HERMES_AGENT="${HERMES_AGENT:-true}"'
+ )
+ parts.append('export GIT_PAGER="${GIT_PAGER:-cat}" PAGER="${PAGER:-cat}"')
+ # ``--`` keeps hyphen-prefixed directory names from being parsed as options.
+ parts.append(f"builtin cd -- {quoted_cwd} || exit 126")
+ parts.append(f"eval '{escaped}'")
+ parts.append("__hermes_ec=$?")
+ parts.append("umask 077")
+ if snapshot_ready:
+ parts.append(
+ f"__hermes_snap_tmp=$(mktemp {snap_tmp_template}) && "
+ f"{{ {_export_dump_excluding_session_vars(_SNAP_TMP, passthrough_names)} "
+ f"&& mv -f {_SNAP_TMP} {quoted_snap}; }} "
+ f"2>/dev/null || rm -f {_SNAP_TMP} 2>/dev/null || true"
+ )
+ parts.append(_cwd_marker_printf(cwd_marker))
+ parts.append("exit $__hermes_ec")
+ return "\n".join(parts)
+
+
+def _split_cwd_marker(output: str, marker: str) -> tuple[str | None, str] | None:
+ """Locate the last ``marker<path>marker`` pair in *output*.
+
+ Returns ``(cwd_path_or_None, output_without_marker_line)``, or ``None`` when
+ no complete pair exists. The stripped span runs from the ``\\n`` the wrapper
+ injected before the marker through the end of the marker line.
+ """
+ last = output.rfind(marker)
+ if last == -1:
+ return None
+ search_start = max(0, last - 4096) # CWD path won't be >4KB
+ first = output.rfind(marker, search_start, last)
+ if first == -1 or first == last:
+ return None
+ cwd_path = output[first + len(marker) : last].strip() or None
+ line_start = output.rfind("\n", 0, first)
+ if line_start == -1:
+ line_start = first
+ line_end = output.find("\n", last + len(marker))
+ line_end = line_end + 1 if line_end != -1 else len(output)
+ return cwd_path, output[:line_start] + output[line_end:]
diff --git a/tools/environments/base_wait.py b/tools/environments/base_wait.py
new file mode 100644
index 00000000000..466d7e4098b
--- /dev/null
+++ b/tools/environments/base_wait.py
@@ -0,0 +1,81 @@
+"""Opt-in interrupt/poll tracing for ``BaseEnvironment._wait_for_process``.
+
+Enabled by ``HERMES_DEBUG_INTERRUPT=1`` (see ``tools.environments.base``):
+logs loop entry/exit, interrupt/timeout detection, and ~30s heartbeats so
+"agent never sees the interrupt" reports can be diagnosed from agent.log.
+"""
+
+import threading
+import time
+
+from tools.interrupt import is_interrupted
+
+_FMT = {
+ "ENTER": "timeout=%ss activity_cb=%s initial_interrupt=%s",
+ "INTERRUPT DETECTED": "iter=%d elapsed=%.1fs — killing process group",
+ "TIMEOUT": "iter=%d timeout=%ss",
+ "HEARTBEAT": "iter=%d elapsed=%.0fs interrupt=%s activity_cb=%s%s",
+ "EXCEPTION_EXIT": "iter=%d elapsed=%.1fs — killing subprocess group before re-raise",
+ "EXIT (natural)": "iter=%d elapsed=%.1fs returncode=%s",
+}
+
+
+class _WaitTrace:
+ """Per-wait debug tracer; every method is a no-op unless ``enabled``."""
+
+ def __init__(self, proc, timeout, *, enabled: bool, logger):
+ self.enabled = enabled
+ self.iterations = 0
+ if not enabled:
+ return
+ from tools.environments.base import get_activity_callback
+
+ self._get_cb, self._log, self._timeout = get_activity_callback, logger, timeout
+ self._tid = threading.current_thread().ident
+ self._pid = getattr(proc, "pid", None)
+ self._start = self._last_heartbeat = time.monotonic()
+ self._cb_was_none = get_activity_callback() is None
+
+ def _emit(self, event: str, *args) -> None:
+ self._log.info(
+ "[interrupt-debug] _wait_for_process %s tid=%s pid=%s " + _FMT[event],
+ event, self._tid, self._pid, *args,
+ )
+
+ def _elapsed(self) -> float:
+ return time.monotonic() - self._start
+
+ def enter(self) -> None:
+ if self.enabled:
+ self._emit("ENTER", self._timeout,
+ "set" if not self._cb_was_none else "MISSING", is_interrupted())
+
+ def interrupted(self) -> None:
+ if self.enabled:
+ self._emit("INTERRUPT DETECTED", self.iterations, self._elapsed())
+
+ def timed_out(self) -> None:
+ if self.enabled:
+ self._emit("TIMEOUT", self.iterations, self._timeout)
+
+ def heartbeat(self) -> None:
+ """Every ~30s: proves the loop is alive and reports whether the thread-local
+ activity callback got clobbered by nested tool calls / executor thread reuse."""
+ if not self.enabled or time.monotonic() - self._last_heartbeat < 30.0:
+ return
+ cb_now_none = self._get_cb() is None
+ self._emit(
+ "HEARTBEAT", self.iterations, self._elapsed(), is_interrupted(),
+ "set" if not cb_now_none else "MISSING",
+ " (LOST during run)" if cb_now_none and not self._cb_was_none else "",
+ )
+ self._last_heartbeat = time.monotonic()
+ self._cb_was_none = cb_now_none
+
+ def exception_exit(self) -> None:
+ if self.enabled:
+ self._emit("EXCEPTION_EXIT", self.iterations, self._elapsed())
+
+ def natural_exit(self, returncode) -> None:
+ if self.enabled:
+ self._emit("EXIT (natural)", self.iterations, self._elapsed(), returncode)
diff --git a/tools/environments/daytona.py b/tools/environments/daytona.py
index 8aba7128041..1eae670e1fd 100644
--- a/tools/environments/daytona.py
+++ b/tools/environments/daytona.py
@@ -1,8 +1,7 @@
"""Daytona cloud execution environment.
-Uses the Daytona Python SDK to run commands in cloud sandboxes.
-Supports persistent sandboxes: when enabled, sandboxes are stopped on cleanup
-and resumed on next creation, preserving the filesystem across sessions.
+Runs commands in Daytona cloud sandboxes via the Python SDK. Persistent mode stops
+the sandbox on cleanup and resumes it next time, preserving the filesystem.
"""
import logging
@@ -12,17 +11,11 @@ import shlex
import threading
from pathlib import Path
-from tools.environments.base import (
- BaseEnvironment,
- _ThreadedProcessHandle,
-)
+from tools.environments.base import BaseEnvironment, _ThreadedProcessHandle
from tools.environments.file_sync import (
- FileSyncManager,
- iter_sync_files,
- quoted_mkdir_command,
- quoted_rm_command,
- unique_parent_dirs,
+ FileSyncManager, iter_sync_files, quoted_mkdir_command, quoted_rm_command, unique_parent_dirs,
)
+from tools.environments.remote_common import ensure_lazy_dep
logger = logging.getLogger(__name__)
@@ -30,41 +23,20 @@ logger = logging.getLogger(__name__)
class DaytonaEnvironment(BaseEnvironment):
"""Daytona cloud sandbox execution backend.
- Spawn-per-call via _ThreadedProcessHandle wrapping blocking SDK calls.
- cancel_fn wired to sandbox.stop() for interrupt support.
- Shell timeout wrapper preserved (SDK timeout unreliable).
+ Spawn-per-call via _ThreadedProcessHandle wrapping blocking SDK calls; cancel_fn
+ is wired to sandbox.stop() for interrupts. Shell timeout wrapper kept (SDK timeout unreliable).
"""
_stdin_mode = "heredoc"
- def __init__(
- self,
- image: str,
- cwd: str = "/home/daytona",
- timeout: int = 60,
- cpu: int = 1,
- memory: int = 5120,
- disk: int = 10240,
- persistent_filesystem: bool = True,
- task_id: str = "default",
- ):
+ def __init__(self, image: str, cwd: str = "/home/daytona", timeout: int = 60, cpu: int = 1,
+ memory: int = 5120, disk: int = 10240, persistent_filesystem: bool = True,
+ task_id: str = "default"):
requested_cwd = cwd
super().__init__(cwd=cwd, timeout=timeout)
- try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("terminal.daytona", prompt=False)
- except ImportError:
- pass
- except Exception as e:
- raise ImportError(str(e))
- from daytona import (
- Daytona,
- CreateSandboxFromImageParams,
- DaytonaError,
- Resources,
- SandboxState,
- )
+ ensure_lazy_dep("terminal.daytona")
+ from daytona import Daytona, CreateSandboxFromImageParams, DaytonaError, Resources, SandboxState
self._persistent = persistent_filesystem
self._task_id = task_id
@@ -76,10 +48,8 @@ class DaytonaEnvironment(BaseEnvironment):
memory_gib = max(1, math.ceil(memory / 1024))
disk_gib = max(1, math.ceil(disk / 1024))
if disk_gib > 10:
- logger.warning(
- "Daytona: requested disk (%dGB) exceeds platform limit (10GB). "
- "Capping to 10GB.", disk_gib,
- )
+ logger.warning("Daytona: requested disk (%dGB) exceeds platform limit (10GB). "
+ "Capping to 10GB.", disk_gib)
disk_gib = 10
resources = Resources(cpu=cpu, memory=memory_gib, disk=disk_gib)
@@ -90,46 +60,31 @@ class DaytonaEnvironment(BaseEnvironment):
try:
self._sandbox = self._daytona.get(sandbox_name)
self._sandbox.start()
- logger.info("Daytona: resumed sandbox %s for task %s",
- self._sandbox.id, task_id)
+ logger.info("Daytona: resumed sandbox %s for task %s", self._sandbox.id, task_id)
except DaytonaError:
self._sandbox = None
except Exception as e:
- logger.warning("Daytona: failed to resume sandbox for task %s: %s",
- task_id, e)
+ logger.warning("Daytona: failed to resume sandbox for task %s: %s", task_id, e)
self._sandbox = None
if self._sandbox is None:
try:
- # Daytona SDK >=0.108.0 uses cursor-based pagination and
- # list() returns an iterator. Offset-based pagination
- # (page=1) is removed on June 10, 2026.
- results = self._daytona.list(labels=labels, limit=1)
- legacy = next(iter(results), None)
+ # SDK list() is a cursor-paginated iterator (offset pagination is gone).
+ legacy = next(iter(self._daytona.list(labels=labels, limit=1)), None)
if legacy is not None:
self._sandbox = legacy
self._sandbox.start()
- logger.info("Daytona: resumed legacy sandbox %s for task %s",
- self._sandbox.id, task_id)
+ logger.info("Daytona: resumed legacy sandbox %s for task %s", self._sandbox.id, task_id)
except Exception as e:
- logger.debug("Daytona: no legacy sandbox found for task %s: %s",
- task_id, e)
+ logger.debug("Daytona: no legacy sandbox found for task %s: %s", task_id, e)
self._sandbox = None
if self._sandbox is None:
- self._sandbox = self._daytona.create(
- CreateSandboxFromImageParams(
- image=image,
- name=sandbox_name,
- labels=labels,
- auto_stop_interval=0,
- resources=resources,
- )
- )
- logger.info("Daytona: created sandbox %s for task %s",
- self._sandbox.id, task_id)
-
- # Detect remote home dir
+ self._sandbox = self._daytona.create(CreateSandboxFromImageParams(
+ image=image, name=sandbox_name, labels=labels, auto_stop_interval=0, resources=resources,
+ ))
+ logger.info("Daytona: created sandbox %s for task %s", self._sandbox.id, task_id)
+
self._remote_home = "/root"
try:
home = self._sandbox.process.exec("echo $HOME").result.strip()
@@ -158,38 +113,25 @@ class DaytonaEnvironment(BaseEnvironment):
self._sandbox.fs.upload_file(host_path, remote_path)
def _daytona_bulk_upload(self, files: list[tuple[str, str]]) -> None:
- """Upload many files in a single HTTP call via Daytona SDK.
-
- Uses ``sandbox.fs.upload_files()`` which batches all files into one
- multipart POST, avoiding per-file TLS/HTTP overhead (~580 files
- goes from ~5 min to <2 s).
- """
+ """Upload many files in one multipart POST via ``sandbox.fs.upload_files()``."""
from daytona.common.filesystem import FileUpload
if not files:
return
-
parents = unique_parent_dirs(files)
if parents:
self._sandbox.process.exec(quoted_mkdir_command(parents))
-
- uploads = [
- FileUpload(source=host_path, destination=remote_path)
- for host_path, remote_path in files
- ]
- self._sandbox.fs.upload_files(uploads)
+ self._sandbox.fs.upload_files(
+ [FileUpload(source=host_path, destination=remote_path) for host_path, remote_path in files]
+ )
def _daytona_bulk_download(self, dest: Path) -> None:
"""Download remote .hermes/ as a tar archive."""
rel_base = f"{self._remote_home}/.hermes".lstrip("/")
- # PID-suffixed remote temp path avoids collisions if sync_back fires
- # concurrently for the same sandbox (e.g. retry after partial failure).
+ # PID-suffixed remote temp path avoids collisions if sync_back runs concurrently.
remote_tar = f"/tmp/.hermes_sync.{os.getpid()}.tar"
- self._sandbox.process.exec(
- f"tar cf {shlex.quote(remote_tar)} -C / {shlex.quote(rel_base)}"
- )
+ self._sandbox.process.exec(f"tar cf {shlex.quote(remote_tar)} -C / {shlex.quote(rel_base)}")
self._sandbox.fs.download_file(remote_tar, str(dest))
- # Clean up remote temp file
try:
self._sandbox.process.exec(f"rm -f {shlex.quote(remote_tar)}")
except Exception:
@@ -199,9 +141,7 @@ class DaytonaEnvironment(BaseEnvironment):
"""Batch-delete remote files via SDK exec."""
self._sandbox.process.exec(quoted_rm_command(remote_paths))
- # ------------------------------------------------------------------
- # Sandbox lifecycle
- # ------------------------------------------------------------------
+ # -- Sandbox lifecycle ----------------------------------------------
def _ensure_sandbox_ready(self) -> None:
"""Restart sandbox if it was stopped (e.g., by a previous interrupt)."""
@@ -216,8 +156,7 @@ class DaytonaEnvironment(BaseEnvironment):
self._ensure_sandbox_ready()
self._sync_manager.sync()
- def _run_bash(self, cmd_string: str, *, login: bool = False,
- timeout: int = 120,
+ def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,
stdin_data: str | None = None):
"""Return a _ThreadedProcessHandle wrapping a blocking Daytona SDK call."""
sandbox = self._sandbox
@@ -230,10 +169,7 @@ class DaytonaEnvironment(BaseEnvironment):
except Exception:
pass
- if login:
- shell_cmd = f"bash -l -c {shlex.quote(cmd_string)}"
- else:
- shell_cmd = f"bash -c {shlex.quote(cmd_string)}"
+ shell_cmd = f"bash {'-l ' if login else ''}-c {shlex.quote(cmd_string)}"
def exec_fn() -> tuple[str, int]:
response = sandbox.process.exec(shell_cmd, timeout=timeout)
@@ -246,10 +182,8 @@ class DaytonaEnvironment(BaseEnvironment):
if self._sandbox is None:
return
- # Sync remote changes back to host before teardown. Running
- # inside the lock (and after the _sandbox is None guard) avoids
- # firing sync_back on an already-cleaned-up env, which would
- # trigger a 3-attempt retry storm against a nil sandbox.
+ # sync_back runs inside the lock and after the None guard so an
+ # already-cleaned-up env can't trigger a 3-attempt retry storm on a nil sandbox.
if self._sync_manager:
logger.info("Daytona: syncing files from sandbox...")
try:
@@ -260,8 +194,7 @@ class DaytonaEnvironment(BaseEnvironment):
try:
if self._persistent:
self._sandbox.stop()
- logger.info("Daytona: stopped sandbox %s (filesystem preserved)",
- self._sandbox.id)
+ logger.info("Daytona: stopped sandbox %s (filesystem preserved)", self._sandbox.id)
else:
self._daytona.delete(self._sandbox)
logger.info("Daytona: deleted sandbox %s", self._sandbox.id)
diff --git a/tools/environments/docker.py b/tools/environments/docker.py
index c54d1cf71ef..ad0a72b7ef9 100644
--- a/tools/environments/docker.py
+++ b/tools/environments/docker.py
@@ -1,10 +1,11 @@
"""Docker execution environment for sandboxed command execution.
-Security hardened (cap-drop ALL, no-new-privileges, PID limits),
-configurable resource limits (CPU, memory, disk), and optional filesystem
-persistence via bind mounts.
+Security hardened (cap-drop ALL, no-new-privileges, PID limits), configurable
+resource limits (CPU, memory, disk), and optional filesystem persistence via
+bind mounts.
"""
+import datetime
import hashlib
import json
import logging
@@ -14,6 +15,7 @@ import shlex
import shutil
import subprocess
import sys
+import threading
import uuid
from pathlib import Path
from typing import Optional
@@ -23,7 +25,20 @@ from tools.environments.base import (
EnvironmentConnectionError,
_popen_bash,
)
+from tools.environments.docker_egress import ( # noqa: F401 — re-exported for tests/patch targets
+ _EGRESS_LABEL_KEY,
+ _critical_egress_env_names,
+ _egress_enforce_on_docker,
+ _egress_proxy_args_for_docker,
+ _egress_reuse_fingerprint,
+ _extra_args_egress_collisions,
+ check_docker_env_collisions,
+ check_extra_args_collisions,
+ check_forward_env_collisions,
+ merge_egress_env,
+)
from tools.environments.path_utils import sanitize_task_id_for_path
+from tools.environments.remote_common import bash_argv, run_capture
from tools.environments.local import (
_HERMES_PROVIDER_ENV_BLOCKLIST,
_is_hermes_internal_secret,
@@ -32,9 +47,8 @@ from tools.environments.local import (
logger = logging.getLogger(__name__)
-# Common Docker Desktop install paths checked when 'docker' is not in PATH.
-# macOS Intel: /usr/local/bin, macOS Apple Silicon (Homebrew): /opt/homebrew/bin,
-# Docker Desktop app bundle: /Applications/Docker.app/Contents/Resources/bin
+# Docker Desktop install paths checked when 'docker' is not in PATH
+# (macOS Intel / Apple Silicon Homebrew / app bundle).
_DOCKER_SEARCH_PATHS = [
"/usr/local/bin/docker",
"/opt/homebrew/bin/docker",
@@ -43,45 +57,35 @@ _DOCKER_SEARCH_PATHS = [
_docker_executable: Optional[str] = None # resolved once, cached
_ENV_VAR_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
-_EGRESS_LABEL_KEY = "hermes-egress"
def _normalize_forward_env_names(forward_env: list[str] | None) -> list[str]:
"""Return a deduplicated list of valid environment variable names."""
normalized: list[str] = []
seen: set[str] = set()
-
for item in forward_env or []:
if not isinstance(item, str):
logger.warning("Ignoring non-string docker_forward_env entry: %r", item)
continue
-
key = item.strip()
if not key:
continue
if not _ENV_VAR_NAME_RE.match(key):
logger.warning("Ignoring invalid docker_forward_env entry: %r", item)
continue
- if key in seen:
- continue
-
- seen.add(key)
- normalized.append(key)
-
+ if key not in seen:
+ seen.add(key)
+ normalized.append(key)
return normalized
def _normalize_env_dict(env: dict | None) -> dict[str, str]:
- """Validate and normalize a docker_env dict to {str: str}.
-
- Filters out entries with invalid variable names or non-string values.
- """
+ """Validate a docker_env dict to {str: str}; scalars are coerced, other values dropped."""
if not env:
return {}
if not isinstance(env, dict):
logger.warning("docker_env is not a dict: %r", env)
return {}
-
normalized: dict[str, str] = {}
for key, value in env.items():
if not isinstance(key, str) or not _ENV_VAR_NAME_RE.match(key.strip()):
@@ -89,15 +93,11 @@ def _normalize_env_dict(env: dict | None) -> dict[str, str]:
continue
key = key.strip()
if not isinstance(value, str):
- # Coerce simple scalar types (int, bool, float) to string;
- # reject complex types.
- if isinstance(value, (int, float, bool)):
- value = str(value)
- else:
+ if not isinstance(value, (int, float, bool)):
logger.warning("Ignoring non-string docker_env value for %r: %r", key, value)
continue
+ value = str(value)
normalized[key] = value
-
return normalized
@@ -105,109 +105,67 @@ def _load_hermes_env_vars() -> dict[str, str]:
"""Load ~/.hermes/.env values without failing Docker command execution."""
try:
from hermes_cli.config import load_env
-
return load_env() or {}
except Exception:
return {}
-# Docker label values must match [a-zA-Z0-9_.-] and stay ≤63 chars to round-trip
-# safely through `docker ps --filter label=key=value`. Profile and task names
-# can technically contain other characters; sanitize defensively.
+# Docker label values must match [a-zA-Z0-9_.-] and stay <=63 chars to round-trip
+# through `docker ps --filter label=key=value`.
_LABEL_VALUE_OK_RE = re.compile(r"[^A-Za-z0-9_.-]")
def _sanitize_label_value(value: str) -> str:
- """Coerce *value* into a Docker label-safe form (alnum + ``_.-``, ≤63 chars).
+ """Coerce *value* into a Docker label-safe form; empty/invalid input becomes ``"unknown"``.
- Empty or all-invalid inputs collapse to ``"unknown"`` so the resulting
- label is always queryable. Used at container-create time; never round-trip
- a sanitized value back into application logic.
+ Lossy — never round-trip a sanitized value back into application logic.
"""
if not isinstance(value, str) or not value:
return "unknown"
- cleaned = _LABEL_VALUE_OK_RE.sub("_", value)
- cleaned = cleaned[:63] or "unknown"
- return cleaned
+ return _LABEL_VALUE_OK_RE.sub("_", value)[:63] or "unknown"
-# The task_id -> host-directory-name mapping is shared with every backend
-# that persists per-task state on the host filesystem (Singularity overlays
-# use the same helper), so the whole bug class is fixed in one place:
-# tools.environments.base.sanitize_task_id_for_path.
+# task_id -> host directory name; shared with every backend persisting per-task
+# state on the host (Singularity overlays) so the mapping is fixed in one place.
_sandbox_dir_name = sanitize_task_id_for_path
def _get_active_profile_name() -> str:
- """Return the active Hermes profile name, or ``"default"`` on any error.
+ """Active Hermes profile name, or ``"default"`` on any error.
- Resolved at container-create time so a single container is permanently
- tagged with the profile that created it. Profile switches inside the
- same process don't retroactively relabel running containers.
+ Resolved at container-create time so a container stays tagged with the
+ profile that created it even if the process switches profiles later.
"""
try:
from hermes_cli.profiles import get_active_profile_name
-
return get_active_profile_name() or "default"
except Exception:
return "default"
def _container_identity(shared_key: str = "") -> str:
- """Return the profile label used for reuse and orphan reaping.
-
- Profiles remain isolated by default. An explicit shared key lets trusted
- profiles that intentionally share a workspace use one Docker identity.
-
- Shared keys are made collision-resistant the same way
- :func:`sanitize_task_id_for_path` is: label sanitization is lossy
- (``team/workspace`` and ``team_workspace`` both sanitize to
- ``team_workspace``, and >63-char keys truncate), and since container
- reuse is label-keyed, two DIFFERENT keys colliding after sanitization
- would silently attach to the same running container. A digest of the
- raw key disambiguates; identical raw keys still map to identical
- labels across processes. Plain profile names keep their historical
- un-suffixed labels for backward compatibility with existing containers.
+ """Profile label used for container reuse and orphan reaping.
+
+ Profiles are isolated by default; an explicit shared key lets trusted
+ profiles share one Docker identity. Label sanitization is lossy and reuse
+ is label-keyed, so two DIFFERENT keys colliding after sanitization would
+ attach to the same container — a digest of the raw key disambiguates.
+ Plain profile names keep their historical un-suffixed labels.
"""
if not shared_key:
return _sanitize_label_value(_get_active_profile_name())
digest = hashlib.sha256(shared_key.encode("utf-8")).hexdigest()[:12]
- stem = _sanitize_label_value(shared_key)[:50]
- return f"{stem}-{digest}"
+ return f"{_sanitize_label_value(shared_key)[:50]}-{digest}"
def reap_orphan_containers(
- *,
- max_age_seconds: int = 600,
- profile_filter: str | None = None,
- docker_exe: str | None = None,
+ *, max_age_seconds: int = 600, profile_filter: str | None = None, docker_exe: str | None = None,
) -> int:
- """Remove stale hermes-tagged containers left behind by prior processes.
-
- Targets containers that match all of:
-
- * ``label=hermes-agent=1`` (created by this codebase)
- * ``status=exited`` (running containers are NEVER reaped — they may
- belong to a sibling Hermes process whose reuse path will pick them
- up; killing them would crash the sibling mid-command)
- * (optional) ``label=hermes-profile=<profile_filter>`` (sweep only the
- caller's profile by default; a hermes process in profile A must not
- tear down profile B's containers)
- * ``State.FinishedAt`` older than *max_age_seconds* ago (so a sibling
- process that just exited and is about to be replaced doesn't get
- its container yanked out from under it)
-
- Returns the number of containers removed. Best-effort: any failure
- (docker daemon unreachable, slow inspect, parse error) is logged at
- debug level and the function returns whatever it managed before the
- failure. Safe to call repeatedly; idempotent.
-
- Issue #20561 — this is the safety net for SIGKILL / OOM / crashed
- terminal exits that bypass the ``atexit`` cleanup hook. Without it,
- even with the cleanup-fix in the prior commit, a hard-killed Hermes
- process leaves its container behind permanently because there's no
- subsequent Hermes process scheduled to reuse that exact (task, profile)
- pair.
+ """Remove stale hermes-tagged containers left behind by prior processes (SIGKILL/OOM
+ exits that bypass atexit). Only ``status=exited`` containers (running ones may belong
+ to a sibling process), only the caller's profile, and only if ``FinishedAt`` is older
+ than *max_age_seconds* (a just-exited sibling may be about to reuse its container).
+ Best-effort and idempotent: failures log at debug and the count removed so far is returned.
"""
docker = docker_exe or find_docker() or "docker"
filters = ["--filter", "label=hermes-agent=1", "--filter", "status=exited"]
@@ -215,74 +173,42 @@ def reap_orphan_containers(
filters.extend(["--filter", f"label=hermes-profile={_sanitize_label_value(profile_filter)}"])
try:
- listing = subprocess.run(
- [docker, "ps", "-a", *filters, "--format", "{{.ID}}"],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=15, check=False,
- stdin=subprocess.DEVNULL,
- )
+ listing = run_capture([docker, "ps", "-a", *filters, "--format", "{{.ID}}"], timeout=15)
except (subprocess.TimeoutExpired, OSError) as e:
logger.debug("orphan reaper docker ps failed: %s", e)
return 0
if listing.returncode != 0:
- logger.debug(
- "orphan reaper docker ps returned %d: %s",
- listing.returncode, listing.stderr.strip(),
- )
+ logger.debug("orphan reaper docker ps returned %d: %s", listing.returncode, listing.stderr.strip())
return 0
- candidate_ids = [ln.strip() for ln in listing.stdout.splitlines() if ln.strip()]
- if not candidate_ids:
- return 0
-
- # Inspect each candidate to get FinishedAt; reap only those exited
- # long enough ago. Doing this per-container (rather than bulk inspect)
- # keeps the failure blast radius to one container at a time.
- import datetime
+ # Per-container inspect keeps the failure blast radius to one container.
now = datetime.datetime.now(datetime.timezone.utc)
removed = 0
- for cid in candidate_ids:
+ for cid in (ln.strip() for ln in listing.stdout.splitlines() if ln.strip()):
finished_at = _container_finished_at(docker, cid)
- if finished_at is None:
- # Couldn't determine age — be conservative and leave it alone.
+ if finished_at is None: # unknown age — be conservative
continue
age = (now - finished_at).total_seconds()
if age < max_age_seconds:
continue
try:
- result = subprocess.run(
- [docker, "rm", "-f", cid],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=30,
- stdin=subprocess.DEVNULL,
- )
+ result = run_capture([docker, "rm", "-f", cid], timeout=30)
if result.returncode == 0:
removed += 1
- logger.info(
- "Reaped orphan container %s (exited %d seconds ago)",
- cid[:12], int(age),
- )
+ logger.info("Reaped orphan container %s (exited %d seconds ago)", cid[:12], int(age))
else:
- logger.debug(
- "docker rm -f %s failed: %s",
- cid[:12], result.stderr.strip(),
- )
+ logger.debug("docker rm -f %s failed: %s", cid[:12], result.stderr.strip())
except (subprocess.TimeoutExpired, OSError) as e:
logger.debug("orphan reaper docker rm %s failed: %s", cid[:12], e)
return removed
def _container_finished_at(docker_exe: str, container_id: str):
- """Parse ``docker inspect`` FinishedAt for *container_id*.
-
- Returns a timezone-aware datetime, or ``None`` if the field is missing,
- unparseable, or the zero-value ``0001-01-01T00:00:00Z`` Docker emits
- for never-finished containers. ``None`` means "don't reap" — the caller
- leaves the container alone.
- """
+ """``docker inspect`` FinishedAt as an aware datetime; ``None`` (= don't reap) when
+ missing/unparseable or Docker's never-finished zero value ``0001-01-01T00:00:00Z``."""
try:
- result = subprocess.run(
- [docker_exe, "inspect", "--format", "{{.State.FinishedAt}}", container_id],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10, check=False,
- stdin=subprocess.DEVNULL,
+ result = run_capture(
+ [docker_exe, "inspect", "--format", "{{.State.FinishedAt}}", container_id], timeout=10,
)
except (subprocess.TimeoutExpired, OSError) as e:
logger.debug("orphan reaper docker inspect %s failed: %s", container_id[:12], e)
@@ -292,85 +218,55 @@ def _container_finished_at(docker_exe: str, container_id: str):
raw = result.stdout.strip()
if not raw or raw.startswith("0001-01-01"):
return None
- # Docker emits RFC3339 with nanoseconds (e.g. "2026-05-28T13:45:00.123456789Z").
- # Python's fromisoformat handles microseconds but not nanoseconds; trim.
- import re as _re
- raw = _re.sub(r"(\.\d{6})\d+", r"\1", raw)
- raw = raw.replace("Z", "+00:00")
+ # Docker emits RFC3339 with nanoseconds; fromisoformat only takes microseconds.
+ raw = re.sub(r"(\.\d{6})\d+", r"\1", raw).replace("Z", "+00:00")
try:
- import datetime
return datetime.datetime.fromisoformat(raw)
except ValueError as e:
logger.debug("could not parse FinishedAt %r for %s: %s", raw, container_id[:12], e)
return None
-def find_docker() -> Optional[str]:
- """Locate the docker (or podman) CLI binary.
+def _is_executable(path: str) -> bool:
+ return os.path.isfile(path) and os.access(path, os.X_OK)
- Resolution order:
- 1. ``HERMES_DOCKER_BINARY`` env var — explicit override (e.g. ``/usr/bin/podman``)
- 2. ``docker`` on PATH via ``shutil.which``
- 3. ``podman`` on PATH via ``shutil.which``
- 4. Well-known macOS Docker Desktop install locations
- Returns the absolute path, or ``None`` if neither runtime can be found.
- """
+def find_docker() -> Optional[str]:
+ """Locate the docker/podman CLI (cached): ``HERMES_DOCKER_BINARY`` override, ``docker``
+ on PATH, ``podman`` on PATH, then macOS Docker Desktop locations; ``None`` if absent."""
global _docker_executable
if _docker_executable is not None:
return _docker_executable
- # 1. Explicit override via env var (e.g. for Podman on immutable distros)
override = os.getenv("HERMES_DOCKER_BINARY")
- if override and os.path.isfile(override) and os.access(override, os.X_OK):
- _docker_executable = override
+ if override and _is_executable(override):
logger.info("Using HERMES_DOCKER_BINARY override: %s", override)
+ _docker_executable = override
return override
-
- # 2. docker on PATH
found = shutil.which("docker")
if found:
_docker_executable = found
return found
-
- # 3. podman on PATH (drop-in compatible for our use case)
found = shutil.which("podman")
if found:
- _docker_executable = found
logger.info("Using podman as container runtime: %s", found)
+ _docker_executable = found
return found
-
- # 4. Well-known macOS Docker Desktop locations
for path in _DOCKER_SEARCH_PATHS:
- if os.path.isfile(path) and os.access(path, os.X_OK):
- _docker_executable = path
+ if _is_executable(path):
logger.info("Found docker at non-PATH location: %s", path)
+ _docker_executable = path
return path
-
return None
-# Security flags applied to every container.
-# The container itself is the security boundary (isolated from host).
-# We drop all capabilities then add back the minimum needed:
-# DAC_OVERRIDE - root can write to bind-mounted dirs owned by host user
-# CHOWN/FOWNER - package managers (pip, npm, apt) need to set file ownership
-# SETUID/SETGID - the image's init drops from root to the 'hermes'
-# user (via `s6-setuidgid` in the bundled image, or whatever
-# privilege-drop helper a user image uses), which requires these
-# caps. Combined with `no-new-privileges`, the dropped process
-# still cannot escalate back to root, so the security posture is
-# preserved. Omitted entirely when the container starts as a
-# non-root user via --user, since no privilege drop is needed
-# in that mode.
-# Block privilege escalation.
-# /tmp is size-limited and nosuid but allows exec (needed by pip/npm builds).
-#
-# Note: ``--pids-limit`` is *not* in this list — it lives in ``resource_args``
-# and is gated on ``_cgroup_limits_available(image)`` because it requires the
-# ``pids`` cgroup controller to be delegated, which is not the case on hosts
-# such as unprivileged LXCs. ``--cpus``/``--memory`` are gated for the same
-# reason.
+# Security flags applied to every container. The container is the security
+# boundary; all caps are dropped and the minimum added back:
+# DAC_OVERRIDE - root can write to bind-mounted dirs owned by the host user
+# CHOWN/FOWNER - package managers need to set file ownership
+# /tmp is size-limited and nosuid but allows exec (pip/npm builds need it).
+# ``--pids-limit``/``--cpus``/``--memory`` live in resource_args instead, gated
+# on ``_cgroup_limits_available`` (unprivileged LXCs lack the controllers).
_BASE_SECURITY_ARGS = [
"--cap-drop", "ALL",
"--cap-add", "DAC_OVERRIDE",
@@ -381,331 +277,56 @@ _BASE_SECURITY_ARGS = [
"--tmpfs", "/var/tmp:rw,noexec,nosuid,size=256m",
]
-# Default per-container PID limit. Applied as ``--pids-limit`` only when the
-# cgroup ``pids`` controller is available (see ``_cgroup_limits_available``).
-_DEFAULT_PIDS_LIMIT = "256"
-
-# Default /dev/shm size. Docker's built-in default is a tiny 64 MB, which
-# silently breaks shared-memory-hungry workloads inside the sandbox: Chromium /
-# Playwright renderers crash tabs, and PyTorch DataLoader workers die with
-# "bus error" / "insufficient shared memory" once they exceed it. tmpfs is
-# lazily allocated, so a 1g ceiling costs nothing until actually used (and
-# usage still counts against the container's --memory cgroup limit).
-# Configurable via ``terminal.docker_shm_size`` in config.yaml; an empty value
-# (or "0") omits the flag and falls back to Docker's 64 MB default.
-# Ported from nanocoai/nanoclaw#2748.
+_DEFAULT_PIDS_LIMIT = "256" # applied only when the pids cgroup controller is available
+
+# Docker's 64 MB /dev/shm default crashes Chromium/Playwright tabs and PyTorch
+# DataLoader workers. tmpfs is lazily allocated so a 1g ceiling costs nothing
+# until used (and still counts against --memory). Empty/"0" config omits the flag.
_DEFAULT_SHM_SIZE = "1g"
def _extra_args_set_shm_size(extra_args: list) -> bool:
- """True when user-supplied docker_extra_args already set ``--shm-size``.
-
- In that case we skip our default so the user's value is unambiguous
- (rather than relying on flag-ordering / last-wins behavior).
- """
+ """True when docker_extra_args already set ``--shm-size`` (then our default is skipped)."""
return any(
isinstance(a, str) and (a == "--shm-size" or a.startswith("--shm-size="))
for a in (extra_args or [])
)
-# /run is split out from _BASE_SECURITY_ARGS because s6-overlay images need it
-# mounted ``exec``: s6 stage0 later runs ``exec /run/s6/basedir/bin/init``, which
-# fails with "Permission denied" (exit 126) on a ``noexec`` mount. For all other
-# images we keep the hardened ``noexec`` default.
+
+# /run is separate from _BASE_SECURITY_ARGS: s6-overlay images exec
+# /run/s6/basedir/bin/init at stage0 and die (exit 126) on a noexec mount.
_RUN_TMPFS_NOEXEC = "--tmpfs", "/run:rw,noexec,nosuid,size=64m"
_RUN_TMPFS_EXEC = "--tmpfs", "/run:rw,exec,nosuid,size=64m"
-# Extra caps needed when the container starts as root and an init/entrypoint
-# must drop privileges (via `s6-setuidgid`, `gosu`, `su`, or similar).
-# Skipped when --user is passed because the container already starts
-# unprivileged and never needs to switch.
-_PRIVDROP_CAP_ARGS = [
- "--cap-add", "SETUID",
- "--cap-add", "SETGID",
-]
-
-
-def _egress_proxy_args_for_docker() -> tuple[list[str], dict[str, str], list[str]]:
- """Build the docker mount/env/host args needed to route a sandbox through
- the iron-proxy egress firewall.
+# SETUID/SETGID let a root-started init drop privileges (s6-setuidgid, gosu,
+# su). Combined with no-new-privileges the dropped process cannot escalate
+# back. Skipped when --user is passed: the container already starts unprivileged.
+_PRIVDROP_CAP_ARGS = ["--cap-add", "SETUID", "--cap-add", "SETGID"]
- Returns ``(volume_args, env_overrides, host_args)``:
-
- * ``volume_args`` — read-only bind mount of the CA cert into the container
- (extends docker's ``-v`` argv list)
- * ``env_overrides`` — env vars to set on container creation: ``HTTPS_PROXY``,
- ``HTTP_PROXY``, ``NO_PROXY`` (loopback only), Python/Node/curl CA-bundle
- paths, and one ``HERMES_PROXY_TOKEN_<NAME>`` per minted mapping
- * ``host_args`` — extra ``--add-host`` flags so the container can reach the
- host-side proxy (Linux needs ``host.docker.internal:host-gateway``;
- Docker Desktop populates this automatically on macOS/Windows)
-
- Returns three empty containers when the proxy is disabled, not yet set up,
- or not currently running. If ``proxy.enforce_on_docker`` is true and the
- proxy is enabled-but-not-running, raises ``RuntimeError`` so the docker
- backend refuses to start the sandbox.
- """
-
- # Narrow except: ImportError is the only legitimate failure here.
- # Bare ``except Exception`` would hide AttributeError, SyntaxError in
- # the config module, etc. and silently start the sandbox without
- # proxy enforcement. We let unexpected exceptions propagate so the
- # docker backend visibly fails rather than degrading silently.
- try:
- from hermes_cli.config import load_config
- from agent.proxy_sources import iron_proxy as ip
- except ImportError as exc:
- logger.debug("Egress proxy plumbing unavailable: %s", exc)
- return ([], {}, [])
-
- cfg = load_config()
- proxy_cfg = cfg.get("proxy") or {}
- if not proxy_cfg.get("enabled"):
- return ([], {}, [])
-
- status = ip.get_status()
- enforce = bool(proxy_cfg.get("enforce_on_docker", True))
-
- if not status.configured:
- msg = (
- "proxy.enabled is true but iron-proxy is not configured. "
- "Run `hermes egress setup` to mint tokens and write proxy.yaml."
- )
- if enforce:
- raise RuntimeError(msg)
- logger.warning("%s — continuing without proxy (enforce_on_docker=false).", msg)
- return ([], {}, [])
-
- if not (status.pid and status.listening):
- msg = (
- f"iron-proxy is enabled but not running on port {status.tunnel_port}. "
- "Start it with `hermes egress start`."
- )
- if enforce:
- raise RuntimeError(msg)
- logger.warning("%s — continuing without proxy (enforce_on_docker=false).", msg)
- return ([], {}, [])
-
- if status.ca_cert_path is None or not status.ca_cert_path.exists():
- # status.configured was True a moment ago but the CA file has
- # disappeared. Treat this with the same enforce semantics as the
- # other failure branches — silently dropping the CA mount would
- # leave the sandbox with proxy env vars pointing at iron-proxy
- # but no trust anchor, so every TLS handshake would 5xx; or
- # worse, with enforce_on_docker=false we'd drop both the proxy
- # vars AND any other isolation, opening the sandbox.
- msg = (
- f"iron-proxy CA cert vanished from {status.ca_cert_path}. "
- "Re-run `hermes egress setup` to regenerate it."
- )
- if enforce:
- raise RuntimeError(msg)
- logger.warning("%s — continuing without proxy (enforce_on_docker=false).", msg)
- return ([], {}, [])
-
- # Corrupt or empty mappings.json is a silent failure mode that's
- # indistinguishable from an upstream outage from inside the sandbox
- # (every request returns 403). Refuse to mount with empty mappings
- # rather than ship a broken sandbox.
- mappings = ip.load_mappings()
- if not mappings:
- msg = (
- "iron-proxy is configured but mappings.json is empty or "
- "corrupt. Re-run `hermes egress setup` to mint provider "
- "tokens before starting a sandbox."
- )
- if enforce:
- raise RuntimeError(msg)
- logger.warning("%s — continuing without proxy (enforce_on_docker=false).", msg)
- return ([], {}, [])
-
- container_ca = "/etc/ssl/certs/hermes-egress-ca.crt"
- volume_args = ["-v", f"{status.ca_cert_path}:{container_ca}:ro"]
-
- # tunnel_port serves CONNECT (HTTPS); the plain-HTTP forward listener
- # is on tunnel_port + 1 (see build_proxy_config's listener-role notes).
- proxy_url = f"http://host.docker.internal:{status.tunnel_port}"
- plain_http_url = f"http://host.docker.internal:{status.tunnel_port + 1}"
- env_overrides: dict[str, str] = {
- # HTTPS_PROXY / HTTP_PROXY are respected by curl, requests, urllib,
- # httpx, node fetch, go default transport, etc. Lowercase variants
- # are also set because some tools only look at one casing.
- "HTTPS_PROXY": proxy_url,
- "https_proxy": proxy_url,
- "HTTP_PROXY": plain_http_url,
- "http_proxy": plain_http_url,
- # Loopback-only NO_PROXY so localhost dev servers inside the sandbox
- # (test fixtures, local LLMs) don't get sent through the proxy.
- "NO_PROXY": "127.0.0.1,localhost,::1",
- "no_proxy": "127.0.0.1,localhost,::1",
- # CA bundle locations for the major language runtimes. iron-proxy
- # presents a leaf cert signed by our CA on every MITM'd connection.
- #
- # CRITICAL ASYMMETRY: Python (REQUESTS_CA_BUNDLE / SSL_CERT_FILE)
- # and curl (CURL_CA_BUNDLE) REPLACE the system CA store.
- # NODE_EXTRA_CA_CERTS ADDS to it. A Node.js process that
- # bypasses HTTPS_PROXY by using a raw socket would still see the
- # system CA store and succeed where Python/curl fail validation.
- # We additionally set NODE_OPTIONS=--use-openssl-ca to force Node
- # through the OpenSSL store that SSL_CERT_FILE controls, narrowing
- # the asymmetry. Not a complete fix — see the docs caveat — but
- # closes the easy case.
- "REQUESTS_CA_BUNDLE": container_ca, # Python `requests`
- "SSL_CERT_FILE": container_ca, # Python ssl module / OpenSSL
- "CURL_CA_BUNDLE": container_ca, # curl
- "NODE_EXTRA_CA_CERTS": container_ca, # Node.js: adds to system store
- # NOTE: NODE_OPTIONS is intentionally NOT placed in env_overrides
- # here as a flat assignment. We need to APPEND --use-openssl-ca
- # to whatever the user already has in NODE_OPTIONS (e.g.
- # --max-old-space-size=4096), not clobber it. The append-merge
- # happens in DockerEnvironment._merge_node_options below.
- # For the agent inside the sandbox to identify itself as proxy-aware.
- "HERMES_EGRESS_PROXY": "1",
- # Sentinel that DockerEnvironment uses to do the NODE_OPTIONS
- # append-merge. Stripped from the final env before docker run.
- "_HERMES_EGRESS_NODE_OPTIONS_APPEND": "--use-openssl-ca",
- }
-
- # Surface the per-provider proxy tokens under the standard provider env
- # names so existing SDKs and provider clients work unchanged inside the
- # sandbox. Alias env names (e.g. GOOGLE_API_KEY for GEMINI_API_KEY)
- # receive the same token so SDKs reading either name authenticate
- # through the proxy. Keep the HERMES_PROXY_TOKEN_* aliases for
- # diagnostics.
- for m in mappings:
- env_overrides[m.real_env_name] = m.proxy_token
- env_overrides[f"HERMES_PROXY_TOKEN_{m.real_env_name}"] = m.proxy_token
- for alias in getattr(m, "alias_env_names", ()) or ():
- env_overrides[alias] = m.proxy_token
-
- # On Linux, host.docker.internal isn't populated by default — Docker Desktop
- # adds it on macOS/Windows; on Linux we need an explicit --add-host with
- # host-gateway. On Desktop this is a no-op (harmless duplicate).
- host_args: list[str] = ["--add-host", "host.docker.internal:host-gateway"]
-
- return (volume_args, env_overrides, host_args)
-
-
-def _egress_reuse_fingerprint(
- volume_args: list[str],
- env_overrides: dict[str, str],
- host_args: list[str],
-) -> str:
- """Stable Docker-label value for the egress posture of a container."""
- if not (volume_args or env_overrides or host_args):
- return "off"
- payload = json.dumps(
- {
- "volume_args": volume_args,
- "env_overrides": env_overrides,
- "host_args": host_args,
- },
- sort_keys=True,
- separators=(",", ":"),
- )
- return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
-
-
-def _egress_enforce_on_docker(default: bool = True) -> bool:
- """Read proxy.enforce_on_docker with fail-safe defaulting."""
- try:
- from hermes_cli.config import load_config as _load_cfg
-
- return bool((_load_cfg().get("proxy") or {}).get("enforce_on_docker", default))
- except (ImportError, OSError):
- return default
- except Exception:
- return default
-
-
-def _critical_egress_env_names(env_overrides: dict[str, str]) -> set[str]:
- """Env names that would weaken or bypass enforced egress if overridden."""
- critical = {
- "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy",
- "NO_PROXY", "no_proxy",
- "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE", "CURL_CA_BUNDLE",
- "NODE_EXTRA_CA_CERTS", "NODE_OPTIONS",
- }
- critical.update(
- key for key in env_overrides
- if key.endswith("_API_KEY") or key.endswith("_TOKEN")
- )
- return critical
-
-
-def _extra_args_egress_collisions(
- extra_args: list[str], critical_names: set[str],
-) -> list[str]:
- """Return docker_extra_args entries that can override egress controls."""
- collisions: list[str] = []
- env_flags = {"-e", "--env", "--env-file"}
- network_flags = {"--network", "--net"}
- i = 0
- while i < len(extra_args):
- arg = extra_args[i]
- nxt = extra_args[i + 1] if i + 1 < len(extra_args) else ""
- if arg in env_flags:
- if arg == "--env-file":
- collisions.append(arg)
- else:
- name = nxt.split("=", 1)[0]
- if name in critical_names:
- collisions.append(name)
- i += 2
- continue
- if any(arg.startswith(f"{flag}=") for flag in env_flags):
- if arg.startswith("--env-file="):
- collisions.append("--env-file")
- else:
- name = arg.split("=", 1)[1].split("=", 1)[0]
- if name in critical_names:
- collisions.append(name)
- elif arg in network_flags or any(arg.startswith(f"{flag}=") for flag in network_flags):
- collisions.append(arg)
- i += 1
- return sorted(set(collisions))
+_S6_INIT_ENTRYPOINTS = ("/init", "/package/admin/s6-overlay/command/init")
def _build_security_args(run_as_host_user: bool, run_exec: bool = False) -> list[str]:
- """Return the security/cap/tmpfs args tailored to the privilege mode.
-
- ``run_exec`` mounts ``/run`` with ``exec`` instead of the hardened
- ``noexec`` default. This is required for s6-overlay images whose ``/init``
- entrypoint execs ``/run/s6/basedir/bin/init`` during startup; see
- ``_image_uses_init_entrypoint``.
- """
- run_tmpfs = list(_RUN_TMPFS_EXEC if run_exec else _RUN_TMPFS_NOEXEC)
- args = list(_BASE_SECURITY_ARGS) + run_tmpfs
+ """Security/cap/tmpfs args for the privilege mode; ``run_exec`` mounts /run exec for s6 images."""
+ args = list(_BASE_SECURITY_ARGS) + list(_RUN_TMPFS_EXEC if run_exec else _RUN_TMPFS_NOEXEC)
if run_as_host_user:
return args
return args + list(_PRIVDROP_CAP_ARGS)
def _image_uses_init_entrypoint(docker_exe: str, image: str) -> bool:
- """Return True if ``image``'s entrypoint is the s6-overlay ``/init``.
-
- Such images (e.g. anything built on ``s6-overlay``, including
- ``hermes-agent:latest``) already provide their own PID-1 init and execute
- ``/run/s6/basedir/bin/init`` during stage0 startup. They are incompatible
- with Docker's ``--init`` (two competing PID-1 inits) and with a ``noexec``
- ``/run`` mount. Detection is best-effort: on any inspection failure we
- return False and keep the hardened defaults.
- """
+ """True if ``image``'s entrypoint is the s6-overlay ``/init`` (own PID 1: incompatible
+ with ``--init`` and a noexec /run). Any inspection failure, including an image not yet
+ pulled, returns False and keeps the hardened defaults."""
try:
- result = subprocess.run(
- [docker_exe, "image", "inspect", image,
- "--format", "{{json .Config.Entrypoint}}"],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
+ result = run_capture(
+ [docker_exe, "image", "inspect", image, "--format", "{{json .Config.Entrypoint}}"],
timeout=15,
- stdin=subprocess.DEVNULL,
)
except (subprocess.SubprocessError, OSError) as e:
logger.debug("Docker: could not inspect entrypoint for %s: %s", image, e)
return False
if result.returncode != 0:
- # Image may not be pulled yet; the run will pull it. Defaults are safe
- # for non-s6 images, so don't block on this.
logger.debug(
"Docker: image inspect for %s returned %d (stderr=%s)",
image, result.returncode, result.stderr.strip(),
@@ -722,18 +343,12 @@ def _image_uses_init_entrypoint(docker_exe: str, image: str) -> bool:
entrypoint = [entrypoint]
if not isinstance(entrypoint, list) or not entrypoint:
return False
- first = str(entrypoint[0]).strip()
- return first in ("/init", "/package/admin/s6-overlay/command/init")
+ return str(entrypoint[0]).strip() in _S6_INIT_ENTRYPOINTS
def _resolve_host_user_spec() -> Optional[str]:
- """Return ``<uid>:<gid>`` for the current host user, or ``None`` on platforms
- where this is not meaningful (e.g. Windows without posix ids).
-
- We intentionally read ``os.getuid()``/``os.getgid()`` directly rather than
- going through ``getpass``/``pwd`` so this stays cheap and never raises on
- nameless UIDs (nss lookups can fail inside sandboxed launchers).
- """
+ """``<uid>:<gid>`` of the host user, or ``None`` without POSIX ids. Uses os.getuid/getgid
+ directly (not pwd/getpass) so nameless UIDs inside sandboxed launchers never raise."""
get_uid = getattr(os, "getuid", None)
get_gid = getattr(os, "getgid", None)
if get_uid is None or get_gid is None:
@@ -749,21 +364,10 @@ _cgroup_limits_ok: Optional[bool] = None # cached result across instances
def _cgroup_limits_available(image: str) -> bool:
- """Probe whether cgroup resource limits work in this environment.
-
- Tests ``--cpus``, ``--memory`` and ``--pids-limit`` together by spawning
- a throwaway container from *image* (the same sandbox image we are about
- to use for real, so no extra pull and no dependency on a public
- registry). The container runs ``sleep 0`` — sleep is guaranteed to be
- present because the sandbox itself uses ``sleep 2h`` as its long-lived
- entrypoint.
-
- On hosts where the corresponding cgroup controllers are not delegated
- to this process (typical inside unprivileged LXCs and some rootless
- setups) these flags cause every container start to fail with ``OCI
- runtime error`` / exit 126. The probe runs once per process and the
- result — which is host-wide, not image-specific — is cached.
- """
+ """Probe once per process whether ``--cpus``/``--memory``/``--pids-limit`` work here, via a
+ throwaway ``sleep 0`` container from *image* (no extra pull). Without delegated cgroup
+ controllers (unprivileged LXCs, rootless) these flags fail every start with exit 126;
+ the result is host-wide, so it is cached."""
global _cgroup_limits_ok
if _cgroup_limits_ok is not None:
return _cgroup_limits_ok
@@ -774,14 +378,10 @@ def _cgroup_limits_available(image: str) -> bool:
return False
try:
- result = subprocess.run(
- [docker_exe, "run", "--rm",
- "--cpus", "0.5", "--memory", "64m", "--pids-limit", "32",
+ result = run_capture(
+ [docker_exe, "run", "--rm", "--cpus", "0.5", "--memory", "64m", "--pids-limit", "32",
image, "sleep", "0"],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
timeout=60,
- stdin=subprocess.DEVNULL,
)
_cgroup_limits_ok = result.returncode == 0
if not _cgroup_limits_ok:
@@ -796,101 +396,110 @@ def _cgroup_limits_available(image: str) -> bool:
except Exception as e:
_cgroup_limits_ok = False
logger.warning("Cgroup limit probe failed; disabling resource limits: %s", e)
-
return _cgroup_limits_ok
-def _ensure_docker_available() -> None:
- """Best-effort check that the docker CLI is available before use.
+def _docker_unavailable(log_msg: str, *log_args, error: str, hint: str, exc_info: bool = False):
+ logger.error(log_msg, *log_args, exc_info=exc_info)
+ return EnvironmentConnectionError(error, retry_hint=hint)
- Reuses ``find_docker()`` so this preflight stays consistent with the rest of
- the Docker backend, including known non-PATH Docker Desktop locations.
- """
+
+def _ensure_docker_available() -> None:
+ """Fail fast with an ``EnvironmentConnectionError`` when the docker CLI/daemon is unusable."""
docker_exe = find_docker()
if not docker_exe:
- logger.error(
+ raise _docker_unavailable(
"Docker backend selected but no docker executable was found in PATH "
"or known install locations. Install Docker Desktop and ensure the "
- "CLI is available."
- )
- raise EnvironmentConnectionError(
- "Docker executable not found in PATH or known install locations. "
- "Install Docker and ensure the 'docker' command is available.",
- retry_hint=(
- "Install Docker (or fix PATH) and retry, or switch "
- "terminal.backend to 'local'."
- ),
+ "CLI is available.",
+ error="Docker executable not found in PATH or known install locations. "
+ "Install Docker and ensure the 'docker' command is available.",
+ hint="Install Docker (or fix PATH) and retry, or switch terminal.backend to 'local'.",
)
-
try:
- result = subprocess.run(
- [docker_exe, "version"],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=5,
- stdin=subprocess.DEVNULL,
- )
+ result = run_capture([docker_exe, "version"], timeout=5)
except FileNotFoundError:
- logger.error(
- "Docker backend selected but the resolved docker executable '%s' could "
- "not be executed.",
- docker_exe,
- exc_info=True,
- )
- raise EnvironmentConnectionError(
- "Docker executable could not be executed. Check your Docker installation.",
- retry_hint="Repair the Docker installation and retry.",
+ raise _docker_unavailable(
+ "Docker backend selected but the resolved docker executable '%s' could not be executed.",
+ docker_exe, exc_info=True,
+ error="Docker executable could not be executed. Check your Docker installation.",
+ hint="Repair the Docker installation and retry.",
)
except subprocess.TimeoutExpired:
- logger.error(
- "Docker backend selected but '%s version' timed out. "
- "The Docker daemon may not be running.",
- docker_exe,
- exc_info=True,
- )
- raise EnvironmentConnectionError(
- "Docker daemon is not responding. Ensure Docker is running and try again.",
- retry_hint=(
- "Start the Docker daemon (e.g. `systemctl start docker` or "
- "launch Docker Desktop), then retry the same command."
- ),
+ raise _docker_unavailable(
+ "Docker backend selected but '%s version' timed out. The Docker daemon may not be running.",
+ docker_exe, exc_info=True,
+ error="Docker daemon is not responding. Ensure Docker is running and try again.",
+ hint="Start the Docker daemon (e.g. `systemctl start docker` or "
+ "launch Docker Desktop), then retry the same command.",
)
except Exception:
- logger.error(
- "Unexpected error while checking Docker availability.",
- exc_info=True,
- )
+ logger.error("Unexpected error while checking Docker availability.", exc_info=True)
raise
- else:
- if result.returncode != 0:
- logger.error(
- "Docker backend selected but '%s version' failed "
- "(exit code %d, stderr=%s)",
- docker_exe,
- result.returncode,
- result.stderr.strip(),
- )
- raise EnvironmentConnectionError(
- "Docker command is available but 'docker version' failed. "
- "Check your Docker installation.",
- retry_hint=(
- "The Docker daemon may be down or the current user lacks "
- "permission (docker group). Fix and retry."
- ),
- )
+ if result.returncode != 0:
+ raise _docker_unavailable(
+ "Docker backend selected but '%s version' failed (exit code %d, stderr=%s)",
+ docker_exe, result.returncode, result.stderr.strip(),
+ error="Docker command is available but 'docker version' failed. Check your Docker installation.",
+ hint="The Docker daemon may be down or the current user lacks "
+ "permission (docker group). Fix and retry.",
+ )
-class DockerEnvironment(BaseEnvironment):
- """Hardened Docker container execution with resource limits and persistence.
+def _name_only_env_args(names) -> list[str]:
+ """``-e KEY`` flags (no values): the docker CLI resolves values from its own env,
+ so secrets live in owner-readable /proc/*/environ instead of world-readable cmdline."""
+ args: list[str] = []
+ for key in sorted(names):
+ args.extend(["-e", key])
+ return args
- Security: all capabilities dropped, no privilege escalation, PID limits,
- size-limited tmpfs for scratch dirs. The container itself is the security
- boundary — the filesystem inside is writable so agents can install packages
- (pip, npm, apt) as needed. Writable workspace via tmpfs or bind mounts.
- Persistence: when enabled, bind mounts preserve /workspace and /root
- across container restarts.
+# Mount kinds declared by skills/credential_files: (getter, expects_file, log noun).
+_RO_MOUNT_SOURCES = (
+ ("get_credential_file_mounts", True, "credential"),
+ ("get_skills_directory_mount", False, "skills dir"),
+ ("get_cache_directory_mounts", False, "cache dir"),
+)
+
+
+def _readonly_skill_mount_args() -> list[str]:
+ """``-v host:container:ro`` args for credential files, skill dirs and cache dirs.
+
+ Read-only so the container can authenticate/read but never modify host state.
+ Missing or wrong-kind sources are skipped with a warning (Docker-in-Docker
+ auto-creates a missing file source as a directory, which would exit 125).
"""
+ args: list[str] = []
+ try:
+ import tools.credential_files as cf
+ for getter, expects_file, noun in _RO_MOUNT_SOURCES:
+ for entry in getattr(cf, getter)():
+ src = Path(entry["host_path"])
+ if expects_file and src.is_dir():
+ logger.warning(
+ "Docker: skipping credential mount — source is a directory "
+ "(likely Docker-in-Docker auto-creation): %s", src,
+ )
+ continue
+ if expects_file and not src.is_file():
+ logger.warning("Docker: skipping credential mount — source not found: %s", src)
+ continue
+ if not expects_file and not src.is_dir():
+ logger.warning("Docker: skipping %s mount — source is not a directory: %s",
+ noun.split()[0], src)
+ continue
+ args.extend(["-v", f"{entry['host_path']}:{entry['container_path']}:ro"])
+ logger.info("Docker: mounting %s %s -> %s", noun, entry["host_path"], entry["container_path"])
+ except Exception as e:
+ logger.debug("Docker: could not load credential file mounts: %s", e)
+ return args
+
+
+class DockerEnvironment(BaseEnvironment):
+ """Hardened Docker container execution (caps dropped, no-new-privileges, PID limits,
+ size-limited tmpfs). The container is the security boundary — its filesystem stays
+ writable so agents can install packages. Persistence bind-mounts /workspace and /root."""
_profile_scoped_passthrough = True
@@ -925,9 +534,8 @@ class DockerEnvironment(BaseEnvironment):
super().__init__(cwd=cwd, timeout=timeout)
self._persistent = persistent_filesystem
self._persist_across_processes = persist_across_processes
- # Set by terminal_tool._create_environment when this container is
- # scoped to a single session (docker + container_persistent: false):
- # survives between turns, removed at session close / idle timeout.
+ # Set by terminal_tool._create_environment for session-scoped containers
+ # (docker + container_persistent: false): removed at session close/idle timeout.
self._session_scoped = False
self._task_id = task_id
self._forward_env = _normalize_forward_env_names(forward_env)
@@ -936,55 +544,148 @@ class DockerEnvironment(BaseEnvironment):
self._container_id: Optional[str] = None
self._labels: dict[str, str] = {}
self._image: str = ""
- self._container_name: str = ""
self._image_uses_s6_init: bool = False
self._all_run_args: list[str] = []
self._run_env_values: dict[str, str] = {}
self._init_env_values: dict[str, str] = {}
+ self._workspace_dir: Optional[str] = None
+ self._home_dir: Optional[str] = None
logger.info("DockerEnvironment volumes: %s", volumes)
- # Ensure volumes is a list (config.yaml could be malformed)
if volumes is not None and not isinstance(volumes, list):
logger.warning("docker_volumes config is not a list: %r", volumes)
volumes = []
- # Fail fast if Docker is not available.
_ensure_docker_available()
- # Build resource limit args (gated by cgroup availability probe so
- # they degrade gracefully on hosts without controller delegation,
- # e.g. unprivileged LXCs). The probe runs once per process and is
- # cached host-wide.
- resource_args = []
+ resource_args = self._resource_args(image, cpu, memory, disk, network, shm_size, extra_args)
+ volume_args, writable_args = self._mount_args(volumes, host_cwd, auto_mount_cwd, task_id)
+ volume_args.extend(_readonly_skill_mount_args())
+
+ # Egress credential-injection proxy: CA mount + HTTPS_PROXY/CA-bundle env
+ # so outbound traffic routes through the host-side proxy and the sandbox
+ # receives proxy tokens instead of real API keys.
+ egress_volume_args, egress_env_overrides, egress_host_args = _egress_proxy_args_for_docker()
+ egress_label = _egress_reuse_fingerprint(egress_volume_args, egress_env_overrides, egress_host_args)
+ enforce_egress = _egress_enforce_on_docker() if egress_env_overrides else True
+ critical_egress_names = _critical_egress_env_names(egress_env_overrides)
+ if egress_env_overrides:
+ check_forward_env_collisions(self._forward_env, critical_egress_names, enforce_egress)
+ check_docker_env_collisions(self._env, egress_env_overrides, enforce_egress)
+ volume_args.extend(egress_volume_args)
+
+ merged_env = merge_egress_env(self._env, egress_env_overrides, enforce_egress)
+ env_args = _name_only_env_args(merged_env)
+ # Injected into the docker-client subprocess env at run time (also reused
+ # verbatim by the container-recreation recovery path).
+ self._run_env_values = dict(merged_env)
+
+ # Run as the host user so files written to bind mounts are owned by
+ # them, not root. Without POSIX ids fall back to the full cap set —
+ # the image's init may still need to drop privileges.
+ user_args: list[str] = []
+ if run_as_host_user:
+ user_spec = _resolve_host_user_spec()
+ if user_spec is not None:
+ user_args = ["--user", user_spec]
+ logger.info("Docker: running container as host user %s", user_spec)
+ else:
+ logger.warning(
+ "docker_run_as_host_user is enabled but this platform does "
+ "not expose POSIX uid/gid; container will start as its "
+ "image default user."
+ )
+
+ # Resolved once so it works when /usr/local/bin is not in PATH (macOS services).
+ self._docker_exe = find_docker() or "docker"
+
+ image_uses_s6_init = _image_uses_init_entrypoint(self._docker_exe, image)
+ if image_uses_s6_init:
+ logger.info(
+ "Docker: image %s uses /init (s6-overlay) as entrypoint — "
+ "skipping --init and mounting /run with exec.",
+ image,
+ )
+ security_args = _build_security_args(run_as_host_user and bool(user_args), run_exec=image_uses_s6_init)
+
+ logger.info("Docker volume_args: %s", volume_args)
+ # docker_extra_args go last so they can override defaults.
+ validated_extra = []
+ for arg in (extra_args or []):
+ if not isinstance(arg, str):
+ logger.warning("Ignoring non-string docker_extra_args entry: %r", arg)
+ continue
+ validated_extra.append(arg)
+ if egress_env_overrides:
+ check_extra_args_collisions(validated_extra, critical_egress_names, enforce_egress)
+
+ all_run_args = (
+ security_args + user_args + writable_args + resource_args
+ + egress_host_args + volume_args + env_args + validated_extra
+ )
+ logger.info("Docker run_args: %s", all_run_args)
+
+ # Labels identify hermes containers to the orphan reaper (hermes-agent=1),
+ # cross-process reuse (task-id/profile) and operators. The reuse identity
+ # is captured at start and never changes for the container's lifetime.
+ # Egress posture gets its own label: env/CA mounts are immutable after
+ # creation, so reusing a pre-egress container would bypass the firewall.
+ profile_name = _container_identity(shared_container_key)
+ task_label = _sanitize_label_value(task_id)
+ self._labels = {
+ "hermes-agent": "1",
+ "hermes-task-id": task_label,
+ "hermes-profile": profile_name,
+ _EGRESS_LABEL_KEY: egress_label,
+ }
+ # Saved for container recreation on "No such container" recovery.
+ self._image = image
+ self._image_uses_s6_init = image_uses_s6_init
+ self._all_run_args = all_run_args
+
+ reused = persist_across_processes and self._attach_existing_container(
+ task_label, profile_name, egress_label, network,
+ )
+ if not reused:
+ self._container_id = self._docker_run(cwd)
+
+ # Init-time env forwarding args seed the snapshot.
+ self._init_env_args = self._build_init_env_args()
+ self.init_session()
+
+ # ------------------------------------------------------------------
+ # __init__ helpers
+ # ------------------------------------------------------------------
+
+ def _resource_args(self, image, cpu, memory, disk, network, shm_size, extra_args) -> list[str]:
+ """cgroup-gated CPU/memory/pids limits, shm size, disk quota and network mode."""
+ args: list[str] = []
if cpu > 0 and _cgroup_limits_available(image):
- resource_args.extend(["--cpus", str(cpu)])
+ args.extend(["--cpus", str(cpu)])
if memory > 0 and _cgroup_limits_available(image):
- resource_args.extend(["--memory", f"{memory}m"])
+ args.extend(["--memory", f"{memory}m"])
if _cgroup_limits_available(image):
- resource_args.extend(["--pids-limit", _DEFAULT_PIDS_LIMIT])
- # /dev/shm size (not cgroup-gated: --shm-size is a tmpfs mount option,
- # no controller delegation required). Skip when the user already sets
- # it via docker_extra_args, or opted out with an empty/"0" value.
+ args.extend(["--pids-limit", _DEFAULT_PIDS_LIMIT])
+ # --shm-size is a tmpfs option, not cgroup-gated. Skipped when the user
+ # sets it in docker_extra_args or opts out with empty/"0".
shm = str(shm_size or "").strip()
if shm and shm != "0" and not _extra_args_set_shm_size(extra_args):
- resource_args.extend(["--shm-size", shm])
+ args.extend(["--shm-size", shm])
if disk > 0 and sys.platform != "darwin":
if self._storage_opt_supported():
- resource_args.extend(["--storage-opt", f"size={disk}m"])
+ args.extend(["--storage-opt", f"size={disk}m"])
else:
logger.warning(
"Docker storage driver does not support per-container disk limits "
"(requires overlay2 on XFS with pquota). Container will run without disk quota."
)
if not network:
- resource_args.append("--network=none")
-
- # Persistent workspace via bind mounts from a configurable host directory
- # (TERMINAL_SANDBOX_DIR, default ~/.hermes/sandboxes/). Non-persistent
- # mode uses tmpfs (ephemeral, fast, gone on cleanup).
- from tools.environments.base import get_sandbox_dir
+ args.append("--network=none")
+ return args
- # User-configured volume mounts (from config.yaml docker_volumes)
- volume_args = []
+ def _mount_args(self, volumes, host_cwd, auto_mount_cwd, task_id) -> tuple[list[str], list[str]]:
+ """``(volume_args, writable_args)`` for user volumes, host cwd and /workspace,/root.
+ Persistent mode bind-mounts from TERMINAL_SANDBOX_DIR (default ~/.hermes/sandboxes/)."""
+ volume_args: list[str] = []
workspace_explicitly_mounted = False
for vol in (volumes or []):
if not isinstance(vol, str):
@@ -993,649 +694,171 @@ class DockerEnvironment(BaseEnvironment):
vol = vol.strip()
if not vol:
continue
- if ":" in vol:
- volume_args.extend(["-v", vol])
- if ":/workspace" in vol:
- workspace_explicitly_mounted = True
- else:
+ if ":" not in vol:
logger.warning("Docker volume '%s' missing colon, skipping", vol)
+ continue
+ volume_args.extend(["-v", vol])
+ if ":/workspace" in vol:
+ workspace_explicitly_mounted = True
host_cwd_abs = os.path.abspath(os.path.expanduser(host_cwd)) if host_cwd else ""
bind_host_cwd = (
- auto_mount_cwd
- and bool(host_cwd_abs)
- and os.path.isdir(host_cwd_abs)
+ auto_mount_cwd and bool(host_cwd_abs) and os.path.isdir(host_cwd_abs)
and not workspace_explicitly_mounted
)
if auto_mount_cwd and host_cwd and not os.path.isdir(host_cwd_abs):
logger.debug("Skipping docker cwd mount: host_cwd is not a valid directory: %s", host_cwd)
+ mount_workspace = not bind_host_cwd and not workspace_explicitly_mounted
- self._workspace_dir: Optional[str] = None
- self._home_dir: Optional[str] = None
- writable_args = []
+ writable_args: list[str] = []
if self._persistent:
+ from tools.environments.base import get_sandbox_dir
# _sandbox_dir_name(): a raw session-key task_id carries colons,
# which `-v` reads as extra spec fields (exit 125).
sandbox = get_sandbox_dir() / "docker" / _sandbox_dir_name(task_id)
self._home_dir = str(sandbox / "home")
os.makedirs(self._home_dir, exist_ok=True)
- writable_args.extend([
- "-v", f"{self._home_dir}:/root",
- ])
- if not bind_host_cwd and not workspace_explicitly_mounted:
+ writable_args += ["-v", f"{self._home_dir}:/root"]
+ if mount_workspace:
self._workspace_dir = str(sandbox / "workspace")
os.makedirs(self._workspace_dir, exist_ok=True)
- writable_args.extend([
- "-v", f"{self._workspace_dir}:/workspace",
- ])
+ writable_args += ["-v", f"{self._workspace_dir}:/workspace"]
else:
- if not bind_host_cwd and not workspace_explicitly_mounted:
- writable_args.extend([
- "--tmpfs", "/workspace:rw,exec,size=10g",
- ])
- writable_args.extend([
- "--tmpfs", "/home:rw,exec,size=1g",
- "--tmpfs", "/root:rw,exec,size=1g",
- ])
+ if mount_workspace:
+ writable_args += ["--tmpfs", "/workspace:rw,exec,size=10g"]
+ writable_args += ["--tmpfs", "/home:rw,exec,size=1g", "--tmpfs", "/root:rw,exec,size=1g"]
if bind_host_cwd:
logger.info("Mounting configured host cwd to /workspace: %s", host_cwd_abs)
volume_args = ["-v", f"{host_cwd_abs}:/workspace", *volume_args]
elif workspace_explicitly_mounted:
logger.debug("Skipping docker cwd mount: /workspace already mounted by user config")
-
- # Mount credential files (OAuth tokens, etc.) declared by skills.
- # Read-only so the container can authenticate but not modify host creds.
- try:
- from tools.credential_files import (
- get_credential_file_mounts,
- get_skills_directory_mount,
- get_cache_directory_mounts,
- )
-
- for mount_entry in get_credential_file_mounts():
- src = Path(mount_entry["host_path"])
- if src.is_dir():
- # Docker-in-Docker: Docker auto-created the source path as
- # a directory when it didn't exist on the host. Mounting a
- # directory over a file destination causes exit 125.
- logger.warning(
- "Docker: skipping credential mount — source is a directory "
- "(likely Docker-in-Docker auto-creation): %s",
- src,
- )
- continue
- if not src.is_file():
- logger.warning(
- "Docker: skipping credential mount — source not found: %s", src,
- )
- continue
- volume_args.extend([
- "-v",
- f"{mount_entry['host_path']}:{mount_entry['container_path']}:ro",
- ])
- logger.info(
- "Docker: mounting credential %s -> %s",
- mount_entry["host_path"],
- mount_entry["container_path"],
- )
-
- # Mount skill directories (local + external) so skill
- # scripts/templates are available inside the container.
- for skills_mount in get_skills_directory_mount():
- src = Path(skills_mount["host_path"])
- if not src.is_dir():
- logger.warning(
- "Docker: skipping skills mount — source is not a directory: %s",
- src,
- )
- continue
- volume_args.extend([
- "-v",
- f"{skills_mount['host_path']}:{skills_mount['container_path']}:ro",
- ])
- logger.info(
- "Docker: mounting skills dir %s -> %s",
- skills_mount["host_path"],
- skills_mount["container_path"],
- )
-
- # Mount host-side cache directories (documents, images, audio,
- # screenshots) so the agent can access uploaded files and other
- # cached media from inside the container. Read-only — the
- # container reads these but the host gateway manages writes.
- for cache_mount in get_cache_directory_mounts():
- src = Path(cache_mount["host_path"])
- if not src.is_dir():
- logger.warning(
- "Docker: skipping cache mount — source is not a directory: %s",
- src,
- )
- continue
- volume_args.extend([
- "-v",
- f"{cache_mount['host_path']}:{cache_mount['container_path']}:ro",
- ])
- logger.info(
- "Docker: mounting cache dir %s -> %s",
- cache_mount["host_path"],
- cache_mount["container_path"],
- )
- except Exception as e:
- logger.debug("Docker: could not load credential file mounts: %s", e)
-
- # Egress credential-injection proxy (iron-proxy) — when configured,
- # mount the CA cert into the sandbox and set HTTPS_PROXY + CA-bundle
- # env vars so outbound traffic routes through the host-side proxy.
- # The sandbox receives PROXY tokens instead of real API keys.
- egress_volume_args, egress_env_overrides, egress_host_args = (
- _egress_proxy_args_for_docker()
- )
- egress_label = _egress_reuse_fingerprint(
- egress_volume_args, egress_env_overrides, egress_host_args,
- )
- _enforce_egress = _egress_enforce_on_docker()
- _critical_egress_names = _critical_egress_env_names(egress_env_overrides)
- if egress_env_overrides:
- _forward_collisions = sorted(
- key for key in self._forward_env if key in _critical_egress_names
- )
- if _forward_collisions:
- _msg = (
- f"docker_forward_env would inject real egress-protected "
- f"variables {_forward_collisions}; enforce_on_docker is "
- f"{'enabled' if _enforce_egress else 'disabled'}."
- )
- if _enforce_egress:
- raise RuntimeError(
- f"{_msg} Remove these names from docker_forward_env "
- "or disable enforce_on_docker to opt out of egress isolation."
- )
+ return volume_args, writable_args
+
+ def _attach_existing_container(self, task_label, profile_name, egress_label, network: bool) -> bool:
+ """Attach to a prior process's labeled container ("ONE long-lived container shared
+ across sessions"; opt out via ``docker_persist_across_processes: false``).
+ Network guard is lockdown-only: a bridge container under ``docker_network: false``
+ is removed and recreated, but a ``none`` container under default config is kept so
+ ``--network=none`` in extra args doesn't churn containers every startup."""
+ existing = self._find_reusable_container(task_label, profile_name, egress_label)
+ if existing is None:
+ return False
+ container_id, state = existing
+ if not network:
+ actual_mode = self._container_network_mode(container_id)
+ if actual_mode != "none":
logger.warning(
- "%s Explicit docker_forward_env values will override egress tokens.",
- _msg,
+ "Existing container %s has NetworkMode=%s but "
+ "docker_network=false requests an air-gapped "
+ "container — removing it and starting fresh "
+ "(task=%s, profile=%s).",
+ container_id[:12], actual_mode or "unknown", task_label, profile_name,
)
- volume_args.extend(egress_volume_args)
- # egress env overrides are merged in further below alongside the
- # other env_args computation.
-
- # Explicit environment variables (docker_env config) — set at container
- # creation so they're available to all processes (including entrypoint).
- # Egress proxy env vars (HTTPS_PROXY, CA-bundle paths, proxy tokens)
- # are merged below. Precedence policy:
- #
- # - When egress enforcement is on AND the user's docker_env tries
- # to override one of the proxy-control vars (HTTPS_PROXY,
- # SSL_CERT_FILE, etc.), fail-loud rather than silently inverting
- # the isolation. The CA mount + tokens would still ship while
- # traffic leaves the sandbox direct with real credentials —
- # exactly what enforce_on_docker is meant to prevent.
- # - When enforcement is off, the user's docker_env wins (current
- # behavior) but we log a warning naming both config sources.
- # - When the user override is identical to the egress value, no-op.
- if egress_env_overrides:
- try:
- from hermes_cli.config import load_config as _load_cfg_for_collision
- _proxy_cfg = (_load_cfg_for_collision().get("proxy") or {})
- except (ImportError, OSError):
- _proxy_cfg = {}
- except Exception as _e: # noqa: BLE001 — narrowed below via yaml import
- # yaml.YAMLError from a malformed config.yaml. We import
- # lazily because PyYAML is a soft dep in some test envs.
try:
- import yaml # noqa: F401
- except ImportError:
- raise
- logger.warning(
- "Could not read proxy config for egress collision check: %s",
- _e,
- )
- _proxy_cfg = {}
- _enforce_egress = bool(_proxy_cfg.get("enforce_on_docker", True))
- # Egress-controlling env vars that affect the proxy posture.
- _critical_proxy_control = {
- "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy",
- "NO_PROXY", "no_proxy",
- "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE", "CURL_CA_BUNDLE",
- "NODE_EXTRA_CA_CERTS",
- }
- # stephenschoettler #2: also block docker_env from injecting
- # real provider keys. `docker_env: {OPENROUTER_API_KEY: sk-real}`
- # in config.yaml puts the live secret into the sandbox while
- # egress is nominally enforced — defeats the entire feature.
- # Pull the mapped real_env_name from each token mapping at
- # call time so this stays in sync with whatever the operator
- # has configured.
- _critical_provider_keys: set[str] = set()
- try:
- from agent.proxy_sources import iron_proxy as _ip_for_mappings
- _critical_provider_keys = {
- m.real_env_name for m in _ip_for_mappings.load_mappings()
- }
- except Exception: # noqa: BLE001 — best-effort collision check
- pass
- _critical = _critical_proxy_control | _critical_provider_keys
- _collisions = sorted(
- k for k in _critical
- if k in self._env
- and (
- k not in egress_env_overrides
- or self._env[k] != egress_env_overrides[k]
- )
- # For provider keys, ANY override is a collision (the egress
- # path mints proxy tokens; a real key in docker_env bypasses
- # the swap regardless of whether the egress dict happens to
- # carry it).
- and (
- k in _critical_provider_keys
- or (k in egress_env_overrides
- and self._env[k] != egress_env_overrides[k])
- )
- )
- if _collisions:
- _msg = (
- f"docker_env in config.yaml overrides egress-proxy "
- f"variables {_collisions}; enforce_on_docker is "
- f"{'enabled' if _enforce_egress else 'disabled'}."
- )
- if _enforce_egress:
- raise RuntimeError(
- f"{_msg} Remove these keys from docker_env or "
- "disable enforce_on_docker to opt out of egress "
- "isolation."
- )
- logger.warning(
- "%s Falling back to docker_env values; sandbox traffic "
- "will NOT route through the proxy.", _msg,
- )
-
- # When enforce_on_docker is true, egress overrides win. When
- # false, docker_env wins (back-compat for users who deliberately
- # opt out). In both cases the collision check above has already
- # surfaced any disagreement.
- try:
- from hermes_cli.config import load_config as _load_cfg_for_precedence
- _enforce_egress_merge = bool(
- (_load_cfg_for_precedence().get("proxy") or {})
- .get("enforce_on_docker", True)
- )
- except (ImportError, OSError):
- _enforce_egress_merge = True
- except Exception: # noqa: BLE001 — yaml.YAMLError or similar
- # Malformed config.yaml; fail-safe to enforced.
- _enforce_egress_merge = True
-
- if _enforce_egress_merge and egress_env_overrides:
- merged_env = dict(self._env)
- merged_env.update(egress_env_overrides)
- else:
- merged_env = dict(egress_env_overrides)
- merged_env.update(self._env)
-
- # arshkumarsingh #1: NODE_OPTIONS append-merge. The egress path
- # wants ``--use-openssl-ca`` so Node routes through the OpenSSL
- # CA store ``SSL_CERT_FILE`` controls. But the operator's
- # ``docker_env: {NODE_OPTIONS: "--max-old-space-size=8192"}``
- # MUST be preserved — replacing it would silently drop their
- # tuning. We carry the egress flag in a sentinel key
- # ``_HERMES_EGRESS_NODE_OPTIONS_APPEND`` and merge here.
- _egress_node_append = merged_env.pop(
- "_HERMES_EGRESS_NODE_OPTIONS_APPEND", None,
- )
- if _egress_node_append:
- existing_node = merged_env.get("NODE_OPTIONS", "")
- existing_tokens = existing_node.split()
- # maxpetrusenko P1: dedupe is not enough — the operator may have set
- # a CONFLICTING CA-mode flag (e.g. --use-bundled-ca) that would
- # otherwise survive alongside our --use-openssl-ca, leaving Node's
- # final trust behavior dependent on option order / Node parsing.
- # Egress isolation requires our flag to win deterministically, so
- # strip any known-conflicting CA-mode flags before appending.
- _CA_MODE_FLAGS = {"--use-openssl-ca", "--use-bundled-ca"}
- append_token = _egress_node_append.strip()
- if append_token in _CA_MODE_FLAGS:
- dropped = [t for t in existing_tokens if t in _CA_MODE_FLAGS and t != append_token]
- if dropped:
- logger.warning(
- "Overriding conflicting NODE_OPTIONS CA-mode flag(s) %s "
- "with egress-required %s to keep Node routed through the "
- "egress CA store.", dropped, append_token,
- )
- existing_tokens = [t for t in existing_tokens if t not in _CA_MODE_FLAGS or t == append_token]
- # De-dup: only add if not already present (the operator may
- # have set the same flag themselves).
- if append_token not in existing_tokens:
- existing_tokens.append(append_token)
- merged_env["NODE_OPTIONS"] = " ".join(existing_tokens).strip()
- if not merged_env["NODE_OPTIONS"]:
- merged_env.pop("NODE_OPTIONS", None)
-
- # Name-only -e flags: the docker CLI resolves a valueless `--env KEY`
- # from its own process environment, so the secret values travel via
- # the spawned client's env (owner-readable /proc/*/environ) instead of
- # its argv (world-readable /proc/*/cmdline). See issue #96268.
- env_args = []
- for key in sorted(merged_env):
- env_args.extend(["-e", key])
- # Values injected into the docker-client subprocess env at run time
- # (also reused verbatim by the container-recreation recovery path).
- self._run_env_values = dict(merged_env)
-
- # Optional: run the container as the host user so files written into
- # bind-mounted dirs (/workspace, /root, docker_volumes entries) are
- # owned by that user on the host instead of by root. Skip cleanly on
- # platforms without POSIX uid/gid (e.g. native Windows Docker).
- user_args: list[str] = []
- if run_as_host_user:
- user_spec = _resolve_host_user_spec()
- if user_spec is not None:
- user_args = ["--user", user_spec]
- logger.info("Docker: running container as host user %s", user_spec)
- else:
- logger.warning(
- "docker_run_as_host_user is enabled but this platform does "
- "not expose POSIX uid/gid; container will start as its "
- "image default user."
- )
- # Fall back to the full cap set — without --user, an image's
- # init may still need s6-setuidgid/gosu/su to drop privileges.
-
- # Resolve the docker executable once so it works even when
- # /usr/local/bin is not in PATH (common on macOS gateway/service).
- self._docker_exe = find_docker() or "docker"
-
- # s6-overlay images (e.g. hermes-agent:latest) already use /init as PID 1
- # and exec /run/s6/basedir/bin/init during startup. For those images we
- # must (a) skip Docker's --init (two competing PID-1 inits) and (b) mount
- # /run with exec instead of noexec, or s6 stage0 dies with exit 126
- # "Permission denied". Detected once here; defaults are kept on any
- # inspection failure. See issue #34628.
- image_uses_s6_init = _image_uses_init_entrypoint(self._docker_exe, image)
- if image_uses_s6_init:
- logger.info(
- "Docker: image %s uses /init (s6-overlay) as entrypoint — "
- "skipping --init and mounting /run with exec.",
- image,
- )
- security_args = _build_security_args(
- run_as_host_user and bool(user_args),
- run_exec=image_uses_s6_init,
- )
+ run_capture([self._docker_exe, "rm", "-f", container_id], timeout=30)
+ except (subprocess.TimeoutExpired, OSError) as e:
+ logger.warning("Failed to remove mismatched container %s: %s", container_id[:12], e)
+ return False
- logger.info("Docker volume_args: %s", volume_args)
- # User-supplied extra docker run flags (docker_extra_args in config.yaml).
- # Appended last so they can override defaults if needed.
- validated_extra = []
- for arg in (extra_args or []):
- if not isinstance(arg, str):
- logger.warning("Ignoring non-string docker_extra_args entry: %r", arg)
- continue
- validated_extra.append(arg)
- if egress_env_overrides:
- _extra_collisions = _extra_args_egress_collisions(
- validated_extra, _critical_egress_names,
- )
- if _extra_collisions:
- _msg = (
- f"docker_extra_args would override egress-proxy controls "
- f"{_extra_collisions}; enforce_on_docker is "
- f"{'enabled' if _enforce_egress else 'disabled'}."
- )
- if _enforce_egress:
- raise RuntimeError(
- f"{_msg} Remove these args or disable enforce_on_docker "
- "to opt out of egress isolation."
- )
+ if state != "running":
+ try:
+ run_capture([self._docker_exe, "start", container_id], timeout=30, check=True)
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
logger.warning(
- "%s Extra Docker args may bypass egress isolation.", _msg,
+ "Failed to start existing container %s (state=%s): "
+ "%s — falling back to a fresh container.",
+ container_id[:12], state, e,
)
-
- all_run_args = (
- security_args
- + user_args
- + writable_args
- + resource_args
- + egress_host_args
- + volume_args
- + env_args
- + validated_extra
+ return False
+ self._container_id = container_id
+ logger.info(
+ "Reusing container %s (task=%s, profile=%s, prior state=%s)",
+ container_id[:12], task_label, profile_name, state,
)
- logger.info("Docker run_args: %s", all_run_args)
+ return True
- # Start the container directly via `docker run -d`.
- container_name = f"hermes-{uuid.uuid4().hex[:8]}"
- # Labels make hermes-created containers identifiable to:
- # * the orphan reaper (`hermes-agent=1` for the global sweep filter)
- # * future cross-process reuse (`hermes-task-id`, `hermes-profile`)
- # * operators running `docker ps --filter label=hermes-agent=1`
- # Values are limited to the safe character set defined by
- # _sanitize_label_value(); the configured reuse identity is captured at
- # container-start time and never changes for the container's lifetime.
- profile_name = _container_identity(shared_container_key)
- task_label = _sanitize_label_value(task_id)
- label_args = [
- "--label", "hermes-agent=1",
- "--label", f"hermes-task-id={task_label}",
- "--label", f"hermes-profile={profile_name}",
- "--label", f"{_EGRESS_LABEL_KEY}={egress_label}",
+ def _run_command(self, name: str, workdir: str) -> list[str]:
+ """``docker run -d`` argv for a fresh ``sleep infinity`` container (idle reaper handles
+ lifetime). s6-overlay images already provide PID 1, so ``--init`` is skipped for them."""
+ label_args: list[str] = []
+ for k, v in self._labels.items():
+ label_args.extend(["--label", f"{k}={v}"])
+ return [
+ self._docker_exe, "run", "-d",
+ *([] if self._image_uses_s6_init else ["--init"]),
+ "--name", name,
+ *label_args,
+ "-w", workdir,
+ *self._all_run_args,
+ self._image,
+ "sleep", "infinity",
]
- # Save args for container recreation on "No such container" recovery.
- self._image = image
- self._container_name = container_name
- self._image_uses_s6_init = image_uses_s6_init
- self._all_run_args = all_run_args
-
- self._labels = {
- "hermes-agent": "1",
- "hermes-task-id": task_label,
- "hermes-profile": profile_name,
- _EGRESS_LABEL_KEY: egress_label,
- }
- # Cross-process container reuse (issue #20561 — docs claim "ONE long-lived
- # container shared across sessions"). If a prior Hermes process
- # already started a container for this (task_id, profile) and it
- # still exists, attach to it instead of starting a fresh one. This
- # restores the documented contract; opt out via
- # ``terminal.docker_persist_across_processes: false``.
- #
- # Reuse matches on labels only. The egress posture gets its own label
- # because env vars, CA mounts, and host mappings are immutable after
- # container creation — reusing a pre-egress or pre-rotation container
- # would silently bypass the credential firewall.
- reused = False
- if persist_across_processes:
- existing = self._find_reusable_container(
- task_label, profile_name, egress_label,
+ def _docker_run(self, cwd: str) -> str:
+ """Start a fresh container and return its id. A failed ``docker run`` (exit 125, timeout
+ mid-pull) can leave a "Created" orphan the exited-only reaper never catches, so it is
+ removed by name before re-raising."""
+ container_name = f"hermes-{uuid.uuid4().hex[:8]}"
+ run_cmd = self._run_command(container_name, cwd)
+ logger.debug("Starting container: %s", ' '.join(run_cmd))
+ try:
+ result = run_capture(
+ run_cmd, timeout=120, check=True, # image pull may take a while
+ env=self._docker_client_env(self._run_env_values),
)
- if existing is not None:
- container_id, state = existing
- # Network-mode guard: reuse must not silently defeat an
- # egress lockdown. A container created before the operator
- # set ``docker_network: false`` keeps its original bridge
- # NetworkMode, so label-only reuse would hand the agent a
- # networked container despite the config. On mismatch we
- # remove the stale container and start fresh — leaving it in
- # place would let the next label-based reuse pick it up again.
- # Only the lockdown direction is guarded: a ``none``-mode
- # container under a default-network config is left alone so
- # operators using ``docker_extra_args: ["--network=none"]``
- # don't get their container churned on every startup.
- mode_mismatch = False
- actual_mode = None
- if not network:
- actual_mode = self._container_network_mode(container_id)
- mode_mismatch = actual_mode != "none"
- if mode_mismatch:
- logger.warning(
- "Existing container %s has NetworkMode=%s but "
- "docker_network=false requests an air-gapped "
- "container — removing it and starting fresh "
- "(task=%s, profile=%s).",
- container_id[:12], actual_mode or "unknown",
- task_label, profile_name,
- )
- try:
- subprocess.run(
- [self._docker_exe, "rm", "-f", container_id],
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=30,
- check=False,
- stdin=subprocess.DEVNULL,
- )
- except (subprocess.TimeoutExpired, OSError) as e:
- logger.warning("Failed to remove mismatched container %s: %s", container_id[:12], e)
- existing = None
- if existing is not None:
- container_id, state = existing
- self._container_id = container_id
- if state != "running":
- try:
- subprocess.run(
- [self._docker_exe, "start", container_id],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=30,
- check=True,
- stdin=subprocess.DEVNULL,
- )
- except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
- logger.warning(
- "Failed to start existing container %s (state=%s): "
- "%s — falling back to a fresh container.",
- container_id[:12], state, e,
- )
- self._container_id = None
- if self._container_id:
- logger.info(
- "Reusing container %s (task=%s, profile=%s, prior state=%s)",
- container_id[:12], task_label, profile_name, state,
- )
- reused = True
-
- if not reused:
- # tini/catatonit as PID 1 reaps zombie children — but s6-overlay
- # images already provide their own /init PID 1, so adding --init
- # there creates two competing inits and breaks startup (#34628).
- init_args = [] if image_uses_s6_init else ["--init"]
- run_cmd = [
- self._docker_exe, "run", "-d",
- *init_args,
- "--name", container_name,
- *label_args,
- "-w", cwd,
- *all_run_args,
- image,
- "sleep", "infinity", # no fixed lifetime — idle reaper handles cleanup
- ]
- logger.debug("Starting container: %s", ' '.join(run_cmd))
- try:
- result = subprocess.run(
- run_cmd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=120, # image pull may take a while
- check=True,
- stdin=subprocess.DEVNULL,
- env=self._docker_client_env(self._run_env_values),
- )
- except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
- # Docker may create the container object before `docker run`
- # fails to start it (e.g. exit code 125 when the daemon isn't
- # ready, or a timeout mid-pull). That orphan is left in
- # "Created" state — which the exited-only orphan reaper
- # (reap_orphan_containers, status=exited) never catches, so it
- # leaks permanently. Remove it by its known name before
- # re-raising. See #7439.
- logger.warning(
- "docker run failed for %s, cleaning up orphaned container: %s",
- container_name, e,
- )
- subprocess.run(
- [self._docker_exe, "rm", "-f", container_name],
- capture_output=True, timeout=10,
- stdin=subprocess.DEVNULL,
- )
- raise
- self._container_id = result.stdout.strip()
- logger.info("Started container %s (%s)", container_name, self._container_id[:12])
-
- # Build the init-time env forwarding args used to seed the snapshot.
- self._init_env_args = self._build_init_env_args()
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
+ logger.warning("docker run failed for %s, cleaning up orphaned container: %s", container_name, e)
+ subprocess.run(
+ [self._docker_exe, "rm", "-f", container_name],
+ capture_output=True, timeout=10, stdin=subprocess.DEVNULL,
+ )
+ raise
+ container_id = result.stdout.strip()
+ logger.info("Started container %s (%s)", container_name, container_id[:12])
+ return container_id
- # Initialize session snapshot inside the container
- self.init_session()
+ # ------------------------------------------------------------------
+ # Env forwarding
+ # ------------------------------------------------------------------
def _docker_client_env(self, values: dict[str, str]) -> dict[str, str] | None:
- """Env for a spawned docker-client subprocess carrying forwarded values.
-
- Name-only ``-e KEY`` flags make the docker CLI read each value from
- its own process environment, keeping secrets out of the client's
- world-readable ``/proc/<pid>/cmdline`` (issue #96268). Values live in
- ``/proc/<pid>/environ`` instead, which is owner/root-only.
- Returns ``None`` (inherit as before) when there is nothing to add.
- """
+ """Env for the docker-client subprocess carrying forwarded values (pairs with name-only
+ ``-e KEY`` flags to keep secrets out of cmdline); ``None`` = inherit when empty."""
if not values:
return None
- client_env = dict(os.environ)
- client_env.update(values)
- return client_env
+ return {**os.environ, **values}
def _build_init_env_args(self) -> list[str]:
- """Build name-only -e args for injecting host env vars into init_session.
-
- These are used during init_session() so that export -p captures the
- configured environment and the current profile's forwarded values.
- The VALUES intentionally do not appear in the argv — they are passed
- via the docker client subprocess env (see _docker_client_env and
- issue #96268); the flags here are name-only ``-e KEY``.
- """
+ """Name-only ``-e`` args for init_session so ``export -p`` captures docker_env
+ plus the current profile's forwarded values (values travel via the client env)."""
passthrough_env, unset_names = self._resolve_passthrough_env()
- exec_env: dict[str, str] = dict(self._env)
- exec_env.update(passthrough_env)
+ exec_env = {**self._env, **passthrough_env}
for name in unset_names:
exec_env.pop(name, None)
self._init_unset_passthrough_names = tuple(sorted(unset_names))
self._init_env_values = dict(exec_env)
-
- args = []
- for key in sorted(exec_env):
- args.extend(["-e", key])
- return args
-
- def _build_passthrough_env(self) -> dict[str, str]:
- """Resolve forwarded host variables through the active profile scope."""
- return self._resolve_passthrough_env()[0]
+ return _name_only_env_args(exec_env)
def _resolve_passthrough_env(self) -> tuple[dict[str, str], set[str]]:
- """Return forwarded values and scoped names that must be unset."""
+ """Forwarded values plus scoped names that must be unset. Explicit docker_forward_env
+ entries are an opt-in that wins over the Hermes secret blocklist; only implicit
+ passthrough keys are filtered (incl. Hermes-internal dynamic secrets)."""
exec_env: dict[str, str] = {}
- explicit_forward_keys = set(self._forward_env)
passthrough_keys: set[str] = set()
resolve_passthrough_value = None
multiplex_active = False
is_global_env = lambda _name: False # noqa: E731
try:
- from tools.env_passthrough import (
- get_all_passthrough,
- resolve_passthrough_value,
- )
+ from tools.env_passthrough import get_all_passthrough, resolve_passthrough_value
from agent.secret_scope import _is_global_env, is_multiplex_active as _is_multiplex_active
is_global_env = _is_global_env
multiplex_active = _is_multiplex_active()
passthrough_keys = set(get_all_passthrough())
except Exception:
pass
- # Explicit docker_forward_env entries are an intentional opt-in and must
- # win over the generic Hermes secret blocklist. Only implicit passthrough
- # keys are filtered. Also strip Hermes-internal dynamic secrets
- # (AUXILIARY_*_API_KEY / _BASE_URL, GATEWAY_RELAY_* auth) that the
- # name-based blocklist doesn't cover — see _is_hermes_internal_secret.
- _implicit_forward = {
- k for k in passthrough_keys if not _is_hermes_internal_secret(k)
- }
- forward_keys = explicit_forward_keys | (_implicit_forward - _HERMES_PROVIDER_ENV_BLOCKLIST)
+ implicit_forward = {k for k in passthrough_keys if not _is_hermes_internal_secret(k)}
+ forward_keys = set(self._forward_env) | (implicit_forward - _HERMES_PROVIDER_ENV_BLOCKLIST)
hermes_env = _load_hermes_env_vars() if forward_keys else {}
unset_names: set[str] = set()
for key in sorted(forward_keys):
@@ -1648,61 +871,38 @@ class DockerEnvironment(BaseEnvironment):
unset_names.add(key)
return exec_env, unset_names
- def _build_runtime_env_args_with_unsets(
- self,
- ) -> tuple[list[str], tuple[str, ...], dict[str, str]]:
- """Build runtime forwarding args, names absent from scope, and values.
-
- The returned args are name-only ``-e KEY`` flags (issue #96268); the
- values dict must be injected into the docker client subprocess env.
- """
+ def _build_runtime_env_args_with_unsets(self) -> tuple[list[str], tuple[str, ...], dict[str, str]]:
+ """Runtime name-only forwarding args, names absent from scope, and the values
+ to inject into the docker client subprocess env."""
passthrough_env, unset_names = self._resolve_passthrough_env()
- args = []
- for key in sorted(passthrough_env):
- args.extend(["-e", key])
- return args, tuple(sorted(unset_names)), dict(passthrough_env)
-
- def _build_runtime_env_args(self) -> list[str]:
- """Build only dynamic forwarded names for a non-login command."""
- return self._build_runtime_env_args_with_unsets()[0]
+ return _name_only_env_args(passthrough_env), tuple(sorted(unset_names)), dict(passthrough_env)
def _run_bash(self, cmd_string: str, *, login: bool = False,
timeout: int = 120,
stdin_data: str | None = None) -> subprocess.Popen:
- """Spawn a bash process inside the Docker container."""
+ """Spawn bash inside the container. Init seeds the snapshot; profile-scoped passthrough
+ values are re-injected on every command because one container can be shared by
+ multiple routed profiles in a gateway process."""
assert self._container_id, "Container not started"
cmd = [self._docker_exe, "exec"]
if stdin_data is not None:
cmd.append("-i")
- # Init seeds the snapshot. Profile-scoped passthrough values are also
- # injected on every later command because this container can be shared
- # by multiple routed profiles in one gateway process.
- # Env flags are name-only; values travel via the client subprocess
- # env so they never hit world-readable /proc/*/cmdline (#96268).
unset_names: tuple[str, ...] = ()
env_values: dict[str, str] = {}
if login:
cmd.extend(self._init_env_args)
env_values = dict(getattr(self, "_init_env_values", {}))
+ unset_names = getattr(self, "_init_unset_passthrough_names", ())
elif self._profile_scoped_passthrough:
- runtime_args, unset_names, env_values = (
- self._build_runtime_env_args_with_unsets()
- )
+ runtime_args, unset_names, env_values = self._build_runtime_env_args_with_unsets()
cmd.extend(runtime_args)
-
- if login:
- unset_names = getattr(self, "_init_unset_passthrough_names", ())
if unset_names:
quoted_names = " ".join(shlex.quote(name) for name in unset_names)
cmd_string = f"unset {quoted_names} 2>/dev/null || true\n{cmd_string}"
- cmd.extend([self._container_id])
-
- if login:
- cmd.extend(["bash", "-l", "-c", cmd_string])
- else:
- cmd.extend(["bash", "-c", cmd_string])
+ cmd.append(self._container_id)
+ cmd.extend(bash_argv(cmd_string, login))
client_env = self._docker_client_env(env_values)
if client_env is not None:
@@ -1710,38 +910,25 @@ class DockerEnvironment(BaseEnvironment):
return _popen_bash(cmd, stdin_data)
# ------------------------------------------------------------------
- # "No such container" recovery (issue #36266)
+ # "No such container" recovery
# ------------------------------------------------------------------
- _NO_CONTAINER_PATTERNS = (
- "No such container",
- "is not running",
- "no such container",
- )
+ _NO_CONTAINER_PATTERNS = ("No such container", "is not running", "no such container")
def _is_container_gone(self, output: str) -> bool:
- """Return True if the output indicates the container no longer exists."""
return any(p in output for p in self._NO_CONTAINER_PATTERNS)
def _recreate_container(self) -> bool:
- """Recreate the container after it was removed out-of-band.
-
- Tries label-based reuse first; if no existing container is found,
- starts a fresh one with the same image and run-args. Returns True
- on success, False if recreation fails (caller should surface the
- original error).
- """
- old_id = (self._container_id or "")[:12]
- logger.warning(
- "Container %s appears to be gone — attempting recovery", old_id,
- )
+ """Recreate a container removed out-of-band: label-based reuse first (another process
+ may have recreated it), else a fresh one from the saved image/run-args. False when
+ recovery fails so the caller surfaces the original error."""
+ logger.warning("Container %s appears to be gone — attempting recovery", (self._container_id or "")[:12])
self._container_id = None
- # 1. Try label-based reuse (another process may have recreated it).
- task_label = self._labels.get("hermes-task-id", "")
- profile_label = self._labels.get("hermes-profile", "")
existing = self._find_reusable_container(
- task_label, profile_label, self._labels.get(_EGRESS_LABEL_KEY, "off"),
+ self._labels.get("hermes-task-id", ""),
+ self._labels.get("hermes-profile", ""),
+ self._labels.get(_EGRESS_LABEL_KEY, "off"),
)
if existing is not None:
cid, state = existing
@@ -1750,54 +937,28 @@ class DockerEnvironment(BaseEnvironment):
logger.info("Recovery: reusing running container %s", cid[:12])
else:
try:
- subprocess.run(
- [self._docker_exe, "start", cid],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=30, check=True,
- stdin=subprocess.DEVNULL,
- )
+ run_capture([self._docker_exe, "start", cid], timeout=30, check=True)
self._container_id = cid
logger.info("Recovery: restarted container %s", cid[:12])
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
logger.warning("Recovery: failed to start container %s: %s", cid[:12], e)
- # 2. No reusable container — create a fresh one.
if not self._container_id:
if not self._image:
logger.error("Recovery: no saved image name, cannot recreate container")
return False
try:
- import uuid as _uuid
- new_name = f"hermes-{_uuid.uuid4().hex[:8]}"
- init_args = [] if self._image_uses_s6_init else ["--init"]
- label_args = []
- for k, v in self._labels.items():
- label_args.extend(["--label", f"{k}={v}"])
- run_cmd = [
- self._docker_exe, "run", "-d",
- *init_args,
- "--name", new_name,
- *label_args,
- "-w", self.cwd,
- *self._all_run_args,
- self._image,
- "sleep", "infinity",
- ]
- result = subprocess.run(
- run_cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=120, check=True,
- stdin=subprocess.DEVNULL,
+ new_name = f"hermes-{uuid.uuid4().hex[:8]}"
+ result = run_capture(
+ self._run_command(new_name, self.cwd), timeout=120, check=True,
env=self._docker_client_env(self._run_env_values),
)
self._container_id = result.stdout.strip()
- self._container_name = new_name
- logger.info(
- "Recovery: created fresh container %s (%s)",
- new_name, self._container_id[:12],
- )
+ logger.info("Recovery: created fresh container %s (%s)", new_name, self._container_id[:12])
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError) as e:
logger.error("Recovery: failed to create new container: %s", e)
return False
- # 3. Re-initialize session snapshot in the (re)created container.
try:
self._snapshot_ready = False
self.init_session()
@@ -1809,98 +970,56 @@ class DockerEnvironment(BaseEnvironment):
return True
def execute(self, command: str, cwd: str = "", **kwargs) -> dict:
- """Execute a command, auto-recovering from dead containers.
-
- If the container was removed out-of-band (idle reaper, docker prune,
- OOM kill, daemon restart), detect the error and recreate the container
- transparently before retrying once.
- """
+ """Execute a command; if the container was removed out-of-band (idle reaper,
+ docker prune, OOM, daemon restart) recreate it and retry once."""
result = super().execute(command, cwd, **kwargs)
if (
result.get("returncode", 0) != 0
and self._is_container_gone(result.get("output", ""))
and self._persist_across_processes
+ and self._recreate_container()
):
- if self._recreate_container():
- result = super().execute(command, cwd, **kwargs)
+ result = super().execute(command, cwd, **kwargs)
return result
@staticmethod
def _storage_opt_supported() -> bool:
- """Check if Docker's storage driver supports --storage-opt size=.
-
- Only overlay2 on XFS with pquota supports per-container disk quotas.
- Ubuntu (and most distros) default to ext4, where this flag errors out.
- """
+ """Whether ``--storage-opt size=`` works (only overlay2 on XFS with pquota; ext4 errors out)."""
global _storage_opt_ok
if _storage_opt_ok is not None:
return _storage_opt_ok
try:
docker = find_docker() or "docker"
- result = subprocess.run(
- [docker, "info", "--format", "{{.Driver}}"],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10,
- stdin=subprocess.DEVNULL,
- )
- driver = result.stdout.strip().lower()
- if driver != "overlay2":
+ result = run_capture([docker, "info", "--format", "{{.Driver}}"], timeout=10)
+ if result.stdout.strip().lower() != "overlay2":
_storage_opt_ok = False
return False
- # overlay2 only supports storage-opt on XFS with pquota.
- # Probe by attempting a dry-ish run — the fastest reliable check.
- probe = subprocess.run(
- [docker, "create", "--storage-opt", "size=1m", "hello-world"],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=15,
- stdin=subprocess.DEVNULL,
- )
- if probe.returncode == 0:
- # Clean up the created container
- container_id = probe.stdout.strip()
- if container_id:
- subprocess.run([docker, "rm", container_id],
- capture_output=True, timeout=5,
- stdin=subprocess.DEVNULL)
- _storage_opt_ok = True
- else:
- _storage_opt_ok = False
+ # Probe with a real create — the fastest reliable check.
+ probe = run_capture([docker, "create", "--storage-opt", "size=1m", "hello-world"], timeout=15)
+ _storage_opt_ok = probe.returncode == 0
+ if _storage_opt_ok and probe.stdout.strip():
+ subprocess.run([docker, "rm", probe.stdout.strip()],
+ capture_output=True, timeout=5, stdin=subprocess.DEVNULL)
except Exception:
_storage_opt_ok = False
logger.debug("Docker --storage-opt support: %s", _storage_opt_ok)
return _storage_opt_ok
def _container_network_mode(self, container_id: str) -> Optional[str]:
- """Return the container's ``HostConfig.NetworkMode`` (e.g. ``bridge``,
- ``none``, ``host``), or ``None`` when inspection fails.
-
- Used by the reuse path to make sure a persisted container's network
- mode still matches the operator's ``docker_network`` setting; callers
- treat ``None`` (unknown) as a mismatch when lockdown was requested,
- so a failed inspect fails closed rather than open.
- """
+ """``HostConfig.NetworkMode`` of a container, or ``None`` when inspection fails (callers
+ treat ``None`` as a mismatch under lockdown, so a failed inspect fails closed)."""
try:
- result = subprocess.run(
- [
- self._docker_exe, "inspect",
- "--format", "{{.HostConfig.NetworkMode}}",
- container_id,
- ],
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
+ result = run_capture(
+ [self._docker_exe, "inspect", "--format", "{{.HostConfig.NetworkMode}}", container_id],
timeout=10,
- check=False,
- stdin=subprocess.DEVNULL,
)
except (subprocess.TimeoutExpired, OSError) as e:
logger.debug("docker inspect NetworkMode failed: %s", e)
return None
if result.returncode != 0:
- logger.debug(
- "docker inspect NetworkMode returned %d: %s",
- result.returncode, result.stderr.strip(),
- )
+ logger.debug("docker inspect NetworkMode returned %d: %s", result.returncode, result.stderr.strip())
return None
- mode = result.stdout.strip()
- return mode or None
+ return result.stdout.strip() or None
def _find_reusable_container(
self,
@@ -1908,48 +1027,24 @@ class DockerEnvironment(BaseEnvironment):
profile_label: str,
egress_label: str,
) -> Optional[tuple[str, str]]:
- """Look for an existing container labeled for this (task, profile).
-
- Returns ``(container_id, state)`` on hit, ``None`` on miss / on any
- failure (including ``docker ps`` itself failing). State is one of the
- values Docker reports via ``{{.State}}`` — e.g. ``running``, ``exited``,
- ``created``, ``paused``, ``restarting``, ``dead``. The caller decides
- whether the state warrants ``docker start`` before reuse.
-
- Restricted to the docker-stored label set this class creates; never
- matches containers that happened to be named ``hermes-*`` but were
- started by some other tool.
- """
+ """``(container_id, state)`` of an existing container labeled for this task/profile/
+ egress posture, or ``None`` on miss or any failure. With egress off the probe is
+ widened to all task+profile containers and post-filtered to reject a non-"off" egress
+ label — else a container built with egress on would be reused after ``hermes egress
+ disable`` with its baked-in proxy env and CA mounts."""
+ egress_off = egress_label == "off"
+ filters = [
+ "--filter", "label=hermes-agent=1",
+ "--filter", f"label=hermes-task-id={task_label}",
+ "--filter", f"label=hermes-profile={profile_label}",
+ ]
+ if egress_off:
+ fmt = '{{.ID}}\t{{.State}}\t{{.Label "' + _EGRESS_LABEL_KEY + '"}}'
+ else:
+ filters.extend(["--filter", f"label={_EGRESS_LABEL_KEY}={egress_label}"])
+ fmt = "{{.ID}}\t{{.State}}"
try:
- filters = [
- "--filter", "label=hermes-agent=1",
- "--filter", f"label=hermes-task-id={task_label}",
- "--filter", f"label=hermes-profile={profile_label}",
- ]
- if egress_label != "off":
- filters.extend(["--filter", f"label={_EGRESS_LABEL_KEY}={egress_label}"])
- fmt = "{{.ID}}\t{{.State}}"
- else:
- # When egress is off, we widen the probe to find any
- # task+profile container (regardless of egress label), then
- # post-filter in Python: reject containers whose
- # hermes-egress label is present and not "off". Without
- # this, a container created with egress=on can be silently
- # reused after the operator runs "hermes egress disable",
- # preserving baked-in proxy env and CA mounts.
- fmt = '{{.ID}}\t{{.State}}\t{{.Label "' + _EGRESS_LABEL_KEY + '"}}'
- result = subprocess.run(
- [
- self._docker_exe, "ps", "-a",
- *filters,
- "--format", fmt,
- ],
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=10,
- check=False,
- stdin=subprocess.DEVNULL,
- )
+ result = run_capture([self._docker_exe, "ps", "-a", *filters, "--format", fmt], timeout=10)
except (subprocess.TimeoutExpired, OSError) as e:
logger.debug("docker ps probe failed: %s — will start a fresh container", e)
return None
@@ -1959,169 +1054,81 @@ class DockerEnvironment(BaseEnvironment):
result.returncode, result.stderr.strip(),
)
return None
- lines = [ln for ln in result.stdout.splitlines() if ln.strip()]
- if not lines:
- return None
- # Multiple matches are unusual (one (task, profile) should produce one
- # container) but can happen if a previous Hermes process crashed
- # mid-cleanup. Prefer a running one if present; otherwise pick the
- # first listed. Stale duplicates get reaped by the orphan-reaper in a
- # follow-up commit; we don't try to be heroic about them here.
+ # Multiple matches can happen after a crash mid-cleanup: prefer a running
+ # one, else the first listed; stale duplicates are the orphan reaper's job.
running = None
first = None
- for ln in lines:
- if egress_label == "off":
- # Format: ID\tState\tEgressLabel — parse all three fields
- # and reject containers with a non-off egress label.
- parts = ln.split("\t", 2)
- if len(parts) < 3:
- continue
- cid, state, egress_val = parts[0], parts[1].lower(), parts[2]
- if egress_val not in ("", "<no value>", "off"):
- logger.debug(
- "skipping container %s for egress=off reuse: "
- "label %s=%r", cid, _EGRESS_LABEL_KEY, egress_val,
- )
- continue
- else:
- parts = ln.split("\t", 1)
- if len(parts) != 2:
- continue
- cid, state = parts[0], parts[1].lower()
+ for ln in (ln for ln in result.stdout.splitlines() if ln.strip()):
+ parts = ln.split("\t", 2 if egress_off else 1)
+ if len(parts) != (3 if egress_off else 2):
+ continue
+ cid, state = parts[0], parts[1].lower()
+ if egress_off and parts[2] not in ("", "<no value>", "off"):
+ logger.debug(
+ "skipping container %s for egress=off reuse: label %s=%r", cid, _EGRESS_LABEL_KEY, parts[2],
+ )
+ continue
if first is None:
first = (cid, state)
if state == "running" and running is None:
running = (cid, state)
return running or first
+ def _remove_bind_dirs(self) -> None:
+ for d in (self._workspace_dir, self._home_dir):
+ if d:
+ shutil.rmtree(d, ignore_errors=True)
+
def cleanup(self, *, force_remove: bool = False):
- """Tear down the container according to persist mode and *force_remove*.
-
- Persist-mode (``persist_across_processes=True``, the default) leaves the
- container **running** untouched. The docs promise "ONE long-lived
- container shared across sessions" and stopping it on every Hermes exit
- breaks that promise:
-
- * Background processes inside the container (``npm run dev``, watchers,
- long-running pytest) get killed every time the user runs ``/quit``.
- * Every reuse requires ``docker start`` + waiting for the container to
- come back up, adding 1–2s to the first tool call of the new session.
- * The user-visible difference between "ONE long-lived container" and
- "a new container that happens to share state" is exactly this:
- processes survive in the former, die in the latter.
-
- Resource reclamation for the persist-mode case lives in the
- ``reap_orphan_containers()`` path (see issue #20561 commit 3): if no
- Hermes process touches a labeled container for ``2 × lifetime_seconds``
- it gets ``docker rm -f``'d at the next Hermes startup. That covers the
- SIGKILL / OOM / abandoned-laptop cases without us needing to stop the
- container on every graceful exit.
-
- Opt-out mode (``persist_across_processes=False``) still does
- ``docker stop`` + ``docker rm -f`` on every cleanup, matching the
- pre-PR behavior for users who explicitly want per-process isolation.
-
- ``force_remove=True`` overrides persist mode and always tears the
- container down (``docker stop`` + ``docker rm -f``). This is the
- explicit-teardown path for ``/reset``, ``cleanup_vm(task_id)``-driven
- resets, or any caller that wants a guaranteed fresh container on next
- ``DockerEnvironment(task_id=...)``. No current caller passes
- ``force_remove=True``; the parameter is here so the explicit-teardown
- semantics can be wired up later without changing this method's
- signature.
-
- Cleanup runs on a daemon thread with bounded ``subprocess.run`` calls
- (not the racy ``Popen(... &)`` pattern from before PR #33645). The
- atexit hook in ``tools/terminal_tool.py`` waits up to 15s for the
- thread to finish before the interpreter exits, so ``docker stop`` /
- ``docker rm`` actually completes when we do trigger it.
- """
+ """Tear down per persist mode. Persist mode (default) leaves the container RUNNING —
+ stopping it on every exit would kill background processes and add a ``docker start``
+ delay per session; reclamation is ``reap_orphan_containers()`` at next startup.
+ ``persist_across_processes=False`` or ``force_remove=True`` (explicit-teardown hook,
+ unused so far) does ``docker stop`` + ``docker rm -f`` on a daemon thread that the
+ atexit hook joins via ``wait_for_cleanup`` so the work completes before exit."""
container_id = self._container_id
if not container_id:
- # Still drop the bind-mount dirs if any were allocated and we're
- # NOT in persist mode (persist mode preserves them).
+ # Bind-mount dirs are still dropped in non-persistent mode.
if not self._persistent:
- for d in (self._workspace_dir, self._home_dir):
- if d:
- shutil.rmtree(d, ignore_errors=True)
+ self._remove_bind_dirs()
return
- # Decide what to actually do. Three cases:
- #
- # force_remove=True → stop + rm (explicit teardown)
- # persist_across_processes=True → no-op (leave container running)
- # persist_across_processes=False → stop + rm (per-process isolation)
- #
- # The persist-mode no-op is the issue-#20561 contract: the container
- # outlives Hermes processes, processes inside it stay alive, and
- # reuse on next startup is instant.
- if force_remove:
- should_stop = True
- should_remove = True
- elif self._persist_across_processes:
- # No-op for the container. Drop the in-process handle so a fresh
- # __init__ will re-probe via labels (and find the running
- # container) instead of trying to reuse a stale Python reference.
+ if not force_remove and self._persist_across_processes:
+ # Drop the in-process handle so a fresh __init__ re-probes via
+ # labels instead of reusing a stale Python reference.
self._container_id = None
return
- else:
- should_stop = True
- should_remove = True
- # Capture state needed by the worker before we null out the attrs —
- # the worker thread can outlive ``self``.
+ # Capture what the worker needs — the thread can outlive ``self``.
docker_exe = self._docker_exe
log_id = container_id[:12]
def _do_cleanup() -> None:
- if should_stop:
+ for verb, argv in (("stop", ["stop", "-t", "10"]), ("rm", ["rm", "-f"])):
try:
subprocess.run(
- [docker_exe, "stop", "-t", "10", container_id],
- capture_output=True, timeout=30,
- stdin=subprocess.DEVNULL,
+ [docker_exe, *argv, container_id],
+ capture_output=True, timeout=30, stdin=subprocess.DEVNULL,
)
except (subprocess.TimeoutExpired, OSError) as e:
- logger.warning("docker stop %s timed out / failed: %s", log_id, e)
- if should_remove:
- try:
- subprocess.run(
- [docker_exe, "rm", "-f", container_id],
- capture_output=True, timeout=30,
- stdin=subprocess.DEVNULL,
- )
- except (subprocess.TimeoutExpired, OSError) as e:
- logger.warning("docker rm -f %s failed: %s", log_id, e)
-
- # Daemon thread: doesn't block interpreter exit (atexit returns
- # promptly), but unlike the old ``Popen(... &)`` shell trick the
- # Python-level join semantics let the thread actually run to
- # completion if the interpreter is still alive. atexit registers
- # ``_atexit_cleanup`` in terminal_tool.py which waits up to ~60s for
- # outstanding cleanups, so most exits complete the work cleanly.
- import threading
+ if verb == "stop":
+ logger.warning("docker stop %s timed out / failed: %s", log_id, e)
+ else:
+ logger.warning("docker rm -f %s failed: %s", log_id, e)
+
t = threading.Thread(target=_do_cleanup, daemon=True, name=f"hermes-cleanup-{log_id}")
t.start()
self._cleanup_thread = t
self._container_id = None
- # Bind-mount dir teardown only runs when we actually removed the
- # container (the dirs are the container's filesystem state; keeping
- # them around with no container would orphan the data on disk).
- if should_remove and not self._persistent:
- for d in (self._workspace_dir, self._home_dir):
- if d:
- shutil.rmtree(d, ignore_errors=True)
+ # Bind-mount dirs are the container's filesystem state; only drop them
+ # once the container itself is removed.
+ if not self._persistent:
+ self._remove_bind_dirs()
def wait_for_cleanup(self, timeout: float = 30.0) -> bool:
- """Block up to *timeout* seconds for the cleanup worker thread.
-
- Returns ``True`` if the thread finished (or no thread was started),
- ``False`` on timeout. The atexit hook in terminal_tool.py calls this
- on every active environment so docker stop/rm actually completes
- before the Python process exits — without this, ``hermes /quit``
- races the interpreter shutdown and leaves stopped containers behind.
- """
+ """Block up to *timeout* seconds for the cleanup thread (atexit hook). True if it
+ finished or none was started, False on timeout."""
thread = getattr(self, "_cleanup_thread", None)
if thread is None or not thread.is_alive():
return True
diff --git a/tools/environments/docker_egress.py b/tools/environments/docker_egress.py
new file mode 100644
index 00000000000..033d67a4f0b
--- /dev/null
+++ b/tools/environments/docker_egress.py
@@ -0,0 +1,271 @@
+"""Egress-proxy (iron-proxy) plumbing for the Docker backend.
+
+Builds the mount/env/host args that route a sandbox through the host-side
+credential firewall, and guards the three config surfaces (docker_forward_env,
+docker_env, docker_extra_args) that could otherwise weaken or bypass it.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+
+logger = logging.getLogger("tools.environments.docker")
+
+_EGRESS_LABEL_KEY = "hermes-egress"
+_CONTAINER_CA = "/etc/ssl/certs/hermes-egress-ca.crt"
+_NODE_OPTIONS_SENTINEL = "_HERMES_EGRESS_NODE_OPTIONS_APPEND"
+_CA_MODE_FLAGS = {"--use-openssl-ca", "--use-bundled-ca"}
+
+# Env names whose override would weaken or bypass enforced egress.
+_PROXY_CONTROL_ENV = frozenset({
+ "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy",
+ "NO_PROXY", "no_proxy",
+ "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE", "CURL_CA_BUNDLE",
+ "NODE_EXTRA_CA_CERTS",
+})
+
+
+def _egress_proxy_args_for_docker() -> tuple[list[str], dict[str, str], list[str]]:
+ """``(volume_args, env_overrides, host_args)`` for routing through iron-proxy; all empty
+ when the proxy is disabled/unconfigured/not running. Under ``proxy.enforce_on_docker``
+ (default) any half-configured state raises so the sandbox refuses to start unprotected;
+ otherwise it warns and continues. Only ImportError is swallowed — a broken config must
+ fail visibly rather than silently disable enforcement."""
+ try:
+ from hermes_cli.config import load_config
+ from agent.proxy_sources import iron_proxy as ip
+ except ImportError as exc:
+ logger.debug("Egress proxy plumbing unavailable: %s", exc)
+ return ([], {}, [])
+
+ proxy_cfg = load_config().get("proxy") or {}
+ if not proxy_cfg.get("enabled"):
+ return ([], {}, [])
+
+ status = ip.get_status()
+ enforce = bool(proxy_cfg.get("enforce_on_docker", True))
+
+ def _degraded(msg: str):
+ if enforce:
+ raise RuntimeError(msg)
+ logger.warning("%s — continuing without proxy (enforce_on_docker=false).", msg)
+ return ([], {}, [])
+
+ if not status.configured:
+ return _degraded(
+ "proxy.enabled is true but iron-proxy is not configured. "
+ "Run `hermes egress setup` to mint tokens and write proxy.yaml."
+ )
+ if not (status.pid and status.listening):
+ return _degraded(
+ f"iron-proxy is enabled but not running on port {status.tunnel_port}. "
+ "Start it with `hermes egress start`."
+ )
+ if status.ca_cert_path is None or not status.ca_cert_path.exists():
+ # Configured a moment ago but the trust anchor vanished: proxy env vars
+ # without the CA would make every TLS handshake fail.
+ return _degraded(
+ f"iron-proxy CA cert vanished from {status.ca_cert_path}. "
+ "Re-run `hermes egress setup` to regenerate it."
+ )
+ # Empty/corrupt mappings look like an upstream outage from inside the
+ # sandbox (every request 403s); refuse rather than ship a broken sandbox.
+ mappings = ip.load_mappings()
+ if not mappings:
+ return _degraded(
+ "iron-proxy is configured but mappings.json is empty or "
+ "corrupt. Re-run `hermes egress setup` to mint provider "
+ "tokens before starting a sandbox."
+ )
+
+ volume_args = ["-v", f"{status.ca_cert_path}:{_CONTAINER_CA}:ro"]
+
+ # tunnel_port serves CONNECT (HTTPS); the plain-HTTP forward listener is on +1.
+ proxy_url = f"http://host.docker.internal:{status.tunnel_port}"
+ plain_http_url = f"http://host.docker.internal:{status.tunnel_port + 1}"
+ env_overrides: dict[str, str] = {
+ # Both casings: some tools only read one.
+ "HTTPS_PROXY": proxy_url,
+ "https_proxy": proxy_url,
+ "HTTP_PROXY": plain_http_url,
+ "http_proxy": plain_http_url,
+ # Loopback-only so in-sandbox dev servers/local LLMs bypass the proxy.
+ "NO_PROXY": "127.0.0.1,localhost,::1",
+ "no_proxy": "127.0.0.1,localhost,::1",
+ # CA bundles: Python/curl vars REPLACE the system store, NODE_EXTRA_CA_CERTS
+ # only ADDS to it. NODE_OPTIONS=--use-openssl-ca narrows that asymmetry
+ # but must be APPENDED to the operator's NODE_OPTIONS, not clobber it —
+ # so it travels in a sentinel key that merge_egress_env() resolves.
+ "REQUESTS_CA_BUNDLE": _CONTAINER_CA,
+ "SSL_CERT_FILE": _CONTAINER_CA,
+ "CURL_CA_BUNDLE": _CONTAINER_CA,
+ "NODE_EXTRA_CA_CERTS": _CONTAINER_CA,
+ "HERMES_EGRESS_PROXY": "1", # lets the in-sandbox agent know it is proxy-aware
+ _NODE_OPTIONS_SENTINEL: "--use-openssl-ca",
+ }
+
+ # Proxy tokens under the standard provider env names (and their aliases) so
+ # SDKs work unchanged; HERMES_PROXY_TOKEN_* copies are for diagnostics.
+ for m in mappings:
+ env_overrides[m.real_env_name] = m.proxy_token
+ env_overrides[f"HERMES_PROXY_TOKEN_{m.real_env_name}"] = m.proxy_token
+ for alias in getattr(m, "alias_env_names", ()) or ():
+ env_overrides[alias] = m.proxy_token
+
+ # Linux needs an explicit host-gateway mapping; Docker Desktop already has it.
+ host_args = ["--add-host", "host.docker.internal:host-gateway"]
+ return (volume_args, env_overrides, host_args)
+
+
+def _egress_reuse_fingerprint(
+ volume_args: list[str], env_overrides: dict[str, str], host_args: list[str],
+) -> str:
+ """Stable Docker-label value for the egress posture of a container."""
+ if not (volume_args or env_overrides or host_args):
+ return "off"
+ payload = json.dumps(
+ {"volume_args": volume_args, "env_overrides": env_overrides, "host_args": host_args},
+ sort_keys=True, separators=(",", ":"),
+ )
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
+
+
+def _egress_enforce_on_docker(default: bool = True) -> bool:
+ """Read proxy.enforce_on_docker; any config failure fails safe to *default*."""
+ try:
+ from hermes_cli.config import load_config
+ return bool((load_config().get("proxy") or {}).get("enforce_on_docker", default))
+ except (ImportError, OSError):
+ return default
+ except Exception as exc: # malformed config.yaml etc.
+ logger.warning("Could not read proxy config for egress collision check: %s", exc)
+ return default
+
+
+def _critical_egress_env_names(env_overrides: dict[str, str]) -> set[str]:
+ """Env names that would weaken or bypass enforced egress if overridden."""
+ critical = set(_PROXY_CONTROL_ENV) | {"NODE_OPTIONS"}
+ critical.update(k for k in env_overrides if k.endswith("_API_KEY") or k.endswith("_TOKEN"))
+ return critical
+
+
+def _extra_args_egress_collisions(extra_args: list[str], critical_names: set[str]) -> list[str]:
+ """Return docker_extra_args entries that can override egress controls."""
+ collisions: list[str] = []
+ env_flags = {"-e", "--env", "--env-file"}
+ network_flags = {"--network", "--net"}
+ i = 0
+ while i < len(extra_args):
+ arg = extra_args[i]
+ nxt = extra_args[i + 1] if i + 1 < len(extra_args) else ""
+ if arg in env_flags:
+ if arg == "--env-file":
+ collisions.append(arg)
+ else:
+ name = nxt.split("=", 1)[0]
+ if name in critical_names:
+ collisions.append(name)
+ i += 2
+ continue
+ if any(arg.startswith(f"{flag}=") for flag in env_flags):
+ if arg.startswith("--env-file="):
+ collisions.append("--env-file")
+ else:
+ name = arg.split("=", 1)[1].split("=", 1)[0]
+ if name in critical_names:
+ collisions.append(name)
+ elif arg in network_flags or any(arg.startswith(f"{flag}=") for flag in network_flags):
+ collisions.append(arg)
+ i += 1
+ return sorted(set(collisions))
+
+
+def _collision_guard(msg: str, *, enforce: bool, remedy: str, consequence: str) -> None:
+ """Fail loud under enforcement, otherwise warn and let the user's config win."""
+ msg = f"{msg}; enforce_on_docker is {'enabled' if enforce else 'disabled'}."
+ if enforce:
+ raise RuntimeError(f"{msg} {remedy}")
+ logger.warning("%s %s", msg, consequence)
+
+
+def check_forward_env_collisions(forward_env: list[str], critical: set[str], enforce: bool) -> None:
+ collisions = sorted(k for k in forward_env if k in critical)
+ if collisions:
+ _collision_guard(
+ f"docker_forward_env would inject real egress-protected variables {collisions}",
+ enforce=enforce,
+ remedy="Remove these names from docker_forward_env or disable enforce_on_docker "
+ "to opt out of egress isolation.",
+ consequence="Explicit docker_forward_env values will override egress tokens.",
+ )
+
+
+def check_docker_env_collisions(user_env: dict[str, str], egress_env: dict[str, str], enforce: bool) -> None:
+ """Reject docker_env overrides of proxy-control vars or real provider keys (read from the
+ live token mappings; for those ANY override collides since a real key bypasses the swap)."""
+ provider_keys: set[str] = set()
+ try:
+ from agent.proxy_sources import iron_proxy as ip
+ provider_keys = {m.real_env_name for m in ip.load_mappings()}
+ except Exception: # best-effort
+ pass
+ def _collides(k: str) -> bool:
+ if k not in user_env:
+ return False
+ if k in provider_keys:
+ return k not in egress_env or user_env[k] != egress_env[k]
+ return k in egress_env and user_env[k] != egress_env[k]
+
+ collisions = sorted(k for k in (_PROXY_CONTROL_ENV | provider_keys) if _collides(k))
+ if collisions:
+ _collision_guard(
+ f"docker_env in config.yaml overrides egress-proxy variables {collisions}",
+ enforce=enforce,
+ remedy="Remove these keys from docker_env or disable enforce_on_docker to opt out "
+ "of egress isolation.",
+ consequence="Falling back to docker_env values; sandbox traffic will NOT route "
+ "through the proxy.",
+ )
+
+
+def check_extra_args_collisions(extra_args: list[str], critical: set[str], enforce: bool) -> None:
+ collisions = _extra_args_egress_collisions(extra_args, critical)
+ if collisions:
+ _collision_guard(
+ f"docker_extra_args would override egress-proxy controls {collisions}",
+ enforce=enforce,
+ remedy="Remove these args or disable enforce_on_docker to opt out of egress isolation.",
+ consequence="Extra Docker args may bypass egress isolation.",
+ )
+
+
+def merge_egress_env(user_env: dict[str, str], egress_env: dict[str, str], enforce: bool) -> dict[str, str]:
+ """Merge docker_env with egress overrides (egress wins under enforcement, docker_env
+ otherwise) and resolve the NODE_OPTIONS sentinel: the flag is APPENDED to the operator's
+ NODE_OPTIONS after stripping conflicting CA-mode flags so it wins deterministically."""
+ if enforce and egress_env:
+ merged = {**user_env, **egress_env}
+ else:
+ merged = {**egress_env, **user_env}
+
+ raw_append = merged.pop(_NODE_OPTIONS_SENTINEL, None)
+ if raw_append:
+ append_token = raw_append.strip()
+ tokens = merged.get("NODE_OPTIONS", "").split()
+ if append_token in _CA_MODE_FLAGS:
+ dropped = [t for t in tokens if t in _CA_MODE_FLAGS and t != append_token]
+ if dropped:
+ logger.warning(
+ "Overriding conflicting NODE_OPTIONS CA-mode flag(s) %s "
+ "with egress-required %s to keep Node routed through the "
+ "egress CA store.", dropped, append_token,
+ )
+ tokens = [t for t in tokens if t not in _CA_MODE_FLAGS or t == append_token]
+ if append_token not in tokens:
+ tokens.append(append_token)
+ merged["NODE_OPTIONS"] = " ".join(tokens).strip()
+ if not merged["NODE_OPTIONS"]:
+ merged.pop("NODE_OPTIONS", None)
+ return merged
diff --git a/tools/environments/file_sync.py b/tools/environments/file_sync.py
index 84a314f5ee8..e024b0fb0e4 100644
--- a/tools/environments/file_sync.py
+++ b/tools/environments/file_sync.py
@@ -1,9 +1,8 @@
"""Shared file sync manager for remote execution backends.
-Tracks local file changes via mtime+size, detects deletions, and
-syncs to remote environments transactionally. Used by SSH, Modal,
-and Daytona. Docker and Singularity use bind mounts (live host FS
-view) and don't need this.
+Tracks local file changes via mtime+size, detects deletions, and syncs to
+remote environments transactionally. Used by SSH, Modal, and Daytona.
+Docker and Singularity use bind mounts (live host FS view) and don't need this.
"""
import hashlib
@@ -30,13 +29,10 @@ from tools.environments.base import _file_mtime_key
logger = logging.getLogger(__name__)
-# Keep retry sleeps patchable without mutating the shared stdlib ``time``
-# module. Patching ``tools.environments.file_sync.time.sleep`` replaces
-# ``time.sleep`` globally because ``time`` is the module object; under xdist
-# that lets unrelated background threads inflate retry-test call counts.
+# Tests patch these module-level aliases instead of ``time.sleep`` /
+# ``time.monotonic``: patching attributes on the shared ``time`` module object
+# leaks into unrelated threads under xdist and inflates retry call counts.
_sleep = time.sleep
-# Same rationale for the rate-limit clock: tests patch ``_monotonic``
-# instead of ``time.monotonic`` on the shared module object.
_monotonic = time.monotonic
_SYNC_INTERVAL_SECONDS = 5.0
@@ -49,57 +45,55 @@ BulkDownloadFn = Callable[[Path], None] # (dest_tar_path) -> writes tar archive
DeleteFn = Callable[[list[str]], None] # (remote_paths) -> raises on failure
GetFilesFn = Callable[[], list[tuple[str, str]]] # () -> [(host_path, remote_path), ...]
+_SYNC_BACK_MAX_RETRIES = 3
+_SYNC_BACK_BACKOFF = (2, 4, 8) # seconds between retries
+_SYNC_BACK_MAX_BYTES = 2 * 1024 * 1024 * 1024 # 2 GiB — refuse to extract larger tars
+
def iter_sync_files(container_base: str = "/root/.hermes") -> list[tuple[str, str]]:
- """Enumerate all files that should be synced to a remote environment.
+ """Enumerate all (host_path, remote_path) pairs to sync to a remote.
- Combines credentials, skills, and cache into a single flat list of
- (host_path, remote_path) pairs. Credential paths are remapped from
- the hardcoded /root/.hermes to *container_base* because the remote
- user's home may differ (e.g. /home/daytona, /home/user).
+ Credential paths are remapped from the hardcoded /root/.hermes to
+ *container_base* because the remote user's home may differ.
"""
- # Late import: credential_files imports agent modules that create
- # circular dependencies if loaded at file_sync module level.
+ # Late import: credential_files pulls in agent modules (circular at module level).
from tools.credential_files import (
get_credential_file_mounts,
iter_cache_files,
iter_skills_files,
)
- files: list[tuple[str, str]] = []
- for entry in get_credential_file_mounts():
- remote = entry["container_path"].replace(
- "/root/.hermes", container_base, 1
- )
- files.append((entry["host_path"], remote))
- for entry in iter_skills_files(container_base=container_base):
- files.append((entry["host_path"], entry["container_path"]))
- for entry in iter_cache_files(container_base=container_base):
+ files: list[tuple[str, str]] = [
+ (entry["host_path"], entry["container_path"].replace("/root/.hermes", container_base, 1))
+ for entry in get_credential_file_mounts()
+ ]
+ for entry in (*iter_skills_files(container_base=container_base),
+ *iter_cache_files(container_base=container_base)):
files.append((entry["host_path"], entry["container_path"]))
return files
+def _resolve_host_path_str(host_path: str) -> str:
+ """Canonical string form of a host path (``resolve()`` falling back to ``expanduser()``)."""
+ try:
+ return str(Path(host_path).expanduser().resolve())
+ except OSError:
+ return str(Path(host_path).expanduser())
+
+
def _credential_host_paths() -> set[str]:
"""Return credential files that are upload-only for remote sandboxes."""
try:
from tools.credential_files import get_credential_file_mounts
- except Exception:
- return set()
- paths: set[str] = set()
- try:
mounts = get_credential_file_mounts()
except Exception:
return set()
- for entry in mounts:
- host_path = entry.get("host_path") if isinstance(entry, dict) else None
- if not host_path:
- continue
- try:
- paths.add(str(Path(host_path).expanduser().resolve()))
- except OSError:
- paths.add(str(Path(host_path).expanduser()))
- return paths
+ return {
+ _resolve_host_path_str(entry["host_path"])
+ for entry in mounts
+ if isinstance(entry, dict) and entry.get("host_path")
+ }
def quoted_rm_command(remote_paths: list[str]) -> str:
@@ -126,20 +120,12 @@ def _sha256_file(path: str) -> str:
return h.hexdigest()
-_SYNC_BACK_MAX_RETRIES = 3
-_SYNC_BACK_BACKOFF = (2, 4, 8) # seconds between retries
-_SYNC_BACK_MAX_BYTES = 2 * 1024 * 1024 * 1024 # 2 GiB — refuse to extract larger tars
-
-
class FileSyncManager:
"""Tracks local file changes and syncs to a remote environment.
- Backends instantiate this with transport callbacks (upload, delete)
- and a file-source callable. The manager handles mtime-based change
- detection, deletion tracking, rate limiting, and transactional state.
-
- Not used by bind-mount backends (Docker, Singularity) — those get
- live host FS views and don't need file sync.
+ Backends instantiate this with transport callbacks (upload, delete) and a
+ file-source callable. The manager handles mtime-based change detection,
+ deletion tracking, rate limiting, and transactional state.
"""
def __init__(
@@ -166,89 +152,89 @@ class FileSyncManager:
def sync(self, *, force: bool = False) -> None:
"""Run a sync cycle: upload changed files, delete removed files.
- Rate-limited to once per ``sync_interval`` unless *force* is True
- or ``HERMES_FORCE_FILE_SYNC=1`` is set.
-
- Transactional: state only committed if ALL operations succeed.
- On failure, state rolls back so the next cycle retries everything.
+ Rate-limited to once per ``sync_interval`` unless *force* is True or
+ ``HERMES_FORCE_FILE_SYNC=1`` is set. Transactional: state is committed
+ only if ALL operations succeed; on failure it rolls back so the next
+ cycle retries everything.
"""
with self._transaction_lock:
self._sync_transaction(force=force)
def _sync_transaction(self, *, force: bool = False) -> None:
"""Execute one sync cycle while holding the per-manager lock."""
- if not force and not os.environ.get(_FORCE_SYNC_ENV):
- now = _monotonic()
- if now - self._last_sync_time < self._sync_interval:
- return
+ if (
+ not force
+ and not os.environ.get(_FORCE_SYNC_ENV)
+ and _monotonic() - self._last_sync_time < self._sync_interval
+ ):
+ return
current_files = self._get_files_fn()
self._upload_only_host_paths.update(_credential_host_paths())
- current_remote_paths = {remote for _, remote in current_files}
-
- # --- Uploads: new or changed files ---
- to_upload: list[tuple[str, str]] = []
- new_files = dict(self._synced_files)
- for host_path, remote_path in current_files:
- file_key = _file_mtime_key(host_path)
- if file_key is None:
- continue
- if self._synced_files.get(remote_path) == file_key:
- continue
- to_upload.append((host_path, remote_path))
- new_files[remote_path] = file_key
-
- # --- Deletes: synced paths no longer in current set ---
- to_delete = [p for p in self._synced_files if p not in current_remote_paths]
+ to_upload, new_files, to_delete = self._plan_sync(current_files)
if not to_upload and not to_delete:
self._last_sync_time = _monotonic()
return
- # Snapshot for rollback (only when there's work to do)
prev_files = dict(self._synced_files)
prev_hashes = dict(self._pushed_hashes)
-
- if to_upload:
- logger.debug("file_sync: uploading %d file(s)", len(to_upload))
- if to_delete:
- logger.debug("file_sync: deleting %d stale remote file(s)", len(to_delete))
-
try:
- if to_upload and self._bulk_upload_fn is not None:
- self._bulk_upload_fn(to_upload)
- logger.debug("file_sync: bulk-uploaded %d file(s)", len(to_upload))
- else:
- for host_path, remote_path in to_upload:
- self._upload_fn(host_path, remote_path)
- logger.debug("file_sync: uploaded %s -> %s", host_path, remote_path)
-
- if to_delete:
- self._delete_fn(to_delete)
- logger.debug("file_sync: deleted %s", to_delete)
-
- # --- Commit (all succeeded) ---
+ self._push(to_upload, to_delete)
+ # Commit (all succeeded).
for host_path, remote_path in to_upload:
self._pushed_hashes[remote_path] = _sha256_file(host_path)
-
for p in to_delete:
new_files.pop(p, None)
self._pushed_hashes.pop(p, None)
-
self._synced_files = new_files
self._last_sync_time = _monotonic()
-
except Exception as exc:
self._synced_files = prev_files
self._pushed_hashes = prev_hashes
- # Do NOT advance _last_sync_time here: a failed cycle rolls state
- # back so the next cycle can retry. Bumping the rate-limit clock on
- # failure would make the next non-forced sync() return early (the
- # guard above), suppressing that retry for up to _sync_interval and
- # leaving the remote with stale files — contradicting this method's
- # documented "next cycle retries everything" contract.
+ # Do NOT advance _last_sync_time: bumping the rate-limit clock on
+ # failure would suppress the retry for up to _sync_interval,
+ # contradicting the "next cycle retries everything" contract.
logger.warning("file_sync: sync failed, rolled back state: %s", exc)
+ def _plan_sync(
+ self, current_files: list[tuple[str, str]]
+ ) -> tuple[list[tuple[str, str]], dict[str, tuple[float, int]], list[str]]:
+ """Diff *current_files* against synced state.
+
+ Returns ``(to_upload, new_synced_state, to_delete)``: new/changed
+ (mtime,size) pairs to upload, the state to commit if everything
+ succeeds, and synced remote paths no longer present locally.
+ """
+ to_upload: list[tuple[str, str]] = []
+ new_files = dict(self._synced_files)
+ for host_path, remote_path in current_files:
+ file_key = _file_mtime_key(host_path)
+ if file_key is None or self._synced_files.get(remote_path) == file_key:
+ continue
+ to_upload.append((host_path, remote_path))
+ new_files[remote_path] = file_key
+ current_remote_paths = {remote for _, remote in current_files}
+ to_delete = [p for p in self._synced_files if p not in current_remote_paths]
+ return to_upload, new_files, to_delete
+
+ def _push(self, to_upload: list[tuple[str, str]], to_delete: list[str]) -> None:
+ """Run the transport calls for one cycle (bulk upload when available)."""
+ if to_upload:
+ logger.debug("file_sync: uploading %d file(s)", len(to_upload))
+ if to_delete:
+ logger.debug("file_sync: deleting %d stale remote file(s)", len(to_delete))
+ if to_upload and self._bulk_upload_fn is not None:
+ self._bulk_upload_fn(to_upload)
+ logger.debug("file_sync: bulk-uploaded %d file(s)", len(to_upload))
+ else:
+ for host_path, remote_path in to_upload:
+ self._upload_fn(host_path, remote_path)
+ logger.debug("file_sync: uploaded %s -> %s", host_path, remote_path)
+ if to_delete:
+ self._delete_fn(to_delete)
+ logger.debug("file_sync: deleted %s", to_delete)
+
# ------------------------------------------------------------------
# Sync-back: pull remote changes to host on teardown
# ------------------------------------------------------------------
@@ -256,24 +242,21 @@ class FileSyncManager:
def sync_back(self, hermes_home: Path | None = None) -> None:
"""Pull remote changes back to the host filesystem.
- Downloads the remote ``.hermes/`` directory as a tar archive,
- unpacks it, and applies only files that differ from what was
- originally pushed (based on SHA-256 content hashes).
-
- Protected against SIGINT (defers the signal until complete) and
- serialized across concurrent gateway sandboxes via file lock.
+ Downloads the remote ``.hermes/`` directory as a tar, unpacks it, and
+ applies only files whose SHA-256 differs from what was pushed. SIGINT is
+ deferred until complete; concurrent gateway sandboxes are serialized
+ via a file lock.
"""
with self._transaction_lock:
self._sync_back_transaction(hermes_home=hermes_home)
def _sync_back_transaction(self, hermes_home: Path | None = None) -> None:
- """Execute sync-back against a stable snapshot of manager state."""
+ """Execute sync-back (with retries) against a stable snapshot of manager state."""
if self._bulk_download_fn is None:
return
- # Nothing was ever committed through this manager — the initial
- # push failed or never ran. Skip sync_back to avoid retry storms
- # against an uninitialized remote .hermes/ directory.
+ # Nothing was ever committed (initial push failed or never ran): skip
+ # to avoid retry storms against an uninitialized remote .hermes/.
if not self._pushed_hashes and not self._synced_files:
logger.debug("sync_back: no prior push state — skipping")
return
@@ -300,9 +283,8 @@ class FileSyncManager:
def _sync_back_once(self, lock_path: Path) -> None:
"""Single sync-back attempt with SIGINT protection and file lock."""
- # signal.signal() only works from the main thread. In gateway
- # contexts cleanup() may run from a worker thread — skip SIGINT
- # deferral there rather than crashing.
+ # signal.signal() only works from the main thread; gateway cleanup()
+ # may run from a worker thread — skip SIGINT deferral there.
on_main_thread = threading.current_thread() is threading.main_thread()
deferred_sigint: list[object] = []
@@ -321,16 +303,10 @@ class FileSyncManager:
if on_main_thread and original_handler is not None:
signal.signal(signal.SIGINT, original_handler)
if deferred_sigint:
- # Re-deliver the deferred Ctrl+C to the just-restored
- # handler. ``os.kill(os.getpid(), signal.SIGINT)`` is NOT a
- # graceful signal on Windows: os.kill only treats
- # CTRL_C_EVENT(0)/CTRL_BREAK_EVENT(1) as console events; any
- # other value (SIGINT == 2) routes to TerminateProcess(sig),
- # hard-killing the CLI (exit code 2) instead of raising
- # KeyboardInterrupt — so a Ctrl+C during a remote-backend
- # sync-back would kill the whole session on Windows.
- # ``signal.raise_signal`` (3.8+) invokes the handler via C
- # ``raise()`` on every platform.
+ # Re-deliver the deferred Ctrl+C to the restored handler.
+ # ``os.kill(os.getpid(), SIGINT)`` is NOT graceful on
+ # Windows (routes to TerminateProcess, hard-killing the
+ # CLI); ``raise_signal`` invokes the handler everywhere.
signal.raise_signal(signal.SIGINT)
def _sync_back_locked(self, lock_path: Path) -> None:
@@ -364,8 +340,7 @@ class FileSyncManager:
with tempfile.NamedTemporaryFile(suffix=".tar") as tf:
self._bulk_download_fn(Path(tf.name))
- # Defensive size cap: a misbehaving sandbox could produce an
- # arbitrarily large tar. Refuse to extract if it exceeds the cap.
+ # A misbehaving sandbox could produce an arbitrarily large tar.
try:
tar_size = os.path.getsize(tf.name)
except OSError:
@@ -381,72 +356,71 @@ class FileSyncManager:
with tarfile.open(tf.name) as tar:
tar.extractall(staging, filter="data")
+ upload_only = self._upload_only_host_paths | _credential_host_paths()
applied = 0
- upload_only_host_paths = (
- self._upload_only_host_paths | _credential_host_paths()
- )
for dirpath, _dirnames, filenames in os.walk(staging):
for fname in filenames:
staged_file = os.path.join(dirpath, fname)
- rel = os.path.relpath(staged_file, staging)
- remote_path = "/" + rel
-
- pushed_hash = self._pushed_hashes.get(remote_path)
-
- # Skip hashing for files unchanged from push
- if pushed_hash is not None:
- remote_hash = _sha256_file(staged_file)
- if remote_hash == pushed_hash:
- continue
- else:
- remote_hash = None # new remote file
-
- # Resolve host path from cached mapping
- host_path = self._resolve_host_path(remote_path, file_mapping)
- if host_path is None:
- host_path = self._infer_host_path(
- remote_path,
- file_mapping,
- upload_only_host_paths=upload_only_host_paths,
- )
- if host_path is None:
- logger.debug(
- "sync_back: skipping %s (no host mapping)",
- remote_path,
- )
- continue
-
- if self._is_upload_only_host_path(host_path, upload_only_host_paths):
- logger.debug(
- "sync_back: skipping upload-only credential file %s",
- remote_path,
- )
- continue
-
- if os.path.exists(host_path) and pushed_hash is not None:
- host_hash = _sha256_file(host_path)
- if host_hash != pushed_hash:
- logger.warning(
- "sync_back: conflict on %s — host modified "
- "since push, remote also changed. Applying "
- "remote version (last-write-wins).",
- remote_path,
- )
-
- os.makedirs(os.path.dirname(host_path), exist_ok=True)
- shutil.copy2(staged_file, host_path)
- applied += 1
+ remote_path = "/" + os.path.relpath(staged_file, staging)
+ applied += self._apply_staged_file(
+ staged_file, remote_path, file_mapping, upload_only
+ )
if applied:
logger.info("sync_back: applied %d changed file(s)", applied)
else:
logger.debug("sync_back: no remote changes detected")
+ def _apply_staged_file(
+ self,
+ staged_file: str,
+ remote_path: str,
+ file_mapping: list[tuple[str, str]],
+ upload_only_host_paths: set[str],
+ ) -> int:
+ """Copy one extracted remote file onto the host if it changed since push.
+
+ Returns 1 if applied, 0 if skipped (unchanged, unmapped, or an
+ upload-only credential). A host file modified since push is
+ overwritten with the remote version (last-write-wins) with a warning.
+ """
+ pushed_hash = self._pushed_hashes.get(remote_path)
+ if pushed_hash is not None and _sha256_file(staged_file) == pushed_hash:
+ return 0 # unchanged from push
+
+ host_path = self._resolve_host_path(remote_path, file_mapping)
+ if host_path is None:
+ host_path = self._infer_host_path(
+ remote_path, file_mapping, upload_only_host_paths=upload_only_host_paths
+ )
+ if host_path is None:
+ logger.debug("sync_back: skipping %s (no host mapping)", remote_path)
+ return 0
+
+ if self._is_upload_only_host_path(host_path, upload_only_host_paths):
+ logger.debug("sync_back: skipping upload-only credential file %s", remote_path)
+ return 0
+
+ if (
+ pushed_hash is not None
+ and os.path.exists(host_path)
+ and _sha256_file(host_path) != pushed_hash
+ ):
+ logger.warning(
+ "sync_back: conflict on %s — host modified "
+ "since push, remote also changed. Applying "
+ "remote version (last-write-wins).",
+ remote_path,
+ )
+
+ os.makedirs(os.path.dirname(host_path), exist_ok=True)
+ shutil.copy2(staged_file, host_path)
+ return 1
+
def _resolve_host_path(self, remote_path: str,
file_mapping: list[tuple[str, str]] | None = None) -> str | None:
"""Find the host path for a known remote path from the file mapping."""
- mapping = file_mapping if file_mapping is not None else []
- for host, remote in mapping:
+ for host, remote in file_mapping or []:
if remote == remote_path:
return host
return None
@@ -457,28 +431,20 @@ class FileSyncManager:
upload_only_host_paths: set[str] | None = None) -> str | None:
"""Infer a host path for a new remote file by matching path prefixes.
- Uses the existing file mapping to find a remote->host directory
- pair, then applies the same prefix substitution to the new file.
- For example, if the mapping has ``/root/.hermes/skills/a.md`` →
- ``~/.hermes/skills/a.md``, a new remote file at
- ``/root/.hermes/skills/b.md`` maps to ``~/.hermes/skills/b.md``.
+ Uses an existing remote->host pair whose parent directory prefixes
+ *remote_path* and applies the same substitution, e.g. mapping
+ ``/root/.hermes/skills/a.md`` -> ``~/.hermes/skills/a.md`` sends a new
+ ``/root/.hermes/skills/b.md`` to ``~/.hermes/skills/b.md``.
"""
- mapping = file_mapping if file_mapping is not None else []
upload_only_host_paths = upload_only_host_paths or set()
- for host, remote in mapping:
+ for host, remote in file_mapping or []:
if self._is_upload_only_host_path(host, upload_only_host_paths):
continue
remote_dir = str(Path(remote).parent)
if remote_path.startswith(remote_dir + "/"):
- host_dir = str(Path(host).parent)
- suffix = remote_path[len(remote_dir):]
- return host_dir + suffix
+ return str(Path(host).parent) + remote_path[len(remote_dir):]
return None
@staticmethod
def _is_upload_only_host_path(host_path: str, upload_only_host_paths: set[str]) -> bool:
- try:
- resolved = str(Path(host_path).expanduser().resolve())
- except OSError:
- resolved = str(Path(host_path).expanduser())
- return resolved in upload_only_host_paths
+ return _resolve_host_path_str(host_path) in upload_only_host_paths
diff --git a/tools/environments/local.py b/tools/environments/local.py
index f876753adae..2978e3d23c6 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -18,30 +18,45 @@ from pathlib import Path
from hermes_constants import get_process_hermes_home
from tools.environments.base import BaseEnvironment, _pipe_stdin
from hermes_cli._subprocess_compat import windows_hide_flags
+# Re-exported so ``from tools.environments.local import X`` and
+# ``patch("tools.environments.local.X")`` keep working after the split.
+from tools.environments.local_env_policy import ( # noqa: F401
+ _ACTIVE_VENV_MARKER_VARS, _ALWAYS_STRIP_KEYS, _AWS_SDK_CREDENTIAL_ENV_VARS,
+ _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX,
+ _TERMINAL_FIRST_PARTY_ENV_PREFIXES, _build_provider_env_blocklist,
+ _buzz_terminal_context_active, _is_hermes_internal_secret,
+ _is_terminal_first_party_env, _matches_terminal_first_party_prefix,
+ _plugin_terminal_env_strip_keys,
+)
+from tools.environments.local_gitbash_probe import ( # noqa: F401
+ _BASH_EXTERNAL_PROGRAM_PROBE, _bash_probe_details_cache, _bash_starts,
+ _bash_starts_cache, _git_bash_aslr_help, _git_root_from_bash,
+ _looks_like_msys_spawn_failure, _mandatory_aslr_enabled,
+)
+from tools.environments.local_pythonpath import ( # noqa: F401
+ _build_hermes_repo_root_aliases, _get_hermes_site_packages, _same_path,
+ _strip_hermes_owned_pythonpath, _strip_hermes_owned_pythonpath_and_runtime_markers,
+ _validated_runtime_venv,
+)
_IS_WINDOWS = platform.system() == "Windows"
logger = logging.getLogger(__name__)
-# --- Terminal temp-cache pruning -------------------------------------------
-#
-# get_temp_dir() now defaults to HERMES_HOME/cache/terminal (real storage)
-# instead of tmpfs /tmp, so stale session artifacts no longer disappear on
-# reboot for free. Prune them ourselves: the gateway housekeeping loop calls
-# cleanup_terminal_temp_cache() hourly (same contract as the other
-# cleanup_*_cache helpers), and a once-per-process best-effort sweep covers
-# CLI-only installs that never run the gateway.
-#
-# Background-process artifacts come in triplets (hermes_bg_<id>.log/.pid/
-# .exit). A long-running server's .pid file never changes mtime while its
-# .log keeps updating — so age is judged per GROUP (newest mtime among files
-# sharing a stem) to avoid yanking the pid/exit files out from under a
-# still-live background session.
+# --- Terminal temp-cache pruning ---------------------------------------------
+# get_temp_dir() defaults to HERMES_HOME/cache/terminal (real storage, not tmpfs
+# /tmp), so stale artifacts no longer vanish on reboot for free: the gateway
+# housekeeping loop prunes hourly and a once-per-process sweep covers CLI-only
+# installs.
TERMINAL_TEMP_MAX_AGE_HOURS = 72
_terminal_temp_prune_lock = threading.Lock()
_terminal_temp_pruned_once = False
+# Background-process artifacts come in triplets (hermes_bg_<id>.log/.pid/.exit).
+# A live server's .pid never changes mtime while its .log does, so age is judged
+# per GROUP (newest mtime sharing a stem) to avoid yanking pid/exit files from
+# under a still-running background session.
_BG_GROUP_RE = re.compile(r"^(hermes_bg_[A-Za-z0-9_-]+)\.(log|pid|exit)$")
@@ -57,47 +72,33 @@ def _default_terminal_temp_dir() -> "Path | None":
def cleanup_terminal_temp_cache(
max_age_hours: int = TERMINAL_TEMP_MAX_AGE_HOURS,
) -> int:
- """Delete session temp artifacts older than *max_age_hours*.
-
- Same contract as the ``cleanup_*_cache`` helpers in
- ``gateway.platforms.base`` — returns the number of entries removed — so
- the gateway housekeeping loop can prune this dir on its hourly cadence.
-
- Only prunes the managed default dir (``HERMES_HOME/cache/terminal``).
- User-pointed ``terminal.temp_dir`` locations are the user's to manage —
- we never bulk-delete inside a directory we don't own.
- """
+ """Delete session temp artifacts older than *max_age_hours*; return count
+ (``cleanup_*_cache`` contract). Only the managed default dir is pruned —
+ never a user-pointed ``terminal.temp_dir`` we don't own."""
root = _default_terminal_temp_dir()
if root is None:
return 0
cutoff = time.time() - (max_age_hours * 3600)
- removed = 0
try:
entries = list(root.iterdir())
except OSError:
return 0
- # Newest mtime per hermes_bg_<id> group, so a live server's fresh .log
- # protects its stale-looking .pid/.exit siblings.
+ mtimes: dict[Path, float] = {}
group_newest: dict[str, float] = {}
- for f in entries:
- m = _BG_GROUP_RE.match(f.name)
- if m:
- try:
- mt = f.stat().st_mtime
- except OSError:
- continue
- key = m.group(1)
- group_newest[key] = max(group_newest.get(key, 0.0), mt)
-
for f in entries:
try:
- mt = f.stat().st_mtime
+ mtimes[f] = mt = f.stat().st_mtime
except OSError:
continue
m = _BG_GROUP_RE.match(f.name)
- effective = group_newest.get(m.group(1), mt) if m else mt
- if effective >= cutoff:
+ if m:
+ group_newest[m.group(1)] = max(group_newest.get(m.group(1), 0.0), mt)
+
+ removed = 0
+ for f, mt in mtimes.items():
+ m = _BG_GROUP_RE.match(f.name)
+ if (group_newest[m.group(1)] if m else mt) >= cutoff:
continue
try:
if f.is_dir():
@@ -123,53 +124,34 @@ def _prune_terminal_temp_once() -> None:
logger.debug("Terminal temp prune failed: %s", exc)
-def _msys_to_windows_path(cwd: str) -> str:
- """Translate a Git Bash / MSYS-style POSIX path (``/c/Users/x``) to the
- native Windows form (``C:\\Users\\x``) so ``os.path.isdir`` and
- ``subprocess.Popen(..., cwd=...)`` can find it.
+# --- Windows / MSYS path translation ---
- Also accepts the Cygwin (``/cygdrive/c/...``) and WSL-mount
- (``/mnt/c/...``) spellings of a drive root. Multi-segment POSIX paths
- like ``/home/x`` or ``/tmp/foo`` are left untouched.
- No-ops on non-Windows hosts or for paths that aren't in MSYS form.
- Returns the input unchanged when no translation applies. This is
- idempotent — calling it on an already-Windows path returns it as-is.
- """
+def _msys_to_windows_path(cwd: str) -> str:
+ """Translate a Git Bash / MSYS path (``/c/Users/x``, ``/cygdrive/c/..``,
+ ``/mnt/c/..``) to native ``C:\\Users\\x`` so ``isdir``/``Popen(cwd=)`` find
+ it. No-op off Windows, for empty input and for multi-segment POSIX paths
+ like ``/home/x``; idempotent on native paths."""
if not _IS_WINDOWS or not cwd:
return cwd
- # Match leading "/<single letter>/" or exactly "/<letter>" (bare drive root),
- # plus /cygdrive/<letter>/... and /mnt/<letter>/... variants.
m = re.match(r'^/(?:(?:cygdrive|mnt)/)?([a-zA-Z])(/.*)?$', cwd)
if not m:
return cwd
- # Reject /cygdrive or /mnt with no drive letter — the optional group above
- # already requires the letter. Multi-char first segments (/home, /tmp)
- # fail the single-letter capture and fall through as no-ops.
drive = m.group(1).upper()
tail = (m.group(2) or "").replace('/', '\\')
return f"{drive}:{tail or chr(92)}" # chr(92) = backslash, avoid raw-string escape
def _resolve_local_initial_cwd(cwd: str) -> str:
- """Resolve the local backend's initial cwd to an absolute host path.
-
- ``TERMINAL_CWD`` can be populated from config.yaml before the terminal
- backend is created. If that value is relative and happens to match the
- directory Hermes was already launched from (for example ``hermes-agent``
- while the process cwd is ``~/.hermes/hermes-agent``), passing it through
- unchanged makes the wrapper run ``cd hermes-agent`` *inside* the project
- and fail with a confusing nested-path error. Anchor relative local cwd
- values once, up front, so both ``subprocess.Popen(cwd=...)`` and the
- in-shell ``cd`` use the same absolute directory.
- """
+ """Resolve the initial cwd to an absolute host path. A relative
+ ``TERMINAL_CWD`` like ``hermes-agent`` naming the launch directory would
+ otherwise make the wrapper ``cd hermes-agent`` *inside* the project; anchor
+ it once so ``Popen(cwd=)`` and the in-shell ``cd`` agree."""
expanded = os.path.expanduser(cwd) if cwd else os.getcwd()
if _IS_WINDOWS:
expanded = _msys_to_windows_path(expanded)
- # Use the Windows-aware check explicitly: when _IS_WINDOWS is
- # patched in tests on a POSIX host, os.path.isabs would reject
- # ``C:\Users\x`` and mangle it through the relative branch.
- import ntpath
+ # ntpath explicitly: with _IS_WINDOWS patched on a POSIX host,
+ # os.path.isabs would reject ``C:\Users\x`` and mangle it below.
if ntpath.isabs(expanded):
return expanded
if os.path.isabs(expanded):
@@ -178,27 +160,17 @@ def _resolve_local_initial_cwd(cwd: str) -> str:
candidate = os.path.abspath(expanded)
current = os.getcwd()
- # Common recovery for config values like ``hermes-agent`` when Hermes was
- # launched from that directory already. ``os.path.abspath`` would point at
- # a nonexistent nested ``./hermes-agent``; use the current directory instead.
+ # Relative name matching the tail of the current dir: use the current dir.
if not os.path.isdir(candidate):
- wanted_parts = Path(expanded).parts
- current_parts = Path(current).parts
- if wanted_parts and len(wanted_parts) <= len(current_parts):
- if current_parts[-len(wanted_parts):] == wanted_parts:
- return current
-
+ wanted, have = Path(expanded).parts, Path(current).parts
+ if wanted and len(wanted) <= len(have) and have[-len(wanted):] == wanted:
+ return current
return candidate
def _windows_to_msys_path(cwd: str) -> str:
- """Translate a native Windows path (``C:\\Users\\x``) to Git Bash /
- MSYS form (``/c/Users/x``) so ``builtin cd`` resolves it reliably.
-
- No-ops on non-Windows hosts or for paths that aren't drive-qualified
- native Windows paths. Returns the input unchanged when no translation
- applies.
- """
+ """Translate native ``C:\\Users\\x`` to Git Bash form ``/c/Users/x`` so
+ ``builtin cd`` resolves it. No-op off Windows / for non-drive paths."""
if not _IS_WINDOWS or not cwd:
return cwd
m = re.match(r'^([a-zA-Z]):[\\/]*(.*)$', cwd)
@@ -210,25 +182,13 @@ def _windows_to_msys_path(cwd: str) -> str:
def _bash_safe_path(path: str) -> str:
- """Return *path* in a form safe to embed in a Git Bash script.
-
- Native ``C:\\Users\\x`` / ``C:/Users/x`` → ``/c/Users/x`` via
- :func:`_windows_to_msys_path`. Mixed MSYS leftovers
- (``/c/Users\\Alexander\\Documents``) get backslashes normalized so
- bash does not eat ``\\U`` and trip the ``Directory \\drivers\\etc``
- failure class. No-op off Windows and for empty input.
-
- ``get_temp_dir`` already emits forward-slash ``C:/...`` forms for
- Python compatibility; those still need the ``/c/...`` rewrite —
- MSYS argument conversion treats ``C:/...`` as a Windows path and
- can corrupt the login-shell ``drivers\\etc`` lookup.
- """
+ """Return *path* in a form safe to embed in a Git Bash script: native
+ ``C:\\Users\\x`` / ``C:/Users/x`` become ``/c/Users/x`` (MSYS argument
+ conversion mangles ``C:/`` forms), and leftover backslashes are normalized
+ so bash does not eat ``\\U``. No-op off Windows and for empty input."""
if not _IS_WINDOWS or not path:
return path
- path = _windows_to_msys_path(path)
- if "\\" in path:
- path = path.replace("\\", "/")
- return path
+ return _windows_to_msys_path(path).replace("\\", "/")
def _quote_bash_path(path: str) -> str:
@@ -240,39 +200,18 @@ def _quote_bash_path(path: str) -> str:
def _cwd_usable(path: str) -> bool:
"""True when *path* is a directory this process can actually chdir into.
-
- ``os.path.isdir`` alone is not enough: stat() on ``/root`` succeeds for a
- non-root user (only ``/`` needs search permission), but
- ``subprocess.Popen(cwd='/root')`` then dies with ``PermissionError:
- [Errno 13] Permission denied: '/root'``. Seen in the wild when a
- root-launched CLI session leaks ``/root`` into shared state that a
- non-root gateway/cron process later reads (#65583) — every cron job's
- terminal/file tool then fails on every command, forever. Checking
- X_OK up front lets the caller fall back instead.
- """
+ ``isdir`` alone is not enough: stat() on ``/root`` succeeds for a non-root
+ user but ``Popen(cwd='/root')`` dies with PermissionError (a root-launched
+ CLI leaking ``/root`` into a non-root gateway's shared state)."""
return os.path.isdir(path) and os.access(path, os.X_OK)
def _resolve_safe_cwd(cwd: str) -> str:
- """Return ``cwd`` if it exists as a directory this process can enter,
- else the nearest existing accessible ancestor. Falls back to
- ``tempfile.gettempdir()`` only if walking up the path can't find any
- usable directory (effectively never on a healthy filesystem, but cheap
- belt-and-braces).
-
- On Windows, also normalizes Git Bash / MSYS-style POSIX paths
- (``/c/Users/x``) to native Windows form before the isdir check so a
- perfectly valid ``pwd -P`` result from bash doesn't get rejected as
- "missing" (see ``_msys_to_windows_path``).
-
- Used by ``_run_bash`` to recover when the configured cwd is gone — most
- commonly because a previous tool call deleted its own working directory
- (issue #17558) — or inaccessible to this user, e.g. ``/root`` leaking
- from a root-launched CLI session into a non-root gateway's cron jobs
- (issue #65583). Without this guard, ``subprocess.Popen(..., cwd=...)``
- raises ``FileNotFoundError``/``PermissionError`` before bash starts,
- wedging every subsequent terminal call until the gateway restarts.
- """
+ """Return ``cwd`` if enterable, else the nearest usable ancestor, else
+ ``tempfile.gettempdir()``. MSYS paths are normalized first on Windows so a
+ valid ``pwd -P`` result is not rejected as missing. Lets ``_run_bash``
+ recover from a deleted/inaccessible cwd instead of ``Popen`` raising before
+ bash starts and wedging every subsequent terminal call."""
cwd = _msys_to_windows_path(cwd) if _IS_WINDOWS else cwd
if cwd and _cwd_usable(cwd):
return cwd
@@ -291,341 +230,12 @@ def _resolve_safe_cwd(cwd: str) -> str:
return parent
next_parent = os.path.dirname(parent)
if next_parent == parent:
- # Reached the filesystem root and it doesn't exist either —
- # genuinely nothing to fall back to except the temp dir.
- break
+ break # filesystem root itself is unusable
parent = next_parent
return tempfile.gettempdir()
-# Hermes-internal env vars that should NOT leak into terminal subprocesses.
-_HERMES_PROVIDER_ENV_FORCE_PREFIX = "_HERMES_FORCE_"
-
-# Hermes-managed AWS *inference* credentials for ``auth_type="aws_sdk"``
-# providers (Bedrock). Scoped DELIBERATELY NARROW: this lists only the
-# Bedrock-specific bearer token, which is a Hermes inference secret exactly
-# analogous to ``OPENAI_API_KEY`` — nobody drives the ``aws``/``terraform``/
-# ``boto3`` toolchain off it, so stripping it from terminal/execute_code
-# subprocesses costs no user capability.
-#
-# The GENERAL AWS credential chain (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,
-# AWS_SESSION_TOKEN, AWS_PROFILE, and the config/role pointers) is INTENTIONALLY
-# left inheritable. Per SECURITY.md §3.2 the local terminal is the user's
-# trusted operator shell; the agent having the same general AWS access the
-# user's own shell has is the intended posture, not a leak. Hard-blocklisting
-# those vars would (a) regress every user who runs aws/terraform/cdk/boto3 in
-# the agent terminal — not just Bedrock users, since the registry is iterated
-# unconditionally — and (b) be unrecoverable, because env_passthrough.py
-# refuses to re-allow anything in this blocklist (GHSA-rhgp-j443-p4rf). See
-# issue #32314 discussion.
-_AWS_SDK_CREDENTIAL_ENV_VARS = frozenset({
- "AWS_BEARER_TOKEN_BEDROCK",
-})
-
-
-def _build_provider_env_blocklist() -> frozenset:
- """Derive the blocklist from provider, tool, and gateway config."""
- blocked: set[str] = set()
-
- try:
- from hermes_cli.auth import PROVIDER_REGISTRY
- for pconfig in PROVIDER_REGISTRY.values():
- blocked.update(pconfig.api_key_env_vars)
- if pconfig.auth_type == "aws_sdk":
- blocked.update(_AWS_SDK_CREDENTIAL_ENV_VARS)
- if pconfig.base_url_env_var:
- blocked.add(pconfig.base_url_env_var)
- except ImportError:
- pass
-
- try:
- from hermes_cli.config import OPTIONAL_ENV_VARS
- for name, metadata in OPTIONAL_ENV_VARS.items():
- category = metadata.get("category")
- if category in {"tool", "messaging"}:
- blocked.add(name)
- elif category == "setting" and metadata.get("password"):
- blocked.add(name)
- except ImportError:
- pass
-
- blocked.update({
- "OPENAI_BASE_URL",
- "OPENAI_API_KEY",
- "OPENAI_API_BASE",
- "OPENAI_ORG_ID",
- "OPENAI_ORGANIZATION",
- "OPENROUTER_API_KEY",
- "ANTHROPIC_BASE_URL",
- "ANTHROPIC_API_KEY",
- "ANTHROPIC_TOKEN",
- "LLM_MODEL",
- "GOOGLE_API_KEY",
- # Path to a GCP service-account JSON, not a bare key, so
- # OPTIONAL_ENV_VARS marks it password=False and the loop above skips it.
- "VERTEX_CREDENTIALS_PATH",
- "GOOGLE_APPLICATION_CREDENTIALS",
- "DEEPSEEK_API_KEY",
- "MISTRAL_API_KEY",
- "GROQ_API_KEY",
- "TOGETHER_API_KEY",
- "PERPLEXITY_API_KEY",
- "COHERE_API_KEY",
- "FIREWORKS_API_KEY",
- "XAI_API_KEY",
- "HELICONE_API_KEY",
- "PARALLEL_API_KEY",
- "FIRECRAWL_API_KEY",
- "FIRECRAWL_API_URL",
- "TELEGRAM_HOME_CHANNEL",
- "TELEGRAM_HOME_CHANNEL_NAME",
- "DISCORD_HOME_CHANNEL",
- "DISCORD_HOME_CHANNEL_NAME",
- "DISCORD_REQUIRE_MENTION",
- "DISCORD_FREE_RESPONSE_CHANNELS",
- "DISCORD_AUTO_THREAD",
- "SLACK_HOME_CHANNEL",
- "SLACK_HOME_CHANNEL_NAME",
- "SLACK_ALLOWED_USERS",
- "WHATSAPP_ENABLED",
- "WHATSAPP_MODE",
- "WHATSAPP_ALLOWED_USERS",
- "SIGNAL_HTTP_URL",
- "SIGNAL_ACCOUNT",
- "SIGNAL_ALLOWED_USERS",
- "SIGNAL_GROUP_ALLOWED_USERS",
- "SIGNAL_HOME_CHANNEL",
- "SIGNAL_HOME_CHANNEL_NAME",
- "SIGNAL_IGNORE_STORIES",
- "HASS_TOKEN",
- "HASS_URL",
- "EMAIL_ADDRESS",
- "EMAIL_PASSWORD",
- "EMAIL_IMAP_HOST",
- "EMAIL_SMTP_HOST",
- "EMAIL_HOME_ADDRESS",
- "EMAIL_HOME_ADDRESS_NAME",
- "HERMES_DASHBOARD_SESSION_TOKEN",
- "GATEWAY_ALLOWED_USERS",
- "GH_TOKEN",
- "GITHUB_APP_ID",
- "GITHUB_APP_PRIVATE_KEY_PATH",
- "GITHUB_APP_INSTALLATION_ID",
- "MODAL_TOKEN_ID",
- "MODAL_TOKEN_SECRET",
- "DAYTONA_API_KEY",
- "GATEWAY_RELAY_ID",
- "GATEWAY_RELAY_SECRET",
- "GATEWAY_RELAY_DELIVERY_KEY",
- "VERCEL_OIDC_TOKEN",
- "VERCEL_TOKEN",
- "VERCEL_PROJECT_ID",
- "VERCEL_TEAM_ID",
- })
- # CLAUDE_CODE_OAUTH_TOKEN is deliberately NOT stripped. It is set and
- # owned by the user's Claude Code install (subscription OAuth), not a
- # Hermes-managed inference credential — Claude subscription auth is not a
- # working Hermes provider path. Stripping it broke agent-spawned
- # ``claude`` CLIs: the child fell through to the shared macOS Keychain /
- # ``~/.claude/.credentials.json`` store and, on auth failure, cleared it,
- # logging the user out of their interactive Claude sessions (#55878).
- # It arrives via the registry loop above (anthropic api_key_env_vars),
- # so remove it explicitly.
- blocked.discard("CLAUDE_CODE_OAUTH_TOKEN")
- # BUZZ_* is deliberately NOT discarded here, even for Buzz-managed agents
- # (BUZZ_MANAGED_AGENT set by the buzz-acp harness). This blocklist is
- # shared by every scrub surface — the terminal paths, execute_code, and
- # the :func:`hermes_subprocess_env` Tier-2 strip (browser / TUI host /
- # copilot-executor spawns) — so an import-time discard would leak
- # BUZZ_PRIVATE_KEY into non-terminal children too. The Buzz carve-out is
- # instead a TERMINAL-ONLY, context-gated scrub-path exemption: see
- # ``_TERMINAL_FIRST_PARTY_ENV_PREFIXES`` / ``_is_terminal_first_party_env``
- # below (issue #78026 / #76243, PRs #78065 + #78511).
- return frozenset(blocked)
-
-
-_HERMES_PROVIDER_ENV_BLOCKLIST = _build_provider_env_blocklist()
-
-# First-party platform credentials the agent's own platform adapters need in
-# terminal children (e.g. the ``BUZZ_*`` vars for the Buzz messaging
-# platform, which drive the platform-mandated ``buzz`` CLI: BUZZ_PRIVATE_KEY,
-# BUZZ_AUTH_TAG, BUZZ_RELAY_URL, and the other BUZZ_* names). These are the
-# agent's OWN credentials — a Buzz community agent is expected to operate the
-# ``buzz`` CLI — so they are carved out of the terminal scrub.
-#
-# CONTEXT-GATED: the carve-out applies ONLY when this process/session is
-# actually operating as a Buzz agent — either the process is a Buzz-ACP
-# managed agent (``BUZZ_MANAGED_AGENT`` is set, only by Buzz Desktop's
-# buzz-acp harness; see #76243 / #78511) or the current session's platform is
-# ``buzz`` (the gateway's ``HERMES_SESSION_PLATFORM`` ContextVar; concurrency
-# safe under a multi-session host). A Telegram/CLI/cron session on a host
-# that also runs a Buzz gateway does NOT get BUZZ_PRIVATE_KEY in its terminal
-# children — blanket passthrough of a signing key to every terminal child on
-# the host would be wrong (maintainer triage note on #76243: don't expose the
-# key to unrelated shell commands).
-#
-# Scope is TERMINAL ONLY: the foreground ``_make_run_env`` and background/PTY
-# ``_sanitize_subprocess_env`` paths pass them through. ``_sanitize_subprocess_env``
-# is also consumed by search workers (e.g. the ddgs web-search subprocess),
-# the computer-use driver binary, and user-script runners (bang ``!``
-# commands, quick commands, cron scripts, webhook-filter scripts), so those
-# children receive the vars too — matching the approved background/PTY scope.
-# Every other surface stays sealed — execute_code scrubbing,
-# :func:`hermes_subprocess_env` (browser / TUI host / copilot-executor
-# spawns), docker children, and ``env_passthrough`` registration (skills/config
-# still cannot register these names). The GHSA-rhgp-j443-p4rf seal is
-# preserved because no registration path is opened; this is a scrub-path
-# exemption, not an allowlist addition.
-#
-# First-party matches use the merged env value directly — they are the
-# process's own env values and are never scope-resolved (a profile secret
-# scope under multiplex would otherwise raise UnscopedSecretError at
-# passthrough-resolution call sites); only skill/config passthrough names
-# resolve through the profile secret scope. The snapshot mechanism treats
-# these names like profile-scoped passthrough names (see
-# ``LocalEnvironment._additional_profile_scoped_passthrough_names``) so they
-# never persist in the shared terminal snapshot across profiles.
-#
-# Prefix-based on purpose: future ``BUZZ_*`` names added by the platform's
-# plugin.yaml (or a user's own credentials file) are covered without another
-# code change. Contrast with CLAUDE_CODE_OAUTH_TOKEN above, which is discarded
-# from the blocklist entirely because it is NOT a Hermes credential; these ARE
-# Hermes-managed first-party platform credentials, so they stay IN the
-# blocklist for every non-terminal surface.
-#
-# See issue #78026 (Buzz agents could not use ``buzz`` from the terminal tool)
-# and #76243 (Buzz Desktop managed agent wakes but cannot reply).
-_TERMINAL_FIRST_PARTY_ENV_PREFIXES = ("BUZZ_",)
-
-
-def _matches_terminal_first_party_prefix(name: str) -> bool:
- """Pure name check: ``name`` is one of the first-party platform
- credential names (``BUZZ_*``), regardless of session context. Used for
- the snapshot exclusion, which must stay conservative even when the
- carve-out itself is inactive."""
- return name.startswith(_TERMINAL_FIRST_PARTY_ENV_PREFIXES)
-
-
-def _buzz_terminal_context_active() -> bool:
- """True when this process/session is operating as a Buzz agent.
-
- Two independent signals, either suffices:
-
- * ``BUZZ_MANAGED_AGENT`` in the process env — set exclusively by Buzz
- Desktop's buzz-acp harness when it spawns ``hermes acp`` (#76243).
- Gateway / CLI / cron / kanban processes never carry it.
- * The live session's platform is ``buzz`` — the gateway's
- ``HERMES_SESSION_PLATFORM`` ContextVar via
- :func:`gateway.session_context.get_session_env`, which is
- ContextVar-authoritative under a concurrent multi-session host, so a
- sibling Telegram/Discord session on the same gateway process resolves
- its OWN platform, not buzz.
- """
- if os.environ.get("BUZZ_MANAGED_AGENT"):
- return True
- try:
- from gateway.session_context import get_session_env
-
- return get_session_env("HERMES_SESSION_PLATFORM", "").strip().lower() == "buzz"
- except Exception:
- return False
-
-
-def _is_terminal_first_party_env(name: str) -> bool:
- """Return True if ``name`` is a first-party platform credential that must
- reach terminal children (the ``BUZZ_*`` set) AND the current
- process/session context entitles it (Buzz-managed agent or a buzz-platform
- session — see :func:`_buzz_terminal_context_active`)."""
- if not _matches_terminal_first_party_prefix(name):
- return False
- return _buzz_terminal_context_active()
-
-
-# Active-virtualenv markers that must NOT leak into terminal subprocesses.
-# The gateway runs inside its own venv, so its process environment carries
-# VIRTUAL_ENV (and possibly CONDA_PREFIX). If those leak into commands the
-# agent runs against OTHER Python projects, tools like ``uv``/``poetry`` treat
-# the inherited value as the active environment and build/sync that other
-# project's dependencies into the Hermes venv path instead of the project's own
-# ``.venv`` — silently clobbering the Hermes environment (e.g. a project pinned
-# to a different Python version overwrites it and breaks the gateway). The
-# Hermes venv stays reachable via PATH (its bin dir is first), so stripping
-# these markers is safe and only prevents the cross-project clobber (#23473).
-#
-# PYTHONHOME is included because a gateway-inherited value redirects the
-# standard-library search of ANY child interpreter — including unrelated
-# system/venv Pythons — to the Hermes venv's stdlib, which crashes with
-# version-mismatch errors before a child script even imports a package
-# (#75018). Hermes itself treats PYTHONHOME as contamination in its own
-# child processes (managed_uv.py, sqlite_runtime.py), so stripping it from
-# subprocess envs is consistent. Users who need PYTHONHOME for a specific
-# child can set it explicitly in the command.
-#
-# PYTHONPATH is NOT included here — it's handled by
-# _strip_hermes_owned_pythonpath() which removes only Hermes-owned entries,
-# preserving user-set paths.
-_ACTIVE_VENV_MARKER_VARS = ("VIRTUAL_ENV", "CONDA_PREFIX", "PYTHONHOME")
-
-
-def _is_hermes_internal_secret(key: str) -> bool:
- """Return True for Hermes-internal secrets injected under *dynamic* names.
-
- ``_HERMES_PROVIDER_ENV_BLOCKLIST`` is name-based and derived from the
- provider/tool registries, but the gateway and CLI also inject secrets into
- ``os.environ`` at runtime under names no static registry knows about:
-
- - ``AUXILIARY_<TASK>_API_KEY`` / ``AUXILIARY_<TASK>_BASE_URL`` — per-task
- side-LLM credentials bridged from ``config.yaml[auxiliary]`` by
- ``gateway/run.py`` and ``cli.py`` (vision, web_extract, approval,
- compression, and any plugin-registered auxiliary task). These are
- separate, often higher-spend API keys plus base URLs that may point at
- private endpoints; a model-authored shell command must never see them.
- - ``GATEWAY_RELAY_*_SECRET`` / ``GATEWAY_RELAY_*_KEY`` /
- ``GATEWAY_RELAY_*_TOKEN`` — relay-auth material provisioned by the
- gateway (``GATEWAY_RELAY_SECRET``, ``GATEWAY_RELAY_DELIVERY_KEY``).
- These are Tier-1 gateway secrets, like the messaging bot tokens in
- ``_ALWAYS_STRIP_KEYS``. Non-secret ``GATEWAY_RELAY_*`` routing hints
- (``GATEWAY_RELAY_URL``, ``GATEWAY_RELAY_PLATFORMS``, …) are NOT matched
- and remain visible.
-
- ``code_execution_tool.py`` already catches these via substring matching on
- ``KEY`` / ``SECRET`` / ``TOKEN``; the terminal backend's narrower name-based
- blocklist did not, which is the leak this predicate closes.
-
- This is the single source of truth for "Hermes-internal dynamic secret"
- across every spawn path — the terminal ``_make_run_env`` /
- ``_sanitize_subprocess_env`` filters, the Docker passthrough filter, and the
- non-terminal :func:`hermes_subprocess_env` helper all call it, so the
- dynamic patterns are stripped **unconditionally** regardless of
- ``env_passthrough`` skill registration or ``inherit_credentials``. Nothing
- a model-driving CLI legitimately needs matches these patterns.
- """
- upper = key.upper()
- if upper.startswith("AUXILIARY_") and (
- upper.endswith("_API_KEY") or upper.endswith("_BASE_URL")
- ):
- return True
- if upper.startswith("GATEWAY_RELAY_") and (
- upper.endswith("_SECRET") or upper.endswith("_KEY") or upper.endswith("_TOKEN")
- ):
- return True
- return False
-
-
-def _plugin_terminal_env_strip_keys() -> frozenset:
- """Credential env keys owned by plugin-registered terminal backends.
-
- Computed at call time (not import time) because plugins register after
- this module is imported. Treated as Tier-1: stripped from every spawned
- subprocess unconditionally, exactly like MODAL_*/DAYTONA_API_KEY in
- ``_ALWAYS_STRIP_KEYS``. Fail-soft to an empty set.
- """
- try:
- from agent.terminal_env_registry import plugin_strip_env_keys
-
- return plugin_strip_env_keys()
- except Exception:
- return frozenset()
+# --- Child-process environment construction ---
def _inject_context_hermes_home(env: dict) -> None:
@@ -640,38 +250,24 @@ def _inject_context_hermes_home(env: dict) -> None:
pass
+def _apply_profile_home(env: dict) -> None:
+ """HERMES_HOME override bridge + the subprocess HOME contract."""
+ _inject_context_hermes_home(env)
+ from hermes_constants import apply_subprocess_home_env
+ apply_subprocess_home_env(env)
+
+
def _inject_session_context_env(env: dict) -> None:
- """Bridge gateway session ContextVars into a subprocess environment dict.
-
- ContextVars don't propagate to child processes, so the live session vars
- (HERMES_SESSION_*) are bridged onto the child env here.
-
- 🔴 Cross-session leak guard. The session vars also have a process-global
- os.environ mirror (written last-writer-wins as a CLI/cron fallback, never
- cleared). Under a concurrent multi-session host (the messaging gateway, ACP
- adapter, API server, TUI) that global belongs to *whichever turn wrote it
- last* — NOT necessarily this task. A subprocess spawned from a task whose
- ContextVar is _UNSET (e.g. a sibling message task that never bound, or one
- that inherited another session's context) would otherwise inherit the
- FOREIGN global and act on another session's identity.
-
- So once the session-context machinery is engaged in this process (any host
- has called set_session_vars), the session vars are ContextVar-authoritative:
- - ContextVar set (incl. explicitly-empty "") → that value wins, overriding
- any stale snapshot/global value.
- - ContextVar _UNSET → STRIP the var from the child env rather than inherit
- the possibly-foreign process-global.
- In a pure single-process CLI/one-shot that never engaged the session-context
- system there is no concurrency to leak across, so the inherited fallback is
- kept. See gateway/session_context.session_context_engaged and
- tests/tools/test_local_env_session_leak.py.
+ """Bridge gateway session ContextVars (HERMES_SESSION_*) into a child env.
+
+ Cross-session leak guard: the vars also have a last-writer-wins ``os.environ``
+ mirror that, under a concurrent multi-session host, may belong to another
+ turn. Once the session-context system is engaged, ContextVars are
+ authoritative: a bound value (incl. "") wins and an _UNSET var is STRIPPED
+ rather than inherited. A CLI that never engaged it keeps the inherited value.
"""
try:
- from gateway.session_context import (
- _UNSET,
- _VAR_MAP,
- session_context_engaged,
- )
+ from gateway.session_context import _UNSET, _VAR_MAP, session_context_engaged
except Exception:
return
@@ -679,241 +275,131 @@ def _inject_session_context_env(env: dict) -> None:
for var_name, var in _VAR_MAP.items():
value = var.get()
if value is not _UNSET:
- # Explicitly bound (including "") — authoritative for this task.
env[var_name] = "" if value is None else str(value)
elif _engaged:
- # Unset for THIS task while a concurrent host is engaged: drop any
- # inherited global so a sibling session's value can't leak in.
env.pop(var_name, None)
-def _sanitize_subprocess_env(base_env: dict | None, extra_env: dict | None = None) -> dict:
- """Filter Hermes-managed secrets from a subprocess environment."""
+def _scrub_delegated_child_kanban_env(env: dict[str, str]) -> dict[str, str]:
+ """Strip dispatcher-owned Kanban env from delegate_task child subprocesses."""
try:
- from tools.env_passthrough import (
- is_env_passthrough as _is_passthrough,
- resolve_passthrough_value as _resolve_passthrough_value,
- )
+ from agent.delegation_context import is_delegated_child_process_context, scrub_kanban_env
+
+ if is_delegated_child_process_context():
+ return scrub_kanban_env(env)
+ except Exception:
+ pass
+ return env
+
+
+def _passthrough_hooks():
+ """Return ``(is_passthrough, resolve_passthrough_value)`` from the
+ env_passthrough skill registry, or inert fallbacks."""
+ try:
+ from tools.env_passthrough import is_env_passthrough, resolve_passthrough_value
+
+ return is_env_passthrough, resolve_passthrough_value
except Exception:
- _is_passthrough = lambda _: False # noqa: E731
- _resolve_passthrough_value = lambda _name, fallback: fallback # noqa: E731
+ return (lambda _: False), (lambda _name, fallback: fallback)
- sanitized: dict[str, str] = {}
- _plugin_strip = _plugin_terminal_env_strip_keys()
- for key, value in (base_env or {}).items():
+def _filter_secret_env(
+ items: Mapping[str, str],
+ out: dict,
+ *,
+ unwrap_force: bool,
+ plugin_strip: frozenset = frozenset(),
+) -> None:
+ """Copy *items* into *out*, dropping Hermes-managed secrets.
+
+ ``_HERMES_FORCE_<NAME>`` unwraps to ``NAME`` when ``unwrap_force`` (caller
+ extras / terminal env), else is dropped. Blocklisted names survive only via
+ env_passthrough registration or as context-entitled first-party ``BUZZ_*``
+ vars; the latter are used directly, never scope-resolved (UnscopedSecretError
+ under multiplex) — only passthrough names resolve through the secret scope.
+ """
+ is_passthrough, resolve_passthrough_value = _passthrough_hooks()
+ for key, value in items.items():
if key.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX):
+ if not unwrap_force:
+ continue
+ real_key = key[len(_HERMES_PROVIDER_ENV_FORCE_PREFIX):]
+ if _is_hermes_internal_secret(real_key):
+ continue
+ out[real_key] = value
continue
- if _is_hermes_internal_secret(key):
- continue
- if key in _plugin_strip:
+ if _is_hermes_internal_secret(key) or key in plugin_strip:
continue
first_party = _is_terminal_first_party_env(key)
- passthrough = _is_passthrough(key)
+ passthrough = is_passthrough(key)
if key in _HERMES_PROVIDER_ENV_BLOCKLIST and not (passthrough or first_party):
continue
- # First-party platform vars are the process's own env values: use them
- # directly, never scope-resolve (multiplex with no scope would raise
- # UnscopedSecretError — a regression where the script previously ran
- # without the var). Only skill/config passthrough names resolve.
resolved = value
if passthrough and not first_party:
- resolved = _resolve_passthrough_value(key, value)
+ resolved = resolve_passthrough_value(key, value)
if resolved is not None:
- sanitized[key] = resolved
+ out[key] = resolved
- for key, value in (extra_env or {}).items():
- if key.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX):
- real_key = key[len(_HERMES_PROVIDER_ENV_FORCE_PREFIX):]
- if _is_hermes_internal_secret(real_key):
- continue
- sanitized[real_key] = value
- elif _is_hermes_internal_secret(key):
- continue
- elif key in _plugin_strip:
- continue
- else:
- first_party = _is_terminal_first_party_env(key)
- passthrough = _is_passthrough(key)
- if key in _HERMES_PROVIDER_ENV_BLOCKLIST and not (passthrough or first_party):
- continue
- resolved = value
- if passthrough and not first_party:
- resolved = _resolve_passthrough_value(key, value)
- if resolved is not None:
- sanitized[key] = resolved
- _inject_context_hermes_home(sanitized)
-
- from hermes_constants import apply_subprocess_home_env
- apply_subprocess_home_env(sanitized)
-
- # Same cross-session leak guard as _make_run_env, for the background/PTY
- # spawn path (process_registry.spawn_local builds env via this function).
- _inject_session_context_env(sanitized)
-
- # Filter PYTHONPATH before removing VIRTUAL_ENV: legacy Windows launchers
- # can run the gateway under a base interpreter while VIRTUAL_ENV identifies
- # the separate Hermes runtime venv. The filter validates that relationship
- # against the repo layout before trusting it.
- _strip_hermes_owned_pythonpath_and_runtime_markers(sanitized)
-
- # Keep bare ``hermes`` invocations available to child jobs even when the
- # gateway was launched by a service manager or cron without the console
- # script's directory on PATH. The terminal environment already applies
- # this invariant; Cron scripts use this sanitizer directly (#92998).
- path_key = _path_env_key(sanitized)
- if path_key is not None:
- sanitized[path_key] = _prepend_hermes_bin_dir(sanitized.get(path_key, ""))
-
- _apply_windows_msys_bash_env_defaults(sanitized)
-
- sanitized = _scrub_delegated_child_kanban_env(sanitized)
-
- return sanitized
+def _finalize_child_env(env: dict) -> dict:
+ """Guards shared by every spawn surface: profile-home propagation,
+ session-context bridging, Hermes-owned PYTHONPATH + venv-marker strip, MSYS
+ defaults, delegate_task Kanban scrub. Returns the (possibly new) dict."""
+ _apply_profile_home(env)
+ _inject_session_context_env(env)
+ _strip_hermes_owned_pythonpath_and_runtime_markers(env)
+ _apply_windows_msys_bash_env_defaults(env)
+ return _scrub_delegated_child_kanban_env(env)
-def _scrub_delegated_child_kanban_env(env: dict[str, str]) -> dict[str, str]:
- """Strip dispatcher-owned Kanban env from delegate_task child subprocesses."""
- try:
- from agent.delegation_context import (
- is_delegated_child_process_context,
- scrub_kanban_env,
- )
+def _sanitize_subprocess_env(base_env: dict | None, extra_env: dict | None = None) -> dict:
+ """Filter Hermes-managed secrets from a subprocess environment.
- if is_delegated_child_process_context():
- return scrub_kanban_env(env)
- except Exception:
- pass
- return env
+ Background/PTY spawn path (``process_registry.spawn_local``), search workers,
+ the computer-use driver, and user-script runners build their env here.
+ """
+ plugin_strip = _plugin_terminal_env_strip_keys()
+ sanitized: dict[str, str] = {}
+ _filter_secret_env(base_env or {}, sanitized, unwrap_force=False, plugin_strip=plugin_strip)
+ _filter_secret_env(extra_env or {}, sanitized, unwrap_force=True, plugin_strip=plugin_strip)
+ # Keep bare ``hermes`` resolvable for children even when the gateway was
+ # launched by a service manager or cron without the console-script dir on
+ # PATH (cron scripts use this sanitizer directly).
+ path_key = _path_env_key(sanitized)
+ if path_key is not None:
+ sanitized[path_key] = _prepend_hermes_bin_dir(sanitized.get(path_key, ""))
-# Tier-1 secrets: stripped from EVERY spawned subprocess unconditionally —
-# even when the caller opts into credential inheritance for a model-driving
-# CLI (claude / codex / gemini). These are not LLM provider credentials; no
-# legitimate child Hermes spawns needs them, and they are the highest-value
-# secrets to keep out of a compromised dependency's reach (gateway bot tokens,
-# GitHub auth, remote-compute tokens, dashboard session secret). The set is a
-# narrow subset of _HERMES_PROVIDER_ENV_BLOCKLIST; provider keys are handled by
-# the conditional Tier-2 strip in hermes_subprocess_env().
-_ALWAYS_STRIP_KEYS: frozenset[str] = frozenset({
- # GitHub auth
- "GH_TOKEN",
- "GITHUB_TOKEN",
- "GITHUB_APP_ID",
- "GITHUB_APP_PRIVATE_KEY_PATH",
- "GITHUB_APP_INSTALLATION_ID",
- # Gateway / messaging bot tokens and access control
- "TELEGRAM_BOT_TOKEN",
- "DISCORD_BOT_TOKEN",
- "SLACK_BOT_TOKEN",
- "SLACK_APP_TOKEN",
- "SLACK_SIGNING_SECRET",
- "GATEWAY_ALLOWED_USERS",
- "GATEWAY_ALLOW_ALL_USERS",
- # Gateway relay auth — the ID/secret/delivery-key triplet the gateway
- # provisions and persists to the 0600 .env. Stripped unconditionally on
- # EVERY spawn surface (terminal + model-driving CLIs) so it can't drift
- # between paths: _SECRET / _DELIVERY_KEY are also matched by
- # _is_hermes_internal_secret, but _ID has no secret suffix, so it must be
- # enumerated here to stay stripped on the inherit_credentials=True path
- # (codex / copilot), which skips the Tier-2 blocklist.
- "GATEWAY_RELAY_ID",
- "GATEWAY_RELAY_SECRET",
- "GATEWAY_RELAY_DELIVERY_KEY",
- "HASS_TOKEN",
- "EMAIL_PASSWORD",
- "HERMES_DASHBOARD_SESSION_TOKEN",
- # Remote-compute / infrastructure secrets
- "MODAL_TOKEN_ID",
- "MODAL_TOKEN_SECRET",
- "DAYTONA_API_KEY",
-})
+ return _finalize_child_env(sanitized)
def hermes_subprocess_env(*, inherit_credentials: bool = False) -> dict[str, str]:
- """Build a sanitized environment dict for a spawned subprocess.
-
- Centralized helper for the **non-terminal** spawn surface (browser,
- ACP/CLI executors, computer-use driver, dep-ensure, TUI Node host,
- detached gateway). Use this instead of copying ``os.environ`` directly
- so strip-by-default is the uniform policy across every spawn site, with a
- single source of truth (``_HERMES_PROVIDER_ENV_BLOCKLIST``). The terminal
- / execute_code path keeps using :func:`_sanitize_subprocess_env`, which is
- skill-aware (``env_passthrough``); this helper is for spawns that have no
- skill-passthrough concept.
-
- Two-tier stripping:
-
- * **Tier 1 (always):** ``_ALWAYS_STRIP_KEYS`` — gateway bot tokens, GitHub
- auth, and remote-compute secrets are removed regardless of
- ``inherit_credentials``. No child Hermes spawns legitimately needs them.
- * **Tier 2 (conditional):** the rest of ``_HERMES_PROVIDER_ENV_BLOCKLIST``
- (LLM provider API keys, tool secrets) is removed unless the caller passes
- ``inherit_credentials=True``.
-
- Pass ``inherit_credentials=True`` **only** when the child legitimately
- needs LLM provider credentials — a user-blessed ``claude`` / ``codex`` /
- ``gemini`` CLI executor, or the TUI Node host that makes model calls. The
- flag is grep-able for audit: ``grep -rn 'inherit_credentials=True'`` lists
- every spawn site that still receives provider credentials.
-
- Callers that need a *specific* non-provider secret (e.g. the browser worker
- needs ``BROWSERBASE_API_KEY`` / ``FIRECRAWL_API_KEY``) should call with
- ``inherit_credentials=False`` and copy just those keys back from
- ``os.environ`` into the returned dict.
+ """Sanitized env for the **non-terminal** spawn surface (browser, ACP/CLI
+ executors, computer-use driver, TUI Node host). Tier 1 (``_ALWAYS_STRIP_KEYS``,
+ plugin keys, force-prefixed hints, dynamic internal secrets) is always
+ removed; Tier 2 (the provider/tool blocklist) unless ``inherit_credentials``
+ — pass that **only** for children that legitimately need LLM credentials
+ (user-blessed claude/codex/gemini CLI, TUI Node host); it is grep-able for
+ audit. Terminal/execute_code use the skill-aware ``_sanitize_subprocess_env``.
"""
env = os.environ.copy()
- # Tier 1 — always strip.
for key in _ALWAYS_STRIP_KEYS:
env.pop(key, None)
for key in _plugin_terminal_env_strip_keys():
env.pop(key, None)
- # Internal routing hints and Hermes-internal dynamic secrets
- # (``AUXILIARY_<TASK>_API_KEY`` / ``_BASE_URL`` side-LLM credentials,
- # ``GATEWAY_RELAY_*`` relay-auth material) must never reach a child,
- # regardless of ``inherit_credentials`` — a model-driving CLI has no
- # legitimate use for them. See :func:`_is_hermes_internal_secret`.
for key in list(env):
- if key.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX):
- env.pop(key, None)
- elif _is_hermes_internal_secret(key):
+ if key.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX) or _is_hermes_internal_secret(key):
env.pop(key, None)
if not inherit_credentials:
- # Tier 2 — strip provider/tool credentials unless explicitly inherited.
for key in _HERMES_PROVIDER_ENV_BLOCKLIST:
env.pop(key, None)
- # Windows UTF-8 safety for spawned processes (#31420).
+ # Windows UTF-8 safety for spawned processes.
env.setdefault("PYTHONUTF8", "1")
- _inject_context_hermes_home(env)
- from hermes_constants import apply_subprocess_home_env
- apply_subprocess_home_env(env)
-
- _strip_hermes_owned_pythonpath_and_runtime_markers(env)
-
- _apply_windows_msys_bash_env_defaults(env)
-
- # Cross-session leak guard, same as the terminal spawn paths: this helper
- # copies os.environ, whose HERMES_SESSION_* mirror is a last-writer-wins
- # global under a concurrent multi-session host. A caller that re-binds the
- # session identity explicitly (slash_worker/ACP via --session-key argv) is
- # unaffected — bound ContextVars win here — but a caller that spawns without
- # re-binding (e.g. tui_gateway cli.exec) would otherwise inherit a FOREIGN
- # session's identity. Strip _UNSET session vars when engaged so that can't
- # happen; single uniform policy across every spawn surface.
- _inject_session_context_env(env)
-
- # Non-terminal subprocess helpers (browser, lazy-deps, TUI/ACP hosts, etc.)
- # also need the delegate_task child lineage marker. Otherwise a child
- # context that later imports Kanban DB code in the spawned process would
- # still see the parent's HERMES_HOME but lose the DB mutation guard.
- env = _scrub_delegated_child_kanban_env(env)
-
- return env
+ return _finalize_child_env(env)
def build_subprocess_env(
@@ -923,47 +409,17 @@ def build_subprocess_env(
scrub_secrets: bool = True,
extra: "Mapping[str, str] | None" = None,
) -> dict[str, str]:
- """Single factory for building a child-process environment.
-
- Every spawn site in the codebase should build its env through this
- function (or :func:`hermes_subprocess_env` for the model-driving-CLI
- surface) instead of copying ``os.environ`` directly, so profile-home
- propagation (``HERMES_HOME`` / subprocess ``HOME`` contract) and the
- Hermes secret-scrub policy have a single owner. History: ~11 separate
- commits each fixed one more spawn site that missed profile-HOME or
- secret-scrub propagation; this factory is the fix for the class.
-
- Parameters:
-
- * ``base`` — starting environment. ``None`` (default) snapshots
- ``os.environ``. Pass an explicit mapping to build on a caller-prepared
- env instead.
- * ``scrub_secrets=True`` (default) — delegate to
- :func:`_sanitize_subprocess_env`, the long-standing owner of the scrub
- list (provider blocklist + ``_is_hermes_internal_secret`` dynamic
- patterns + kanban/venv-marker/session-context guards) **and** of
- ``HERMES_HOME`` / subprocess-HOME propagation. On this path profile
- home propagation is inherent — ``inherit_profile_home`` is ignored
- (always applied), exactly matching today's sanitize semantics.
- * ``scrub_secrets=False`` — preserve the base env content byte-for-byte
- (no key is removed). Use for children that intentionally receive
- secrets (git credential flows, ``bws``/``op`` secret CLIs) or where
- scrubbing could change behavior. The site is still a win: it becomes
- grep-able and future-fixable.
- * ``inherit_profile_home`` — on the non-scrub path, when True, bridge the
- context-local Hermes home override into ``HERMES_HOME`` and apply the
- subprocess HOME contract (``hermes_constants.apply_subprocess_home_env``).
- Pass False to keep the inherited env untouched (exact legacy
- ``os.environ.copy()`` behavior).
- * ``extra`` — applied **last** on the non-scrub path so explicit caller
- overrides (e.g. a session-scoped ``HERMES_HOME``) always win. On the
- scrub path it is forwarded as ``_sanitize_subprocess_env``'s
- ``extra_env`` (same force-prefix / blocklist handling as today).
+ """Single factory for child-process environments, so profile-home
+ propagation and the secret-scrub policy have one owner.
+
+ ``base=None`` snapshots ``os.environ``. ``scrub_secrets=True`` delegates to
+ :func:`_sanitize_subprocess_env` (``extra`` -> ``extra_env``; profile home is
+ inherent, ``inherit_profile_home`` ignored). ``scrub_secrets=False`` keeps the
+ base byte-for-byte (git credential flows, ``bws``/``op``); then
+ ``inherit_profile_home`` bridges HERMES_HOME + HOME and ``extra`` is applied
+ last so caller overrides win.
"""
if scrub_secrets:
- # _sanitize_subprocess_env already performs HERMES_HOME override
- # bridging + apply_subprocess_home_env unconditionally; delegating
- # wholesale keeps one owner and zero drift.
return _sanitize_subprocess_env(
dict(base) if base is not None else os.environ.copy(),
dict(extra) if extra else None,
@@ -971,14 +427,45 @@ def build_subprocess_env(
env: dict[str, str] = dict(base) if base is not None else os.environ.copy()
if inherit_profile_home:
- _inject_context_hermes_home(env)
- from hermes_constants import apply_subprocess_home_env
- apply_subprocess_home_env(env)
+ _apply_profile_home(env)
if extra:
env.update(extra)
return env
+# --- Shell discovery ---
+
+
+def _windows_bash_candidates(custom: "str | None") -> list[str]:
+ """Ordered bash.exe candidates on Windows: HERMES_GIT_BASH_PATH, our
+ portable Git under %LOCALAPPDATA%\\hermes\\git (PortableGit ``bin`` and
+ MinGit ``usr\\bin`` layouts), known Git-for-Windows dirs, then PATH last —
+ ``shutil.which`` may return WSL's bash, which fails silently on Windows paths."""
+ candidates: list[str] = []
+
+ def add(candidate: str) -> None:
+ if candidate and os.path.isfile(candidate) and candidate not in candidates:
+ candidates.append(candidate)
+
+ add(custom or "")
+
+ local_appdata = os.environ.get("LOCALAPPDATA", "")
+ if local_appdata:
+ portable = os.path.join(local_appdata, "hermes", "git")
+ add(os.path.join(portable, "bin", "bash.exe"))
+ add(os.path.join(portable, "usr", "bin", "bash.exe"))
+
+ add(os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe"))
+ add(os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Git", "bin", "bash.exe"))
+ if local_appdata:
+ add(os.path.join(local_appdata, "Programs", "Git", "bin", "bash.exe"))
+
+ found = shutil.which("bash")
+ if found and found not in candidates:
+ candidates.append(found)
+ return candidates
+
+
def _find_bash() -> str:
"""Find bash for command execution."""
if not _IS_WINDOWS:
@@ -990,74 +477,27 @@ def _find_bash() -> str:
or "/bin/sh"
)
- candidates: list[str] = []
-
custom = os.environ.get("HERMES_GIT_BASH_PATH")
- if custom and os.path.isfile(custom):
- candidates.append(custom)
-
- # Prefer our own portable Git install — a broken or partially-uninstalled
- # system Git (or a stale HERMES_GIT_BASH_PATH pointing at one) must not
- # brick the terminal. install.ps1 drops PortableGit here when needed.
- #
- # Layouts (both checked so upgrades between MinGit and PortableGit
- # installs work transparently):
- # PortableGit: %LOCALAPPDATA%\hermes\git\bin\bash.exe (primary)
- # MinGit: %LOCALAPPDATA%\hermes\git\usr\bin\bash.exe (legacy/32-bit fallback)
- _local_appdata = os.environ.get("LOCALAPPDATA", "")
- _hermes_portable_git = os.path.join(_local_appdata, "hermes", "git") if _local_appdata else ""
- if _hermes_portable_git:
- for candidate in (
- os.path.join(_hermes_portable_git, "bin", "bash.exe"), # PortableGit (primary)
- os.path.join(_hermes_portable_git, "usr", "bin", "bash.exe"), # MinGit fallback
- ):
- if os.path.isfile(candidate) and candidate not in candidates:
- candidates.append(candidate)
-
- # Check known Git for Windows install locations before PATH lookup.
- # On machines with both WSL and Git for Windows, shutil.which("bash")
- # may return WSL's bash (which doesn't understand Windows paths and
- # will fail silently). Explicit Git-for-Windows paths avoid that.
- for candidate in (
- os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe"),
- os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Git", "bin", "bash.exe"),
- os.path.join(_local_appdata, "Programs", "Git", "bin", "bash.exe") if _local_appdata else "",
- ):
- if candidate and os.path.isfile(candidate) and candidate not in candidates:
- candidates.append(candidate)
+ candidates = _windows_bash_candidates(custom)
- found = shutil.which("bash")
- if found and found not in candidates:
- candidates.append(found)
-
- # Prefer the first candidate that can actually start. A stale
- # HERMES_GIT_BASH_PATH pointing at a broken Git-for-Windows install
- # (``Directory \\drivers\\etc does not exist``) must not win over a
- # healthy portable Git under %LOCALAPPDATA%\\hermes\\git.
+ # First candidate that can actually start wins: a stale HERMES_GIT_BASH_PATH
+ # pointing at a broken install must not beat a healthy portable Git.
for candidate in candidates:
if _bash_starts(candidate):
if candidate != custom and custom and os.path.isfile(custom):
logger.warning(
- "HERMES_GIT_BASH_PATH=%s fails to start; using %s instead",
- custom,
- candidate,
+ "HERMES_GIT_BASH_PATH=%s fails to start; using %s instead", custom, candidate,
)
return candidate
if candidates:
probe_details = "\n".join(
- detail
- for candidate in candidates
- if (detail := _bash_probe_details_cache.get(candidate))
+ detail for c in candidates if (detail := _bash_probe_details_cache.get(c))
)
- if _mandatory_aslr_enabled() is True or _looks_like_msys_spawn_failure(
- probe_details
- ):
+ if _mandatory_aslr_enabled() is True or _looks_like_msys_spawn_failure(probe_details):
raise RuntimeError(_git_bash_aslr_help(candidates[0], probe_details))
-
- # Last resort for failures unrelated to the known MSYS/ASLR class:
- # return the first path so the caller still sees the real bash error
- # instead of the less useful "not found" message.
+ # Unknown failure class: return the first path so the caller sees the
+ # real bash error instead of a less useful "not found".
return candidates[0]
raise RuntimeError(
@@ -1067,241 +507,70 @@ def _find_bash() -> str:
)
-_bash_starts_cache: dict[str, bool] = {}
-_bash_probe_details_cache: dict[str, str] = {}
-_mandatory_aslr_enabled_cache: "bool | None" = None
-
-_BASH_EXTERNAL_PROGRAM_PROBE = "/usr/bin/true; /usr/bin/cat --version >/dev/null"
-
-
-def _looks_like_msys_spawn_failure(details: str) -> bool:
- """Match Git-for-Windows child-launch failures associated with ASLR."""
- lowered = details.lower()
- return any(
- marker in lowered
- for marker in (
- "dofork:",
- "child_copy:",
- "0xc0000142",
- "0xc0000005",
- )
- )
-
-
-def _mandatory_aslr_enabled() -> "bool | None":
- """Return Windows' system-wide ForceRelocateImages state when available."""
- global _mandatory_aslr_enabled_cache
- if _mandatory_aslr_enabled_cache is not None:
- return _mandatory_aslr_enabled_cache
-
- try:
- powershell = shutil.which("powershell.exe") or "powershell.exe"
- result = subprocess.run(
- [
- powershell,
- "-NoProfile",
- "-NonInteractive",
- "-Command",
- "(Get-ProcessMitigation -System).Aslr.ForceRelocateImages.ToString()",
- ],
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=10,
- creationflags=windows_hide_flags(),
- )
- if result.returncode != 0:
- return None
- value = (result.stdout or "").strip().upper()
- if value == "ON":
- _mandatory_aslr_enabled_cache = True
- return True
- if value in {"OFF", "NOTSET"}:
- _mandatory_aslr_enabled_cache = False
- return False
- except Exception as exc:
- logger.debug("Could not query Windows Mandatory ASLR state: %s", exc)
- return None
-
-
-def _git_root_from_bash(bash: str) -> str:
- """Resolve Git's root from either <root>/bin or <root>/usr/bin bash."""
- bin_dir = ntpath.dirname(ntpath.normpath(bash))
- if ntpath.basename(bin_dir).lower() != "bin":
- return ntpath.dirname(bin_dir)
- parent = ntpath.dirname(bin_dir)
- if ntpath.basename(parent).lower() == "usr":
- return ntpath.dirname(parent)
- return parent
-
-
-def _git_bash_aslr_help(bash: str, details: str = "") -> str:
- """Build the targeted per-program Mandatory-ASLR remediation."""
- git_root = _git_root_from_bash(bash)
- escaped_root = git_root.replace("'", "''")
- detail_line = f"\nGit Bash probe output: {details[:500]}" if details else ""
- return (
- f"Git Bash at {bash} cannot launch required MSYS child processes while "
- "Windows Mandatory ASLR (ForceRelocateImages) is enabled, or its output "
- f"matches that Git-for-Windows failure class.{detail_line}\n"
- "Reinstalling Git will not change the Windows mitigation policy. Open "
- "PowerShell as Administrator and run:\n"
- f"$gitRoot = '{escaped_root}'\n"
- 'Get-Item "$gitRoot\\bin\\bash.exe", "$gitRoot\\usr\\bin\\*.exe" '
- "-ErrorAction SilentlyContinue | ForEach-Object { "
- "Set-ProcessMitigation -Name $_.FullName -Disable ForceRelocateImages }\n"
- "Then restart Hermes. If the override is blocked or later re-applied, "
- "ask your Windows administrator to allow this per-program exception."
- )
-
-
-def _bash_starts(bash: str) -> bool:
- """True if *bash* can launch external MSYS programs.
-
- Uses ``--noprofile --norc`` so a broken login post-install
- (``Directory \\drivers\\etc``) does not falsely condemn an otherwise
- usable bash. The external ``true`` and ``cat`` calls are intentional:
- a builtin-only ``exit 0`` probe misses Git-for-Windows fork/spawn failures
- under system-wide Mandatory ASLR. Cached per path for the process lifetime.
- """
- cached = _bash_starts_cache.get(bash)
- if cached is not None:
- return cached
-
- try:
- result = subprocess.run(
- [bash, "--noprofile", "--norc", "-c", _BASH_EXTERNAL_PROGRAM_PROBE],
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=15,
- creationflags=windows_hide_flags() if _IS_WINDOWS else 0,
- )
- ok = result.returncode == 0
- if not ok:
- combined = f"{result.stdout or ''}{result.stderr or ''}"
- _bash_probe_details_cache[bash] = combined.strip()[:2000]
- logger.debug("bash probe failed for %s: %s", bash, combined.strip()[:200])
- except Exception as exc:
- _bash_probe_details_cache[bash] = str(exc)[:2000]
- logger.debug("bash probe error for %s: %s", bash, exc)
- ok = False
-
- _bash_starts_cache[bash] = ok
- return ok
-
-
_git_bash_bin_dirs_cache: "list[str] | None" = None
def _git_bash_bin_dirs() -> list[str]:
- """Git Bash's coreutils/binary dirs, in ``/etc/profile`` precedence order.
-
- A non-login ``bash -c`` (the fallback used when ``bash -l`` is broken —
- the classic Windows ``Directory \\drivers\\etc does not exist`` failure)
- never sources ``/etc/profile``, so it never gets ``…\\usr\\bin`` on PATH.
- That directory holds every coreutil the file/terminal tools shell out to
- (``cat``, ``mktemp``, ``mv``, ``wc``, ``head``, ``stat``, ``chmod``,
- ``mkdir``, ``find`` …). Without it, ``write_file`` fails with an empty
- error (the failure text went to a missing binary's stderr) and terminal
- commands exit 127. We derive these dirs from the resolved ``bash.exe`` so
- the fallback shell can find coreutils regardless of the login shell.
-
- Returns ``[]`` off Windows or when bash can't be located. Dirs are
- returned in the order Git Bash's own ``/etc/profile`` prepends them
- (mingw first, then usr/bin, then bin) and only if they exist on disk.
- """
+ """Git Bash's coreutils dirs in ``/etc/profile`` order (mingw first so
+ coreutils beat System32 lookalikes); ``[]`` off Windows. A non-login
+ ``bash -c`` (fallback when ``bash -l`` is broken) never sources
+ ``/etc/profile``, so without these ``cat``/``mktemp``/``mv`` are missing:
+ ``write_file`` fails with an empty error and commands exit 127."""
global _git_bash_bin_dirs_cache
- if _git_bash_bin_dirs_cache is not None:
- return _git_bash_bin_dirs_cache
+ if _git_bash_bin_dirs_cache is None:
+ _git_bash_bin_dirs_cache = _compute_git_bash_bin_dirs() if _IS_WINDOWS else []
+ return _git_bash_bin_dirs_cache
- if not _IS_WINDOWS:
- _git_bash_bin_dirs_cache = []
- return _git_bash_bin_dirs_cache
- dirs: list[str] = []
+def _compute_git_bash_bin_dirs() -> list[str]:
try:
bash = _find_bash()
except Exception:
- _git_bash_bin_dirs_cache = []
- return _git_bash_bin_dirs_cache
-
- bin_dir = os.path.dirname(bash) # <root>\bin or <root>\usr\bin
+ return []
+ bin_dir = os.path.dirname(bash) # <root>\bin or <root>\usr\bin (MinGit)
parent = os.path.dirname(bin_dir)
- # MinGit ships bash under usr\bin; PortableGit/system Git under bin.
root = os.path.dirname(parent) if os.path.basename(parent).lower() == "usr" else parent
-
- # Order mirrors Git-for-Windows /etc/profile so coreutils win over the
- # same-named Windows System32 tools (find.exe, sort.exe) inside the shell.
- for candidate in (
- os.path.join(root, "mingw64", "bin"),
- os.path.join(root, "mingw32", "bin"),
- os.path.join(root, "usr", "local", "bin"),
- os.path.join(root, "usr", "bin"),
- os.path.join(root, "bin"),
- ):
+ dirs: list[str] = []
+ for sub in (("mingw64", "bin"), ("mingw32", "bin"), ("usr", "local", "bin"), ("usr", "bin"), ("bin",)):
+ candidate = os.path.join(root, *sub)
if os.path.isdir(candidate) and candidate not in dirs:
dirs.append(candidate)
-
- _git_bash_bin_dirs_cache = dirs
return dirs
-def _prepend_git_bash_dirs(existing_path: str) -> str:
- """Prepend Git Bash's binary dirs to ``existing_path`` if missing.
-
- No-op off Windows or when the dirs can't be resolved. First-occurrence
- wins, so a PATH that already lists a dir keeps its position. This is what
- lets the non-login ``bash -c`` fallback find coreutils; in the healthy
- case the session snapshot re-exports the full login PATH inside the shell,
- so this only matters when that snapshot is absent.
- """
- git_dirs = _git_bash_bin_dirs()
- if not git_dirs:
+def _prepend_missing_path_entries(existing_path: str, dirs: list[str]) -> str:
+ """Prepend *dirs* missing from *existing_path* (``os.pathsep``); an
+ already-listed dir keeps its position and the input is returned unchanged
+ when nothing is missing."""
+ if not dirs:
return existing_path
sep = os.pathsep
entries = [e for e in existing_path.split(sep) if e] if existing_path else []
- missing = [d for d in git_dirs if d not in entries]
+ missing = [d for d in dirs if d not in entries]
if not missing:
return existing_path
return sep.join([*missing, *entries])
-# POSIX-sh-family shells that understand the ``[shell, "-lic", "set +m; …"]``
-# invocation spawn_local uses. $SHELL values outside this set (fish, csh/tcsh,
-# nushell, elvish, xonsh, …) would error on that syntax, so _find_shell falls
-# back to bash for them rather than honouring $SHELL. (#42203)
+def _prepend_git_bash_dirs(existing_path: str) -> str:
+ """Prepend Git Bash's binary dirs if missing (no-op off Windows), so the
+ non-login ``bash -c`` fallback can find coreutils when no login snapshot
+ re-exports the full PATH inside the shell."""
+ return _prepend_missing_path_entries(existing_path, _git_bash_bin_dirs())
+
+
+# POSIX-sh-family shells that understand spawn_local's ``[shell, "-lic",
+# "set +m; …"]`` invocation. fish, csh/tcsh, nushell, elvish, xonsh would error
+# on that syntax, so _find_shell falls back to bash for them.
_SPAWN_COMPATIBLE_SHELLS = frozenset({"bash", "zsh", "sh", "dash", "ksh", "mksh"})
def _find_shell() -> str:
- """Find the user's login shell for background process spawning.
-
- Unlike ``_find_bash`` (which always returns a bash binary for callers
- that explicitly need bash), this function prefers the user's configured
- ``$SHELL`` on POSIX so that ``spawn_local`` uses the shell the user
- actually logs in with.
-
- On macOS Catalina+ the default login shell is zsh, but
- ``shutil.which("bash")`` still finds the system ``/bin/bash`` (GNU bash
- 3.2). When bash 3.2 is invoked with ``-l`` (login) and stdin is
- ``/dev/null``, it sources ``~/.bash_profile`` which on many macOS setups
- contains ``exec /bin/zsh -l``. That ``exec`` replaces bash with zsh but
- drops the ``-c`` argument, so the background command never runs — the
- subprocess exits 0 with no output and no side effects.
-
- Preferring ``$SHELL`` (when it is a POSIX-``sh``-family shell) avoids this
- because zsh/bash/sh/dash/ksh handle ``-lic`` correctly even with
- redirected stdin.
-
- Only POSIX-sh-family shells are honoured: ``spawn_local`` invokes the
- shell as ``[shell, "-lic", "set +m; <cmd>"]``, and that ``-lic`` bundle +
- ``set +m`` job-control syntax is NOT understood by fish, csh/tcsh,
- nushell, elvish, xonsh, etc. Returning such a ``$SHELL`` would trade the
- bash-3.2 swallow for a parse error on every background command, so for any
- non-allowlisted shell we fall back to ``_find_bash`` (the prior behaviour).
-
- On Windows, ``$SHELL`` is typically bash (Git Bash), so behaviour is
- unchanged — we fall through to ``_find_bash``.
- """
+ """User's login shell for background spawning: ``$SHELL`` on POSIX when it
+ is an executable sh-family shell, else ``_find_bash``. macOS's system bash
+ 3.2 under ``-l`` with stdin ``/dev/null`` sources ``~/.bash_profile``, which
+ often ``exec /bin/zsh -l`` and drops ``-c`` — the command silently never
+ runs. Non-allowlisted shells would trade that for a parse error."""
if not _IS_WINDOWS:
user_shell = os.environ.get("SHELL")
if (
@@ -1314,6 +583,8 @@ def _find_shell() -> str:
return _find_bash()
+# --- PATH completion for the terminal subshell ---
+
# Standard PATH entries for environments with minimal PATH.
_SANE_PATH = (
"/opt/homebrew/bin:/opt/homebrew/sbin:"
@@ -1327,28 +598,11 @@ _HERMES_BIN_DIR: "str | None | object" = _SENTINEL
def _resolve_hermes_bin_dir() -> str | None:
- """Return the directory holding the ``hermes`` console-script, or None.
-
- The terminal tool runs in a freshly-spawned subshell whose PATH is the
- agent process's PATH plus a static set of system dirs (``_SANE_PATH``).
- When the gateway is launched by something that does NOT source the user's
- shell rc — systemd, a service manager, a desktop launcher, cron — the
- hermes install dir (``~/.local/bin``, the venv ``bin``/``Scripts``, pipx,
- nix) is absent from that PATH, so plugins shelling out to bare ``hermes``
- via the terminal tool hit ``command not found`` (exit 127) even though
- ``hermes`` works fine in the user's own interactive terminal.
-
- We resolve the install dir once (it never changes within a process) and
- prepend-if-missing it to the subshell PATH so bare ``hermes`` resolves
- regardless of how the gateway was started.
-
- Resolution order (cheap, no heavy imports):
- 1. ``shutil.which("hermes")`` — normal PATH-installed shim.
- 2. The directory of ``sys.argv[0]`` when it's an absolute path to a
- real ``hermes`` executable (covers nix-store / venv wrappers).
- 3. The directory of ``sys.executable`` — the running interpreter's
- venv ``bin``/``Scripts`` is where its console-scripts live.
- """
+ """Directory holding the ``hermes`` console-script, or None (cached).
+ Launched by systemd/cron/a desktop launcher, the gateway's PATH lacks the
+ install dir (``~/.local/bin``, venv ``bin``, pipx, nix) and bare ``hermes``
+ exits 127. Order: ``which``; absolute ``sys.argv[0]`` naming a real hermes
+ executable; ``sys.executable``'s dir if it holds the shim."""
global _HERMES_BIN_DIR
if _HERMES_BIN_DIR is not _SENTINEL:
return _HERMES_BIN_DIR # type: ignore[return-value]
@@ -1371,10 +625,9 @@ def _resolve_hermes_bin_dir() -> str | None:
if candidate is None:
exe_dir = os.path.dirname(sys.executable) if sys.executable else ""
- if exe_dir:
- shim = "hermes.exe" if _IS_WINDOWS else "hermes"
- if os.path.isfile(os.path.join(exe_dir, shim)):
- candidate = exe_dir
+ shim = "hermes.exe" if _IS_WINDOWS else "hermes"
+ if exe_dir and os.path.isfile(os.path.join(exe_dir, shim)):
+ candidate = exe_dir
if candidate and not os.path.isdir(candidate):
candidate = None
@@ -1384,41 +637,16 @@ def _resolve_hermes_bin_dir() -> str | None:
def _prepend_hermes_bin_dir(existing_path: str) -> str:
- """Prepend the hermes install dir to ``existing_path`` if it's missing.
-
- Cross-platform (uses ``os.pathsep``). First-occurrence wins, so a PATH
- that already contains the dir is returned unchanged. Returns the input
- unchanged when the install dir can't be resolved.
- """
+ """Prepend the hermes install dir to ``existing_path`` if it's missing
+ (unchanged when already present or unresolvable)."""
bin_dir = _resolve_hermes_bin_dir()
- if not bin_dir:
- return existing_path
- sep = os.pathsep
- entries = [e for e in existing_path.split(sep) if e] if existing_path else []
- if bin_dir in entries:
- return existing_path
- return sep.join([bin_dir, *entries])
+ return _prepend_missing_path_entries(existing_path, [bin_dir] if bin_dir else [])
def _managed_runtime_path_entries() -> list[str]:
- """Return existing Hermes-managed runtime dirs for the terminal subshell PATH.
-
- The terminal tool spawns a subshell whose PATH is the agent process's PATH
- plus ``_SANE_PATH``. Neither carries the runtimes Hermes installs for
- itself, so on a machine where Hermes provisioned its own toolchain a
- command the agent runs resolves a system copy instead — or nothing at all:
-
- - ``$HERMES_HOME/node`` (+ ``/bin``) — installed to satisfy the desktop and
- browser toolchain. ``tools/browser_tool.py`` already does this for its own
- subprocesses; the agent's shell deserves the same.
- - ``$HERMES_HOME/bin`` — the managed ``uv``. ``install.sh`` writes it there
- and nothing has ever put that directory on PATH, so an install whose only
- uv is the managed one looks uv-less to both the agent and the model.
-
- Resolved per call rather than cached in a module constant because
- ``get_hermes_home()`` is profile-scoped and a managed tree can appear
- mid-process (``heal_hermes_managed_node``, a first browser install).
- """
+ """Existing Hermes-managed runtime dirs: ``$HERMES_HOME/node`` (+``/bin``)
+ and ``$HERMES_HOME/bin`` (managed ``uv``). Per call, not cached: home is
+ profile-scoped and a managed tree can appear mid-process."""
try:
from hermes_constants import get_hermes_home, iter_hermes_node_dirs
@@ -1429,32 +657,10 @@ def _managed_runtime_path_entries() -> list[str]:
def _append_missing_sane_path_entries(existing_path: str) -> str:
- """Return a normalised POSIX PATH with missing sane entries appended.
-
- On POSIX the caller-supplied PATH is rewritten (not merely appended to):
- empty entries and duplicate entries are dropped, preserving
- first-occurrence order, then each missing ``_SANE_PATH`` entry is appended
- once at the end so existing entries keep their precedence.
-
- Two intentional normalisations beyond the bare "add Homebrew dirs" fix:
-
- - **Empty entries are stripped.** A leading/trailing/double ``:`` encodes
- an empty PATH element, which POSIX shells interpret as the current
- working directory — a mild foot-gun in a default terminal environment.
- We drop these rather than carry them through.
- - **Duplicates are collapsed** (first occurrence wins), so a caller PATH
- that already contains repeats is not propagated verbatim.
-
- Hermes-managed runtime dirs are appended alongside the sane entries, not
- prepended: a tool the user deliberately put on their own PATH still wins,
- and the managed one only fills the gap where there would otherwise be
- nothing.
-
- For a well-formed PATH (no empties, no duplicates) the leading segment is
- byte-identical to the input and ordering is preserved; only the missing
- sane entries are appended. On Windows this is a no-op passthrough (the
- separator is ``;`` and the native PATH must not be touched).
- """
+ """Normalised POSIX PATH with missing sane entries appended: empty entries
+ dropped (shells read them as cwd), duplicates collapsed (first wins), then
+ missing ``_SANE_PATH`` / managed-runtime dirs appended so user entries keep
+ precedence. Windows is a no-op passthrough (native ``;`` PATH untouched)."""
if _IS_WINDOWS:
return existing_path
@@ -1464,43 +670,17 @@ def _append_missing_sane_path_entries(existing_path: str) -> str:
)
if not existing_path:
return ":".join(sane_entries)
-
- # De-duplicate the caller PATH (first occurrence wins) and drop empty
- # entries before merging in the sane fallbacks.
- seen: set[str] = set()
- ordered_entries: list[str] = []
- for entry in existing_path.split(":"):
- if not entry or entry in seen:
- continue
- seen.add(entry)
- ordered_entries.append(entry)
-
- # _SANE_PATH is a static, duplicate-free constant, so a membership check
- # against the caller entries is sufficient — no need to track `seen` here.
- for entry in sane_entries:
- if entry not in seen:
- ordered_entries.append(entry)
-
- return ":".join(ordered_entries)
+ # dict preserves first-occurrence order; empty entries dropped.
+ ordered = dict.fromkeys(entry for entry in existing_path.split(":") if entry)
+ ordered.update(dict.fromkeys(sane_entries))
+ return ":".join(ordered)
def _apply_windows_msys_bash_env_defaults(env: dict) -> None:
- """Disable MSYS argument path conversion for Git Bash subprocesses.
-
- Git Bash rewrites arguments that look like Unix paths (``/FO``, ``/TN``,
- ``/Create``) into ``C:/.../git/FO``-style paths, which breaks native
- Windows commands such as ``tasklist``, ``schtasks``, and ``wmic``. Hermes
- runs terminal commands through bash on Windows, so set the standard MSYS
- opt-out by default. Users who need conversion can override in their env.
- Refs #56700.
-
- ``MSYS_NO_PATHCONV`` is honored by Git for Windows bash only. MSYS2-proper
- and Cygwin bash (which ``_find_bash`` can still return via the final
- ``shutil.which`` fallback) ignore it and honor ``MSYS2_ARG_CONV_EXCL``
- instead, so set both. ``*`` disables all argv conversion — the semantic
- equivalent of ``MSYS_NO_PATHCONV=1``. Also fixes ``cmd /c`` mangling
- (#56147).
- """
+ """Disable MSYS argument path conversion (``/FO`` -> ``C:/.../git/FO``
+ breaks tasklist/schtasks/wmic/``cmd /c``). Git for Windows honors
+ ``MSYS_NO_PATHCONV``; MSYS2/Cygwin bash honor ``MSYS2_ARG_CONV_EXCL`` — set
+ both. Users can override in their env."""
if not _IS_WINDOWS:
return
env.setdefault("MSYS_NO_PATHCONV", "1")
@@ -1508,15 +688,8 @@ def _apply_windows_msys_bash_env_defaults(env: dict) -> None:
def _path_env_key(run_env: dict) -> str | None:
- """Return the PATH env key to update without altering Windows casing.
-
- Note: this is deliberately a *second* Windows guard, distinct from the
- early-return in ``_append_missing_sane_path_entries``. Its job is to pick
- the correctly-cased key (``Path`` vs ``PATH``) so completion writes back to
- the key the caller already used; the helper's guard makes that helper safe
- to call standalone (it is, e.g. in the Windows unit tests). Both are
- intentional.
- """
+ """Return the PATH env key to update without altering Windows casing
+ (``Path`` vs ``PATH``); None when a Windows env has no PATH key at all."""
if not _IS_WINDOWS:
return "PATH"
for key in run_env:
@@ -1527,357 +700,51 @@ def _path_env_key(run_env: dict) -> str | None:
def _make_run_env(env: dict) -> dict:
"""Build a run environment with a sane PATH and provider-var stripping."""
- try:
- from tools.env_passthrough import (
- is_env_passthrough as _is_passthrough,
- resolve_passthrough_value as _resolve_passthrough_value,
- )
- except Exception:
- _is_passthrough = lambda _: False # noqa: E731
- _resolve_passthrough_value = lambda _name, fallback: fallback # noqa: E731
-
- merged = dict(os.environ | env)
- run_env = {}
- for k, v in merged.items():
- if k.startswith(_HERMES_PROVIDER_ENV_FORCE_PREFIX):
- real_key = k[len(_HERMES_PROVIDER_ENV_FORCE_PREFIX):]
- if _is_hermes_internal_secret(real_key):
- continue
- run_env[real_key] = v
- elif _is_hermes_internal_secret(k):
- continue
- else:
- first_party = _is_terminal_first_party_env(k)
- passthrough = _is_passthrough(k)
- if k in _HERMES_PROVIDER_ENV_BLOCKLIST and not (passthrough or first_party):
- continue
- # First-party vars use the merged env value directly (see
- # _sanitize_subprocess_env); only passthrough names resolve.
- value = v
- if passthrough and not first_party:
- value = _resolve_passthrough_value(k, v)
- if value is not None:
- run_env[k] = value
+ run_env: dict = {}
+ _filter_secret_env(dict(os.environ | env), run_env, unwrap_force=True)
path_key = _path_env_key(run_env)
if path_key is not None:
new_path = _append_missing_sane_path_entries(run_env.get(path_key, ""))
- # On Windows, ensure Git Bash's coreutils dirs (…\usr\bin etc.) are on
- # PATH. A non-login ``bash -c`` fallback (used when ``bash -l`` is
- # broken) never sources /etc/profile, so without this cat/mktemp/mv and
- # friends are missing and every write_file/terminal call fails (empty
- # error / exit 127). No-op off Windows and when a login snapshot is
- # healthy (the snapshot re-exports the full PATH inside the shell).
new_path = _prepend_git_bash_dirs(new_path)
- # Ensure the hermes install dir is reachable so plugins can shell out
- # to bare ``hermes`` via the terminal tool even when the gateway was
- # launched without it on PATH (systemd, service managers, cron, etc.).
run_env[path_key] = _prepend_hermes_bin_dir(new_path)
-
- _inject_context_hermes_home(run_env)
-
- from hermes_constants import apply_subprocess_home_env
- apply_subprocess_home_env(run_env)
-
- # Bridge ContextVar-based session vars into the subprocess env (with the
- # cross-session leak guard — strips _UNSET vars when a concurrent host is
- # engaged so a sibling session's os.environ mirror can't leak in).
- _inject_session_context_env(run_env)
-
- _strip_hermes_owned_pythonpath_and_runtime_markers(run_env)
-
- _apply_windows_msys_bash_env_defaults(run_env)
-
- run_env = _scrub_delegated_child_kanban_env(run_env)
-
- return run_env
-
-
-def _same_path(left: Path, right: Path) -> bool:
- """Compare path spellings with host filesystem case semantics."""
- left_parts = [os.path.normcase(part) for part in left.parts]
- right_parts = [os.path.normcase(part) for part in right.parts]
- return left_parts == right_parts
-
-
-def _build_hermes_repo_root_aliases(
- resolved_root: Path,
- lexical_root: Path,
- configured_home: Path,
-) -> tuple[Path, ...]:
- """Return exact repo-root spellings emitted by Hermes launchers.
-
- ``gateway_windows._preserve_hermes_home_path`` maps a physical path under
- the resolved HERMES_HOME back onto the configured HERMES_HOME spelling.
- Mirror that producer contract here so a junction-backed install is matched
- without treating arbitrary descendants of HERMES_HOME as Hermes-owned.
- Additionally, when the repo itself is a junction under the configured root
- (repo-level junction, possibly cross-drive), the single deterministic
- candidate <root>/<repo dirname> is accepted only when strict resolve
- proves it is the exact physical repo root.
- """
- aliases: list[Path] = []
-
- def add(candidate: Path) -> None:
- if not any(_same_path(candidate, existing) for existing in aliases):
- aliases.append(candidate)
-
- add(resolved_root)
- add(lexical_root)
-
- # Profile re-home: with --profile / sticky active_profile the configured
- # home becomes <root>/profiles/<name>. The repo root then lives beside
- # the profiles directory (not under the profile home), so the home-
- # relative mapping below cannot reach it. Derive the root spelling
- # lexically the same way get_default_hermes_root() does (parent of a
- # "profiles" component) and run the same exact-ownership mapping against
- # it -- this recovers the launcher's lexical root under profile re-home
- # while still never matching arbitrary descendants of HERMES_HOME.
- home_candidates = [configured_home]
- if configured_home.parent.name == "profiles":
- home_candidates.append(configured_home.parent.parent)
-
- for home in home_candidates:
- try:
- resolved_home = home.resolve()
- home_key = os.path.normcase(str(resolved_home))
- root_key = os.path.normcase(str(resolved_root))
- if os.path.commonpath([home_key, root_key]) == home_key:
- relative_root = os.path.relpath(str(resolved_root), str(resolved_home))
- add(home / relative_root)
- except (OSError, ValueError):
- pass
-
- # Repo-level junction recovery: the repository itself may be a
- # junction/symlink under the configured root (e.g. D:\hermes\hermes-agent
- # -> C:\...\hermes-agent) while the import spelling (editable install)
- # resolves to the physical location. The home-relative mapping above
- # cannot express a cross-drive link (commonpath raises on different
- # drives), so prove the EXACT filesystem identity of the single
- # deterministic candidate -- <lexical root>/<repo dirname> -- with a
- # strict resolve before accepting it as Hermes-owned. Fail-closed: a
- # missing path (strict resolve raises), a real directory that is not the
- # known physical root, or any unrelated spelling never becomes an alias.
- for home in home_candidates:
- repo_candidate = home / resolved_root.name
- try:
- if repo_candidate.resolve(strict=True) == resolved_root.resolve(strict=True):
- add(repo_candidate)
- except OSError:
- pass
-
- return tuple(aliases)
+ return _finalize_child_env(run_env)
# --- Hermes venv / repo-root detection (module-level, computed once) ---
+# Owned here; read lazily by tools.environments.local_pythonpath.
-#: The Hermes repository root - three levels up from this file
-#: (``tools/environments/local.py`` -> ``tools/environments`` -> ``tools``
-#: -> repo root). This is the directory the Electron app prepends to
-#: PYTHONPATH so the backend can do ``import tools``, ``import hermes_cli``,
-#: etc. Subprocesses that are NOT the Hermes backend don't need it and it
-#: can shadow local packages.
+#: The Hermes repository root (three levels up from this file). The Electron
+#: app prepends it to PYTHONPATH so the backend can ``import tools``; other
+#: subprocesses don't need it and it can shadow local packages.
_hermes_repo_root: Path = Path(__file__).resolve().parents[2]
-#: Alternate spellings of the repo root that Hermes launchers may emit.
-#: ``Path(__file__).resolve()`` canonicalizes symlinks/junctions, but the
-#: Windows gateway launcher deliberately renders Hermes-owned paths under
-#: the configured HERMES_HOME spelling (which may be a junction to another
-#: drive — see ``hermes_cli/gateway_windows.py::_preserve_hermes_home_path``).
-#: ``Path(__file__)`` (unresolved) keeps that spelling, so a PYTHONPATH
-#: entry written by the launcher still matches even though it differs
-#: lexically from the resolved root.
+#: Alternate repo-root spellings Hermes launchers may emit. ``resolve()``
+#: canonicalizes junctions, but the Windows gateway launcher renders
+#: Hermes-owned paths under the configured HERMES_HOME spelling (possibly a
+#: junction to another drive); the unresolved ``Path(__file__)`` keeps it.
_hermes_repo_root_aliases: tuple[Path, ...] = _build_hermes_repo_root_aliases(
_hermes_repo_root,
Path(__file__).absolute().parents[2],
get_process_hermes_home(),
)
-#: Whether the current interpreter is running inside a venv. On Python 3.3+
-#: ``sys.base_prefix != sys.prefix`` indicates a venv (or virtualenv).
-#: ``sys.real_prefix`` is the old virtualenv (<20) marker.
+#: Whether the interpreter runs inside a venv (``sys.real_prefix`` is the old
+#: virtualenv<20 marker).
_in_venv: bool = (
getattr(sys, "base_prefix", sys.prefix) != sys.prefix
or hasattr(sys, "real_prefix")
)
-#: Cached set of site-packages directories that belong to the running
-#: interpreter's own venv. Computed lazily (once) because ``site`` import
-#: and path construction are not free and this function is called on every
-#: subprocess spawn.
+#: Lazily-cached site-packages dirs of the running interpreter's own venv.
_hermes_site_packages: list[Path] | None = None
-def _validated_runtime_venv(env: dict) -> Path | None:
- """Return a producer-owned runtime venv identified by VIRTUAL_ENV.
-
- A user may carry an unrelated VIRTUAL_ENV, so the variable alone is not
- provenance. The legacy Windows base-Python gateway producer uses the exact
- ``<Hermes repo>/venv`` layout and a real venv marker; require both before
- accepting its separate runtime venv.
- """
- value = env.get("VIRTUAL_ENV")
- if not value:
- return None
-
- candidate = Path(value)
- if not any(_same_path(candidate, repo_root / "venv") for repo_root in _hermes_repo_root_aliases):
- return None
-
- try:
- if not (candidate / "pyvenv.cfg").is_file():
- return None
- except OSError:
- return None
-
- return candidate
-
-
-def _get_hermes_site_packages(env: dict) -> list[Path]:
- """Return exact site-packages dirs owned by the Hermes runtime.
-
- Uses ``site.getsitepackages()`` when available for robustness (it respects
- ``.pth`` rewrites and platform conventions), with a manual fallback that
- constructs the canonical path from ``sys.prefix`` for POSIX and Windows.
- A validated Windows base-interpreter launch contributes its separate
- ``VIRTUAL_ENV/Lib/site-packages`` directory as an additional exact entry.
- """
- global _hermes_site_packages
- if _hermes_site_packages is not None:
- result = list(_hermes_site_packages)
- else:
- result = []
- if _in_venv:
- try:
- import site
- for sp in site.getsitepackages():
- result.append(Path(sp))
- except Exception:
- pass
-
- # Fallback: construct manually. On POSIX:
- # sys.prefix / lib / python{X.Y} / site-packages
- # On Windows:
- # sys.prefix / Lib / site-packages
- if not result:
- if _IS_WINDOWS:
- result.append(Path(sys.prefix) / "Lib" / "site-packages")
- else:
- pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"
- result.append(Path(sys.prefix) / "lib" / pyver / "site-packages")
-
- _hermes_site_packages = list(result)
-
- runtime_venv = _validated_runtime_venv(env)
- if runtime_venv is not None:
- runtime_site_packages = runtime_venv / "Lib" / "site-packages"
- if not any(_same_path(runtime_site_packages, existing) for existing in result):
- result.append(runtime_site_packages)
-
- return result
-
-
-def _strip_hermes_owned_pythonpath_and_runtime_markers(env: dict) -> None:
- """Strip Hermes-owned PYTHONPATH entries, then the runtime marker vars.
-
- Ordering is load-bearing: PYTHONPATH filtering must run BEFORE the
- markers are removed so a validated Windows base-interpreter launch
- (VIRTUAL_ENV -> <repo>/venv) can still prove ownership.
- """
- _strip_hermes_owned_pythonpath(env)
- for _marker in _ACTIVE_VENV_MARKER_VARS:
- env.pop(_marker, None)
-
-
-def _strip_hermes_owned_pythonpath(env: dict) -> None:
- """Remove Hermes-owned PYTHONPATH entries from subprocess environments.
-
- Launchers prepend the Hermes repo root and the Hermes venv's
- site-packages so the backend can ``import tools``; leaking those into a
- child Python of a DIFFERENT version makes it load the backend's C
- extensions and crash (``numpy._core._multiarray_umath``, ``PIL._imaging``,
- ``cryptography``). Blanket-removing PYTHONPATH would discard legitimate
- user entries, so only entries proven Hermes-owned are removed:
-
- 1. The exact repo root (never direct children -- no launcher injects
- one, and user paths under the repo must survive).
- 2. The exact runtime site-packages dirs (running interpreter's venv or
- a validated Windows base-Python runtime venv; descendants are user
- paths).
-
- Everything else -- user libs, Nix plugin paths, a pythonX.Y/site-packages
- entry meant for a DIFFERENT child version -- is preserved byte-for-byte:
- ownership is decided by path provenance, never by a cross-version
- heuristic (#74817 follow-up).
- """
- pp = env.get("PYTHONPATH")
- if not pp:
- return
-
- hermes_site_packages = _get_hermes_site_packages(env)
-
- kept: list[str] = []
- stripped: list[str] = []
-
- for entry in pp.split(os.pathsep):
- # Empty and non-normalized components are user-owned semantics. In
- # particular, an empty component means the current working directory.
- # Preserve raw spelling unless the exact component is Hermes-owned.
- if entry == "":
- kept.append(entry)
- continue
-
- entry_path = Path(entry)
- should_strip = False
-
- # --- Check 1: Hermes venv site-packages ---
- # Producers inject the exact directory, never a descendant. Exact
- # matching avoids deleting a user path nested below site-packages.
- for sp in hermes_site_packages:
- if _same_path(entry_path, sp):
- should_strip = True
- break
- if should_strip:
- stripped.append(entry)
- continue
-
- # --- Check 2: Hermes repo root ---
- # The Electron app prepends the repo root so ``import tools`` works
- # in the backend. Subprocesses don't need it and it can shadow
- # local packages of the same name. Only the EXACT root is stripped:
- # no launcher injects a direct child (``<repo>/tools`` etc.) as an
- # independent PYTHONPATH entry, and user paths that merely happen to
- # live under the repo directory must be preserved. Both the
- # resolved and unresolved (HERMES_HOME/junction) spellings count as
- # Hermes-owned.
- if not should_strip:
- should_strip = any(
- _same_path(entry_path, repo_root)
- for repo_root in _hermes_repo_root_aliases
- )
-
- if should_strip:
- stripped.append(entry)
- else:
- kept.append(entry)
-
- if kept:
- env["PYTHONPATH"] = os.pathsep.join(kept)
- else:
- env.pop("PYTHONPATH", None)
-
- if stripped:
- logger.debug(
- "Stripped Hermes-owned entries from PYTHONPATH: %s",
- stripped,
- )
+# --- Login-shell init files ---
def _read_terminal_shell_init_config() -> tuple[list[str], bool]:
"""Return (shell_init_files, auto_source_bashrc) from config.yaml.
-
- Best-effort — returns sensible defaults on any failure so terminal
- execution never breaks because the config file is unreadable.
- """
+ Best-effort: defaults on any failure so terminal execution never breaks."""
try:
from hermes_cli.config import load_config
@@ -1893,34 +760,17 @@ def _read_terminal_shell_init_config() -> tuple[list[str], bool]:
def _resolve_shell_init_files() -> list[str]:
- """Resolve the list of files to source before the login-shell snapshot.
-
- Expands ``~`` and ``${VAR}`` references and drops anything that doesn't
- exist on disk, so a missing ``~/.bashrc`` never breaks the snapshot.
- The ``auto_source_bashrc`` path runs only when the user hasn't supplied
- an explicit list — once they have, Hermes trusts them.
- """
+ """Files to source before the login-shell snapshot (``~``/``${VAR}``
+ expanded, missing dropped). ``auto_source_bashrc`` applies only without an
+ explicit list: ~/.profile and ~/.bash_profile first (no interactivity guard;
+ where n/nvm/asdf/pyenv add PATH), ~/.bashrc last (Debian's default returns
+ early when non-interactive, but guard-less bashrcs keep working)."""
explicit, auto_bashrc = _read_terminal_shell_init_config()
candidates: list[str] = []
if explicit:
candidates.extend(explicit)
elif auto_bashrc and not _IS_WINDOWS:
- # Build a login-shell-ish source list so tools like n / nvm / asdf /
- # pyenv that self-install into the user's shell rc land on PATH in
- # the captured snapshot.
- #
- # ~/.profile and ~/.bash_profile run first because they have no
- # interactivity guard — installers like ``n`` and ``nvm`` append
- # their PATH export there on most distros, and a non-interactive
- # ``. ~/.profile`` picks that up.
- #
- # ~/.bashrc runs last. On Debian/Ubuntu the default bashrc starts
- # with ``case $- in *i*) ;; *) return;; esac`` and exits early
- # when sourced non-interactively, which is why sourcing bashrc
- # alone misses nvm/n PATH additions placed below that guard. We
- # still include it so users who put PATH logic in bashrc (and
- # stripped the guard, or never had one) keep working.
candidates.extend(["~/.profile", "~/.bash_profile", "~/.bashrc"])
resolved: list[str] = []
@@ -1935,26 +785,135 @@ def _resolve_shell_init_files() -> list[str]:
def _prepend_shell_init(cmd_string: str, files: list[str]) -> str:
- """Prepend ``source <file>`` lines (guarded + silent) to a bash script.
-
- Each file is wrapped so a failing rc file doesn't abort the whole
- bootstrap: ``set +e`` keeps going on errors, ``2>/dev/null`` hides
- noisy prompts, and ``|| true`` neutralises the exit status.
- """
+ """Prepend guarded, silent ``source <file>`` lines to a bash script:
+ ``set +e`` keeps going on errors, ``2>/dev/null`` hides noisy prompts,
+ ``|| true`` neutralises the exit status."""
if not files:
return cmd_string
prelude_parts = ["set +e"]
for path in files:
- # shlex.quote isn't available here without an import; the files list
- # comes from os.path.expanduser output so it's a concrete absolute
- # path. Escape single quotes defensively anyway.
safe = path.replace("'", "'\\''")
prelude_parts.append(f"[ -r '{safe}' ] && . '{safe}' 2>/dev/null || true")
prelude = "\n".join(prelude_parts) + "\n"
return prelude + cmd_string
+# --- Process-group teardown (POSIX) ---
+
+
+def _group_alive(pgid: int) -> bool:
+ """POSIX-only probe; callers are behind the _IS_WINDOWS gate."""
+ try:
+ os.killpg(pgid, 0) # windows-footgun: ok — POSIX process-group alive probe
+ return True
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True # exists, even if we cannot signal it
+
+
+def _wait_for_group_exit(proc, pgid: int, timeout: float) -> bool:
+ """Wait until the process group is gone, reaping the wrapper as we go
+ (a dead but unreaped group leader still makes ``killpg(pgid, 0)`` succeed)."""
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ try:
+ proc.poll()
+ except Exception:
+ pass
+ if not _group_alive(pgid):
+ return True
+ time.sleep(0.05)
+ try:
+ proc.poll()
+ except Exception:
+ pass
+ return not _group_alive(pgid)
+
+
+def _snapshot_descendants(proc) -> list:
+ """psutil children snapshot; empty on any failure (must never break the kill)."""
+ try:
+ import psutil
+
+ return psutil.Process(proc.pid).children(recursive=True)
+ except Exception:
+ return []
+
+
+def _sweep_escaped_descendants(descendants: list, pgid: int) -> None:
+ """SIGKILL snapshotted survivors that escaped the process group via
+ ``setsid`` — after TERM→KILL so in-group members keep their grace; psutil's
+ identity-aware Process skips recycled PIDs. POSIX-only (see _IS_WINDOWS gate)."""
+ for child in descendants:
+ try:
+ if not child.is_running():
+ continue
+ try:
+ if os.getpgid(child.pid) == pgid:
+ continue # group-kill already covers it
+ except (ProcessLookupError, PermissionError, OSError):
+ pass
+ child.kill()
+ except Exception:
+ continue
+
+
+def _kill_process_group_posix(proc) -> None:
+ """TERM the group, wait, KILL, then sweep setsid escapees. POSIX-only
+ (_IS_WINDOWS handled by the caller). Descendants are snapshotted BEFORE the
+ first signal — once the wrapper dies they reparent to init — and we wait on
+ the group, not the wrapper, which can exit before grandchildren under load."""
+ try:
+ pgid = os.getpgid(proc.pid)
+ except ProcessLookupError:
+ pgid = getattr(proc, "_hermes_pgid", None)
+ if pgid is None:
+ raise
+
+ descendants = _snapshot_descendants(proc)
+
+ try:
+ os.killpg(pgid, signal.SIGTERM) # windows-footgun: ok — POSIX only (see _IS_WINDOWS gate in caller)
+ except ProcessLookupError:
+ _sweep_escaped_descendants(descendants, pgid)
+ return
+
+ if _wait_for_group_exit(proc, pgid, 1.0):
+ _sweep_escaped_descendants(descendants, pgid)
+ return
+
+ try:
+ os.killpg(pgid, signal.SIGKILL) # windows-footgun: ok — POSIX only (see _IS_WINDOWS gate in caller)
+ except ProcessLookupError:
+ _sweep_escaped_descendants(descendants, pgid)
+ return
+ _wait_for_group_exit(proc, pgid, 2.0)
+ try:
+ proc.wait(timeout=0.2)
+ except (subprocess.TimeoutExpired, OSError):
+ pass
+ _sweep_escaped_descendants(descendants, pgid)
+
+
+def _kill_process_windows(proc) -> None:
+ try:
+ from gateway.status import get_process_start_time, terminate_pid
+
+ terminate_pid(
+ proc.pid,
+ force=True,
+ expected_start_time=get_process_start_time(proc.pid),
+ )
+ except Exception:
+ proc.kill()
+ try:
+ proc.wait(timeout=2.0)
+ except (subprocess.TimeoutExpired, OSError):
+ pass
+
+
class LocalEnvironment(BaseEnvironment):
"""Run commands directly on the host machine.
@@ -1970,35 +929,17 @@ class LocalEnvironment(BaseEnvironment):
is_local = True
def _additional_profile_scoped_passthrough_names(self) -> tuple[str, ...]:
- """Return first-party terminal env names (``BUZZ_*``) present in the
- current env, so they are excluded from the shared session snapshot.
-
- The login-shell snapshot (``init_session`` ``export -p`` dump and the
- per-command re-dump) captures the child env, which now includes the
- ``BUZZ_*`` vars the terminal carve-out passes through. The exclusion
- set is derived from ``get_all_passthrough()`` plus backend-specific
- additions — and ``BUZZ_*`` can NEVER be in it, because env_passthrough
- refuses blocklisted names (GHSA-rhgp-j443-p4rf). Under a multiplexed
- gateway, profile A's BUZZ_PRIVATE_KEY would land in
- ``hermes-snap-<id>.sh`` and a later command from profile B sharing
- this collapsed LocalEnvironment would ``source`` it: a cross-profile
- nsec leak that defeats profile isolation.
-
- Treating these names like profile-scoped passthrough names keeps them
- out of the dump and save/restores the current profile's value (or
- unsets the name) per command in ``_wrap_command``. The set is monotonic
- for the environment lifetime: once a name is seen it stays excluded,
- so a later profile that lacks the var still gets the unset-guard.
- """
+ """First-party ``BUZZ_*`` names present in the env, excluded from the
+ shared session snapshot. env_passthrough can never list them (it refuses
+ blocklisted names), so under a multiplexed gateway profile A's
+ BUZZ_PRIVATE_KEY would land in the snapshot and be sourced by profile B.
+ Prefix-only and monotonic on purpose: conservative even when the
+ context-gated carve-out is inactive."""
merged = dict(os.environ | self.env)
return tuple(
sorted(
name
for name in merged
- # Prefix-only on purpose: the snapshot exclusion stays
- # conservative even when the context-gated carve-out is
- # inactive (the var then never reaches the child env anyway,
- # but a monotonic exclusion is a cheap extra guard).
if isinstance(name, str) and _matches_terminal_first_party_prefix(name)
)
)
@@ -2009,41 +950,16 @@ class LocalEnvironment(BaseEnvironment):
self.init_session()
def get_temp_dir(self) -> str:
- """Return a shell-safe writable temp dir for local execution.
-
- Termux does not provide /tmp by default, but exposes a POSIX TMPDIR.
- Prefer POSIX-style env vars when available, keep using /tmp on regular
- Unix systems, and only fall back to tempfile.gettempdir() when it also
- resolves to a POSIX path.
-
- Check the environment configured for this backend first so callers can
- override the temp root explicitly (for example via terminal.temp_dir,
- terminal.env, or a custom TMPDIR), then fall back to the host process
- environment.
-
- **Default (no override set):** a dedicated cache dir under
- ``HERMES_HOME`` (``~/.hermes/cache/terminal``) rather than ``/tmp``.
- On several distros (Arch and friends) ``/tmp`` is a small RAM-backed
- tmpfs, and Hermes session artifacts — background-process logs,
- code-execution sandboxes, spilled tool results — can fill it under
- load. Real storage is the safer default; stale artifacts are pruned
- by ``cleanup_terminal_temp_cache`` (gateway housekeeping + a
- once-per-process best-effort sweep) since we no longer get tmpfs
- reboot wipes for free.
-
- **Windows:** hardcoded ``/tmp`` is wrong in two ways — native Python
- can't open the path, and the Windows default temp (``%TEMP%``) often
- contains spaces (``C:\\Users\\Some Name\\AppData\\Local\\Temp``) that
- break unquoted bash interpolations. Use a dedicated cache dir under
- ``HERMES_HOME`` instead — single-word path, guaranteed to exist, same
- string resolves in both Git Bash and native Python.
+ """Shell-safe writable temp dir. Precedence: ``TERMINAL_TEMP_DIR``,
+ POSIX TMPDIR/TMP/TEMP (Termux has no /tmp), ``HERMES_HOME/cache/terminal``,
+ /tmp, POSIX ``tempfile.gettempdir()``; backend env before process env so
+ terminal.env overrides work. The default is real storage because tmpfs
+ /tmp fills under Hermes load (pruned by ``cleanup_terminal_temp_cache``).
+ Windows: ``%TEMP%`` often has spaces that break unquoted bash, so always
+ the HERMES_HOME cache dir with forward slashes (valid in bash and Python).
"""
if _IS_WINDOWS:
- # Derive a Windows-safe temp dir under HERMES_HOME. Using
- # forward slashes makes the same string work unchanged in bash
- # command interpolations AND in Python ``open()`` — Windows
- # accepts forward slashes in filesystem paths, and we control
- # the path so we can guarantee no spaces.
+ # Forward slashes: one string valid in bash interpolation AND Python open().
try:
from hermes_constants import get_hermes_home
cache_dir = get_hermes_home() / "cache" / "terminal"
@@ -2051,24 +967,20 @@ class LocalEnvironment(BaseEnvironment):
cache_dir = Path(tempfile.gettempdir()) / "hermes_terminal"
cache_dir.mkdir(parents=True, exist_ok=True)
_prune_terminal_temp_once()
- # Force forward slashes so the same string serves both contexts.
return str(cache_dir).replace("\\", "/")
- # Explicit temp-dir override from terminal.temp_dir (TERMINAL_TEMP_DIR).
- # Honored ahead of the generic TMPDIR so users can redirect Hermes' temp
- # root to real storage when /tmp is a small tmpfs.
+ def _posix(p: str) -> str:
+ return p.rstrip("/") or "/"
+
configured = self.env.get("TERMINAL_TEMP_DIR") or os.environ.get("TERMINAL_TEMP_DIR")
if configured and configured.startswith("/") and os.path.isdir(configured):
- return configured.rstrip("/") or "/"
+ return _posix(configured)
for env_var in ("TMPDIR", "TMP", "TEMP"):
candidate = self.env.get(env_var) or os.environ.get(env_var)
if candidate and candidate.startswith("/"):
- return candidate.rstrip("/") or "/"
+ return _posix(candidate)
- # Default: HERMES_HOME/cache/terminal — real storage, mirroring the
- # Windows branch above. /tmp is only a last-resort fallback now
- # because RAM-backed tmpfs /tmp fills up under Hermes load.
try:
from hermes_constants import get_hermes_home
cache_dir = get_hermes_home() / "cache" / "terminal"
@@ -2076,7 +988,7 @@ class LocalEnvironment(BaseEnvironment):
resolved = str(cache_dir)
if resolved.startswith("/") and os.access(resolved, os.W_OK | os.X_OK):
_prune_terminal_temp_once()
- return resolved.rstrip("/") or "/"
+ return _posix(resolved)
except Exception:
pass
@@ -2084,10 +996,7 @@ class LocalEnvironment(BaseEnvironment):
return "/tmp"
candidate = tempfile.gettempdir()
- if candidate.startswith("/"):
- return candidate.rstrip("/") or "/"
-
- return "/tmp"
+ return _posix(candidate) if candidate.startswith("/") else "/tmp"
@staticmethod
def _quote_cwd_for_cd(cwd: str) -> str:
@@ -2098,16 +1007,30 @@ class LocalEnvironment(BaseEnvironment):
"""Rewrite native/mixed Windows paths before quoting for Git Bash."""
return _quote_bash_path(path)
+ def _recover_cwd(self) -> None:
+ """Swap ``self.cwd`` for a usable directory if it vanished or is
+ inaccessible (e.g. a previous command ``rm -rf``'d its own cwd) —
+ otherwise Popen raises before bash starts and every subsequent call
+ fails. A benign MSYS→Windows normalization is not warned about."""
+ safe_cwd = _resolve_safe_cwd(self.cwd)
+ if safe_cwd == self.cwd:
+ return
+ normalized = _msys_to_windows_path(self.cwd) if _IS_WINDOWS else self.cwd
+ if safe_cwd != normalized:
+ logger.warning(
+ "LocalEnvironment cwd %r is missing on disk; "
+ "falling back to %r so terminal commands keep working.",
+ self.cwd,
+ safe_cwd,
+ )
+ self.cwd = safe_cwd
+
def _run_bash(self, cmd_string: str, *, login: bool = False,
timeout: int = 120,
stdin_data: str | None = None) -> subprocess.Popen:
bash = _find_bash()
- # For login-shell invocations (used by init_session to build the
- # environment snapshot), prepend sources for the user's bashrc /
- # custom init files so tools registered outside bash_profile
- # (nvm, asdf, pyenv, …) end up on PATH in the captured snapshot.
- # Non-login invocations are already sourcing the snapshot and
- # don't need this.
+ # Login invocations (init_session's env snapshot) source the user's rc /
+ # custom init files so nvm/asdf/pyenv land on PATH in the snapshot.
if login:
init_files = _resolve_shell_init_files()
if init_files:
@@ -2115,32 +1038,7 @@ class LocalEnvironment(BaseEnvironment):
args = [bash, "-l", "-c", cmd_string] if login else [bash, "-c", cmd_string]
run_env = _make_run_env(self.env)
- # Recover when the cwd has been deleted out from under us — usually by
- # a previous tool call that ran ``rm -rf`` on its own working dir
- # (issue #17558). Popen would otherwise raise FileNotFoundError on
- # the cwd before bash starts, wedging every subsequent call until the
- # gateway restarts.
- #
- # On Windows, ``_resolve_safe_cwd`` also normalises Git Bash-style
- # POSIX paths (``/c/Users/...``) to native form so a perfectly valid
- # ``pwd -P`` result from bash isn't mistakenly treated as "missing"
- # and spammed as a warning on every command.
- safe_cwd = _resolve_safe_cwd(self.cwd)
- if safe_cwd != self.cwd:
- # MSYS → Windows translation alone shouldn't surface as a warning
- # (it's a benign normalization, not a recovery). Only warn when
- # the directory really doesn't exist on disk.
- normalized = _msys_to_windows_path(self.cwd) if _IS_WINDOWS else self.cwd
- if safe_cwd != normalized:
- logger.warning(
- "LocalEnvironment cwd %r is missing on disk; "
- "falling back to %r so terminal commands keep working.",
- self.cwd,
- safe_cwd,
- )
- self.cwd = safe_cwd
-
- _popen_cwd = self.cwd
+ self._recover_cwd()
_popen_kwargs = {"creationflags": windows_hide_flags()} if _IS_WINDOWS else {}
@@ -2154,7 +1052,7 @@ class LocalEnvironment(BaseEnvironment):
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE if stdin_data is not None else subprocess.DEVNULL,
start_new_session=True,
- cwd=_popen_cwd,
+ cwd=self.cwd,
**_popen_kwargs,
)
if not _IS_WINDOWS:
@@ -2170,126 +1068,11 @@ class LocalEnvironment(BaseEnvironment):
def _kill_process(self, proc):
"""Kill the entire process group (all children)."""
-
- def _group_alive(pgid: int) -> bool:
- try:
- # POSIX-only: _IS_WINDOWS is handled before this helper is used.
- os.killpg(pgid, 0) # windows-footgun: ok — POSIX process-group alive probe
- return True
- except ProcessLookupError:
- return False
- except PermissionError:
- # The group exists, even if this process cannot signal it.
- return True
-
- def _wait_for_group_exit(pgid: int, timeout: float) -> bool:
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- # Reap the wrapper promptly. A dead but unreaped group leader
- # still makes killpg(pgid, 0) report the group as alive.
- try:
- proc.poll()
- except Exception:
- pass
- if not _group_alive(pgid):
- return True
- time.sleep(0.05)
- try:
- proc.poll()
- except Exception:
- pass
- return not _group_alive(pgid)
-
try:
if _IS_WINDOWS:
- try:
- from gateway.status import get_process_start_time, terminate_pid
-
- terminate_pid(
- proc.pid,
- force=True,
- expected_start_time=get_process_start_time(proc.pid),
- )
- except Exception:
- proc.kill()
- try:
- proc.wait(timeout=2.0)
- except (subprocess.TimeoutExpired, OSError):
- pass
+ _kill_process_windows(proc)
else:
- try:
- pgid = os.getpgid(proc.pid)
- except ProcessLookupError:
- pgid = getattr(proc, "_hermes_pgid", None)
- if pgid is None:
- raise
-
- # Snapshot the descendant set BEFORE the first signal: once
- # the wrapper dies its children reparent to init and a parent
- # walk finds nothing (same rationale as agent/deadline.py
- # kill_process_tree). A descendant that called ``setsid``
- # escapes the process group entirely and would survive the
- # group-kill below — the #71148 class, terminal flavor
- # (issue #84967's local sibling). The snapshot must never
- # break the kill path, so any failure just yields an empty
- # sweep set.
- descendants: list = []
- try:
- import psutil
-
- descendants = psutil.Process(proc.pid).children(recursive=True)
- except Exception:
- descendants = []
-
- def _sweep_escaped_descendants() -> None:
- """SIGKILL snapshotted survivors outside the (dead) group.
-
- Runs after the TERM→KILL group escalation so in-group
- members keep their SIGTERM grace window; only escapees
- (own setsid sessions) are force-killed. psutil's
- identity-aware Process means recycled PIDs are skipped.
-
- POSIX-only: reached solely from the non-_IS_WINDOWS
- branch above (the win32 path returns earlier).
- """
- for child in descendants:
- try:
- if not child.is_running():
- continue
- try:
- if os.getpgid(child.pid) == pgid:
- continue # group-kill already covers it
- except (ProcessLookupError, PermissionError, OSError):
- pass
- child.kill()
- except Exception:
- continue
-
- try:
- os.killpg(pgid, signal.SIGTERM) # windows-footgun: ok — POSIX process-group SIGTERM (guarded by _IS_WINDOWS above)
- except ProcessLookupError:
- _sweep_escaped_descendants()
- return
-
- # Wait on the process group, not just the shell wrapper. Under
- # load the wrapper can exit before grandchildren do; returning
- # at that point leaves orphaned process-group members behind.
- if _wait_for_group_exit(pgid, 1.0):
- _sweep_escaped_descendants()
- return
-
- try:
- # POSIX-only: _IS_WINDOWS is handled by the outer branch.
- os.killpg(pgid, signal.SIGKILL) # windows-footgun: ok — POSIX process-group SIGKILL
- except ProcessLookupError:
- _sweep_escaped_descendants()
- return
- _wait_for_group_exit(pgid, 2.0)
- try:
- proc.wait(timeout=0.2)
- except (subprocess.TimeoutExpired, OSError):
- pass
- _sweep_escaped_descendants()
+ _kill_process_group_posix(proc)
except (ProcessLookupError, PermissionError, OSError):
try:
proc.kill()
@@ -2297,29 +1080,15 @@ class LocalEnvironment(BaseEnvironment):
pass
def _update_cwd(self, result: dict):
- """Update cwd from the stdout marker emitted by the wrapped command.
-
- The base command wrapper already appends ``pwd -P`` to stdout inside a
- session-specific marker, so the local backend can share the same parser
- as remote backends instead of re-reading the temp file it just wrote.
- ``_extract_cwd_from_output`` keeps the local Windows normalization and
- stale-path rollback semantics intact.
- """
+ """Update cwd from the stdout marker the base wrapper emits (``pwd -P``),
+ sharing the remote backends' parser instead of re-reading a temp file."""
self._extract_cwd_from_output(result)
def _extract_cwd_from_output(self, result: dict):
- """Same semantics as the base class, but on Windows the value
- emitted by ``pwd -P`` inside Git Bash is in MSYS form
- (``/c/Users/x``). Normalize to native Windows form and validate
- the directory exists before assigning to ``self.cwd`` — otherwise
- ``_run_bash``'s safe-cwd recovery would warn on every subsequent
- command.
-
- Always defers to the base class for stripping the marker text from
- ``result["output"]`` so output formatting is identical.
- """
- # Snapshot pre-existing cwd, defer to base for parsing + marker
- # stripping, then validate / normalize whatever it assigned.
+ """Base semantics plus: Git Bash ``pwd -P`` emits MSYS form on Windows —
+ normalize to native and require the dir to exist, else ``_run_bash`` would
+ warn every command. A stale path rolls back to the previous cwd, which
+ this command did not observe, so ``cwd_observed`` is dropped."""
prev_cwd = self.cwd
super()._extract_cwd_from_output(result)
if self.cwd != prev_cwd:
@@ -2328,29 +1097,21 @@ class LocalEnvironment(BaseEnvironment):
self.cwd = normalized
result["cwd"] = normalized
else:
- # Stale / non-existent path — keep previous cwd; _run_bash
- # will resolve a safe fallback on the next call if needed.
- # The rollback restores a value this command did not observe,
- # so it is not attributable to this command's session either.
self.cwd = prev_cwd
result.pop("cwd_observed", None)
result.pop("cwd", None)
def cleanup(self):
- """Clean up temp files."""
- for f in (self._snapshot_path, self._cwd_file):
+ """Clean up temp files, including orphaned atomic-write snapshots
+ (``snap.tmp.<bashpid>``) a failed/interrupted mv could leave behind."""
+ import glob
+
+ try:
+ stale = glob.glob(f"{self._snapshot_path}.tmp.*")
+ except Exception:
+ stale = []
+ for f in (self._snapshot_path, self._cwd_file, *stale):
try:
os.unlink(f)
except OSError:
pass
- # Remove any orphaned atomic-write temp snapshots (snap.tmp.<bashpid>)
- # a failed/interrupted mv could have left behind (#38249).
- try:
- import glob
- for tmp in glob.glob(f"{self._snapshot_path}.tmp.*"):
- try:
- os.unlink(tmp)
- except OSError:
- pass
- except Exception:
- pass
diff --git a/tools/environments/local_env_policy.py b/tools/environments/local_env_policy.py
new file mode 100644
index 00000000000..2c91639557d
--- /dev/null
+++ b/tools/environments/local_env_policy.py
@@ -0,0 +1,187 @@
+"""Secret-scrub policy for Hermes child processes: pure data + predicates for
+which env names are Hermes-managed credentials. The env *builders* applying it
+(``_sanitize_subprocess_env``, ``_make_run_env``, ``hermes_subprocess_env``,
+``build_subprocess_env``) live in ``tools.environments.local``."""
+
+import os
+
+# Prefix a caller uses in ``extra_env`` to force a blocklisted var through.
+_HERMES_PROVIDER_ENV_FORCE_PREFIX = "_HERMES_FORCE_"
+
+# Hermes-managed AWS *inference* credentials for ``auth_type="aws_sdk"`` (Bedrock).
+# Deliberately only the Bedrock bearer token — an inference secret like
+# OPENAI_API_KEY that no aws/terraform/boto3 toolchain uses. The general AWS
+# credential chain stays inheritable on purpose: the local terminal is the user's
+# trusted operator shell (SECURITY.md §3.2), and env_passthrough can never
+# re-allow a blocklisted name (GHSA-rhgp-j443-p4rf), so blocking would be
+# unrecoverable for every aws/terraform user.
+_AWS_SDK_CREDENTIAL_ENV_VARS = frozenset({
+ "AWS_BEARER_TOKEN_BEDROCK",
+})
+
+_STATIC_PROVIDER_ENV_BLOCKLIST = frozenset({
+ "OPENAI_BASE_URL", "OPENAI_API_KEY", "OPENAI_API_BASE", "OPENAI_ORG_ID",
+ "OPENAI_ORGANIZATION", "OPENROUTER_API_KEY", "ANTHROPIC_BASE_URL",
+ "ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "LLM_MODEL", "GOOGLE_API_KEY",
+ # Path to a GCP service-account JSON, not a bare key, so OPTIONAL_ENV_VARS
+ # marks it password=False and the registry loop skips it.
+ "VERTEX_CREDENTIALS_PATH", "GOOGLE_APPLICATION_CREDENTIALS", "DEEPSEEK_API_KEY",
+ "MISTRAL_API_KEY", "GROQ_API_KEY", "TOGETHER_API_KEY", "PERPLEXITY_API_KEY",
+ "COHERE_API_KEY", "FIREWORKS_API_KEY", "XAI_API_KEY", "HELICONE_API_KEY",
+ "PARALLEL_API_KEY", "FIRECRAWL_API_KEY", "FIRECRAWL_API_URL",
+ "TELEGRAM_HOME_CHANNEL", "TELEGRAM_HOME_CHANNEL_NAME", "DISCORD_HOME_CHANNEL",
+ "DISCORD_HOME_CHANNEL_NAME", "DISCORD_REQUIRE_MENTION",
+ "DISCORD_FREE_RESPONSE_CHANNELS", "DISCORD_AUTO_THREAD", "SLACK_HOME_CHANNEL",
+ "SLACK_HOME_CHANNEL_NAME", "SLACK_ALLOWED_USERS", "WHATSAPP_ENABLED",
+ "WHATSAPP_MODE", "WHATSAPP_ALLOWED_USERS", "SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT",
+ "SIGNAL_ALLOWED_USERS", "SIGNAL_GROUP_ALLOWED_USERS", "SIGNAL_HOME_CHANNEL",
+ "SIGNAL_HOME_CHANNEL_NAME", "SIGNAL_IGNORE_STORIES", "HASS_TOKEN", "HASS_URL",
+ "EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_IMAP_HOST", "EMAIL_SMTP_HOST",
+ "EMAIL_HOME_ADDRESS", "EMAIL_HOME_ADDRESS_NAME", "HERMES_DASHBOARD_SESSION_TOKEN",
+ "GATEWAY_ALLOWED_USERS", "GH_TOKEN", "GITHUB_APP_ID", "GITHUB_APP_PRIVATE_KEY_PATH",
+ "GITHUB_APP_INSTALLATION_ID", "MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET",
+ "DAYTONA_API_KEY", "GATEWAY_RELAY_ID", "GATEWAY_RELAY_SECRET",
+ "GATEWAY_RELAY_DELIVERY_KEY", "VERCEL_OIDC_TOKEN", "VERCEL_TOKEN",
+ "VERCEL_PROJECT_ID", "VERCEL_TEAM_ID",
+})
+
+
+def _build_provider_env_blocklist() -> frozenset:
+ """Derive the blocklist from provider, tool, and gateway config."""
+ blocked: set[str] = set(_STATIC_PROVIDER_ENV_BLOCKLIST)
+
+ try:
+ from hermes_cli.auth import PROVIDER_REGISTRY
+ for pconfig in PROVIDER_REGISTRY.values():
+ blocked.update(pconfig.api_key_env_vars)
+ if pconfig.auth_type == "aws_sdk":
+ blocked.update(_AWS_SDK_CREDENTIAL_ENV_VARS)
+ if pconfig.base_url_env_var:
+ blocked.add(pconfig.base_url_env_var)
+ except ImportError:
+ pass
+
+ try:
+ from hermes_cli.config import OPTIONAL_ENV_VARS
+ for name, metadata in OPTIONAL_ENV_VARS.items():
+ category = metadata.get("category")
+ if category in {"tool", "messaging"} or (
+ category == "setting" and metadata.get("password")
+ ):
+ blocked.add(name)
+ except ImportError:
+ pass
+
+ # CLAUDE_CODE_OAUTH_TOKEN is owned by the user's Claude Code install, not a
+ # Hermes credential (subscription auth is not a Hermes provider path).
+ # Stripping it made agent-spawned ``claude`` CLIs fall through to the shared
+ # Keychain / ~/.claude credentials store and, on auth failure, wipe it —
+ # logging the user out. It arrives via the anthropic registry entry above.
+ blocked.discard("CLAUDE_CODE_OAUTH_TOKEN")
+ # BUZZ_* is deliberately NOT discarded, even for Buzz-managed agents: this
+ # blocklist feeds every scrub surface (terminal, execute_code, the
+ # hermes_subprocess_env Tier-2 strip), so an import-time discard would leak
+ # BUZZ_PRIVATE_KEY into non-terminal children. The Buzz carve-out is a
+ # terminal-only, context-gated scrub-path exemption — see
+ # ``_is_terminal_first_party_env``.
+ return frozenset(blocked)
+
+
+_HERMES_PROVIDER_ENV_BLOCKLIST = _build_provider_env_blocklist()
+
+# First-party platform credentials (``BUZZ_*``, driving the platform-mandated
+# ``buzz`` CLI) carved out of the TERMINAL scrub only (``_make_run_env``,
+# ``_sanitize_subprocess_env``); execute_code, hermes_subprocess_env, docker and
+# env_passthrough registration stay sealed, so GHSA-rhgp-j443-p4rf holds.
+# CONTEXT-GATED (``_buzz_terminal_context_active``): a Telegram/CLI/cron session
+# on a host that also runs a Buzz gateway must not get the signing key. Values
+# are used directly, never scope-resolved (UnscopedSecretError under multiplex),
+# and the snapshot treats them as profile-scoped so they never persist across
+# profiles. Prefix-based so future BUZZ_* names need no code change.
+_TERMINAL_FIRST_PARTY_ENV_PREFIXES = ("BUZZ_",)
+
+
+def _matches_terminal_first_party_prefix(name: str) -> bool:
+ """Pure name check (``BUZZ_*``), regardless of session context — the
+ snapshot exclusion must stay conservative even when the carve-out is inactive."""
+ return name.startswith(_TERMINAL_FIRST_PARTY_ENV_PREFIXES)
+
+
+def _buzz_terminal_context_active() -> bool:
+ """True when this process/session operates as a Buzz agent.
+
+ Either signal suffices: ``BUZZ_MANAGED_AGENT`` in the process env (set only
+ by Buzz Desktop's buzz-acp harness), or the live session's platform is
+ ``buzz`` via the gateway ContextVar — authoritative under a concurrent
+ multi-session host, so a sibling Telegram session resolves its OWN platform.
+ """
+ if os.environ.get("BUZZ_MANAGED_AGENT"):
+ return True
+ try:
+ from gateway.session_context import get_session_env
+
+ return get_session_env("HERMES_SESSION_PLATFORM", "").strip().lower() == "buzz"
+ except Exception:
+ return False
+
+
+def _is_terminal_first_party_env(name: str) -> bool:
+ """``name`` is a first-party platform credential (``BUZZ_*``) AND the
+ current process/session context entitles it to reach terminal children."""
+ return _matches_terminal_first_party_prefix(name) and _buzz_terminal_context_active()
+
+
+# Active-venv markers that must NOT leak: a leaked VIRTUAL_ENV/CONDA_PREFIX makes
+# uv/poetry sync ANOTHER project's deps into the Hermes venv (clobbering it; the
+# venv stays reachable via PATH so stripping is safe), and PYTHONHOME redirects
+# any child interpreter's stdlib to the Hermes venv (version-mismatch crashes).
+# PYTHONPATH is handled separately — only Hermes-owned entries are removed.
+_ACTIVE_VENV_MARKER_VARS = ("VIRTUAL_ENV", "CONDA_PREFIX", "PYTHONHOME")
+
+
+def _is_hermes_internal_secret(key: str) -> bool:
+ """True for Hermes-internal secrets injected under *dynamic* names the
+ static blocklist cannot enumerate: ``AUXILIARY_<TASK>_API_KEY``/``_BASE_URL``
+ (per-task side-LLM credentials) and ``GATEWAY_RELAY_*_SECRET``/``_KEY``/
+ ``_TOKEN`` (relay auth; non-secret routing hints stay visible). Single source
+ of truth for every spawn path, stripped regardless of env_passthrough
+ registration or ``inherit_credentials``."""
+ upper = key.upper()
+ if upper.startswith("AUXILIARY_") and upper.endswith(("_API_KEY", "_BASE_URL")):
+ return True
+ return upper.startswith("GATEWAY_RELAY_") and upper.endswith(("_SECRET", "_KEY", "_TOKEN"))
+
+
+def _plugin_terminal_env_strip_keys() -> frozenset:
+ """Credential env keys owned by plugin-registered terminal backends.
+
+ Computed at call time because plugins register after import. Tier-1:
+ stripped from every spawned subprocess unconditionally. Fail-soft to empty.
+ """
+ try:
+ from agent.terminal_env_registry import plugin_strip_env_keys
+
+ return plugin_strip_env_keys()
+ except Exception:
+ return frozenset()
+
+
+# Tier-1 secrets: stripped from EVERY spawned subprocess even under
+# inherit_credentials (claude/codex/gemini). Not provider credentials — no child
+# needs them and they are the highest-value secrets to keep from a compromised
+# dependency. Provider keys are the conditional Tier-2 strip.
+_ALWAYS_STRIP_KEYS: frozenset[str] = frozenset({
+ # GitHub auth
+ "GH_TOKEN", "GITHUB_TOKEN", "GITHUB_APP_ID", "GITHUB_APP_PRIVATE_KEY_PATH",
+ "GITHUB_APP_INSTALLATION_ID",
+ # Gateway / messaging bot tokens and access control
+ "TELEGRAM_BOT_TOKEN", "DISCORD_BOT_TOKEN", "SLACK_BOT_TOKEN", "SLACK_APP_TOKEN",
+ "SLACK_SIGNING_SECRET", "GATEWAY_ALLOWED_USERS", "GATEWAY_ALLOW_ALL_USERS",
+ # Gateway relay auth triplet. _SECRET/_DELIVERY_KEY are also matched by
+ # _is_hermes_internal_secret, but _ID has no secret suffix, so it must be
+ # enumerated here to stay stripped on the inherit_credentials=True path.
+ "GATEWAY_RELAY_ID", "GATEWAY_RELAY_SECRET", "GATEWAY_RELAY_DELIVERY_KEY",
+ "HASS_TOKEN", "EMAIL_PASSWORD", "HERMES_DASHBOARD_SESSION_TOKEN",
+ # Remote-compute / infrastructure secrets
+ "MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET", "DAYTONA_API_KEY",
+})
diff --git a/tools/environments/local_gitbash_probe.py b/tools/environments/local_gitbash_probe.py
new file mode 100644
index 00000000000..a57fcb0937f
--- /dev/null
+++ b/tools/environments/local_gitbash_probe.py
@@ -0,0 +1,128 @@
+"""Git Bash health probe + Mandatory-ASLR diagnostics (Windows), used by
+``local._find_bash`` to pick a bash.exe that can actually launch MSYS children
+and to build the targeted remediation when none can."""
+
+import logging
+import ntpath
+import platform
+import shutil
+import subprocess
+
+from hermes_cli._subprocess_compat import windows_hide_flags
+
+_IS_WINDOWS = platform.system() == "Windows"
+
+# Same logger as the origin module so log routing is unchanged.
+logger = logging.getLogger("tools.environments.local")
+
+_bash_starts_cache: dict[str, bool] = {}
+_bash_probe_details_cache: dict[str, str] = {}
+_mandatory_aslr_enabled_cache: "bool | None" = None
+
+# External ``true`` and ``cat`` are intentional: a builtin-only ``exit 0`` probe
+# misses Git-for-Windows fork/spawn failures under system-wide Mandatory ASLR.
+_BASH_EXTERNAL_PROGRAM_PROBE = "/usr/bin/true; /usr/bin/cat --version >/dev/null"
+
+_MSYS_SPAWN_FAILURE_MARKERS = ("dofork:", "child_copy:", "0xc0000142", "0xc0000005")
+
+
+def _looks_like_msys_spawn_failure(details: str) -> bool:
+ """Match Git-for-Windows child-launch failures associated with ASLR."""
+ lowered = details.lower()
+ return any(marker in lowered for marker in _MSYS_SPAWN_FAILURE_MARKERS)
+
+
+def _mandatory_aslr_enabled() -> "bool | None":
+ """Return Windows' system-wide ForceRelocateImages state when available."""
+ global _mandatory_aslr_enabled_cache
+ if _mandatory_aslr_enabled_cache is not None:
+ return _mandatory_aslr_enabled_cache
+
+ try:
+ powershell = shutil.which("powershell.exe") or "powershell.exe"
+ result = subprocess.run(
+ [
+ powershell,
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "(Get-ProcessMitigation -System).Aslr.ForceRelocateImages.ToString()",
+ ],
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ timeout=10,
+ creationflags=windows_hide_flags(),
+ )
+ if result.returncode != 0:
+ return None
+ value = (result.stdout or "").strip().upper()
+ if value == "ON":
+ _mandatory_aslr_enabled_cache = True
+ return True
+ if value in {"OFF", "NOTSET"}:
+ _mandatory_aslr_enabled_cache = False
+ return False
+ except Exception as exc:
+ logger.debug("Could not query Windows Mandatory ASLR state: %s", exc)
+ return None
+
+
+def _git_root_from_bash(bash: str) -> str:
+ """Resolve Git's root from either <root>/bin or <root>/usr/bin bash."""
+ bin_dir = ntpath.dirname(ntpath.normpath(bash))
+ if ntpath.basename(bin_dir).lower() != "bin":
+ return ntpath.dirname(bin_dir)
+ parent = ntpath.dirname(bin_dir)
+ if ntpath.basename(parent).lower() == "usr":
+ return ntpath.dirname(parent)
+ return parent
+
+
+def _git_bash_aslr_help(bash: str, details: str = "") -> str:
+ """Build the targeted per-program Mandatory-ASLR remediation."""
+ git_root = _git_root_from_bash(bash)
+ escaped_root = git_root.replace("'", "''")
+ detail_line = f"\nGit Bash probe output: {details[:500]}" if details else ""
+ return (
+ f"Git Bash at {bash} cannot launch required MSYS child processes while "
+ "Windows Mandatory ASLR (ForceRelocateImages) is enabled, or its output "
+ f"matches that Git-for-Windows failure class.{detail_line}\n"
+ "Reinstalling Git will not change the Windows mitigation policy. Open "
+ "PowerShell as Administrator and run:\n"
+ f"$gitRoot = '{escaped_root}'\n"
+ 'Get-Item "$gitRoot\\bin\\bash.exe", "$gitRoot\\usr\\bin\\*.exe" '
+ "-ErrorAction SilentlyContinue | ForEach-Object { "
+ "Set-ProcessMitigation -Name $_.FullName -Disable ForceRelocateImages }\n"
+ "Then restart Hermes. If the override is blocked or later re-applied, "
+ "ask your Windows administrator to allow this per-program exception."
+ )
+
+
+def _bash_starts(bash: str) -> bool:
+ """True if *bash* can launch external MSYS programs (cached per path).
+ ``--noprofile --norc`` so a broken login post-install (``Directory
+ \\drivers\\etc``) does not falsely condemn an otherwise usable bash."""
+ cached = _bash_starts_cache.get(bash)
+ if cached is not None:
+ return cached
+
+ try:
+ result = subprocess.run(
+ [bash, "--noprofile", "--norc", "-c", _BASH_EXTERNAL_PROGRAM_PROBE],
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ timeout=15,
+ creationflags=windows_hide_flags() if _IS_WINDOWS else 0,
+ )
+ ok = result.returncode == 0
+ if not ok:
+ combined = f"{result.stdout or ''}{result.stderr or ''}"
+ _bash_probe_details_cache[bash] = combined.strip()[:2000]
+ logger.debug("bash probe failed for %s: %s", bash, combined.strip()[:200])
+ except Exception as exc:
+ _bash_probe_details_cache[bash] = str(exc)[:2000]
+ logger.debug("bash probe error for %s: %s", bash, exc)
+ ok = False
+
+ _bash_starts_cache[bash] = ok
+ return ok
diff --git a/tools/environments/local_pythonpath.py b/tools/environments/local_pythonpath.py
new file mode 100644
index 00000000000..daef83fc91f
--- /dev/null
+++ b/tools/environments/local_pythonpath.py
@@ -0,0 +1,193 @@
+"""Hermes-owned PYTHONPATH stripping for child processes.
+
+Launchers prepend the repo root and the Hermes venv's site-packages so the
+backend can ``import tools``; leaked into a child Python of a DIFFERENT version
+they load the backend's C extensions and crash (numpy, PIL, cryptography). Only
+entries proven Hermes-owned by *path provenance* are removed — never by a
+cross-version heuristic — so user entries survive. Module state
+(``_hermes_repo_root_aliases``, ``_in_venv``, ``_hermes_site_packages``) stays
+in ``tools.environments.local`` and is read via :func:`_state` so tests that
+monkeypatch it there keep working.
+"""
+
+import logging
+import os
+import platform
+import sys
+from pathlib import Path
+
+from tools.environments.local_env_policy import _ACTIVE_VENV_MARKER_VARS
+
+_IS_WINDOWS = platform.system() == "Windows"
+
+logger = logging.getLogger("tools.environments.local")
+
+
+def _state():
+ """Return the ``tools.environments.local`` module (owner of the caches)."""
+ from tools.environments import local
+
+ return local
+
+
+def _same_path(left: Path, right: Path) -> bool:
+ """Compare path spellings with host filesystem case semantics."""
+ left_parts = [os.path.normcase(part) for part in left.parts]
+ right_parts = [os.path.normcase(part) for part in right.parts]
+ return left_parts == right_parts
+
+
+def _build_hermes_repo_root_aliases(
+ resolved_root: Path,
+ lexical_root: Path,
+ configured_home: Path,
+) -> tuple[Path, ...]:
+ """Exact repo-root spellings emitted by Hermes launchers. Mirrors
+ ``gateway_windows._preserve_hermes_home_path`` (physical path under the
+ resolved HERMES_HOME -> configured spelling) so a junction-backed install
+ matches without treating arbitrary HERMES_HOME descendants as Hermes-owned.
+ A repo-level junction (possibly cross-drive) is accepted only when a strict
+ resolve proves <root>/<repo dirname> is the physical root (fail-closed)."""
+ aliases: list[Path] = []
+
+ def add(candidate: Path) -> None:
+ if not any(_same_path(candidate, existing) for existing in aliases):
+ aliases.append(candidate)
+
+ add(resolved_root)
+ add(lexical_root)
+
+ # Profile re-home: with --profile the configured home is <root>/profiles/<name>
+ # and the repo lives beside the profiles dir, so derive the root lexically the
+ # same way get_default_hermes_root() does and map against it too.
+ home_candidates = [configured_home]
+ if configured_home.parent.name == "profiles":
+ home_candidates.append(configured_home.parent.parent)
+
+ for home in home_candidates:
+ try:
+ resolved_home = home.resolve()
+ home_key = os.path.normcase(str(resolved_home))
+ root_key = os.path.normcase(str(resolved_root))
+ if os.path.commonpath([home_key, root_key]) == home_key:
+ relative_root = os.path.relpath(str(resolved_root), str(resolved_home))
+ add(home / relative_root)
+ except (OSError, ValueError):
+ pass
+
+ # Repo-level junction recovery (commonpath raises across drives, so the
+ # home-relative mapping above cannot express a cross-drive link).
+ for home in home_candidates:
+ repo_candidate = home / resolved_root.name
+ try:
+ if repo_candidate.resolve(strict=True) == resolved_root.resolve(strict=True):
+ add(repo_candidate)
+ except OSError:
+ pass
+
+ return tuple(aliases)
+
+
+def _validated_runtime_venv(env: dict) -> Path | None:
+ """Producer-owned runtime venv identified by VIRTUAL_ENV, or None. The
+ variable alone is not provenance (users carry unrelated venvs): require the
+ legacy Windows base-Python producer's exact ``<repo>/venv`` layout AND a
+ real ``pyvenv.cfg``."""
+ value = env.get("VIRTUAL_ENV")
+ if not value:
+ return None
+
+ candidate = Path(value)
+ aliases = _state()._hermes_repo_root_aliases
+ if not any(_same_path(candidate, repo_root / "venv") for repo_root in aliases):
+ return None
+
+ try:
+ if not (candidate / "pyvenv.cfg").is_file():
+ return None
+ except OSError:
+ return None
+
+ return candidate
+
+
+def _get_hermes_site_packages(env: dict) -> list[Path]:
+ """Exact site-packages dirs owned by the Hermes runtime (cached):
+ ``site.getsitepackages()`` with a ``sys.prefix`` fallback, plus a validated
+ Windows base-interpreter launch's ``VIRTUAL_ENV/Lib/site-packages``."""
+ local = _state()
+ if local._hermes_site_packages is not None:
+ result = list(local._hermes_site_packages)
+ else:
+ result = []
+ if local._in_venv:
+ try:
+ import site
+ for sp in site.getsitepackages():
+ result.append(Path(sp))
+ except Exception:
+ pass
+
+ if not result:
+ if _IS_WINDOWS:
+ result.append(Path(sys.prefix) / "Lib" / "site-packages")
+ else:
+ pyver = f"python{sys.version_info[0]}.{sys.version_info[1]}"
+ result.append(Path(sys.prefix) / "lib" / pyver / "site-packages")
+
+ local._hermes_site_packages = list(result)
+
+ runtime_venv = _validated_runtime_venv(env)
+ if runtime_venv is not None:
+ runtime_site_packages = runtime_venv / "Lib" / "site-packages"
+ if not any(_same_path(runtime_site_packages, existing) for existing in result):
+ result.append(runtime_site_packages)
+
+ return result
+
+
+def _strip_hermes_owned_pythonpath_and_runtime_markers(env: dict) -> None:
+ """Strip Hermes-owned PYTHONPATH entries, then the runtime marker vars.
+
+ Ordering is load-bearing: PYTHONPATH filtering must run BEFORE the markers
+ are removed so a validated Windows base-interpreter launch
+ (VIRTUAL_ENV -> <repo>/venv) can still prove ownership.
+ """
+ _strip_hermes_owned_pythonpath(env)
+ for _marker in _ACTIVE_VENV_MARKER_VARS:
+ env.pop(_marker, None)
+
+
+def _strip_hermes_owned_pythonpath(env: dict) -> None:
+ """Remove Hermes-owned PYTHONPATH entries. Only exact matches of the repo
+ root (any launcher spelling) and runtime site-packages are stripped — never
+ children/descendants, which are user paths. Empty components (= cwd) and
+ everything else are preserved byte-for-byte."""
+ pp = env.get("PYTHONPATH")
+ if not pp:
+ return
+
+ hermes_site_packages = _get_hermes_site_packages(env)
+ repo_roots = _state()._hermes_repo_root_aliases
+
+ kept: list[str] = []
+ stripped: list[str] = []
+
+ for entry in pp.split(os.pathsep):
+ if entry == "":
+ kept.append(entry)
+ continue
+
+ entry_path = Path(entry)
+ owned = any(_same_path(entry_path, sp) for sp in hermes_site_packages) or any(
+ _same_path(entry_path, repo_root) for repo_root in repo_roots
+ )
+ (stripped if owned else kept).append(entry)
+
+ if kept:
+ env["PYTHONPATH"] = os.pathsep.join(kept)
+ else:
+ env.pop("PYTHONPATH", None)
+
+ if stripped:
+ logger.debug("Stripped Hermes-owned entries from PYTHONPATH: %s", stripped)
diff --git a/tools/environments/managed_modal.py b/tools/environments/managed_modal.py
index 52b00f19a3d..a4a5a9687cf 100644
--- a/tools/environments/managed_modal.py
+++ b/tools/environments/managed_modal.py
@@ -10,15 +10,13 @@ import uuid
from dataclasses import dataclass
from typing import Any, Dict, Optional
-from tools.environments.modal_utils import (
- BaseModalExecutionEnvironment,
- ModalExecStart,
- PreparedModalExec,
-)
+from tools.environments.modal_utils import BaseModalExecutionEnvironment, ModalExecStart, PreparedModalExec
from tools.managed_tool_gateway import resolve_managed_tool_gateway
logger = logging.getLogger(__name__)
+_TERMINAL_EXEC_STATUSES = frozenset({"completed", "failed", "cancelled", "timeout"})
+
def _request_timeout_env(name: str, default: float) -> float:
try:
@@ -43,23 +41,14 @@ class ManagedModalEnvironment(BaseModalExecutionEnvironment):
_interrupt_output = "[Command interrupted - Modal sandbox exec cancelled]"
_unexpected_error_prefix = "Managed Modal exec failed"
- def __init__(
- self,
- image: str,
- cwd: str = "/root",
- timeout: int = 60,
- modal_sandbox_kwargs: Optional[Dict[str, Any]] = None,
- persistent_filesystem: bool = True,
- task_id: str = "default",
- ):
+ def __init__(self, image: str, cwd: str = "/root", timeout: int = 60,
+ modal_sandbox_kwargs: Optional[Dict[str, Any]] = None,
+ persistent_filesystem: bool = True, task_id: str = "default"):
super().__init__(cwd=cwd, timeout=timeout)
-
self._guard_unsupported_credential_passthrough()
-
gateway = resolve_managed_tool_gateway("modal")
if gateway is None:
raise ValueError("Managed Modal requires a configured tool gateway and Nous user token")
-
self._gateway_origin = gateway.gateway_origin.rstrip("/")
self._nous_user_token = gateway.nous_user_token
self._task_id = task_id
@@ -69,81 +58,46 @@ class ManagedModalEnvironment(BaseModalExecutionEnvironment):
self._create_idempotency_key = str(uuid.uuid4())
self._sandbox_id = self._create_sandbox()
+ def _result_from_body(self, body: dict) -> dict | None:
+ """Final result dict if the exec body reports a terminal status, else ``None``."""
+ if body.get("status") in _TERMINAL_EXEC_STATUSES:
+ return self._result(body.get("output", ""), body.get("returncode", 1))
+ return None
+
def _start_modal_exec(self, prepared: PreparedModalExec) -> ModalExecStart:
exec_id = str(uuid.uuid4())
- payload: Dict[str, Any] = {
- "execId": exec_id,
- "command": prepared.command,
- "cwd": prepared.cwd,
- "timeoutMs": int(prepared.timeout * 1000),
- }
+ payload: Dict[str, Any] = {"execId": exec_id, "command": prepared.command, "cwd": prepared.cwd,
+ "timeoutMs": int(prepared.timeout * 1000)}
if prepared.stdin_data is not None:
payload["stdinData"] = prepared.stdin_data
-
try:
- response = self._request(
- "POST",
- f"/v1/sandboxes/{self._sandbox_id}/execs",
- json=payload,
- timeout=10,
- )
+ response = self._request("POST", f"/v1/sandboxes/{self._sandbox_id}/execs", json=payload, timeout=10)
except Exception as exc:
- return ModalExecStart(
- immediate_result=self._error_result(f"Managed Modal exec failed: {exc}")
- )
-
+ return ModalExecStart(immediate_result=self._error_result(f"Managed Modal exec failed: {exc}"))
if response.status_code >= 400:
- return ModalExecStart(
- immediate_result=self._error_result(
- self._format_error("Managed Modal exec failed", response)
- )
- )
-
+ return ModalExecStart(immediate_result=self._error_result(
+ self._format_error("Managed Modal exec failed", response)))
body = response.json()
- status = body.get("status")
- if status in {"completed", "failed", "cancelled", "timeout"}:
- return ModalExecStart(
- immediate_result=self._result(
- body.get("output", ""),
- body.get("returncode", 1),
- )
- )
-
+ final = self._result_from_body(body)
+ if final is not None:
+ return ModalExecStart(immediate_result=final)
if body.get("execId") != exec_id:
- return ModalExecStart(
- immediate_result=self._error_result(
- "Managed Modal exec start did not return the expected exec id"
- )
- )
-
+ return ModalExecStart(immediate_result=self._error_result(
+ "Managed Modal exec start did not return the expected exec id"))
return ModalExecStart(handle=_ManagedModalExecHandle(exec_id=exec_id))
def _poll_modal_exec(self, handle: _ManagedModalExecHandle) -> dict | None:
try:
status_response = self._request(
- "GET",
- f"/v1/sandboxes/{self._sandbox_id}/execs/{handle.exec_id}",
- timeout=(self._CONNECT_TIMEOUT_SECONDS, self._POLL_READ_TIMEOUT_SECONDS),
- )
+ "GET", f"/v1/sandboxes/{self._sandbox_id}/execs/{handle.exec_id}",
+ timeout=(self._CONNECT_TIMEOUT_SECONDS, self._POLL_READ_TIMEOUT_SECONDS))
except Exception as exc:
return self._error_result(f"Managed Modal exec poll failed: {exc}")
-
if status_response.status_code == 404:
return self._error_result("Managed Modal exec not found")
-
if status_response.status_code >= 400:
- return self._error_result(
- self._format_error("Managed Modal exec poll failed", status_response)
- )
-
- status_body = status_response.json()
- status = status_body.get("status")
- if status in {"completed", "failed", "cancelled", "timeout"}:
- return self._result(
- status_body.get("output", ""),
- status_body.get("returncode", 1),
- )
- return None
+ return self._error_result(self._format_error("Managed Modal exec poll failed", status_response))
+ return self._result_from_body(status_response.json())
def _cancel_modal_exec(self, handle: _ManagedModalExecHandle) -> None:
self._cancel_exec(handle.exec_id)
@@ -154,59 +108,31 @@ class ManagedModalEnvironment(BaseModalExecutionEnvironment):
def cleanup(self):
if not getattr(self, "_sandbox_id", None):
return
-
try:
- self._request(
- "POST",
- f"/v1/sandboxes/{self._sandbox_id}/terminate",
- json={
- "snapshotBeforeTerminate": self._persistent,
- },
- timeout=60,
- )
+ self._request("POST", f"/v1/sandboxes/{self._sandbox_id}/terminate",
+ json={"snapshotBeforeTerminate": self._persistent}, timeout=60)
except Exception as exc:
logger.warning("Managed Modal cleanup failed: %s", exc)
finally:
self._sandbox_id = None
def _create_sandbox(self) -> str:
- cpu = self._coerce_number(self._sandbox_kwargs.get("cpu"), 1)
- memory = self._coerce_number(
- self._sandbox_kwargs.get("memoryMiB", self._sandbox_kwargs.get("memory")),
- 5120,
- )
- disk = self._coerce_number(
- self._sandbox_kwargs.get("ephemeral_disk", self._sandbox_kwargs.get("diskMiB")),
- None,
- )
-
+ kw = self._sandbox_kwargs
+ cpu = self._coerce_number(kw.get("cpu"), 1)
+ memory = self._coerce_number(kw.get("memoryMiB", kw.get("memory")), 5120)
+ disk = self._coerce_number(kw.get("ephemeral_disk", kw.get("diskMiB")), None)
create_payload = {
- "image": self._image,
- "cwd": self.cwd,
- "cpu": cpu,
- "memoryMiB": memory,
- "timeoutMs": 3_600_000,
+ "image": self._image, "cwd": self.cwd, "cpu": cpu, "memoryMiB": memory, "timeoutMs": 3_600_000,
"idleTimeoutMs": max(300_000, int(self.timeout * 1000)),
- "persistentFilesystem": self._persistent,
- "logicalKey": self._task_id,
+ "persistentFilesystem": self._persistent, "logicalKey": self._task_id,
}
if disk is not None:
create_payload["diskMiB"] = disk
-
- response = self._request(
- "POST",
- "/v1/sandboxes",
- json=create_payload,
- timeout=60,
- extra_headers={
- "x-idempotency-key": self._create_idempotency_key,
- },
- )
+ response = self._request("POST", "/v1/sandboxes", json=create_payload, timeout=60,
+ extra_headers={"x-idempotency-key": self._create_idempotency_key})
if response.status_code >= 400:
raise RuntimeError(self._format_error("Managed Modal create failed", response))
-
- body = response.json()
- sandbox_id = body.get("id")
+ sandbox_id = response.json().get("id")
if not isinstance(sandbox_id, str) or not sandbox_id:
raise RuntimeError("Managed Modal create did not return a sandbox id")
return sandbox_id
@@ -217,41 +143,24 @@ class ManagedModalEnvironment(BaseModalExecutionEnvironment):
from tools.credential_files import get_credential_file_mounts
except Exception:
return
-
- mounts = get_credential_file_mounts()
- if mounts:
+ if get_credential_file_mounts():
raise ValueError(
"Managed Modal does not support host credential-file passthrough. "
"Use TERMINAL_MODAL_MODE=direct when skills or config require "
"credential files inside the sandbox."
)
- def _request(self, method: str, path: str, *,
- json: Dict[str, Any] | None = None,
- timeout: int = 30,
+ def _request(self, method: str, path: str, *, json: Dict[str, Any] | None = None, timeout: int = 30,
extra_headers: Dict[str, str] | None = None) -> requests.Response:
- headers = {
- "Authorization": f"Bearer {self._nous_user_token}",
- "Content-Type": "application/json",
- }
+ headers = {"Authorization": f"Bearer {self._nous_user_token}", "Content-Type": "application/json"}
if extra_headers:
headers.update(extra_headers)
-
- return requests.request(
- method,
- f"{self._gateway_origin}{path}",
- headers=headers,
- json=json,
- timeout=timeout,
- )
+ return requests.request(method, f"{self._gateway_origin}{path}", headers=headers, json=json, timeout=timeout)
def _cancel_exec(self, exec_id: str) -> None:
try:
- self._request(
- "POST",
- f"/v1/sandboxes/{self._sandbox_id}/execs/{exec_id}/cancel",
- timeout=(self._CONNECT_TIMEOUT_SECONDS, self._CANCEL_READ_TIMEOUT_SECONDS),
- )
+ self._request("POST", f"/v1/sandboxes/{self._sandbox_id}/execs/{exec_id}/cancel",
+ timeout=(self._CONNECT_TIMEOUT_SECONDS, self._CANCEL_READ_TIMEOUT_SECONDS))
except Exception as exc:
logger.warning("Managed Modal exec cancel failed: %s", exc)
@@ -275,8 +184,5 @@ class ManagedModalEnvironment(BaseModalExecutionEnvironment):
return f"{prefix}: {json.dumps(payload, ensure_ascii=False)}"
except Exception:
pass
-
text = response.text.strip()
- if text:
- return f"{prefix}: {text}"
- return f"{prefix}: HTTP {response.status_code}"
+ return f"{prefix}: {text}" if text else f"{prefix}: HTTP {response.status_code}"
diff --git a/tools/environments/modal.py b/tools/environments/modal.py
index 3137b322113..36df4709b43 100644
--- a/tools/environments/modal.py
+++ b/tools/environments/modal.py
@@ -1,12 +1,10 @@
-"""Modal cloud execution environment using the native Modal SDK directly.
-
-Uses ``Sandbox.create()`` + ``Sandbox.exec()`` instead of the older runtime
-wrapper, while preserving Hermes' persistent snapshot behavior across sessions.
-"""
+"""Modal cloud execution environment using the native Modal SDK directly
+(``Sandbox.create()`` + ``Sandbox.exec()``) with persistent snapshots across sessions."""
import asyncio
import base64
import io
+import itertools
import logging
import shlex
import tarfile
@@ -15,19 +13,11 @@ from pathlib import Path
from typing import Any, Optional
from hermes_constants import get_hermes_home
-from tools.environments.base import (
- BaseEnvironment,
- _ThreadedProcessHandle,
- _load_json_store,
- _save_json_store,
-)
+from tools.environments.base import BaseEnvironment, _ThreadedProcessHandle, _load_json_store, _save_json_store
from tools.environments.file_sync import (
- FileSyncManager,
- iter_sync_files,
- quoted_mkdir_command,
- quoted_rm_command,
- unique_parent_dirs,
+ FileSyncManager, iter_sync_files, quoted_mkdir_command, quoted_rm_command, unique_parent_dirs,
)
+from tools.environments.remote_common import bash_argv, ensure_lazy_dep
logger = logging.getLogger(__name__)
@@ -48,14 +38,12 @@ def _direct_snapshot_key(task_id: str) -> str:
def _get_snapshot_restore_candidate(task_id: str) -> tuple[str | None, bool]:
+ """Return (snapshot_id, from_legacy_key); the namespaced key wins over the legacy bare task id."""
snapshots = _load_snapshots()
- namespaced_key = _direct_snapshot_key(task_id)
- snapshot_id = snapshots.get(namespaced_key)
- if isinstance(snapshot_id, str) and snapshot_id:
- return snapshot_id, False
- legacy_snapshot_id = snapshots.get(task_id)
- if isinstance(legacy_snapshot_id, str) and legacy_snapshot_id:
- return legacy_snapshot_id, True
+ for key, legacy in ((_direct_snapshot_key(task_id), False), (task_id, True)):
+ snapshot_id = snapshots.get(key)
+ if isinstance(snapshot_id, str) and snapshot_id:
+ return snapshot_id, legacy
return None, False
@@ -71,9 +59,7 @@ def _delete_direct_snapshot(task_id: str, snapshot_id: str | None = None) -> Non
updated = False
for key in (_direct_snapshot_key(task_id), task_id):
value = snapshots.get(key)
- if value is None:
- continue
- if snapshot_id is None or value == snapshot_id:
+ if value is not None and (snapshot_id is None or value == snapshot_id):
snapshots.pop(key, None)
updated = True
if updated:
@@ -82,46 +68,40 @@ def _delete_direct_snapshot(task_id: str, snapshot_id: str | None = None) -> Non
def _ensure_modal_sdk() -> None:
"""Lazy-install modal on demand. Idempotent — fast no-op once installed."""
- try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("terminal.modal", prompt=False)
- except ImportError:
- pass
- except Exception as e:
- raise ImportError(str(e))
+ ensure_lazy_dep("terminal.modal")
def _resolve_modal_image(image_spec: Any) -> Any:
- """Convert registry references or snapshot ids into Modal image objects.
-
- Includes add_python support for ubuntu/debian images (absorbed from PR 4511).
- """
+ """Convert registry references or snapshot ids into Modal image objects. Registry images
+ get pip repaired (ensurepip) before Modal's bootstrap; ubuntu/debian also get python3."""
_ensure_modal_sdk()
import modal as _modal
if not isinstance(image_spec, str):
return image_spec
-
if image_spec.startswith("im-"):
return _modal.Image.from_id(image_spec)
- # PR 4511: add python to ubuntu/debian images that don't have it
- lower = image_spec.lower()
- add_python = any(base in lower for base in ("ubuntu", "debian"))
-
setup_commands = [
"RUN rm -rf /usr/local/lib/python*/site-packages/pip* 2>/dev/null; "
"python -m ensurepip --upgrade --default-pip 2>/dev/null || true",
]
- if add_python:
+ if any(base in image_spec.lower() for base in ("ubuntu", "debian")):
setup_commands.insert(0,
"RUN apt-get update -qq && apt-get install -y -qq python3 python3-venv > /dev/null 2>&1 || true"
)
+ return _modal.Image.from_registry(image_spec, setup_dockerfile_commands=setup_commands)
+
- return _modal.Image.from_registry(
- image_spec,
- setup_dockerfile_commands=setup_commands,
- )
+async def _stream_stdin(proc, payload: str, chunk_size: int) -> None:
+ """Write ``payload`` to ``proc.stdin`` in ``chunk_size`` pieces, draining after each, then EOF."""
+ offset = 0
+ while offset < len(payload):
+ proc.stdin.write(payload[offset:offset + chunk_size])
+ await proc.stdin.drain.aio()
+ offset += chunk_size
+ proc.stdin.write_eof()
+ await proc.stdin.drain.aio()
class _AsyncWorker:
@@ -162,105 +142,64 @@ class _AsyncWorker:
class ModalEnvironment(BaseEnvironment):
- """Modal cloud execution via native Modal sandboxes.
-
- Spawn-per-call via _ThreadedProcessHandle wrapping async SDK calls.
- cancel_fn wired to sandbox.terminate for interrupt support.
- """
+ """Modal cloud execution via native Modal sandboxes: spawn-per-call via _ThreadedProcessHandle
+ wrapping async SDK calls, cancel_fn wired to sandbox.terminate for interrupt support."""
_stdin_mode = "heredoc"
_snapshot_timeout = 60 # Modal cold starts can be slow
+ # Modal SDK stdin buffer limit: the command-router path allows 16 MB but the
+ # legacy server path caps at 2 MB, so chunks stay under 2 MB and each is
+ # flushed individually via drain().
+ _STDIN_CHUNK_SIZE = 1 * 1024 * 1024 # 1 MB — safe for both transport paths
- def __init__(
- self,
- image: str,
- cwd: str = "/root",
- timeout: int = 60,
- modal_sandbox_kwargs: Optional[dict[str, Any]] = None,
- persistent_filesystem: bool = True,
- task_id: str = "default",
- ):
+ def __init__(self, image: str, cwd: str = "/root", timeout: int = 60,
+ modal_sandbox_kwargs: Optional[dict[str, Any]] = None,
+ persistent_filesystem: bool = True, task_id: str = "default"):
super().__init__(cwd=cwd, timeout=timeout)
-
self._persistent = persistent_filesystem
self._task_id = task_id
self._sandbox = None
self._app = None
self._worker = _AsyncWorker()
self._sync_manager: FileSyncManager | None = None # initialized after sandbox creation
-
sandbox_kwargs = dict(modal_sandbox_kwargs or {})
-
restored_snapshot_id = None
restored_from_legacy_key = False
if self._persistent:
- restored_snapshot_id, restored_from_legacy_key = _get_snapshot_restore_candidate(
- self._task_id
- )
+ restored_snapshot_id, restored_from_legacy_key = _get_snapshot_restore_candidate(self._task_id)
if restored_snapshot_id:
logger.info("Modal: restoring from snapshot %s", restored_snapshot_id[:20])
-
_ensure_modal_sdk()
import modal as _modal
-
cred_mounts = []
try:
- from tools.credential_files import (
- get_credential_file_mounts,
- iter_skills_files,
- iter_cache_files,
- )
+ from tools.credential_files import get_credential_file_mounts, iter_skills_files, iter_cache_files
- for mount_entry in get_credential_file_mounts():
- cred_mounts.append(
- _modal.Mount.from_local_file(
- mount_entry["host_path"],
- remote_path=mount_entry["container_path"],
- )
- )
- for entry in iter_skills_files():
- cred_mounts.append(
- _modal.Mount.from_local_file(
- entry["host_path"],
- remote_path=entry["container_path"],
- )
- )
- cache_files = iter_cache_files()
- for entry in cache_files:
+ # from_iterable keeps each source lazy so a failure mid-way leaves the earlier mounts in place
+ for entry in itertools.chain.from_iterable(
+ fn() for fn in (get_credential_file_mounts, iter_skills_files, iter_cache_files)
+ ):
cred_mounts.append(
- _modal.Mount.from_local_file(
- entry["host_path"],
- remote_path=entry["container_path"],
- )
+ _modal.Mount.from_local_file(entry["host_path"], remote_path=entry["container_path"])
)
except Exception as e:
logger.debug("Modal: could not load credential file mounts: %s", e)
-
self._worker.start()
async def _create_sandbox(image_spec: Any):
app = await _modal.App.lookup.aio("hermes-agent", create_if_missing=True)
create_kwargs = dict(sandbox_kwargs)
if cred_mounts:
- existing_mounts = list(create_kwargs.pop("mounts", []))
- existing_mounts.extend(cred_mounts)
- create_kwargs["mounts"] = existing_mounts
+ create_kwargs["mounts"] = list(create_kwargs.pop("mounts", [])) + cred_mounts
sandbox = await _modal.Sandbox.create.aio(
- "sleep", "infinity",
- image=image_spec,
- app=app,
- timeout=int(create_kwargs.pop("timeout", 3600)),
- **create_kwargs,
+ "sleep", "infinity", image=image_spec, app=app,
+ timeout=int(create_kwargs.pop("timeout", 3600)), **create_kwargs,
)
return app, sandbox
-
try:
- target_image_spec = restored_snapshot_id or image
try:
- effective_image = _resolve_modal_image(target_image_spec)
- self._app, self._sandbox = self._worker.run_coroutine(
- _create_sandbox(effective_image), timeout=300,
- )
+ effective_image = _resolve_modal_image(restored_snapshot_id or image)
+ self._app, self._sandbox = self._worker.run_coroutine(_create_sandbox(effective_image), timeout=300)
except Exception as exc:
if not restored_snapshot_id:
raise
@@ -269,119 +208,65 @@ class ModalEnvironment(BaseEnvironment):
restored_snapshot_id[:20], exc,
)
_delete_direct_snapshot(self._task_id, restored_snapshot_id)
- base_image = _resolve_modal_image(image)
self._app, self._sandbox = self._worker.run_coroutine(
- _create_sandbox(base_image), timeout=300,
- )
+ _create_sandbox(_resolve_modal_image(image)), timeout=300)
else:
if restored_snapshot_id and restored_from_legacy_key:
_store_direct_snapshot(self._task_id, restored_snapshot_id)
except Exception:
self._worker.stop()
raise
-
logger.info("Modal: sandbox created (task=%s)", self._task_id)
-
self._sync_manager = FileSyncManager(
get_files_fn=lambda: iter_sync_files("/root/.hermes"),
- upload_fn=self._modal_upload,
- delete_fn=self._modal_delete,
- bulk_upload_fn=self._modal_bulk_upload,
- bulk_download_fn=self._modal_bulk_download,
+ upload_fn=self._modal_upload, delete_fn=self._modal_delete,
+ bulk_upload_fn=self._modal_bulk_upload, bulk_download_fn=self._modal_bulk_download,
)
self._sync_manager.sync(force=True)
self.init_session()
def _modal_upload(self, host_path: str, remote_path: str) -> None:
"""Upload a single file via base64 piped through stdin."""
- content = Path(host_path).read_bytes()
- b64 = base64.b64encode(content).decode("ascii")
+ b64 = base64.b64encode(Path(host_path).read_bytes()).decode("ascii")
container_dir = str(Path(remote_path).parent)
- cmd = (
- f"mkdir -p {shlex.quote(container_dir)} && "
- f"base64 -d > {shlex.quote(remote_path)}"
- )
+ cmd = f"mkdir -p {shlex.quote(container_dir)} && base64 -d > {shlex.quote(remote_path)}"
async def _write():
proc = await self._sandbox.exec.aio("bash", "-c", cmd)
- offset = 0
- chunk_size = self._STDIN_CHUNK_SIZE
- while offset < len(b64):
- proc.stdin.write(b64[offset:offset + chunk_size])
- await proc.stdin.drain.aio()
- offset += chunk_size
- proc.stdin.write_eof()
- await proc.stdin.drain.aio()
+ await _stream_stdin(proc, b64, self._STDIN_CHUNK_SIZE)
await proc.wait.aio()
-
self._worker.run_coroutine(_write(), timeout=30)
- # Modal SDK stdin buffer limit (legacy server path). The command-router
- # path allows 16 MB, but we must stay under the smaller 2 MB cap for
- # compatibility. Chunks are written below this threshold and flushed
- # individually via drain().
- _STDIN_CHUNK_SIZE = 1 * 1024 * 1024 # 1 MB — safe for both transport paths
-
def _modal_bulk_upload(self, files: list[tuple[str, str]]) -> None:
- """Upload many files via tar archive piped through stdin.
-
- Builds a gzipped tar archive in memory and streams it into a
- ``base64 -d | tar xzf -`` pipeline via the process's stdin,
- avoiding the Modal SDK's 64 KB ``ARG_MAX_BYTES`` exec-arg limit.
- """
+ """Upload many files as one in-memory gzipped tar streamed through stdin
+ into ``base64 -d | tar xzf -``, avoiding the SDK's 64 KB exec-arg limit."""
if not files:
return
-
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
for host_path, remote_path in files:
tar.add(host_path, arcname=remote_path.lstrip("/"))
payload = base64.b64encode(buf.getvalue()).decode("ascii")
-
- parents = unique_parent_dirs(files)
- mkdir_part = quoted_mkdir_command(parents)
- cmd = f"{mkdir_part} && base64 -d | tar xzf - -C /"
+ cmd = f"{quoted_mkdir_command(unique_parent_dirs(files))} && base64 -d | tar xzf - -C /"
async def _bulk():
proc = await self._sandbox.exec.aio("bash", "-c", cmd)
-
- # Stream payload through stdin in chunks to stay under the
- # SDK's per-write buffer limit (2 MB legacy / 16 MB router).
- offset = 0
- chunk_size = self._STDIN_CHUNK_SIZE
- while offset < len(payload):
- proc.stdin.write(payload[offset:offset + chunk_size])
- await proc.stdin.drain.aio()
- offset += chunk_size
-
- proc.stdin.write_eof()
- await proc.stdin.drain.aio()
-
+ await _stream_stdin(proc, payload, self._STDIN_CHUNK_SIZE)
exit_code = await proc.wait.aio()
if exit_code != 0:
stderr_text = await proc.stderr.read.aio()
- raise RuntimeError(
- f"Modal bulk upload failed (exit {exit_code}): {stderr_text}"
- )
-
+ raise RuntimeError(f"Modal bulk upload failed (exit {exit_code}): {stderr_text}")
self._worker.run_coroutine(_bulk(), timeout=120)
def _modal_bulk_download(self, dest: Path) -> None:
- """Download remote .hermes/ as a tar archive.
-
- Modal sandboxes always run as root, so /root/.hermes is hardcoded
- (consistent with iter_sync_files call on line 269).
- """
+ """Download remote .hermes/ as a tar archive (sandboxes run as root, so /root/.hermes)."""
async def _download():
- proc = await self._sandbox.exec.aio(
- "bash", "-c", "tar cf - -C / root/.hermes"
- )
+ proc = await self._sandbox.exec.aio("bash", "-c", "tar cf - -C / root/.hermes")
data = await proc.stdout.read.aio()
exit_code = await proc.wait.aio()
if exit_code != 0:
raise RuntimeError(f"Modal bulk download failed (exit {exit_code})")
return data
-
tar_bytes = self._worker.run_coroutine(_download(), timeout=120)
if isinstance(tar_bytes, str):
tar_bytes = tar_bytes.encode()
@@ -394,20 +279,13 @@ class ModalEnvironment(BaseEnvironment):
async def _rm():
proc = await self._sandbox.exec.aio("bash", "-c", rm_cmd)
await proc.wait.aio()
-
self._worker.run_coroutine(_rm(), timeout=15)
def _before_execute(self) -> None:
"""Sync files to sandbox via FileSyncManager (rate-limited internally)."""
self._sync_manager.sync()
- # ------------------------------------------------------------------
- # Execution
- # ------------------------------------------------------------------
-
- def _run_bash(self, cmd_string: str, *, login: bool = False,
- timeout: int = 120,
- stdin_data: str | None = None):
+ def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120, stdin_data: str | None = None):
"""Return a _ThreadedProcessHandle wrapping an async Modal sandbox exec."""
sandbox = self._sandbox
worker = self._worker
@@ -417,12 +295,7 @@ class ModalEnvironment(BaseEnvironment):
def exec_fn() -> tuple[str, int]:
async def _do():
- args = ["bash"]
- if login:
- args.extend(["-l", "-c", cmd_string])
- else:
- args.extend(["-c", cmd_string])
- process = await sandbox.exec.aio(*args, timeout=timeout)
+ process = await sandbox.exec.aio(*bash_argv(cmd_string, login), timeout=timeout)
stdout = await process.stdout.read.aio()
stderr = await process.stderr.read.aio()
exit_code = await process.wait.aio()
@@ -434,40 +307,30 @@ class ModalEnvironment(BaseEnvironment):
if stderr:
output = f"{stdout}\n{stderr}" if stdout else stderr
return output, exit_code
-
return worker.run_coroutine(_do(), timeout=timeout + 30)
-
return _ThreadedProcessHandle(exec_fn, cancel_fn=cancel)
def cleanup(self):
"""Snapshot the filesystem (if persistent) then stop the sandbox."""
if self._sandbox is None:
return
-
if self._sync_manager:
logger.info("Modal: syncing files from sandbox...")
self._sync_manager.sync_back()
-
if self._persistent:
try:
async def _snapshot():
img = await self._sandbox.snapshot_filesystem.aio()
return img.object_id
-
try:
snapshot_id = self._worker.run_coroutine(_snapshot(), timeout=60)
except Exception:
snapshot_id = None
-
if snapshot_id:
_store_direct_snapshot(self._task_id, snapshot_id)
- logger.info(
- "Modal: saved filesystem snapshot %s for task %s",
- snapshot_id[:20], self._task_id,
- )
+ logger.info("Modal: saved filesystem snapshot %s for task %s", snapshot_id[:20], self._task_id)
except Exception as e:
logger.warning("Modal: filesystem snapshot failed: %s", e)
-
try:
self._worker.run_coroutine(self._sandbox.terminate.aio(), timeout=15)
except Exception:
diff --git a/tools/environments/modal_utils.py b/tools/environments/modal_utils.py
index 167ac3856cd..e0dc7091495 100644
--- a/tools/environments/modal_utils.py
+++ b/tools/environments/modal_utils.py
@@ -1,14 +1,9 @@
"""Shared Hermes-side execution flow for Modal transports.
-This module deliberately stops at the Hermes boundary:
-- command preparation
-- cwd/timeout normalization
-- stdin/sudo shell wrapping
-- common result shape
-- interrupt/cancel polling
-
-Direct Modal and managed Modal keep separate transport logic, persistence, and
-trust-boundary decisions in their own modules.
+Stops at the Hermes boundary: command preparation, cwd/timeout normalization,
+stdin/sudo shell wrapping, common result shape, interrupt/cancel polling.
+Direct and managed Modal keep transport, persistence and trust-boundary logic
+in their own modules.
"""
from __future__ import annotations
@@ -58,13 +53,10 @@ def wrap_modal_sudo_pipe(command: str, sudo_stdin: str) -> str:
class BaseModalExecutionEnvironment(BaseEnvironment):
"""Execution flow for the *managed* Modal transport (gateway-owned sandbox).
- This deliberately overrides :meth:`BaseEnvironment.execute` because the
- tool-gateway handles command preparation, CWD tracking, and env-snapshot
- management on the server side. The base class's ``_wrap_command`` /
- ``_wait_for_process`` / snapshot machinery does not apply here — the
- gateway owns that responsibility. See ``ManagedModalEnvironment`` for the
- concrete subclass.
- """
+ Deliberately overrides :meth:`BaseEnvironment.execute`: the tool-gateway does command
+ preparation, CWD tracking and env-snapshot management server-side, so the base
+ ``_wrap_command`` / ``_wait_for_process`` / snapshot machinery does not apply.
+ See ``ManagedModalEnvironment`` for the concrete subclass."""
_stdin_mode = "payload"
_poll_interval_seconds = 0.25
@@ -72,124 +64,74 @@ class BaseModalExecutionEnvironment(BaseEnvironment):
_interrupt_output = "[Command interrupted]"
_unexpected_error_prefix = "Modal execution error"
- def execute(
- self,
- command: str,
- cwd: str = "",
- *,
- timeout: int | None = None,
- stdin_data: str | None = None,
- rewrite_compound_background: bool = True,
- bounded_capture: bool = False,
- ) -> dict:
- # Managed/remote modal transports execute commands via explicit transport
- # and do not rely on shell background rewriters. Keep parameter for
- # compatibility with BaseEnvironment callers.
- _ = rewrite_compound_background
- # bounded_capture: accepted for BaseEnvironment.execute() signature
- # parity (the terminal tool passes it). Modal transports return the
- # remote function's result in one payload, so streaming-time bounding
- # does not apply; the terminal tool's final truncation still caps it.
- _ = bounded_capture
+ def execute(self, command: str, cwd: str = "", *, timeout: int | None = None, stdin_data: str | None = None,
+ rewrite_compound_background: bool = True, bounded_capture: bool = False) -> dict:
+ # Signature parity with BaseEnvironment.execute only: the transport runs
+ # commands explicitly (no shell background rewriting) and returns the
+ # remote result in one payload, so streaming-time bounding does not apply
+ # (the terminal tool's final truncation still caps it).
+ del rewrite_compound_background, bounded_capture
self._before_execute()
- prepared = self._prepare_modal_exec(
- command,
- cwd=cwd,
- timeout=timeout,
- stdin_data=stdin_data,
- )
-
+ prepared = self._prepare_modal_exec(command, cwd=cwd, timeout=timeout, stdin_data=stdin_data)
try:
start = self._start_modal_exec(prepared)
except Exception as exc:
return self._error_result(f"{self._unexpected_error_prefix}: {exc}")
-
if start.immediate_result is not None:
return start.immediate_result
-
if start.handle is None:
- return self._error_result(
- f"{self._unexpected_error_prefix}: transport did not return an exec handle"
- )
-
+ return self._error_result(f"{self._unexpected_error_prefix}: transport did not return an exec handle")
deadline = None
if self._client_timeout_grace_seconds is not None:
deadline = time.monotonic() + prepared.timeout + self._client_timeout_grace_seconds
-
_now = time.monotonic()
- _activity_state = {
- "last_touch": _now,
- "start": _now,
- }
-
+ _activity_state = {"last_touch": _now, "start": _now}
while True:
if is_interrupted():
- try:
- self._cancel_modal_exec(start.handle)
- except Exception:
- pass
+ self._cancel_quietly(start.handle)
return self._result(self._interrupt_output, 130)
-
try:
result = self._poll_modal_exec(start.handle)
except Exception as exc:
return self._error_result(f"{self._unexpected_error_prefix}: {exc}")
-
if result is not None:
return result
-
if deadline is not None and time.monotonic() >= deadline:
- try:
- self._cancel_modal_exec(start.handle)
- except Exception:
- pass
+ self._cancel_quietly(start.handle)
return self._timeout_result_for_modal(prepared.timeout)
- # Periodic activity touch so the gateway knows we're alive
+ # Periodic activity touch so the gateway knows we're alive (lazy import:
+ # tests stub tools.environments.base with only BaseEnvironment)
try:
from tools.environments.base import touch_activity_if_due
touch_activity_if_due(_activity_state, "modal command running")
except Exception:
pass
-
time.sleep(self._poll_interval_seconds)
+ def _cancel_quietly(self, handle: Any) -> None:
+ try:
+ self._cancel_modal_exec(handle)
+ except Exception:
+ pass
+
def _before_execute(self) -> None:
"""Hook for backends that need pre-exec sync or validation."""
- pass
-
- def _prepare_modal_exec(
- self,
- command: str,
- *,
- cwd: str = "",
- timeout: int | None = None,
- stdin_data: str | None = None,
- ) -> PreparedModalExec:
- effective_cwd = cwd or self.cwd
- effective_timeout = timeout or self.timeout
+ def _prepare_modal_exec(self, command: str, *, cwd: str = "", timeout: int | None = None,
+ stdin_data: str | None = None) -> PreparedModalExec:
exec_command = command
exec_stdin = stdin_data if self._stdin_mode == "payload" else None
if stdin_data is not None and self._stdin_mode == "heredoc":
exec_command = wrap_modal_stdin_heredoc(exec_command, stdin_data)
-
exec_command, sudo_stdin = self._prepare_command(exec_command)
if sudo_stdin is not None:
exec_command = wrap_modal_sudo_pipe(exec_command, sudo_stdin)
-
- return PreparedModalExec(
- command=exec_command,
- cwd=effective_cwd,
- timeout=effective_timeout,
- stdin_data=exec_stdin,
- )
+ return PreparedModalExec(command=exec_command, cwd=cwd or self.cwd, timeout=timeout or self.timeout,
+ stdin_data=exec_stdin)
def _result(self, output: str, returncode: int) -> dict:
- return {
- "output": output,
- "returncode": returncode,
- }
+ return {"output": output, "returncode": returncode}
def _error_result(self, output: str) -> dict:
return self._result(output, 1)
diff --git a/tools/environments/remote_common.py b/tools/environments/remote_common.py
new file mode 100644
index 00000000000..f02f22671de
--- /dev/null
+++ b/tools/environments/remote_common.py
@@ -0,0 +1,39 @@
+"""Helpers shared by the non-local terminal backends (docker, ssh, singularity, cloud SDKs)."""
+
+from __future__ import annotations
+
+import subprocess
+
+
+def run_capture(cmd: list[str], *, timeout: float, check: bool = False, env: dict | None = None,
+ ) -> subprocess.CompletedProcess:
+ """``subprocess.run`` with the backend-standard capture settings.
+
+ Text mode with utf-8/replace decoding and stdin closed (DEVNULL) so a CLI
+ that unexpectedly prompts cannot hang the agent.
+ """
+ return subprocess.run(
+ cmd,
+ capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=timeout, check=check, stdin=subprocess.DEVNULL, env=env,
+ )
+
+
+def bash_argv(cmd_string: str, login: bool = False) -> list[str]:
+ """``bash [-l] -c <cmd>`` argv tail used by every spawn-per-call backend."""
+ return ["bash", "-l", "-c", cmd_string] if login else ["bash", "-c", cmd_string]
+
+
+def ensure_lazy_dep(feature: str) -> None:
+ """Lazy-install an optional SDK via ``tools.lazy_deps`` (idempotent).
+
+ Missing ``tools.lazy_deps`` is tolerated (the SDK import that follows will
+ fail with its own message); any other failure surfaces as ``ImportError``.
+ """
+ try:
+ from tools.lazy_deps import ensure as _lazy_ensure
+ _lazy_ensure(feature, prompt=False)
+ except ImportError:
+ pass
+ except Exception as e:
+ raise ImportError(str(e))
diff --git a/tools/environments/singularity.py b/tools/environments/singularity.py
index b55043de639..f03ef85cf79 100644
--- a/tools/environments/singularity.py
+++ b/tools/environments/singularity.py
@@ -1,8 +1,7 @@
"""Singularity/Apptainer persistent container environment.
-Security-hardened with --containall, --no-home, capability dropping.
-Supports configurable resource limits and optional filesystem persistence
-via writable overlay directories that survive across sessions.
+Security-hardened with --containall, --no-home, capability dropping. Supports
+resource limits and optional persistence via writable overlay dirs that survive sessions.
"""
import logging
@@ -15,13 +14,9 @@ from pathlib import Path
from typing import Optional
from hermes_constants import get_hermes_home
-from tools.environments.base import (
- BaseEnvironment,
- _load_json_store,
- _popen_bash,
- _save_json_store,
-)
+from tools.environments.base import BaseEnvironment, _load_json_store, _popen_bash, _save_json_store
from tools.environments.path_utils import sanitize_task_id_for_path
+from tools.environments.remote_common import bash_argv, run_capture
logger = logging.getLogger(__name__)
@@ -45,14 +40,9 @@ def _ensure_singularity_available() -> str:
"""Preflight check: resolve the executable and verify it responds."""
exe = _find_singularity_executable()
try:
- result = subprocess.run(
- [exe, "version"], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10,
- stdin=subprocess.DEVNULL,
- )
+ result = run_capture([exe, "version"], timeout=10)
except FileNotFoundError:
- raise RuntimeError(
- f"Singularity backend selected but '{exe}' could not be executed."
- )
+ raise RuntimeError(f"Singularity backend selected but '{exe}' could not be executed.")
except subprocess.TimeoutExpired:
raise RuntimeError(f"'{exe} version' timed out.")
@@ -93,12 +83,7 @@ def _get_scratch_dir() -> Path:
def _get_apptainer_cache_dir() -> Path:
cache_dir = os.getenv("APPTAINER_CACHEDIR")
- if cache_dir:
- cache_path = Path(cache_dir)
- cache_path.mkdir(parents=True, exist_ok=True)
- return cache_path
- scratch = _get_scratch_dir()
- cache_path = scratch / ".apptainer"
+ cache_path = Path(cache_dir) if cache_dir else _get_scratch_dir() / ".apptainer"
cache_path.mkdir(parents=True, exist_ok=True)
return cache_path
@@ -115,7 +100,6 @@ def _get_or_build_sif(image: str, executable: str = "apptainer") -> str:
image_name = image.replace('docker://', '').replace('/', '-').replace(':', '-')
cache_dir = _get_apptainer_cache_dir()
sif_path = cache_dir / f"{image_name}.sif"
-
if sif_path.exists():
return str(sif_path)
@@ -130,19 +114,14 @@ def _get_or_build_sif(image: str, executable: str = "apptainer") -> str:
tmp_dir = cache_dir / "tmp"
tmp_dir.mkdir(parents=True, exist_ok=True)
- # apptainer/singularity build: external tool, may need registry
- # credentials from the user env — exact preservation.
+ # External build tool may need registry credentials from the user env — exact preservation.
from tools.environments.local import build_subprocess_env
env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False)
env["APPTAINER_TMPDIR"] = str(tmp_dir)
env["APPTAINER_CACHEDIR"] = str(cache_dir)
try:
- result = subprocess.run(
- [executable, "build", str(sif_path), image],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=600, env=env,
- stdin=subprocess.DEVNULL,
- )
+ result = run_capture([executable, "build", str(sif_path), image], timeout=600, env=env)
if result.returncode != 0:
logger.warning("SIF build failed, falling back to docker:// URL")
logger.warning(" Error: %s", result.stderr[:500])
@@ -163,21 +142,12 @@ class SingularityEnvironment(BaseEnvironment):
"""Hardened Singularity/Apptainer container with resource limits and persistence.
Spawn-per-call: every execute() spawns a fresh ``apptainer exec ... bash -c`` process.
- Session snapshot preserves env vars across calls.
- CWD persists via in-band stdout markers.
+ Session snapshot preserves env vars across calls; CWD persists via in-band stdout markers.
"""
- def __init__(
- self,
- image: str,
- cwd: str = "~",
- timeout: int = 60,
- cpu: float = 0,
- memory: int = 0,
- disk: int = 0,
- persistent_filesystem: bool = False,
- task_id: str = "default",
- ):
+ def __init__(self, image: str, cwd: str = "~", timeout: int = 60, cpu: float = 0,
+ memory: int = 0, disk: int = 0, persistent_filesystem: bool = False,
+ task_id: str = "default"):
super().__init__(cwd=cwd, timeout=timeout)
self.executable = _ensure_singularity_available()
self.image = _get_or_build_sif(image, self.executable)
@@ -192,10 +162,8 @@ class SingularityEnvironment(BaseEnvironment):
if self._persistent:
overlay_base = _get_scratch_dir() / "hermes-overlays"
overlay_base.mkdir(parents=True, exist_ok=True)
- # A raw session-key task_id carries colons and other characters
- # that are unsafe in host path components (same class of bug as
- # the docker -v mount failure); route it through the shared
- # sanitizer so all backends agree on the mapping.
+ # A raw session-key task_id carries colons etc. unsafe in host path components;
+ # the shared sanitizer keeps all backends agreeing on the mapping.
self._overlay_dir = overlay_base / f"overlay-{sanitize_task_id_for_path(task_id)}"
self._overlay_dir.mkdir(parents=True, exist_ok=True)
@@ -203,9 +171,7 @@ class SingularityEnvironment(BaseEnvironment):
self.init_session()
def _start_instance(self):
- cmd = [self.executable, "instance", "start"]
- cmd.extend(["--containall", "--no-home"])
-
+ cmd = [self.executable, "instance", "start", "--containall", "--no-home"]
if self._persistent and self._overlay_dir:
cmd.extend(["--overlay", str(self._overlay_dir)])
else:
@@ -224,44 +190,30 @@ class SingularityEnvironment(BaseEnvironment):
cmd.extend(["--memory", f"{self._memory}M"])
if self._cpu > 0:
cmd.extend(["--cpus", str(self._cpu)])
-
cmd.extend([str(self.image), self.instance_id])
try:
- result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=120, stdin=subprocess.DEVNULL)
+ result = run_capture(cmd, timeout=120)
if result.returncode != 0:
raise RuntimeError(f"Failed to start instance: {result.stderr}")
self._instance_started = True
- logger.info("Singularity instance %s started (persistent=%s)",
- self.instance_id, self._persistent)
+ logger.info("Singularity instance %s started (persistent=%s)", self.instance_id, self._persistent)
except subprocess.TimeoutExpired:
raise RuntimeError("Instance start timed out")
- def _run_bash(self, cmd_string: str, *, login: bool = False,
- timeout: int = 120,
+ def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,
stdin_data: str | None = None) -> subprocess.Popen:
"""Spawn a bash process inside the Singularity instance."""
if not self._instance_started:
raise RuntimeError("Singularity instance not started")
-
- cmd = [self.executable, "exec",
- f"instance://{self.instance_id}"]
- if login:
- cmd.extend(["bash", "-l", "-c", cmd_string])
- else:
- cmd.extend(["bash", "-c", cmd_string])
-
+ cmd = [self.executable, "exec", f"instance://{self.instance_id}", *bash_argv(cmd_string, login)]
return _popen_bash(cmd, stdin_data)
def cleanup(self):
"""Stop the instance. If persistent, the overlay dir survives."""
if self._instance_started:
try:
- subprocess.run(
- [self.executable, "instance", "stop", self.instance_id],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=30,
- stdin=subprocess.DEVNULL,
- )
+ run_capture([self.executable, "instance", "stop", self.instance_id], timeout=30)
logger.info("Singularity instance %s stopped", self.instance_id)
except Exception as e:
logger.warning("Failed to stop Singularity instance %s: %s", self.instance_id, e)
diff --git a/tools/environments/ssh.py b/tools/environments/ssh.py
index 1260c070b09..fbdef1526f2 100644
--- a/tools/environments/ssh.py
+++ b/tools/environments/ssh.py
@@ -3,53 +3,39 @@
import hashlib
import logging
import os
-
-# Windows OpenSSH has no Unix-domain-socket ControlMaster support —
-# passing ControlPath/ControlMaster options fails the connection outright
-# ('getsockname failed: Not a socket', #73927). Skip multiplexing there;
-# each command pays a fresh connection but the backend works.
-_SSH_MULTIPLEX = os.name != "nt"
import shlex
import shutil
import subprocess
import tempfile
from pathlib import Path
-from tools.environments.base import (
- BaseEnvironment,
- EnvironmentConnectionError,
- _popen_bash,
-)
+from tools.environments.base import BaseEnvironment, EnvironmentConnectionError, _popen_bash
from tools.environments.file_sync import (
- FileSyncManager,
- iter_sync_files,
- quoted_mkdir_command,
- quoted_rm_command,
- unique_parent_dirs,
+ FileSyncManager, iter_sync_files, quoted_mkdir_command, quoted_rm_command, unique_parent_dirs,
)
+from tools.environments.remote_common import bash_argv, run_capture
logger = logging.getLogger(__name__)
+# Windows OpenSSH has no Unix-socket ControlMaster: ControlPath/ControlMaster options
+# fail the connection outright ('getsockname failed: Not a socket'). Skip multiplexing there.
+_SSH_MULTIPLEX = os.name != "nt"
+
def _ensure_ssh_available() -> None:
"""Fail fast with a clear error when the SSH client is unavailable."""
if not shutil.which("ssh"):
- raise RuntimeError(
- "SSH is not installed or not in PATH. Install OpenSSH client: apt install openssh-client"
- )
+ raise RuntimeError("SSH is not installed or not in PATH. Install OpenSSH client: apt install openssh-client")
if not shutil.which("scp"):
- raise RuntimeError(
- "SCP is not installed or not in PATH. Install OpenSSH client: apt install openssh-client"
- )
+ raise RuntimeError("SCP is not installed or not in PATH. Install OpenSSH client: apt install openssh-client")
class SSHEnvironment(BaseEnvironment):
"""Run commands on a remote machine over SSH.
Spawn-per-call: every execute() spawns a fresh ``ssh ... bash -c`` process.
- Session snapshot preserves env vars across calls.
- CWD persists via in-band stdout markers.
- Uses SSH ControlMaster for connection reuse.
+ Session snapshot preserves env vars across calls; CWD persists via in-band
+ stdout markers. Uses SSH ControlMaster for connection reuse.
"""
def __init__(self, host: str, user: str, cwd: str = "~",
@@ -62,17 +48,11 @@ class SSHEnvironment(BaseEnvironment):
self.control_dir = Path(tempfile.gettempdir()) / "hermes-ssh"
self.control_dir.mkdir(parents=True, exist_ok=True)
- # Keep the socket filename short and deterministic so the full path
- # stays under the 104-byte sun_path limit that macOS enforces on
- # Unix domain sockets. A raw ``user@host:port`` — especially with an
- # IPv6 host — plus the 16-byte random suffix SSH appends in
- # ControlMaster mode easily exceeds the limit under macOS's
- # deeply-nested $TMPDIR (e.g. /var/folders/xx/yy/T/). Hashing the
- # triple keeps the path stable across reconnects so ControlMaster
- # reuse still works.
- _socket_id = hashlib.sha256(
- f"{user}@{host}:{port}".encode()
- ).hexdigest()[:16]
+ # Short, deterministic socket name: the full path must stay under macOS's
+ # 104-byte sun_path limit (raw user@host:port + SSH's 16-byte random suffix
+ # under a deep $TMPDIR exceeds it), and stability across reconnects keeps
+ # ControlMaster reuse working.
+ _socket_id = hashlib.sha256(f"{user}@{host}:{port}".encode()).hexdigest()[:16]
self.control_socket = self.control_dir / f"{_socket_id}.sock"
_ensure_ssh_available()
self._establish_connection()
@@ -87,18 +67,15 @@ class SSHEnvironment(BaseEnvironment):
bulk_download_fn=self._ssh_bulk_download,
)
self._sync_manager.sync(force=True)
-
self.init_session()
def _build_ssh_command(self, extra_args: list | None = None) -> list:
cmd = ["ssh"]
if _SSH_MULTIPLEX:
- cmd.extend(["-o", f"ControlPath={self.control_socket}"])
- cmd.extend(["-o", "ControlMaster=auto"])
- cmd.extend(["-o", "ControlPersist=300"])
- cmd.extend(["-o", "BatchMode=yes"])
- cmd.extend(["-o", "StrictHostKeyChecking=accept-new"])
- cmd.extend(["-o", "ConnectTimeout=10"])
+ cmd.extend(["-o", f"ControlPath={self.control_socket}",
+ "-o", "ControlMaster=auto", "-o", "ControlPersist=300"])
+ cmd.extend(["-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new",
+ "-o", "ConnectTimeout=10"])
if self.port != 22:
cmd.extend(["-p", str(self.port)])
if self.key_path:
@@ -108,90 +85,54 @@ class SSHEnvironment(BaseEnvironment):
cmd.append(f"{self.user}@{self.host}")
return cmd
- def _establish_connection(self):
+ def _run_ssh(self, remote_cmd: str, timeout: float) -> subprocess.CompletedProcess:
+ """Run one remote shell command over the multiplexed connection, capturing output."""
cmd = self._build_ssh_command()
- cmd.append("echo 'SSH connection established'")
+ cmd.append(remote_cmd)
+ return run_capture(cmd, timeout=timeout)
+
+ def _establish_connection(self):
try:
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=15,
- stdin=subprocess.DEVNULL,
- )
+ result = self._run_ssh("echo 'SSH connection established'", timeout=15)
if result.returncode != 0:
error_msg = result.stderr.strip() or result.stdout.strip()
raise EnvironmentConnectionError(
f"SSH connection failed: {error_msg}",
- retry_hint=(
- f"Verify {self.user}@{self.host}:{self.port} is reachable "
- "(host up, sshd running, key/agent auth working), then "
- "retry — the connection is re-established automatically."
- ),
+ retry_hint=(f"Verify {self.user}@{self.host}:{self.port} is reachable "
+ "(host up, sshd running, key/agent auth working), then "
+ "retry — the connection is re-established automatically."),
)
except subprocess.TimeoutExpired:
raise EnvironmentConnectionError(
f"SSH connection to {self.user}@{self.host} timed out",
- retry_hint=(
- f"Check network connectivity to {self.host}:{self.port} "
- "and that sshd is accepting connections, then retry."
- ),
+ retry_hint=(f"Check network connectivity to {self.host}:{self.port} "
+ "and that sshd is accepting connections, then retry."),
)
def _detect_remote_home(self) -> str:
"""Detect the remote user's home directory."""
try:
- cmd = self._build_ssh_command()
- cmd.append("echo $HOME")
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=10,
- stdin=subprocess.DEVNULL,
- )
+ result = self._run_ssh("echo $HOME", timeout=10)
home = result.stdout.strip()
if home and result.returncode == 0:
logger.debug("SSH: remote home = %s", home)
return home
except Exception:
pass
- if self.user == "root":
- return "/root"
- return f"/home/{self.user}"
+ return "/root" if self.user == "root" else f"/home/{self.user}"
- # ------------------------------------------------------------------
- # File sync (via FileSyncManager)
- # ------------------------------------------------------------------
+ # -- File sync (via FileSyncManager) --------------------------------
def _ensure_remote_dirs(self) -> None:
"""Create base ~/.hermes directory tree on remote in one SSH call."""
base = f"{self._remote_home}/.hermes"
dirs = [base, f"{base}/skills", f"{base}/credentials", f"{base}/cache"]
- cmd = self._build_ssh_command()
- cmd.append(quoted_mkdir_command(dirs))
- subprocess.run(
- cmd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=10,
- stdin=subprocess.DEVNULL,
- )
-
- # _get_sync_files provided via iter_sync_files in FileSyncManager init
+ self._run_ssh(quoted_mkdir_command(dirs), timeout=10)
def _scp_upload(self, host_path: str, remote_path: str) -> None:
"""Upload a single file via scp over ControlMaster."""
parent = str(Path(remote_path).parent)
- mkdir_cmd = self._build_ssh_command()
- mkdir_cmd.append(f"mkdir -p {shlex.quote(parent)}")
- subprocess.run(
- mkdir_cmd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=10,
- stdin=subprocess.DEVNULL,
- )
+ self._run_ssh(f"mkdir -p {shlex.quote(parent)}", timeout=10)
scp_cmd = ["scp"]
if _SSH_MULTIPLEX:
@@ -201,32 +142,19 @@ class SSHEnvironment(BaseEnvironment):
if self.key_path:
scp_cmd.extend(["-i", self.key_path])
scp_cmd.extend([host_path, f"{self.user}@{self.host}:{remote_path}"])
- result = subprocess.run(
- scp_cmd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=30,
- stdin=subprocess.DEVNULL,
- )
+ result = run_capture(scp_cmd, timeout=30)
if result.returncode != 0:
raise EnvironmentConnectionError(
f"scp failed: {result.stderr.strip()}",
- retry_hint=(
- f"File sync to {self.user}@{self.host} failed — verify the "
- "SSH connection is healthy, then retry."
- ),
+ retry_hint=(f"File sync to {self.user}@{self.host} failed — verify the "
+ "SSH connection is healthy, then retry."),
)
def _ssh_bulk_upload(self, files: list[tuple[str, str]]) -> None:
"""Upload many files in a single tar-over-SSH stream.
- Pipes ``tar c`` on the local side through an SSH connection to
- ``tar x`` on the remote, transferring all files in one TCP stream
- instead of spawning a subprocess per file. Directory creation is
- batched into a single ``mkdir -p`` call beforehand.
-
- Typical improvement: ~580 files goes from O(N) scp round-trips
- to a single streaming transfer.
+ Local ``tar c`` is piped through one SSH connection to remote ``tar x``;
+ directory creation is batched into a single ``mkdir -p`` beforehand.
"""
if not files:
return
@@ -234,49 +162,31 @@ class SSHEnvironment(BaseEnvironment):
base = f"{self._remote_home}/.hermes"
parents = unique_parent_dirs(files)
if parents:
- cmd = self._build_ssh_command()
- cmd.append(quoted_mkdir_command(parents))
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=30,
- stdin=subprocess.DEVNULL,
- )
+ result = self._run_ssh(quoted_mkdir_command(parents), timeout=30)
if result.returncode != 0:
raise EnvironmentConnectionError(
f"remote mkdir failed: {result.stderr.strip()}",
- retry_hint=(
- f"Remote directory setup on {self.host} failed — verify "
- "the SSH connection is healthy, then retry."
- ),
+ retry_hint=(f"Remote directory setup on {self.host} failed — verify "
+ "the SSH connection is healthy, then retry."),
)
- # Symlink staging avoids fragile GNU tar --transform rules.
- # On Windows without Developer Mode, symlink creation raises
- # OSError with winerror 1314 (privilege not held). Catch only
- # that specific error and fall back to a plain copy; all other
- # OSErrors (e.g. disk full, bad path) are re-raised as normal.
+ # Symlink staging avoids fragile GNU tar --transform rules. On Windows
+ # without Developer Mode symlink creation raises OSError winerror 1314;
+ # only that case falls back to a plain copy, other OSErrors re-raise.
with tempfile.TemporaryDirectory(prefix="hermes-ssh-bulk-") as staging:
for host_path, remote_path in files:
try:
rel_remote = os.path.relpath(remote_path, base)
except ValueError as exc:
- raise RuntimeError(
- f"remote path {remote_path!r} is not under sync base {base!r}"
- ) from exc
-
+ raise RuntimeError(f"remote path {remote_path!r} is not under sync base {base!r}") from exc
if rel_remote == "." or rel_remote.startswith("../"):
- raise RuntimeError(
- f"remote path {remote_path!r} escapes sync base {base!r}"
- )
+ raise RuntimeError(f"remote path {remote_path!r} escapes sync base {base!r}")
staged = os.path.join(staging, rel_remote)
os.makedirs(os.path.dirname(staged), exist_ok=True)
try:
os.symlink(os.path.abspath(host_path), staged)
except OSError as e:
- # WinError 1314: symlink privilege not held (Windows without Dev Mode)
if getattr(e, "winerror", None) == 1314:
shutil.copy2(host_path, staged)
else:
@@ -284,23 +194,15 @@ class SSHEnvironment(BaseEnvironment):
tar_cmd = ["tar", "-chf", "-", "-C", staging, "."]
ssh_cmd = self._build_ssh_command()
- # --no-overwrite-dir prevents tar from overwriting the mode of
- # existing directories (e.g. /home/<user>) with the staging
- # directory's mode. Without this, a umask 002 produces 0775
- # dirs which breaks sshd StrictModes (refuses authorized_keys).
+ # --no-overwrite-dir keeps tar from stamping the staging dir's mode onto
+ # existing dirs (e.g. /home/<user>); a umask-002 0775 home breaks sshd StrictModes.
ssh_cmd.append(f"tar xf - --no-overwrite-dir -C {shlex.quote(base)}")
- tar_proc = subprocess.Popen(
- tar_cmd,
- stdin=subprocess.DEVNULL,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- )
+ tar_proc = subprocess.Popen(tar_cmd, stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
- ssh_proc = subprocess.Popen(
- ssh_cmd, stdin=tar_proc.stdout, stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- )
+ ssh_proc = subprocess.Popen(ssh_cmd, stdin=tar_proc.stdout,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception:
tar_proc.kill()
tar_proc.wait()
@@ -311,8 +213,7 @@ class SSHEnvironment(BaseEnvironment):
try:
_, ssh_stderr = ssh_proc.communicate(timeout=120)
- # Use communicate() instead of wait() to drain stderr and
- # avoid deadlock if tar produces more than PIPE_BUF of errors.
+ # communicate() (not wait()) drains stderr so tar can't deadlock on >PIPE_BUF errors.
tar_stderr_raw = b""
if tar_proc.poll() is None:
_, tar_stderr_raw = tar_proc.communicate(timeout=10)
@@ -325,91 +226,60 @@ class SSHEnvironment(BaseEnvironment):
ssh_proc.wait()
raise EnvironmentConnectionError(
"SSH bulk upload timed out",
- retry_hint=(
- f"Bulk file sync to {self.host} timed out — check the "
- "connection and retry."
- ),
+ retry_hint=f"Bulk file sync to {self.host} timed out — check the connection and retry.",
)
if tar_proc.returncode != 0:
- raise RuntimeError(
- f"tar create failed (rc={tar_proc.returncode}): "
- f"{tar_stderr_raw.decode(errors='replace').strip()}"
- )
+ raise RuntimeError(f"tar create failed (rc={tar_proc.returncode}): "
+ f"{tar_stderr_raw.decode(errors='replace').strip()}")
if ssh_proc.returncode != 0:
raise EnvironmentConnectionError(
f"tar extract over SSH failed (rc={ssh_proc.returncode}): "
f"{ssh_stderr.decode(errors='replace').strip()}",
- retry_hint=(
- f"File sync over SSH to {self.host} failed — verify the "
- "connection is healthy, then retry."
- ),
+ retry_hint=(f"File sync over SSH to {self.host} failed — verify the "
+ "connection is healthy, then retry."),
)
logger.debug("SSH: bulk-uploaded %d file(s) via tar pipe", len(files))
def _ssh_bulk_download(self, dest: Path) -> None:
"""Download remote .hermes/ as a tar archive."""
- # Tar from / with the full path so archive entries preserve absolute
- # paths (e.g. home/user/.hermes/skills/f.py), matching _pushed_hashes keys.
+ # Tar from / with the full path so archive entries keep absolute paths
+ # (home/user/.hermes/skills/f.py), matching _pushed_hashes keys.
rel_base = f"{self._remote_home}/.hermes".lstrip("/")
ssh_cmd = self._build_ssh_command()
ssh_cmd.append(f"tar cf - -C / {shlex.quote(rel_base)}")
with open(dest, "wb") as f:
- result = subprocess.run(
- ssh_cmd,
- stdin=subprocess.DEVNULL,
- stdout=f,
- stderr=subprocess.PIPE,
- timeout=120,
- )
+ result = subprocess.run(ssh_cmd, stdin=subprocess.DEVNULL, stdout=f,
+ stderr=subprocess.PIPE, timeout=120)
if result.returncode != 0:
raise EnvironmentConnectionError(
f"SSH bulk download failed: {result.stderr.decode(errors='replace').strip()}",
- retry_hint=(
- f"File sync from {self.host} failed — verify the SSH "
- "connection is healthy, then retry."
- ),
+ retry_hint=(f"File sync from {self.host} failed — verify the SSH "
+ "connection is healthy, then retry."),
)
def _ssh_delete(self, remote_paths: list[str]) -> None:
"""Batch-delete remote files in one SSH call."""
- cmd = self._build_ssh_command()
- cmd.append(quoted_rm_command(remote_paths))
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True, encoding='utf-8', errors='replace',
- timeout=10,
- stdin=subprocess.DEVNULL,
- )
+ result = self._run_ssh(quoted_rm_command(remote_paths), timeout=10)
if result.returncode != 0:
raise EnvironmentConnectionError(
f"remote rm failed: {result.stderr.strip()}",
- retry_hint=(
- f"Remote file cleanup on {self.host} failed — verify the "
- "SSH connection is healthy, then retry."
- ),
+ retry_hint=(f"Remote file cleanup on {self.host} failed — verify the "
+ "SSH connection is healthy, then retry."),
)
def _before_execute(self) -> None:
"""Sync files to remote via FileSyncManager (rate-limited internally)."""
self._sync_manager.sync()
- # ------------------------------------------------------------------
- # Execution
- # ------------------------------------------------------------------
+ # -- Execution ------------------------------------------------------
- def _run_bash(self, cmd_string: str, *, login: bool = False,
- timeout: int = 120,
+ def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,
stdin_data: str | None = None) -> subprocess.Popen:
"""Spawn an SSH process that runs bash on the remote host."""
cmd = self._build_ssh_command()
- if login:
- cmd.extend(["bash", "-l", "-c", shlex.quote(cmd_string)])
- else:
- cmd.extend(["bash", "-c", shlex.quote(cmd_string)])
-
+ cmd.extend(bash_argv(shlex.quote(cmd_string), login))
return _popen_bash(cmd, stdin_data)
def cleanup(self):
@@ -419,14 +289,8 @@ class SSHEnvironment(BaseEnvironment):
if self.control_socket.exists():
try:
- cmd = ["ssh", "-o", f"ControlPath={self.control_socket}",
- "-O", "exit", f"{self.user}@{self.host}"]
- subprocess.run(
- cmd,
- capture_output=True,
- timeout=5,
- stdin=subprocess.DEVNULL,
- )
+ cmd = ["ssh", "-o", f"ControlPath={self.control_socket}", "-O", "exit", f"{self.user}@{self.host}"]
+ subprocess.run(cmd, capture_output=True, timeout=5, stdin=subprocess.DEVNULL)
except (OSError, subprocess.SubprocessError):
pass
try:
diff --git a/tools/environments/vercel_sandbox.py b/tools/environments/vercel_sandbox.py
index 4b6e4ea6569..088cddba03c 100644
--- a/tools/environments/vercel_sandbox.py
+++ b/tools/environments/vercel_sandbox.py
@@ -1,9 +1,8 @@
"""Vercel Sandbox execution environment.
-Uses the Vercel Python SDK to run commands in cloud sandboxes through Hermes'
-shared ``BaseEnvironment`` shell contract. When persistence is enabled, the
-backend stores task-scoped snapshot metadata under ``HERMES_HOME`` and restores
-new sandboxes from those snapshots on later task reuse.
+Runs commands in Vercel cloud sandboxes through the shared ``BaseEnvironment``
+shell contract. With persistence enabled, task-scoped snapshot ids are stored
+under ``HERMES_HOME`` and new sandboxes are restored from them on task reuse.
"""
from __future__ import annotations
@@ -23,17 +22,9 @@ from typing import TYPE_CHECKING, Any
import httpx
from hermes_constants import get_hermes_home
-from tools.environments.base import (
- BaseEnvironment,
- _ThreadedProcessHandle,
- _load_json_store,
- _save_json_store,
-)
-from tools.environments.file_sync import (
- FileSyncManager,
- iter_sync_files,
- quoted_rm_command,
-)
+from tools.environments.base import BaseEnvironment, _ThreadedProcessHandle, _load_json_store, _save_json_store
+from tools.environments.file_sync import FileSyncManager, iter_sync_files, quoted_rm_command
+from tools.environments.remote_common import ensure_lazy_dep
logger = logging.getLogger(__name__)
@@ -46,21 +37,12 @@ _DEFAULT_CONTAINER_DISK_MB = 51200
def _ensure_vercel_sdk() -> None:
"""Lazy-install vercel SDK on demand. Idempotent."""
- # The vercel SDK (>=0.7) ships default-on usage telemetry
- # (vercel-internal-telemetry posts to telemetry.vercel.com). Hermes
- # policy is no outbound telemetry without explicit user opt-in, so
- # disable it before the SDK is ever imported. Users who genuinely want
- # it can re-enable by exporting VERCEL_TELEMETRY_DISABLED=0 after this
- # module loads — we only set the default, never override an explicit
- # user value.
+ # The vercel SDK (>=0.7) ships default-on usage telemetry posting to
+ # telemetry.vercel.com. Hermes policy is no outbound telemetry without
+ # explicit opt-in, so disable it before the SDK is ever imported. Only the
+ # default is set — an explicit user value (e.g. "0") is never overridden.
os.environ.setdefault("VERCEL_TELEMETRY_DISABLED", "1")
- try:
- from tools.lazy_deps import ensure as _lazy_ensure
- _lazy_ensure("terminal.vercel", prompt=False)
- except ImportError:
- pass
- except Exception as e:
- raise ImportError(str(e))
+ ensure_lazy_dep("terminal.vercel")
_CREATE_RETRY_ATTEMPTS = 3
@@ -74,6 +56,8 @@ _RUNNING_WAIT_POLL_INTERVAL = timedelta(milliseconds=250)
_STOP_TIMEOUT = timedelta(seconds=15)
_STOP_POLL_INTERVAL = timedelta(milliseconds=500)
_SNAPSHOT_STORE_NAME = "vercel_sandbox_snapshots.json"
+_SNAPSHOT_ID_KEYS = ("snapshot_id", "snapshotId", "id")
+_MISSING = object()
def _exception_chain(exc: BaseException) -> list[BaseException]:
@@ -97,26 +81,15 @@ def _extract_status_code(exc: BaseException) -> int | None:
def _is_transient_vercel_error(exc: BaseException) -> bool:
for error in _exception_chain(exc):
- status_code = _extract_status_code(error)
- if status_code in _TRANSIENT_STATUS_CODES:
- return True
- if isinstance(
- error,
- (httpx.NetworkError, httpx.ProtocolError, httpx.ReadError),
- ):
- return True
error_name = type(error).__name__.lower()
- if "ratelimit" in error_name or "servererror" in error_name:
+ if (_extract_status_code(error) in _TRANSIENT_STATUS_CODES
+ or isinstance(error, (httpx.NetworkError, httpx.ProtocolError, httpx.ReadError))
+ or "ratelimit" in error_name or "servererror" in error_name):
return True
return False
-def _retry_vercel_call(
- label: str,
- callback,
- *,
- attempts: int,
-):
+def _retry_vercel_call(label: str, callback, *, attempts: int):
backoff_seconds = _RETRY_BACKOFF_STEP.total_seconds()
for attempt in range(1, attempts + 1):
try:
@@ -124,22 +97,14 @@ def _retry_vercel_call(
except Exception as exc:
if attempt >= attempts or not _is_transient_vercel_error(exc):
raise
- logger.warning(
- "Vercel: %s failed (%s); retrying %d/%d",
- label,
- exc,
- attempt,
- attempts,
- )
+ logger.warning("Vercel: %s failed (%s); retrying %d/%d", label, exc, attempt, attempts)
time.sleep(backoff_seconds * attempt)
def _coerce_text(value: Any) -> str:
- if value is None:
- return ""
if isinstance(value, bytes):
return value.decode("utf-8", errors="replace")
- return str(value)
+ return "" if value is None else str(value)
def _extract_result_output(result: Any) -> str:
@@ -150,26 +115,18 @@ def _extract_result_output(result: Any) -> str:
def _extract_result_returncode(result: Any) -> int:
- try:
- exit_code = result.exit_code
- except AttributeError:
- try:
- exit_code = result.returncode
- except AttributeError:
- return 1
+ exit_code = getattr(result, "exit_code", _MISSING)
+ if exit_code is _MISSING:
+ exit_code = getattr(result, "returncode", None)
return exit_code if isinstance(exit_code, int) else 1
-def _snapshot_store_path() -> Path:
- return get_hermes_home() / _SNAPSHOT_STORE_NAME
-
-
def _load_snapshots() -> dict:
- return _load_json_store(_snapshot_store_path())
+ return _load_json_store(get_hermes_home() / _SNAPSHOT_STORE_NAME)
def _save_snapshots(data: dict) -> None:
- _save_json_store(_snapshot_store_path(), data)
+ _save_json_store(get_hermes_home() / _SNAPSHOT_STORE_NAME, data)
def _get_snapshot_id(task_id: str) -> str | None:
@@ -192,22 +149,20 @@ def _delete_snapshot(task_id: str, snapshot_id: str | None = None) -> None:
return
snapshots = _load_snapshots()
existing = snapshots.get(task_id)
- if existing is None:
- return
- if snapshot_id is not None and existing != snapshot_id:
+ if existing is None or (snapshot_id is not None and existing != snapshot_id):
return
snapshots.pop(task_id, None)
_save_snapshots(snapshots)
def _extract_snapshot_id(snapshot: Any) -> str | None:
- for attr in ("snapshot_id", "snapshotId", "id"):
- value = getattr(snapshot, attr, None)
- if isinstance(value, str) and value:
- return value
+ """Accept SDK objects or raw dicts; attribute lookup first, then dict keys."""
+ getters = [lambda k: getattr(snapshot, k, None)]
if isinstance(snapshot, dict):
- for key in ("snapshot_id", "snapshotId", "id"):
- value = snapshot.get(key)
+ getters.append(snapshot.get)
+ for get in getters:
+ for key in _SNAPSHOT_ID_KEYS:
+ value = get(key)
if isinstance(value, str) and value:
return value
return None
@@ -217,20 +172,13 @@ def _extract_snapshot_id(snapshot: Any) -> str | None:
def _sandbox_status_type() -> type[SandboxStatus]:
_ensure_vercel_sdk()
from vercel.sandbox import SandboxStatus
-
return SandboxStatus
@cache
def _terminal_sandbox_states() -> frozenset[SandboxStatus]:
SandboxStatus = _sandbox_status_type()
- return frozenset(
- {
- SandboxStatus.ABORTED,
- SandboxStatus.FAILED,
- SandboxStatus.STOPPED,
- }
- )
+ return frozenset({SandboxStatus.ABORTED, SandboxStatus.FAILED, SandboxStatus.STOPPED})
@dataclass(frozen=True, slots=True)
@@ -245,35 +193,37 @@ class VercelSandboxEnvironment(BaseEnvironment):
_stdin_mode = "heredoc"
- def __init__(
- self,
- runtime: str | None = None,
- cwd: str = DEFAULT_VERCEL_CWD,
- timeout: int = 60,
- cpu: float = 1,
- memory: int = 5120,
- disk: int = _DEFAULT_CONTAINER_DISK_MB,
- persistent_filesystem: bool = True,
- task_id: str = "default",
- ):
- requested_cwd = cwd
+ def __init__(self, runtime: str | None = None, cwd: str = DEFAULT_VERCEL_CWD, timeout: int = 60,
+ cpu: float = 1, memory: int = 5120, disk: int = _DEFAULT_CONTAINER_DISK_MB,
+ persistent_filesystem: bool = True, task_id: str = "default"):
super().__init__(cwd=cwd, timeout=timeout)
-
self._runtime = runtime or None
self._persistent = persistent_filesystem
self._task_id = task_id
- self._requested_cwd = requested_cwd
+ self._requested_cwd = cwd
self._lock = threading.Lock()
self._sandbox: Sandbox | None = None
self._workspace_root = DEFAULT_VERCEL_CWD
self._remote_home = DEFAULT_VERCEL_CWD
self._sync_manager: FileSyncManager | None = None
self._create_params = self._build_create_params(cpu=cpu, memory=memory, disk=disk)
+ self._attach_fresh_sandbox(cwd)
+ self._sync_manager.sync(force=True)
+ self.init_session()
+
+ def _require_sandbox(self) -> Sandbox:
+ sandbox = self._sandbox
+ if sandbox is None:
+ raise RuntimeError("Vercel sandbox is not attached")
+ return sandbox
+ def _attach_fresh_sandbox(self, requested_cwd: str) -> None:
self._sandbox = self._create_sandbox()
self._configure_attached_sandbox(requested_cwd=requested_cwd)
- self._sync_manager.sync(force=True)
- self.init_session()
+
+ def _remote_hermes_dir(self) -> str:
+ home = self._remote_home
+ return "/.hermes" if home == "/" else f"{home.rstrip('/')}/.hermes"
def _build_create_params(self, *, cpu: float, memory: int, disk: int) -> _SandboxCreateParams:
if disk not in {0, _DEFAULT_CONTAINER_DISK_MB}:
@@ -281,63 +231,37 @@ class VercelSandboxEnvironment(BaseEnvironment):
"Vercel Sandbox does not support configurable container_disk. "
"Use the default shared setting."
)
-
_ensure_vercel_sdk()
from vercel.sandbox import Resources
-
- sandbox_timeout = max(
- timedelta(seconds=max(self.timeout, 0)),
- _MIN_SANDBOX_TIMEOUT,
- )
+ sandbox_timeout = max(timedelta(seconds=max(self.timeout, 0)), _MIN_SANDBOX_TIMEOUT)
vcpus = math.floor(cpu) if cpu > 0 else None
memory_mb = memory if memory > 0 else None
- resources = (
- Resources(vcpus=vcpus, memory=memory_mb)
- if vcpus is not None or memory_mb is not None
- else None
- )
-
- return _SandboxCreateParams(
- timeout=sandbox_timeout,
- runtime=self._runtime,
- resources=resources,
- )
+ resources = Resources(vcpus=vcpus, memory=memory_mb) if vcpus is not None or memory_mb is not None else None
+ return _SandboxCreateParams(timeout=sandbox_timeout, runtime=self._runtime, resources=resources)
def _create_sandbox(self) -> Sandbox:
_ensure_vercel_sdk()
from vercel.sandbox import Sandbox
-
+ params = self._create_params
snapshot_id = _get_snapshot_id(self._task_id) if self._persistent else None
if snapshot_id:
try:
return _retry_vercel_call(
"sandbox restore",
- lambda: Sandbox.create(
- timeout=self._create_params.timeout,
- runtime=self._create_params.runtime,
- resources=self._create_params.resources,
- source={"type": "snapshot", "snapshot_id": snapshot_id},
- ),
+ lambda: Sandbox.create(timeout=params.timeout, runtime=params.runtime, resources=params.resources,
+ source={"type": "snapshot", "snapshot_id": snapshot_id}),
attempts=_CREATE_RETRY_ATTEMPTS,
)
except Exception as exc:
logger.warning(
"Vercel: failed to restore snapshot %s for task %s; "
"falling back to a fresh sandbox: %s",
- snapshot_id,
- self._task_id,
- exc,
+ snapshot_id, self._task_id, exc,
)
_delete_snapshot(self._task_id, snapshot_id)
-
- params = self._create_params
return _retry_vercel_call(
"sandbox create",
- lambda: Sandbox.create(
- timeout=params.timeout,
- runtime=params.runtime,
- resources=params.resources,
- ),
+ lambda: Sandbox.create(timeout=params.timeout, runtime=params.runtime, resources=params.resources),
attempts=_CREATE_RETRY_ATTEMPTS,
)
@@ -345,11 +269,7 @@ class VercelSandboxEnvironment(BaseEnvironment):
self._wait_for_running()
self._workspace_root = self._detect_workspace_root()
self._remote_home = self._detect_remote_home()
-
- if self._remote_home == "/":
- container_base = "/.hermes"
- else:
- container_base = f"{self._remote_home.rstrip('/')}/.hermes"
+ container_base = self._remote_hermes_dir()
self._sync_manager = FileSyncManager(
get_files_fn=lambda: iter_sync_files(container_base),
upload_fn=self._vercel_upload,
@@ -357,7 +277,6 @@ class VercelSandboxEnvironment(BaseEnvironment):
bulk_upload_fn=self._vercel_bulk_upload,
bulk_download_fn=self._vercel_bulk_download,
)
-
if requested_cwd == "~":
self.cwd = self._remote_home
elif requested_cwd in {"", DEFAULT_VERCEL_CWD}:
@@ -366,59 +285,35 @@ class VercelSandboxEnvironment(BaseEnvironment):
self.cwd = requested_cwd
def _detect_workspace_root(self) -> str:
- sandbox = self._sandbox
- if sandbox is None:
- raise RuntimeError("Vercel sandbox is not attached")
- cwd = sandbox.sandbox.cwd
+ cwd = self._require_sandbox().sandbox.cwd
return cwd if cwd.startswith("/") else DEFAULT_VERCEL_CWD
def _detect_remote_home(self) -> str:
- sandbox = self._sandbox
- if sandbox is None:
- raise RuntimeError("Vercel sandbox is not attached")
+ sandbox = self._require_sandbox()
try:
- result = sandbox.run_command(
- "sh",
- ["-lc", 'printf %s "$HOME"'],
- cwd=self._workspace_root,
- )
+ result = sandbox.run_command("sh", ["-lc", 'printf %s "$HOME"'], cwd=self._workspace_root)
except Exception as exc:
- logger.debug(
- "Vercel: home detection failed for task %s: %s",
- self._task_id,
- exc,
- )
+ logger.debug("Vercel: home detection failed for task %s: %s", self._task_id, exc)
return self._workspace_root
-
home = _extract_result_output(result).strip()
- if home.startswith("/"):
- return home
- return self._workspace_root
+ return home if home.startswith("/") else self._workspace_root
def _wait_for_running(self, timeout: timedelta = _RUNNING_WAIT_TIMEOUT) -> None:
- sandbox = self._sandbox
- if sandbox is None:
- raise RuntimeError("Vercel sandbox is not attached")
+ sandbox = self._require_sandbox()
SandboxStatus = _sandbox_status_type()
status = sandbox.status
if status is None or status == SandboxStatus.RUNNING:
return
if status in _terminal_sandbox_states():
raise RuntimeError(f"Sandbox entered terminal state: {status}")
-
try:
- sandbox.wait_for_status(
- SandboxStatus.RUNNING,
- timeout=max(timeout, _MIN_RUNNING_WAIT),
- poll_interval=_RUNNING_WAIT_POLL_INTERVAL,
- )
+ sandbox.wait_for_status(SandboxStatus.RUNNING, timeout=max(timeout, _MIN_RUNNING_WAIT),
+ poll_interval=_RUNNING_WAIT_POLL_INTERVAL)
except TimeoutError as exc:
status = sandbox.status
if status in _terminal_sandbox_states():
raise RuntimeError(f"Sandbox entered terminal state: {status}") from exc
- raise RuntimeError(
- f"Sandbox did not reach running state (last status: {status})"
- ) from exc
+ raise RuntimeError(f"Sandbox did not reach running state (last status: {status})") from exc
def _close_sandbox_client(self, sandbox: Sandbox | None) -> None:
if sandbox is None:
@@ -432,11 +327,7 @@ class VercelSandboxEnvironment(BaseEnvironment):
if sandbox is None:
return
try:
- sandbox.stop(
- blocking=True,
- timeout=_STOP_TIMEOUT,
- poll_interval=_STOP_POLL_INTERVAL,
- )
+ sandbox.stop(blocking=True, timeout=_STOP_TIMEOUT, poll_interval=_STOP_POLL_INTERVAL)
except TypeError:
try:
sandbox.stop()
@@ -451,63 +342,35 @@ class VercelSandboxEnvironment(BaseEnvironment):
try:
snapshot = sandbox.snapshot()
except Exception as exc:
- logger.warning(
- "Vercel: filesystem snapshot failed for task %s: %s",
- self._task_id,
- exc,
- )
+ logger.warning("Vercel: filesystem snapshot failed for task %s: %s", self._task_id, exc)
return None
-
snapshot_id = _extract_snapshot_id(snapshot)
if not snapshot_id:
- logger.warning(
- "Vercel: filesystem snapshot for task %s did not return a snapshot id",
- self._task_id,
- )
+ logger.warning("Vercel: filesystem snapshot for task %s did not return a snapshot id", self._task_id)
return None
-
_store_snapshot(self._task_id, snapshot_id)
- logger.info(
- "Vercel: saved filesystem snapshot %s for task %s",
- snapshot_id,
- self._task_id,
- )
+ logger.info("Vercel: saved filesystem snapshot %s for task %s", snapshot_id, self._task_id)
return snapshot_id
def _ensure_sandbox_ready(self) -> None:
sandbox = self._sandbox
requested_cwd = self.cwd or self._requested_cwd or DEFAULT_VERCEL_CWD
-
if sandbox is None:
- self._sandbox = self._create_sandbox()
- self._configure_attached_sandbox(requested_cwd=requested_cwd)
+ self._attach_fresh_sandbox(requested_cwd)
return
-
try:
sandbox.refresh()
except Exception as exc:
- logger.warning(
- "Vercel: sandbox refresh failed for task %s: %s; recreating",
- self._task_id,
- exc,
- )
+ logger.warning("Vercel: sandbox refresh failed for task %s: %s; recreating", self._task_id, exc)
self._close_sandbox_client(sandbox)
- self._sandbox = self._create_sandbox()
- self._configure_attached_sandbox(requested_cwd=requested_cwd)
+ self._attach_fresh_sandbox(requested_cwd)
return
-
status = sandbox.status
if status in _terminal_sandbox_states():
- logger.warning(
- "Vercel: sandbox entered state %s for task %s; recreating",
- status,
- self._task_id,
- )
+ logger.warning("Vercel: sandbox entered state %s for task %s; recreating", status, self._task_id)
self._close_sandbox_client(sandbox)
- self._sandbox = self._create_sandbox()
- self._configure_attached_sandbox(requested_cwd=requested_cwd)
+ self._attach_fresh_sandbox(requested_cwd)
return
-
self._wait_for_running()
def _vercel_upload(self, host_path: str, remote_path: str) -> None:
@@ -516,75 +379,36 @@ class VercelSandboxEnvironment(BaseEnvironment):
def _vercel_bulk_upload(self, files: list[tuple[str, str]]) -> None:
if not files:
return
-
payload: list[WriteFile] = [
- {
- "path": remote_path,
- "content": Path(host_path).read_bytes(),
- }
- for host_path, remote_path in files
+ {"path": remote_path, "content": Path(host_path).read_bytes()} for host_path, remote_path in files
]
-
- sandbox = self._sandbox
- if sandbox is None:
- raise RuntimeError("Vercel sandbox is not attached")
- _retry_vercel_call(
- "write_files",
- lambda: sandbox.write_files(payload),
- attempts=_WRITE_RETRY_ATTEMPTS,
- )
+ sandbox = self._require_sandbox()
+ _retry_vercel_call("write_files", lambda: sandbox.write_files(payload), attempts=_WRITE_RETRY_ATTEMPTS)
def _vercel_delete(self, remote_paths: list[str]) -> None:
if not remote_paths:
return
-
- sandbox = self._sandbox
- if sandbox is None:
- raise RuntimeError("Vercel sandbox is not attached")
- result = sandbox.run_command(
- "bash",
- ["-lc", quoted_rm_command(remote_paths)],
- cwd=self._workspace_root,
+ result = self._require_sandbox().run_command(
+ "bash", ["-lc", quoted_rm_command(remote_paths)], cwd=self._workspace_root,
)
if _extract_result_returncode(result) != 0:
- raise RuntimeError(
- f"Vercel delete failed: {_extract_result_output(result).strip()}"
- )
+ raise RuntimeError(f"Vercel delete failed: {_extract_result_output(result).strip()}")
def _vercel_bulk_download(self, dest_tar_path: Path) -> None:
- remote_hermes = (
- "/.hermes"
- if self._remote_home == "/"
- else f"{self._remote_home.rstrip('/')}/.hermes"
- )
- archive_member = remote_hermes.lstrip("/")
+ archive_member = self._remote_hermes_dir().lstrip("/")
remote_tar = f"/tmp/.hermes_sync.{os.getpid()}.tar"
- sandbox = self._sandbox
- if sandbox is None:
- raise RuntimeError("Vercel sandbox is not attached")
-
+ sandbox = self._require_sandbox()
try:
result = sandbox.run_command(
- "bash",
- [
- "-lc",
- f"tar cf {shlex.quote(remote_tar)} -C / {shlex.quote(archive_member)}",
- ],
+ "bash", ["-lc", f"tar cf {shlex.quote(remote_tar)} -C / {shlex.quote(archive_member)}"],
cwd=self._workspace_root,
)
if _extract_result_returncode(result) != 0:
- raise RuntimeError(
- f"Vercel bulk download failed: {_extract_result_output(result).strip()}"
- )
-
+ raise RuntimeError(f"Vercel bulk download failed: {_extract_result_output(result).strip()}")
sandbox.download_file(remote_tar, dest_tar_path)
finally:
try:
- sandbox.run_command(
- "bash",
- ["-lc", f"rm -f {shlex.quote(remote_tar)}"],
- cwd=self._workspace_root,
- )
+ sandbox.run_command("bash", ["-lc", f"rm -f {shlex.quote(remote_tar)}"], cwd=self._workspace_root)
except Exception:
pass
@@ -594,31 +418,13 @@ class VercelSandboxEnvironment(BaseEnvironment):
if self._sync_manager is not None:
self._sync_manager.sync()
- def _run_bash(
- self,
- cmd_string: str,
- *,
- login: bool = False,
- timeout: int = 120,
- stdin_data: str | None = None,
- ):
- """Run a bash command in the Vercel sandbox.
-
- ``timeout`` is not forwarded to the Vercel SDK (which does not expose
- a per-exec timeout parameter); the base class ``_wait_for_process``
- enforces timeout by killing the sandbox via ``cancel_fn``.
-
- ``stdin_data`` is intentionally discarded here because
- ``_stdin_mode = "heredoc"`` causes the base class ``execute()`` to
- embed any stdin payload into the command string before calling this
- method.
- """
- del timeout
- del stdin_data
-
- sandbox = self._sandbox
- if sandbox is None:
- raise RuntimeError("Vercel sandbox is not attached")
+ def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120, stdin_data: str | None = None):
+ """``timeout`` is not forwarded (the SDK has no per-exec timeout); the base
+ ``_wait_for_process`` enforces it by killing the sandbox via ``cancel_fn``.
+ ``stdin_data`` is discarded: ``_stdin_mode = "heredoc"`` makes the base
+ ``execute()`` embed stdin into the command string before calling this."""
+ del timeout, stdin_data
+ sandbox = self._require_sandbox()
workspace_root = self._workspace_root
lock = self._lock
@@ -627,13 +433,8 @@ class VercelSandboxEnvironment(BaseEnvironment):
self._stop_sandbox(sandbox)
def exec_fn() -> tuple[str, int]:
- result = sandbox.run_command(
- "bash",
- ["-lc" if login else "-c", cmd_string],
- cwd=workspace_root,
- )
+ result = sandbox.run_command("bash", ["-lc" if login else "-c", cmd_string], cwd=workspace_root)
return _extract_result_output(result), _extract_result_returncode(result)
-
return _ThreadedProcessHandle(exec_fn, cancel_fn=cancel)
def cleanup(self):
@@ -644,19 +445,12 @@ class VercelSandboxEnvironment(BaseEnvironment):
try:
sync_manager.sync_back()
except Exception as exc:
- logger.warning(
- "Vercel: sync_back failed for task %s: %s",
- self._task_id,
- exc,
- )
+ logger.warning("Vercel: sync_back failed for task %s: %s", self._task_id, exc)
self._sandbox = None
self._sync_manager = None
-
if sandbox is None:
return
-
- snapshot_id = self._snapshot_sandbox(sandbox)
- # Always stop the sandbox during cleanup to avoid resource leaks,
- # matching the Modal and Daytona patterns.
+ self._snapshot_sandbox(sandbox)
+ # Always stop the sandbox during cleanup to avoid resource leaks (matches Modal/Daytona).
self._stop_sandbox(sandbox)
self._close_sandbox_client(sandbox)
diff --git a/tools/process_registry.py b/tools/process_registry.py
index a2314ee47e4..950329e38e6 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -1,32 +1,12 @@
"""
-Process Registry -- In-memory registry for managed background processes.
-
-Tracks processes spawned via terminal(background=true), providing:
- - Output buffering (rolling 200KB window)
- - Status polling and log retrieval
- - Blocking wait with interrupt support
- - Process killing
- - Crash recovery via JSON checkpoint file
- - Session-scoped tracking for gateway reset protection
-
-Background processes execute THROUGH the environment interface -- nothing
-runs on the host machine unless TERMINAL_ENV=local. For Docker, Singularity,
-Modal, Daytona, and SSH backends, the command runs inside the sandbox.
-
-Usage:
- from tools.process_registry import process_registry
-
- # Spawn a background process (called from terminal_tool)
- session = process_registry.spawn(env, "pytest -v", task_id="task_123")
-
- # Poll for status
- result = process_registry.poll(session.id)
-
- # Block until done
- result = process_registry.wait(session.id, timeout=300)
-
- # Kill it
- process_registry.kill(session.id)
+Process Registry -- in-memory registry for background processes spawned via
+terminal(background=true): rolling 200KB output buffer, poll/log/wait/kill,
+crash recovery via a JSON checkpoint, and session-scoped tracking for gateway
+reset protection.
+
+Background processes execute THROUGH the environment interface -- nothing runs
+on the host unless TERMINAL_ENV=local; for Docker/Singularity/Modal/Daytona/SSH
+the command runs inside the sandbox.
"""
import codecs
@@ -66,28 +46,22 @@ CHECKPOINT_PATH = get_hermes_home() / "processes.json"
MAX_OUTPUT_CHARS = 200_000 # 200KB rolling output buffer
FINISHED_TTL_SECONDS = 1800 # Keep finished processes for 30 minutes
MAX_PROCESSES = 64 # Max concurrent tracked processes (LRU pruning)
-MAX_ACTIVE_PROCESS_AGE = 86400 # 24h default — see session_reset.bg_process_max_age_hours (#29177)
-
-# Watch pattern rate limiting — PER SESSION.
-# Hard rule: at most ONE watch-match notification every WATCH_MIN_INTERVAL_SECONDS.
-# Any match arriving inside that cooldown window is dropped and counted as a strike.
-# After WATCH_STRIKE_LIMIT consecutive strike windows, watch_patterns for that
-# session is permanently disabled and the session falls back to notify_on_complete
-# semantics (one notification when the process actually exits).
-WATCH_MIN_INTERVAL_SECONDS = 15 # Minimum spacing between consecutive watch matches
-WATCH_STRIKE_LIMIT = 3 # Strikes in a row → disable watch + promote to notify_on_complete
-
-# Lifetime cap — independent of the strike counter above. A process whose
-# pattern recurs at a cadence just above WATCH_MIN_INTERVAL_SECONDS (e.g. a
-# service restarted repeatedly over a day) never trips the consecutive-strike
-# limit, since each match lands in its own clean cooldown window, yet still
-# forces a full-context agent turn every single time (#93513). watch_patterns
-# is documented as "ONLY for rare one-shot mid-process signals", so once a
-# session has delivered this many matches over its whole life we disable it
-# and fall back to notify_on_complete, same as the strike-limit path.
+
+# Watch pattern rate limiting — PER SESSION. At most ONE watch-match notification
+# every WATCH_MIN_INTERVAL_SECONDS; a match inside the cooldown is dropped and counts
+# as one strike per window. After WATCH_STRIKE_LIMIT consecutive strike windows the
+# session's watch_patterns are permanently disabled and it falls back to
+# notify_on_complete semantics (one notification when the process exits).
+WATCH_MIN_INTERVAL_SECONDS = 15
+WATCH_STRIKE_LIMIT = 3
+
+# Lifetime cap — independent of the strike counter. A pattern recurring at a cadence
+# just above the cooldown never trips the strike limit yet forces a full-context agent
+# turn every time; watch_patterns is documented as "ONLY for rare one-shot signals",
+# so after this many delivered matches we disable it and fall back to notify_on_complete.
WATCH_LIFETIME_MAX_HITS = 8
-# Global circuit breaker — across all sessions. Secondary safety net so concurrent
+# Global circuit breaker across all sessions — secondary safety net so concurrent
# siblings can't collectively flood the user even when each is under its own cap.
WATCH_GLOBAL_MAX_PER_WINDOW = 15
WATCH_GLOBAL_WINDOW_SECONDS = 10
@@ -95,20 +69,13 @@ WATCH_GLOBAL_COOLDOWN_SECONDS = 30
# ---------------------------------------------------------------------------
-# systemd cgroup isolation for gateway-spawned local executors (#70716)
+# systemd cgroup isolation for gateway-spawned local executors
# ---------------------------------------------------------------------------
-# When Hermes runs as a systemd gateway with MemoryHigh/MemoryMax limits,
-# local background terminal commands inherit the gateway's cgroup. A
-# memory-heavy executor (Codex, tests, Node) can push the whole cgroup past
-# MemoryMax and trigger systemd-oomd to kill the ENTIRE gateway — taking down
-# the messaging control plane and silently losing the active turn.
-#
-# Wrapping the spawn in ``systemd-run --user --scope --unit=hermes-worker-<pid>``
-# places the worker in its own transient cgroup so an OOM in the worker kills
-# only the worker, not the gateway. We probe *once* whether
-# ``systemd-run --user --scope`` is actually usable (the binary can exist on
-# the PATH while the user D-Bus session is unavailable — common for system
-# services and containers), and cache the result for the process lifetime.
+# Under a systemd gateway with MemoryMax, local background commands inherit the
+# gateway's cgroup, so a memory-heavy executor can get the ENTIRE gateway killed by
+# systemd-oomd. Wrapping the spawn in ``systemd-run --user --scope`` gives the worker
+# its own transient cgroup. Usability is probed once (the binary can exist while the
+# user D-Bus session is absent — system services, containers) and cached.
_SYSTEMD_SCOPE_AVAILABLE: Optional[bool] = None
_SYSTEMD_SCOPE_PROBE_LOCK = threading.Lock()
@@ -120,28 +87,22 @@ _WORKER_MEMORY_MAX_CAP_BYTES = 4 * 1024 * 1024 * 1024
def _worker_memory_max_bytes() -> int:
- """Return a finite per-worker cgroup limit without widening host risk.
-
- The proposed local-memory-guard environment override is honored when it
- tightens the safe bound, so this isolation composes with PR #57121 instead
- of inventing a second knob. An oversized override cannot widen host risk.
- Otherwise retain the tighter of the gateway's current cgroup-v2
- ``memory.max`` and half of physical RAM, capped at 4 GiB. This keeps the
- sibling worker outside the gateway cgroup while ensuring the worker cannot
- consume memory up to the enclosing user slice or host limit.
+ """Finite per-worker cgroup limit that can never widen host risk.
+
+ ``TERMINAL_LOCAL_MEMORY_MAX_MB`` is honored only when it *tightens* the safe
+ bound (min of the gateway's cgroup-v2 ``memory.max`` and half of physical RAM,
+ capped at 4 GiB), so an oversized override cannot exceed the enclosing slice.
"""
override_bound: Optional[int] = None
override = os.getenv("TERMINAL_LOCAL_MEMORY_MAX_MB", "").strip()
if override:
- override_valid = False
try:
parsed = int(override) * 1024 * 1024
- if parsed >= _MIN_WORKER_MEMORY_MAX_BYTES:
- override_bound = parsed
- override_valid = True
except ValueError:
- pass
- if not override_valid:
+ parsed = -1
+ if parsed >= _MIN_WORKER_MEMORY_MAX_BYTES:
+ override_bound = parsed
+ else:
logger.warning(
"Ignoring invalid TERMINAL_LOCAL_MEMORY_MAX_MB=%r; "
"expected an integer representing at least %d MiB",
@@ -157,23 +118,18 @@ def _worker_memory_max_bytes() -> int:
raw_limit = (
Path("/sys/fs/cgroup") / relative / "memory.max"
).read_text(encoding="utf-8").strip()
- if raw_limit.isdigit():
- cgroup_limit = int(raw_limit)
- if cgroup_limit >= _MIN_WORKER_MEMORY_MAX_BYTES:
- candidates.append(cgroup_limit)
+ if raw_limit.isdigit() and int(raw_limit) >= _MIN_WORKER_MEMORY_MAX_BYTES:
+ candidates.append(int(raw_limit))
break
except (OSError, ValueError):
pass
try:
- physical_bytes = int(os.sysconf("SC_PHYS_PAGES")) * int(
- os.sysconf("SC_PAGE_SIZE")
- )
- physical_bound = min(
+ physical_bytes = int(os.sysconf("SC_PHYS_PAGES")) * int(os.sysconf("SC_PAGE_SIZE"))
+ candidates.append(min(
_WORKER_MEMORY_MAX_CAP_BYTES,
max(_MIN_WORKER_MEMORY_MAX_BYTES, physical_bytes // 2),
- )
- candidates.append(physical_bound)
+ ))
except (OSError, ValueError, TypeError):
pass
@@ -181,42 +137,58 @@ def _worker_memory_max_bytes() -> int:
return min(override_bound, safe_bound) if override_bound else safe_bound
-def _systemd_run_user_scope_available() -> bool:
- """Return True if ``systemd-run --user --scope`` can create a cgroup.
+def _systemd_scope_argv(binary: str, unit_name: str, *argv: str) -> List[str]:
+ """``systemd-run --user --scope`` command line shared by the probe and real spawns.
- Cached after the first probe. ``shutil.which`` alone is insufficient:
- in system-service deployments (and containers) the user D-Bus session
- bus that ``systemd-run --user`` needs may be absent even though the
- binary is on PATH, causing every spawn to fail with
- ``Failed to connect to user bus``. We do a cheap no-op probe
- (``systemd-run --user --scope --unit=… -- /bin/true``) and remember the
- outcome.
+ ``--collect`` makes the transient scope self-clean after exit; ``--unit`` gives it
+ a recognisable name for ``systemctl --user status`` / journalctl.
+ """
+ return [
+ binary, "--user", "--scope", "--quiet",
+ "--unit", unit_name,
+ "--collect",
+ "--property", "MemoryAccounting=yes",
+ "--property", f"MemoryMax={_worker_memory_max_bytes()}",
+ "--property", "OOMPolicy=kill",
+ "--",
+ *argv,
+ ]
+
+
+def _systemd_scope_cached() -> Optional[bool]:
+ """Cached probe verdict, or None when a (re)probe is due.
+
+ A True verdict is permanent; a False one expires after
+ ``_SYSTEMD_SCOPE_FAILURE_TTL_SECONDS`` so a transient D-Bus outage isn't sticky.
"""
- global _SYSTEMD_SCOPE_AVAILABLE, _SYSTEMD_SCOPE_PROBED_AT
cached = _SYSTEMD_SCOPE_AVAILABLE
- now = time.monotonic()
if cached is True:
return True
- if (
- cached is False
- and now - _SYSTEMD_SCOPE_PROBED_AT < _SYSTEMD_SCOPE_FAILURE_TTL_SECONDS
- ):
+ if cached is False and time.monotonic() - _SYSTEMD_SCOPE_PROBED_AT < _SYSTEMD_SCOPE_FAILURE_TTL_SECONDS:
return False
+ return None
+
+
+def _systemd_run_user_scope_available() -> bool:
+ """Return True if ``systemd-run --user --scope`` can create a cgroup.
+
+ ``shutil.which`` alone is insufficient: system-service deployments and containers
+ may lack the user D-Bus session bus even though the binary is on PATH, so every
+ spawn would fail with ``Failed to connect to user bus``. We run a cheap no-op
+ probe (``systemd-run --user --scope --unit=… -- /bin/true``) and cache the outcome.
+ """
+ global _SYSTEMD_SCOPE_AVAILABLE, _SYSTEMD_SCOPE_PROBED_AT
+ verdict = _systemd_scope_cached()
+ if verdict is not None:
+ return verdict
- # Double-checked locking keeps concurrent first-use spawns from observing
- # a temporary False while the definitive probe is still in flight. Such a
- # race would launch the losing workload back inside the gateway cgroup.
+ # Double-checked locking keeps concurrent first-use spawns from observing a
+ # temporary False while the definitive probe is still in flight — such a race
+ # would launch the losing workload back inside the gateway cgroup.
with _SYSTEMD_SCOPE_PROBE_LOCK:
- cached = _SYSTEMD_SCOPE_AVAILABLE
- now = time.monotonic()
- if cached is True:
- return True
- if (
- cached is False
- and now - _SYSTEMD_SCOPE_PROBED_AT
- < _SYSTEMD_SCOPE_FAILURE_TTL_SECONDS
- ):
- return False
+ verdict = _systemd_scope_cached()
+ if verdict is not None:
+ return verdict
available = False
if _IS_LINUX:
@@ -225,20 +197,10 @@ def _systemd_run_user_scope_available() -> bool:
binary = shutil.which("systemd-run")
if binary:
- # Probe: create a transient scope that immediately exits.
- # A unique unit avoids collisions; timeout bounds D-Bus.
+ # A unique unit avoids collisions; the timeout bounds D-Bus.
probe_unit = f"hermes-probe-scope-{os.getpid()}-{uuid.uuid4().hex[:8]}"
result = subprocess.run(
- [
- binary, "--user", "--scope", "--quiet",
- "--unit", probe_unit,
- "--collect",
- "--property", "MemoryAccounting=yes",
- "--property", f"MemoryMax={_worker_memory_max_bytes()}",
- "--property", "OOMPolicy=kill",
- "--",
- "/bin/true",
- ],
+ _systemd_scope_argv(binary, probe_unit, "/bin/true"),
capture_output=True,
timeout=3,
)
@@ -247,9 +209,7 @@ def _systemd_run_user_scope_available() -> bool:
logger.debug(
"systemd-run --user --scope probe failed (rc=%s): %s",
result.returncode,
- (result.stderr or b"").decode(
- "utf-8", "replace"
- ).strip(),
+ (result.stderr or b"").decode("utf-8", "replace").strip(),
)
except Exception as exc:
logger.debug("systemd-run --user --scope probe error: %s", exc)
@@ -260,13 +220,12 @@ def _systemd_run_user_scope_available() -> bool:
def _is_supervised_gateway_process() -> bool:
- """Return whether this process is in a supervised Hermes gateway runtime.
+ """Whether this process is the live, supervised Hermes gateway itself.
- Both supervisor markers and ``_HERMES_GATEWAY`` are inherited by every
- descendant, and importing ``gateway.run`` also sets the latter. Require
- this process to own the live gateway PID file as well. That keeps transient
- systemd scopes limited to the gateway itself instead of terminal children
- or unrelated interactive CLIs in the same supervised process tree.
+ Supervisor markers and ``_HERMES_GATEWAY`` are inherited by every descendant
+ (and importing ``gateway.run`` sets the latter), so also require ownership of
+ the live gateway PID file — transient scopes are for the gateway, not terminal
+ children or unrelated CLIs in the same supervised tree.
"""
if os.environ.get("_HERMES_GATEWAY") != "1":
return False
@@ -288,13 +247,8 @@ def _build_systemd_scope_argv(
shell_argv: List[str],
unit_suffix: str,
) -> List[str]:
- """Wrap *shell_argv* in a ``systemd-run --user --scope`` invocation.
-
- The resulting cgroup gets its own memory accounting so an OOM in the
- worker does not kill the gateway cgroup (#70716). ``--collect`` makes
- the transient scope self-clean after exit; ``--unit`` gives it a
- recognisable name for ``systemctl --user status`` / journalctl.
- """
+ """Wrap *shell_argv* in a ``systemd-run --user --scope`` invocation with its own
+ memory accounting, so an OOM in the worker cannot kill the gateway cgroup."""
import shutil
binary = shutil.which("systemd-run")
@@ -302,38 +256,19 @@ def _build_systemd_scope_argv(
# Caller should have checked _systemd_run_user_scope_available();
# guard anyway so we never pass None into Popen.
return shell_argv
- unit_name = f"hermes-worker-{unit_suffix}"
- memory_max = _worker_memory_max_bytes()
- return [
- binary,
- "--user",
- "--scope",
- "--quiet",
- "--unit",
- unit_name,
- "--collect",
- "--property",
- "MemoryAccounting=yes",
- "--property",
- f"MemoryMax={memory_max}",
- "--property",
- "OOMPolicy=kill",
- "--",
- *shell_argv,
- ]
+ return _systemd_scope_argv(binary, f"hermes-worker-{unit_suffix}", *shell_argv)
def _stop_systemd_unit(unit_name: str) -> bool:
"""Stop a transient systemd user scope by unit name.
- This reaps the *entire* cgroup — catching double-forked descendants that
- survive a plain PID signal because they were reparented to init inside the
- scope (issue #70716, reviewer gap #2). ``systemctl --user stop`` sends
- SIGTERM to every process in the unit's cgroup and escalates to SIGKILL
- after the unit's ``TimeoutStopSec``.
+ Reaps the *entire* cgroup — catching double-forked descendants that survive a
+ plain PID signal because they were reparented to init inside the scope.
+ ``systemctl --user stop`` SIGTERMs every process in the cgroup and escalates to
+ SIGKILL after ``TimeoutStopSec``.
- Returns True if the unit was successfully stopped (or was already gone),
- False if ``systemctl`` is unavailable or the stop command failed.
+ Returns True if the unit was stopped (or was already gone), False if
+ ``systemctl`` is unavailable or the stop command failed.
"""
import shutil
@@ -383,10 +318,9 @@ class ProcessSession:
id: str # Unique session ID ("proc_xxxxxxxxxxxx")
command: str # Original command string
task_id: str = "" # Task/sandbox isolation key
- owner_task_id: str = "" # RAW spawning task id (e.g. subagent "sa-...");
- # task_id is the CONTAINER key and may be collapsed
- # to "default"/session key by _resolve_container_task_id,
- # so ownership checks must use this field (#child-notify)
+ owner_task_id: str = "" # RAW spawning task id (e.g. "sa-..."); task_id is the
+ # CONTAINER key (may be collapsed by _resolve_container_task_id)
+ # so ownership checks must use this field
session_key: str = "" # Gateway session key (for reset protection)
pid: Optional[int] = None # OS process ID
process: Optional[subprocess.Popen] = None # Popen handle (local only)
@@ -411,24 +345,17 @@ class ProcessSession:
watcher_thread_id: str = ""
watcher_message_id: str = "" # Triggering message id — reply anchor for topic routing
watcher_interval: int = 0 # 0 = no watcher configured
- # Session-db id of the conversation that spawned this process. Lets the
- # gateway's completion pre-flight (_classify_completion_target) drop
- # notifications whose spawning session was closed at an explicit user
- # boundary (/new), instead of injecting them into the chat's NEW session.
+ # Session-db id of the spawning conversation; lets the gateway drop completions
+ # whose session was closed at a user boundary (/new) instead of injecting them
+ # into the chat's NEW session.
parent_session_id: str = ""
notify_on_complete: bool = False # Queue agent notification on exit
- # Watch patterns — trigger agent notification when output matches any pattern
watch_patterns: List[str] = field(default_factory=list)
_watch_hits: int = field(default=0, repr=False) # total matches delivered
_watch_suppressed: int = field(default=0, repr=False) # matches dropped by rate limit
_watch_disabled: bool = field(default=False, repr=False) # permanently killed after strike limit
- # Per-session rate limit state: at most one match every WATCH_MIN_INTERVAL_SECONDS.
- # When an emission happens, _watch_cooldown_until is set to now + interval and
- # _watch_strike_candidate becomes True. The next match to arrive before that
- # deadline counts as one strike (regardless of how many matches were dropped in
- # between — a strike is a window, not a match). After WATCH_STRIKE_LIMIT strikes
- # in a row, watch_patterns is disabled and the session promotes to
- # notify_on_complete.
+ # Per-session rate-limit state (see WATCH_* constants). A strike is a WINDOW with
+ # drops, not a dropped match.
_watch_last_emit_at: float = field(default=0.0, repr=False)
_watch_cooldown_until: float = field(default=0.0, repr=False)
_watch_strike_candidate: bool = field(default=False, repr=False)
@@ -438,15 +365,35 @@ class ProcessSession:
_reader_thread: Optional[threading.Thread] = field(default=None, repr=False)
_pty: Any = field(default=None, repr=False) # ptyprocess handle (when use_pty=True)
+ def append_output(self, text: str) -> None:
+ """Append to the rolling output buffer under the session lock, keeping the tail."""
+ with self._lock:
+ self.output_buffer += text
+ if len(self.output_buffer) > self.max_output_chars:
+ self.output_buffer = self.output_buffer[-self.max_output_chars:]
+
+
+# Session fields persisted verbatim in the crash-recovery checkpoint (plus
+# ``session_id``; ``command`` is redacted and ``owner_task_id`` defaulted on write).
+_CHECKPOINT_FIELDS = (
+ "command", "pid", "pid_scope", "host_start_time", "systemd_unit", "cwd",
+ "started_at", "task_id", "owner_task_id", "session_key",
+ "watcher_platform", "watcher_chat_id", "watcher_user_id", "watcher_user_name",
+ "watcher_thread_id", "watcher_message_id", "watcher_interval",
+ "parent_session_id", "notify_on_complete", "watch_patterns",
+)
+_CHECKPOINT_DEFAULTS = {
+ f.name: ([] if f.name == "watch_patterns" else f.default)
+ for f in ProcessSession.__dataclass_fields__.values()
+ if f.name in _CHECKPOINT_FIELDS
+}
+
class ProcessRegistry:
- """
- In-memory registry of running and finished background processes.
+ """In-memory registry of running and finished background processes.
- Thread-safe. Accessed from:
- - Executor threads (terminal_tool, process tool handlers)
- - Gateway asyncio loop (watcher tasks, session reset checks)
- - Cleanup thread (sandbox reaping coordination)
+ Thread-safe: accessed from executor threads (terminal_tool, process handlers),
+ the gateway asyncio loop (watchers, reset checks) and the cleanup thread.
"""
_SHELL_NOISE_SUBSTRINGS = (
@@ -465,52 +412,38 @@ class ProcessRegistry:
# Side-channel for check_interval watchers (gateway reads after agent run)
self.pending_watchers: List[Dict[str, Any]] = []
- # Notification queue — unified queue for all background process events.
- # Completion notifications (notify_on_complete) and watch pattern matches
- # both land here, distinguished by "type" field. CLI process_loop and
- # gateway drain this after each agent turn to auto-trigger new turns.
+ # Unified queue for all background events (completion, watch_match,
+ # async_delegation...; distinguished by "type"). CLI process_loop and the
+ # gateway drain it after each agent turn to auto-trigger new turns.
import queue as _queue_mod
self.completion_queue: _queue_mod.Queue = _queue_mod.Queue()
- # Rehydrate durable delegation completions only at registry startup.
- # Consumers still inject them as fresh turns through this existing rail.
+ # Rehydrate durable delegation completions once, at registry startup.
try:
from tools.async_delegation import restore_undelivered_completions
restore_undelivered_completions(self.completion_queue)
except Exception as exc:
logger.warning("Could not restore async delegation completions: %s", exc)
- # Track sessions whose completion was already consumed by the agent
- # via wait/log. Drain loops AND gateway/tui watchers skip notifications
- # for these — a blocking wait() or a full read_log() means the agent
- # has the output in hand and is acting on it this turn.
+ # Sessions whose completion the agent already consumed via wait()/read_log()
+ # — it has the output in hand, so drain loops AND gateway/tui watchers skip.
self._completion_consumed: set = set()
-
- # Track sessions the agent merely *observed* exited via poll(). poll()
- # is a read-only status check, so it does NOT mark _completion_consumed
- # (that would let a status check suppress the gateway/tui watcher's
- # autonomous delivery turn — #10156). But on the CLI the poll result
- # is returned inline in the same turn, so the idle/post-turn drain must
- # still skip the queued completion to avoid a duplicate [SYSTEM: ...]
- # injection (the bug #8228 originally fixed). drain_notifications()
- # consults this set; the gateway/tui watchers deliberately do NOT.
+ # Sessions merely *observed* exited via poll(). poll() is read-only and must
+ # NOT mark consumed (a status check would suppress the watcher's autonomous
+ # delivery turn), but on the CLI the poll result is inline in the same turn,
+ # so drain_notifications() skips these to avoid a duplicate [SYSTEM: ...];
+ # gateway/tui watchers deliberately ignore this set.
self._poll_observed: set = set()
- # Global watch-match circuit breaker — across all sessions.
- # Prevents sibling processes from collectively flooding the user even
- # when each stays under its own per-session cap.
+ # Global watch-match circuit breaker across all sessions.
self._global_watch_lock = threading.Lock()
self._global_watch_window_start: float = 0.0
self._global_watch_window_hits: int = 0
self._global_watch_tripped_until: float = 0.0
self._global_watch_suppressed_during_trip: int = 0
- # Live-output sink set by a driver (e.g. the desktop gateway): called from
- # reader threads with (session, chunk) to stream output to a UI in
- # real time, instead of polling the output tail.
+ # Driver-installed sinks (desktop gateway): on_output(session, chunk) streams
+ # live output from reader threads; on_close(session_or_none, process_id) drops
+ # a read-only terminal tab without killing the process.
self.on_output = None
- # Close-view sink set by a driver (desktop gateway): called with
- # (session_or_none, process_id) when the agent asks to close a read-only
- # terminal tab. Distinct from kill — the process keeps running; only the
- # UI view is dropped (the user can reopen it from the status stack).
self.on_close = None
@staticmethod
@@ -533,30 +466,17 @@ class ProcessRegistry:
pass
def _check_watch_patterns(self, session: ProcessSession, new_text: str) -> None:
- """Scan new output for watch patterns and queue notifications.
-
- Called from reader threads with new_text being the freshly-read chunk.
-
- Per-session rate limit: at most ONE watch-match notification per
- WATCH_MIN_INTERVAL_SECONDS. Any match arriving inside the cooldown
- window is dropped and counts as ONE strike for that window. After
- WATCH_STRIKE_LIMIT consecutive strike windows, watch_patterns is
- disabled for this session and the session is promoted to
- notify_on_complete semantics — one notification when the process
- actually exits, no more mid-process spam.
-
- Independently, WATCH_LIFETIME_MAX_HITS caps the total number of
- matches ever delivered for a session, so a pattern that keeps
- recurring at a cadence just above the cooldown (e.g. a service
- restarted repeatedly over a day) still gets disabled instead of
- forcing a full-context agent turn indefinitely.
+ """Scan a freshly-read chunk for watch patterns and queue notifications.
+
+ Rate limiting per session (see the WATCH_* constants): one match per cooldown
+ window, a match inside the window is one strike, WATCH_STRIKE_LIMIT
+ consecutive strikes or WATCH_LIFETIME_MAX_HITS total deliveries disable
+ watching and promote the session to notify_on_complete.
"""
if not session.watch_patterns or session._watch_disabled:
return
- # Suppress-after-exit: once the reader loop has declared the process
- # exited, any late chunk we still see is post-exit noise. Dropping these
- # prevents the "stale notifications delivered minutes after the process
- # ended" spam when completion_queue consumers run async.
+ # Late chunks after the reader declared exit are post-exit noise; dropping them
+ # avoids stale notifications minutes after the process ended.
if session.exited:
return
@@ -578,10 +498,8 @@ class ProcessRegistry:
should_disable = False
lifetime_exhausted = False
with session._lock:
- # Case 1: still inside the cooldown from the last emission.
- # Count this as a strike for the current window (only once per window)
- # and drop the event. If we've hit the strike limit, disable watch
- # and promote to notify_on_complete.
+ # Case 1: inside the cooldown — drop, count one strike per window, and
+ # disable + promote once the strike limit is hit.
if session._watch_cooldown_until and now < session._watch_cooldown_until:
session._watch_suppressed += len(matched_lines)
if not session._watch_strike_candidate:
@@ -596,15 +514,9 @@ class ProcessRegistry:
should_disable = True
return_early = True
else:
- # Case 2: cooldown has expired.
- # Decide whether this window was a "clean" one (no drops) or a
- # strike window. If no strike candidate was set during the prior
- # cooldown, reset the consecutive-strike counter — we're back to
- # healthy emission cadence.
- if (
- session._watch_cooldown_until
- and not session._watch_strike_candidate
- ):
+ # Case 2: cooldown expired. A prior window with no drops resets the
+ # consecutive-strike counter (healthy cadence again).
+ if session._watch_cooldown_until and not session._watch_strike_candidate:
session._watch_consecutive_strikes = 0
session._watch_strike_candidate = False
@@ -615,9 +527,7 @@ class ProcessRegistry:
suppressed = session._watch_suppressed
session._watch_suppressed = 0
return_early = False
- # Lifetime cap: this match is delivered (it already earned it),
- # but disable further ones regardless of how cleanly spaced
- # they are — see WATCH_LIFETIME_MAX_HITS above.
+ # Lifetime cap: this match is still delivered, but no further ones.
lifetime_exhausted = session._watch_hits >= WATCH_LIFETIME_MAX_HITS
if lifetime_exhausted:
session._watch_disabled = True
@@ -625,22 +535,11 @@ class ProcessRegistry:
if return_early:
if should_disable:
- # Emit exactly one "watch disabled, falling back to notify_on_complete"
- # summary event so the agent/user sees why things went quiet.
+ # Exactly one summary so the agent/user sees why things went quiet.
self.completion_queue.put({
- "session_id": session.id,
- "session_key": session.session_key,
- "task_id": session.task_id,
- "owner_task_id": session.owner_task_id or session.task_id,
- "command": session.command,
+ **self._watch_event_base(session),
"type": "watch_disabled",
"suppressed": session._watch_suppressed,
- "platform": session.watcher_platform,
- "chat_id": session.watcher_chat_id,
- "user_id": session.watcher_user_id,
- "user_name": session.watcher_user_name,
- "thread_id": session.watcher_thread_id,
- "message_id": session.watcher_message_id,
"message": (
f"Watch patterns disabled for process {session.id} — "
f"{WATCH_STRIKE_LIMIT} consecutive rate-limit windows triggered "
@@ -656,76 +555,81 @@ class ProcessRegistry:
if len(output) > 2000:
output = output[:2000] + "\n...(truncated)"
- # Global circuit breaker — across all sessions (secondary safety net).
if not self._global_watch_admit(now):
+ # Even when the breaker drops the final match, still explain the silence.
if lifetime_exhausted:
- # The final match was dropped by the global breaker, but the
- # session is already disabled — still tell the user why things
- # went quiet (the strike path emits its summary unconditionally
- # too).
self._emit_lifetime_watch_disabled(session)
return
notification = {
- "session_id": session.id,
- "session_key": session.session_key,
- "task_id": session.task_id,
- "owner_task_id": session.owner_task_id or session.task_id,
- "command": session.command,
+ **self._watch_event_base(session),
"type": "watch_match",
"pattern": matched_pattern,
"output": output,
"suppressed": suppressed,
- "platform": session.watcher_platform,
- "chat_id": session.watcher_chat_id,
- "user_id": session.watcher_user_id,
- "user_name": session.watcher_user_name,
- "thread_id": session.watcher_thread_id,
- "message_id": session.watcher_message_id,
}
_redact_process_result(notification)
self.completion_queue.put(notification)
if lifetime_exhausted:
- # Same "why things went quiet" summary as the strike-limit path,
- # queued right after the final delivered match.
self._emit_lifetime_watch_disabled(session)
def _emit_lifetime_watch_disabled(self, session: ProcessSession) -> None:
- """Queue the watch_disabled summary for the lifetime-cap path (#93513)."""
+ """Queue the watch_disabled summary for the lifetime-cap path."""
self.completion_queue.put({
+ **self._watch_event_base(session),
+ "type": "watch_disabled",
+ "suppressed": 0,
+ "message": (
+ f"Watch patterns disabled for process {session.id} — "
+ f"reached the lifetime cap of {WATCH_LIFETIME_MAX_HITS} delivered "
+ f"matches. Falling back to notify_on_complete semantics; you'll get "
+ f"exactly one notification when the process exits."
+ ),
+ })
+
+ @staticmethod
+ def _watch_event_base(session: ProcessSession) -> dict:
+ """Session identity + watcher routing fields shared by every watch event."""
+ return {
"session_id": session.id,
"session_key": session.session_key,
"task_id": session.task_id,
"owner_task_id": session.owner_task_id or session.task_id,
"command": session.command,
- "type": "watch_disabled",
- "suppressed": 0,
"platform": session.watcher_platform,
"chat_id": session.watcher_chat_id,
"user_id": session.watcher_user_id,
"user_name": session.watcher_user_name,
"thread_id": session.watcher_thread_id,
"message_id": session.watcher_message_id,
- "message": (
- f"Watch patterns disabled for process {session.id} — "
- f"reached the lifetime cap of {WATCH_LIFETIME_MAX_HITS} delivered "
- f"matches. Falling back to notify_on_complete semantics; you'll get "
- f"exactly one notification when the process exits."
- ),
- })
+ }
+
+ @staticmethod
+ def _global_watch_event(type_: str, message: str, **extra) -> dict:
+ """Unaddressed (all-sessions) watch breaker event."""
+ return {
+ "session_id": "",
+ "session_key": "",
+ "command": "",
+ "type": type_,
+ **extra,
+ "message": message,
+ "platform": "",
+ "chat_id": "",
+ "user_id": "",
+ "user_name": "",
+ "thread_id": "",
+ }
def _global_watch_admit(self, now: float) -> bool:
- """Return True if this watch_match event is allowed through the global breaker.
-
- Semantics:
- - If we're currently in a cooldown period, drop the event and count it.
- - Otherwise, slide the rolling window and check the global cap.
- - If the cap is exceeded, trip the breaker for WATCH_GLOBAL_COOLDOWN_SECONDS
- and emit ONE summary event so the agent/user sees "N notifications were
- suppressed" instead of getting them individually.
- - When the cooldown ends, emit a release summary and reset counters.
+ """True if this watch_match may pass the global breaker.
+
+ In cooldown: drop and count. Otherwise slide the rolling window; exceeding
+ the cap trips the breaker for WATCH_GLOBAL_COOLDOWN_SECONDS with ONE
+ "tripped" summary, and the cooldown's end emits ONE "released" summary.
"""
+ release_msg = None
with self._global_watch_lock:
# Handle cooldown expiry first so we can emit the release summary.
if self._global_watch_tripped_until and now >= self._global_watch_tripped_until:
@@ -735,27 +639,13 @@ class ProcessRegistry:
self._global_watch_window_start = now
self._global_watch_window_hits = 0
if suppressed > 0:
- # Queue a summary event outside the lock (below).
- release_msg = {
- "session_id": "",
- "session_key": "",
- "command": "",
- "type": "watch_overflow_released",
- "suppressed": suppressed,
- "message": (
- f"Watch-pattern notifications resumed. "
- f"{suppressed} match event(s) were suppressed during the flood."
- ),
- "platform": "",
- "chat_id": "",
- "user_id": "",
- "user_name": "",
- "thread_id": "",
- }
- else:
- release_msg = None
- else:
- release_msg = None
+ # Queued outside the lock (below).
+ release_msg = self._global_watch_event(
+ "watch_overflow_released",
+ f"Watch-pattern notifications resumed. "
+ f"{suppressed} match event(s) were suppressed during the flood.",
+ suppressed=suppressed,
+ )
# Still in cooldown — drop and count.
if self._global_watch_tripped_until and now < self._global_watch_tripped_until:
@@ -783,23 +673,13 @@ class ProcessRegistry:
if release_msg is not None:
self.completion_queue.put(release_msg)
if trip_now is not None:
- self.completion_queue.put({
- "session_id": "",
- "session_key": "",
- "command": "",
- "type": "watch_overflow_tripped",
- "message": (
- f"Watch-pattern overflow: >{WATCH_GLOBAL_MAX_PER_WINDOW} "
- f"notifications in {WATCH_GLOBAL_WINDOW_SECONDS}s across all processes. "
- f"Suppressing further watch_match events for "
- f"{WATCH_GLOBAL_COOLDOWN_SECONDS}s."
- ),
- "platform": "",
- "chat_id": "",
- "user_id": "",
- "user_name": "",
- "thread_id": "",
- })
+ self.completion_queue.put(self._global_watch_event(
+ "watch_overflow_tripped",
+ f"Watch-pattern overflow: >{WATCH_GLOBAL_MAX_PER_WINDOW} "
+ f"notifications in {WATCH_GLOBAL_WINDOW_SECONDS}s across all processes. "
+ f"Suppressing further watch_match events for "
+ f"{WATCH_GLOBAL_COOLDOWN_SECONDS}s.",
+ ))
return admit
@staticmethod
@@ -827,16 +707,10 @@ class ProcessRegistry:
def _host_pid_is_ours(cls, pid: Optional[int], expected_start: Optional[int]) -> bool:
"""True only if ``pid`` is alive AND still the process we spawned.
- The kernel recycles PID/PGID numbers once a process exits and is reaped,
- so a stored PID can later name an *unrelated* process — observed in the
- wild as a recycled number landing on a desktop browser's session leader,
- which our tree-kill then SIGTERMs (Firefox dying at irregular intervals).
- We compare the kernel start time captured at spawn against the live one;
- a mismatch means the number was recycled and must never be signalled.
-
- When no baseline was captured (legacy checkpoints, or platforms without
- ``/proc``) we degrade to a bare liveness check rather than refusing to
- act, preserving prior best-effort behaviour.
+ The kernel recycles PIDs, so a stored number can later name an unrelated
+ process (seen in the wild: a browser's session leader tree-killed). The kernel
+ start time captured at spawn must match the live one; with no baseline
+ (legacy checkpoints, no ``/proc``) degrade to a bare liveness check.
"""
if not cls._is_host_pid_alive(pid):
return False
@@ -849,9 +723,8 @@ class ProcessRegistry:
if session is None or session.exited or not session.detached or session.pid_scope != "host":
return session
- # Identity-aware liveness: a recycled PID (alive but a different process
- # than we spawned) must be treated as "our process exited", so it is
- # moved to finished and can never be tree-killed by a later kill().
+ # A recycled PID (alive but not ours) counts as "our process exited" so a
+ # later kill() can never tree-kill the stranger.
if self._host_pid_is_ours(session.pid, session.host_start_time):
return session
@@ -881,20 +754,24 @@ class ProcessRegistry:
return False
@staticmethod
- def _daemon_term_grace_seconds() -> float:
- """Grace window (s) between SIGTERM and escalated SIGKILL.
+ def _config_value(section: str, key: str, fallback):
+ """``config.yaml`` value for ``section.key``, else the DEFAULT_CONFIG value.
- Read from ``terminal.daemon_term_grace_seconds`` in config.yaml; floored
- at 0 (0 disables escalation). Falls back to the DEFAULT_CONFIG value if
- config is unreadable, so callers always get a sane number.
+ Raises if config is unreadable; callers wrap with their own hard fallback so
+ registry code paths never crash on a broken config file.
"""
+ from hermes_cli.config import DEFAULT_CONFIG, cfg_get, read_raw_config
+
+ val = cfg_get(read_raw_config(), section, key)
+ return DEFAULT_CONFIG[section][key] if val is None else val
+
+ @staticmethod
+ def _daemon_term_grace_seconds() -> float:
+ """Grace window (s) between SIGTERM and escalated SIGKILL, floored at 0
+ (0 disables escalation). ``terminal.daemon_term_grace_seconds``; 2.0 if
+ config is unreadable."""
try:
- from hermes_cli.config import read_raw_config, cfg_get, DEFAULT_CONFIG
- cfg = read_raw_config()
- val = cfg_get(cfg, "terminal", "daemon_term_grace_seconds")
- if val is None:
- val = DEFAULT_CONFIG["terminal"]["daemon_term_grace_seconds"]
- return max(float(val), 0.0)
+ return max(float(ProcessRegistry._config_value("terminal", "daemon_term_grace_seconds", 2.0)), 0.0)
except Exception:
return 2.0
@@ -902,54 +779,34 @@ class ProcessRegistry:
def _terminate_host_pid(cls, pid: int, expected_start: Optional[int] = None) -> None:
"""Terminate a host-visible PID and its descendants.
- ``expected_start`` is the kernel start time captured when we spawned the
- process. When provided, it is re-validated against the live PID before
- any signal is sent; a mismatch (or a dead PID) means the number was
- recycled onto an unrelated process and we refuse to touch it, so a stale
- background-session PID can never tree-kill a browser or other stranger.
-
- POSIX: walks the process tree with ``psutil`` and SIGTERMs
- children before the parent so subprocess trees (e.g. Chromium
- renderers/GPU helpers spawned by an ``agent-browser`` daemon)
- don't get reparented to init and survive cleanup. After a bounded
- grace window (``terminal.daemon_term_grace_seconds``) any tree member
- that ignored SIGTERM — a daemon stalled in its signal handler — is
- escalated to SIGKILL so it can't leak indefinitely. Set the grace to
- 0 to disable escalation (SIGTERM only).
-
- Windows: shells out to ``taskkill /PID <pid> /T /F``. This is
- the documented Microsoft primitive for tree-kill and matches the
- existing convention in ``gateway.status.terminate_pid``. ``/F`` is
- already a hard kill, so no separate escalation step is needed. We
- can't reuse the POSIX psutil path on Windows because:
-
- 1. Windows doesn't maintain a Unix-style process tree —
- ``psutil.Process.children(recursive=True)`` walks PPID
- links that go stale when intermediate processes exit, so
- enumeration is best-effort and misses orphaned descendants.
- 2. ``psutil.Process.terminate()`` on Windows is
- ``TerminateProcess()`` which kills only the target handle
- and is a hard kill — there is no Windows equivalent of a
- SIGTERM that cascades through a process group. (See the
- warning in ``gateway/status.py::terminate_pid``: "os.kill
- with SIGTERM is not equivalent to a tree-killing hard stop"
- on Windows.) Headless Chromium has no GUI window, so the
- softer ``taskkill /T`` without ``/F`` won't reach it either.
-
- ``psutil`` is a hard dependency (see ``pyproject.toml``); the
- bare-``os.kill`` fallback covers OSError / PermissionError on
- POSIX and a missing ``taskkill.exe`` on Windows (effectively
- unreachable on real Windows installs, but cheap insurance).
+ ``expected_start`` (kernel start time at spawn) is re-validated first; a
+ mismatch or dead PID means the number was recycled onto a stranger and we
+ refuse to touch it — a leaked orphan beats tree-killing someone's browser.
+
+ POSIX: psutil walks the tree and SIGTERMs children before the parent so
+ subprocess trees (Chromium renderers under an agent-browser daemon) aren't
+ reparented to init and survive. After ``terminal.daemon_term_grace_seconds``
+ any survivor is SIGKILLed (0 disables escalation).
+
+ Windows: ``taskkill /PID <pid> /T /F`` (same primitive as
+ ``gateway.status.terminate_pid``; ``/F`` is already a hard kill). The psutil
+ path is unusable there: PPID links go stale so ``children(recursive=True)``
+ misses orphans, and ``terminate()`` is ``TerminateProcess()`` on one handle —
+ nothing cascades like a SIGTERM to a process group. The bare ``os.kill``
+ fallback covers OSError/PermissionError and a missing ``taskkill.exe``.
"""
if expected_start is not None and not cls._host_pid_is_ours(pid, expected_start):
- # PID was recycled (start time changed) or is gone — never signal a
- # stranger. A leaked orphan is strictly preferable to killing e.g.
- # a browser whose session leader reused this dead session's PID.
logger.warning(
"Refusing to terminate host pid %d: start-time mismatch — "
"PID was recycled onto an unrelated process.", pid,
)
return
+ def _sigterm_quietly():
+ try:
+ os.kill(pid, signal.SIGTERM)
+ except (OSError, ProcessLookupError, PermissionError):
+ pass
+
if _IS_WINDOWS:
try:
subprocess.run(
@@ -961,10 +818,7 @@ class ProcessRegistry:
stdin=subprocess.DEVNULL,
)
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
- try:
- os.kill(pid, signal.SIGTERM)
- except (OSError, ProcessLookupError, PermissionError):
- pass
+ _sigterm_quietly()
return
import psutil
@@ -973,10 +827,7 @@ class ProcessRegistry:
except psutil.NoSuchProcess:
return
except (OSError, PermissionError):
- try:
- os.kill(pid, signal.SIGTERM)
- except (OSError, ProcessLookupError, PermissionError):
- pass
+ _sigterm_quietly()
return
# Snapshot the whole tree (children before parent) and SIGTERM each.
@@ -989,24 +840,17 @@ class ProcessRegistry:
for proc in targets:
try:
proc.terminate()
- except psutil.NoSuchProcess:
- pass
- except (psutil.AccessDenied, OSError):
+ except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
pass
- # Escalate to SIGKILL for anything that ignored SIGTERM within the
- # grace window — a daemon stalled in its signal handler would otherwise
- # leak indefinitely.
+ # Escalate to SIGKILL for anything that ignored SIGTERM within the grace
+ # window. We deliberately do NOT trust ``psutil.wait_procs``' gone/alive
+ # partition: it reaps via ``Process.wait()`` and mis-partitions across
+ # zombie transitions in a parent/child tree, leaving survivors un-killed.
+ # A direct liveness re-probe of every target is deterministic.
grace = cls._daemon_term_grace_seconds()
if grace <= 0:
return
- # Sleep out the grace window, then independently re-probe every target
- # and SIGKILL any survivor. We deliberately do NOT trust
- # ``psutil.wait_procs``'s gone/alive partition here: it reaps via
- # ``Process.wait()`` and can mis-partition when a target transitions
- # through a zombie state or when reaping is racy across a parent/child
- # tree, which left survivors un-killed. A direct liveness re-probe is
- # deterministic.
deadline = time.monotonic() + grace
while time.monotonic() < deadline:
if not any(cls._proc_alive(_p) for _p in targets):
@@ -1021,9 +865,7 @@ class ProcessRegistry:
"Escalated to SIGKILL for pid %d (ignored SIGTERM within "
"%.1fs grace)", proc.pid, grace,
)
- except psutil.NoSuchProcess:
- pass
- except (psutil.AccessDenied, OSError):
+ except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):
pass
# ----- Spawn -----
@@ -1041,6 +883,70 @@ class ProcessRegistry:
logger.debug("Could not resolve environment temp dir: %s", exc)
return "/tmp"
+ def _scope_argv(self, session: ProcessSession, argv: List[str], unit_suffix: str, label: str):
+ """Wrap *argv* in a transient systemd scope when we are the supervised gateway.
+
+ Returns ``(argv, scoped)``. A scoped worker gets its own cgroup so an OOM kills
+ only the worker, not the gateway (and its messaging control plane).
+ """
+ in_supervised_gateway = _IS_LINUX and _is_supervised_gateway_process()
+ if in_supervised_gateway and _systemd_run_user_scope_available():
+ session.systemd_unit = f"hermes-worker-{unit_suffix}.scope"
+ return _build_systemd_scope_argv(argv, unit_suffix=unit_suffix), True
+ if in_supervised_gateway:
+ # Under a supervisor but no private cgroup: an OOM in the worker can
+ # still take the whole gateway down.
+ logger.debug(
+ "%s background executor not isolated in a systemd scope "
+ "(systemd-run --user unavailable); worker shares the gateway cgroup.",
+ label,
+ )
+ return argv, False
+
+ def _track_started(self, session: ProcessSession, reader_target, reader_name: str) -> None:
+ """Start the output reader thread, register the session and checkpoint it."""
+ reader = threading.Thread(
+ target=reader_target, args=(session,), daemon=True, name=reader_name,
+ )
+ session._reader_thread = reader
+ reader.start()
+ with self._lock:
+ self._prune_if_needed()
+ self._running[session.id] = session
+ self._write_checkpoint()
+
+ def _spawn_local_pty(self, session: ProcessSession, safe_command: str, env_vars: dict) -> ProcessSession:
+ """PTY spawn for interactive CLI tools (Codex, Claude Code, REPLs).
+
+ Raises ImportError when no PTY backend is installed and re-raises any spawn
+ failure; ``spawn_local`` falls back to pipe mode in both cases.
+ """
+ if _IS_WINDOWS:
+ from winpty import PtyProcess as _PtyProcessCls
+ else:
+ from ptyprocess import PtyProcess as _PtyProcessCls
+ user_shell = _find_shell()
+ pty_env = _sanitize_subprocess_env(os.environ, env_vars)
+ pty_env["PYTHONUNBUFFERED"] = "1"
+ # A PTY is a real TTY, so pager-happy tools (git log/diff, man) WILL page and
+ # hang waiting for `q` — default them to cat, honoring any pager the user set.
+ pty_env.setdefault("GIT_PAGER", "cat")
+ pty_env.setdefault("PAGER", "cat")
+ pty_argv, _ = self._scope_argv(
+ session, [user_shell, "-lic", f"set +m; {safe_command}"], session.id, "PTY",
+ )
+ pty_proc = _PtyProcessCls.spawn(
+ pty_argv,
+ cwd=session.cwd,
+ env=pty_env,
+ dimensions=(30, 120),
+ )
+ session.pid = pty_proc.pid
+ session.host_start_time = self._safe_host_start_time(session.pid)
+ session._pty = pty_proc
+ self._track_started(session, self._pty_reader_loop, f"proc-pty-reader-{session.id}")
+ return session
+
def spawn_local(
self,
command: str,
@@ -1051,21 +957,15 @@ class ProcessRegistry:
use_pty: bool = False,
owner_task_id: str = "",
) -> ProcessSession:
- """
- Spawn a background process locally.
-
- Only for TERMINAL_ENV=local. Other backends use spawn_via_env().
+ """Spawn a background process locally (TERMINAL_ENV=local only; other
+ backends use spawn_via_env()).
- Args:
- use_pty: If True, use a pseudo-terminal via ptyprocess for interactive
- CLI tools (Codex, Claude Code, Python REPL). Falls back to
- subprocess.Popen if ptyprocess is not installed.
+ ``use_pty`` requests a pseudo-terminal via ptyprocess/pywinpty for interactive
+ CLI tools; it falls back to a plain pipe when that is unavailable or fails.
"""
- # Guard against the `A && B &` subshell-wait trap (issue #68915).
- # Bash parses ``A && B &`` as ``(A && B) &`` — a subshell that holds
- # the stdout pipe open forever when B is a long-running server.
- # The rewriter wraps it to ``A && { B & }`` so no subshell fork.
- # Lazy import avoids circular dependency (terminal_tool imports this).
+ # Bash parses ``A && B &`` as ``(A && B) &`` — a subshell that holds our stdout
+ # pipe open forever when B is a long-running server. The rewriter turns it into
+ # ``A && { B & }``. Lazy import: terminal_tool imports this module.
from tools.terminal_tool import _rewrite_compound_background as _rewrite_bg
safe_command = _rewrite_bg(command)
@@ -1082,79 +982,14 @@ class ProcessRegistry:
pty_scope_attempted = False
if use_pty:
- # Try PTY mode for interactive CLI tools
try:
- if _IS_WINDOWS:
- from winpty import PtyProcess as _PtyProcessCls
- else:
- from ptyprocess import PtyProcess as _PtyProcessCls
- user_shell = _find_shell()
- pty_env = _sanitize_subprocess_env(os.environ, env_vars)
- pty_env["PYTHONUNBUFFERED"] = "1"
- # PTY mode is a real TTY, so pager-happy tools (git log/diff,
- # man) WILL page and hang waiting for `q` — default them to
- # cat, honoring any pager the user already exported.
- pty_env.setdefault("GIT_PAGER", "cat")
- pty_env.setdefault("PAGER", "cat")
- pty_argv = [user_shell, "-lic", f"set +m; {safe_command}"]
-
- # Cgroup isolation for PTY mode (#70716, reviewer gap #1):
- # Wrap the PTY command in a systemd scope so interactive
- # executors get their own cgroup, same as pipe mode.
- pty_in_supervised_gateway = (
- _IS_LINUX and _is_supervised_gateway_process()
- )
- pty_use_systemd_scope = (
- pty_in_supervised_gateway and _systemd_run_user_scope_available()
- )
-
- if pty_use_systemd_scope:
- pty_argv = _build_systemd_scope_argv(
- pty_argv,
- unit_suffix=session.id,
- )
- session.systemd_unit = f"hermes-worker-{session.id}.scope"
- pty_scope_attempted = True
- elif pty_in_supervised_gateway:
- logger.debug(
- "PTY background executor not isolated in a "
- "systemd scope (systemd-run --user unavailable); "
- "worker shares the gateway cgroup."
- )
-
- pty_proc = _PtyProcessCls.spawn(
- pty_argv,
- cwd=session.cwd,
- env=pty_env,
- dimensions=(30, 120),
- )
- session.pid = pty_proc.pid
- session.host_start_time = self._safe_host_start_time(session.pid)
- # Store the pty handle on the session for read/write
- session._pty = pty_proc
-
- # PTY reader thread
- reader = threading.Thread(
- target=self._pty_reader_loop,
- args=(session,),
- daemon=True,
- name=f"proc-pty-reader-{session.id}",
- )
- session._reader_thread = reader
- reader.start()
-
- with self._lock:
- self._prune_if_needed()
- self._running[session.id] = session
-
- self._write_checkpoint()
- return session
-
+ return self._spawn_local_pty(session, safe_command, env_vars)
except ImportError:
logger.warning("ptyprocess not installed, falling back to pipe mode")
except Exception as e:
logger.warning("PTY spawn failed (%s), falling back to pipe mode", e)
- if pty_scope_attempted and session.systemd_unit:
+ if session.systemd_unit:
+ pty_scope_attempted = True
if not _stop_systemd_unit(session.systemd_unit):
raise RuntimeError(
"PTY scope could not be reaped; refusing pipe fallback "
@@ -1162,64 +997,24 @@ class ProcessRegistry:
) from e
session.systemd_unit = ""
- # Standard Popen path (non-PTY or PTY fallback)
- # Use the user's login shell for consistency with LocalEnvironment --
- # ensures rc files are sourced and user tools are available.
+ # Pipe path (non-PTY or PTY fallback). The user's login shell keeps parity with
+ # LocalEnvironment (rc files sourced, user tools on PATH). PYTHONUNBUFFERED so
+ # tqdm/datasets-style buffering doesn't hide progress from process(action="poll").
user_shell = _find_shell()
- # Force unbuffered output for Python scripts so progress is visible
- # during background execution (libraries like tqdm/datasets buffer when
- # stdout is a pipe, hiding output from process(action="poll")).
bg_env = _sanitize_subprocess_env(os.environ, env_vars)
bg_env["PYTHONUNBUFFERED"] = "1"
_popen_kwargs = {"creationflags": windows_hide_flags()} if _IS_WINDOWS else {}
- # Cgroup isolation (#70716): when running in the live, supervised
- # systemd gateway, wrap the worker in its own transient systemd
- # scope so it gets a separate cgroup. An OOM in the worker then
- # kills only the worker instead of taking down the whole gateway
- # cgroup (and the messaging control plane with it). This applies to
- # both pipe mode and the PTY path above.
- shell_argv = [user_shell, "-lic", f"set +m; {safe_command}"]
- in_supervised_gateway = _IS_LINUX and _is_supervised_gateway_process()
- use_systemd_scope = (
- in_supervised_gateway and _systemd_run_user_scope_available()
+ unit_suffix = f"{session.id}-pipe-fallback" if pty_scope_attempted else session.id
+ spawn_argv, _ = self._scope_argv(
+ session, [user_shell, "-lic", f"set +m; {safe_command}"], unit_suffix, "Local",
)
- if use_systemd_scope:
- unit_suffix = (
- f"{session.id}-pipe-fallback" if pty_scope_attempted else session.id
- )
- spawn_argv = _build_systemd_scope_argv(
- shell_argv,
- unit_suffix=unit_suffix,
- )
- session.systemd_unit = f"hermes-worker-{unit_suffix}.scope"
- # CRITICAL (#70716 regression): systemd-run --scope does NOT give
- # the worker a new session — the invoked process keeps the
- # parent's session and inherits its controlling terminal. From an
- # interactive TUI this drops the worker into the same session as
- # the foreground process group: background spawns then stop the
- # whole session (observed as 5 dead TUIs in state T / "Arrêté").
- # start_new_session=True gives systemd-run (and the scoped worker
- # below it) a private session. Cgroup isolation is preserved:
- # the scope is attached to the invoked process, not to the
- # spawning session.
- popen_start_new_session = True
- else:
- spawn_argv = shell_argv
- popen_start_new_session = True
- if in_supervised_gateway:
- # Running under a supervisor but could not get a private
- # cgroup — the worker shares the gateway cgroup, so an OOM
- # in the worker can still kill the whole gateway (#70716).
- logger.debug(
- "Local background executor not isolated in a systemd scope "
- "(in_supervised_gateway=%s, systemd-run --user available=%s); "
- "worker shares the gateway cgroup.",
- in_supervised_gateway,
- _systemd_run_user_scope_available(),
- )
-
+ # start_new_session is REQUIRED with systemd-run --scope too: the scope does not
+ # give the worker a new session, so from an interactive TUI the worker would
+ # share the foreground process group and background spawns would stop the whole
+ # session (observed as dead TUIs in state T). Cgroup isolation is unaffected —
+ # the scope attaches to the invoked process, not the spawning session.
proc = subprocess.Popen(
spawn_argv,
text=True,
@@ -1230,7 +1025,7 @@ class ProcessRegistry:
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.DEVNULL,
- start_new_session=popen_start_new_session,
+ start_new_session=True,
**_popen_kwargs,
)
@@ -1239,33 +1034,14 @@ class ProcessRegistry:
session.host_start_time = self._safe_host_start_time(session.pid)
try:
- # Start output reader thread
- reader = threading.Thread(
- target=self._reader_loop,
- args=(session,),
- daemon=True,
- name=f"proc-reader-{session.id}",
- )
- session._reader_thread = reader
- reader.start()
-
- with self._lock:
- self._prune_if_needed()
- self._running[session.id] = session
-
- self._write_checkpoint()
+ self._track_started(session, self._reader_loop, f"proc-reader-{session.id}")
except Exception:
- # Post-Popen setup failed — kill the orphaned subprocess (and any
- # descendants spawned via setsid) before re-raising so they do not
- # leak as untracked background processes.
+ # Post-Popen setup failed — kill the orphaned subprocess (and any setsid
+ # descendants) before re-raising so nothing leaks untracked.
try:
if session.systemd_unit:
- # The worker runs in its own systemd scope and, since the
- # #70716 session-isolation fix, its own session. Stop the
- # scope (kills every process in the worker cgroup), then
- # terminate the systemd-run wrapper PID as fallback.
- # Never killpg: scope teardown is the authoritative
- # cleanup for the worker cgroup.
+ # Scope teardown is the authoritative cleanup for the worker cgroup
+ # (never killpg here); the wrapper PID is terminated as fallback.
_stop_systemd_unit(session.systemd_unit)
self._terminate_host_pid(proc.pid, session.host_start_time)
elif not _IS_WINDOWS:
@@ -1296,16 +1072,11 @@ class ProcessRegistry:
timeout: int = 10,
owner_task_id: str = "",
) -> ProcessSession:
- """
- Spawn a background process through a non-local environment backend.
-
- For Docker/Singularity/Modal/Daytona/SSH: runs the command inside the sandbox
- using the environment's execute() interface. We wrap the command to
- capture the in-sandbox PID and redirect output to a log file inside
- the sandbox, then poll the log via subsequent execute() calls.
+ """Spawn a background process inside a non-local backend's sandbox.
- This is less capable than local spawn (no live stdout pipe, no stdin),
- but it ensures the command runs in the correct sandbox context.
+ The command is wrapped to capture its in-sandbox PID and redirect output to
+ a log file, which later execute() calls poll. Less capable than local spawn
+ (no live pipe, no stdin) but runs in the correct sandbox context.
"""
session = ProcessSession(
id=f"proc_{uuid.uuid4().hex[:12]}",
@@ -1349,9 +1120,8 @@ class ProcessRegistry:
if line.isdigit():
session.pid = int(line)
break
- # If the wrapper couldn't produce a PID (for example, syntax
- # error or broken redirect), treat it as a failed launch instead
- # of exposing a fake running session.
+ # No PID from the wrapper (syntax error, broken redirect): a failed launch,
+ # not a fake running session.
if session.pid is None:
session.exited = True
session.exit_code = int(result.get("returncode", -1))
@@ -1393,34 +1163,22 @@ class ProcessRegistry:
def _reader_loop(self, session: ProcessSession):
"""Background thread: read stdout from a local Popen process.
- IMPORTANT: avoid ``TextIOWrapper.read(4096)`` here. On pipes that call can
- block until EOF (or a large buffer fills), which makes "live" output land
- in one burst at process exit. ``buffer.read1(4096)`` yields incremental
- chunks as bytes become available, then we decode to text.
-
- Orphaned-pipe guard (issue #68915): when the user's command backgrounds
- a long-lived process (``node server.js &``, ``sleep 300 &``), that
- grandchild inherits the write end of our stdout pipe via ``fork()``.
- The direct ``bash`` child exits promptly, but the pipe never reaches
- EOF while the grandchild lives — so a blocking read would park this
- thread forever, ``session.exited`` would never flip, and
- ``notify_on_complete`` would never fire (``_reconcile_local_exit``
- only runs lazily from poll()/wait(), which an autonomous notification
- can't rely on). On POSIX we therefore ``select()`` with a short poll
- interval and stop draining shortly after the direct child exits, even
- if the pipe hasn't EOF'd — mirroring the foreground fix in
- ``tools/environments/base.py::_wait_for_process`` (#8340). Windows
- pipes don't support select(); the blocking path is kept there and the
- lazy reconcile in poll()/wait() remains the safety net.
+ Uses ``buffer.read1(4096)`` not ``TextIOWrapper.read(4096)``: on pipes the
+ latter blocks until EOF, landing "live" output in one burst at exit.
+
+ Orphaned-pipe guard: a backgrounded grandchild (``node server.js &``)
+ inherits our pipe's write end, so EOF never arrives while it lives — a
+ blocking read would park this thread, ``session.exited`` would never flip
+ and ``notify_on_complete`` never fire (``_reconcile_local_exit`` only runs
+ lazily from poll()/wait()). On POSIX we ``select()`` with a short interval
+ and stop draining shortly after the direct child exits, mirroring
+ ``tools/environments/base.py::_wait_for_process``. Windows pipes lack
+ select(); the blocking path stays and the lazy reconcile is the safety net.
"""
first_chunk = True
- # Incremental decoder: raw pipe reads can split a multibyte UTF-8
- # character across two read1() chunks. A stateless per-chunk
- # ``bytes.decode(errors="replace")`` turns both halves into U+FFFD
- # mojibake. The incremental decoder holds the partial sequence until
- # the continuation bytes arrive — same treatment the foreground path
- # already has in ``tools/environments/base.py::_wait_for_process``.
- # (Ported from openclaw/openclaw#112325.)
+ # A multibyte UTF-8 char split across read1() chunks would become U+FFFD
+ # mojibake with stateless decoding; the incremental decoder holds the partial
+ # sequence until the continuation bytes arrive.
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
def _append_chunk(chunk: str):
@@ -1428,12 +1186,7 @@ class ProcessRegistry:
if first_chunk:
chunk = self._clean_shell_noise(chunk)
first_chunk = False
- with session._lock:
- session.output_buffer += chunk
- if len(session.output_buffer) > session.max_output_chars:
- session.output_buffer = session.output_buffer[-session.max_output_chars:]
- self._check_watch_patterns(session, chunk)
- self._emit_output(session, chunk)
+ self._ingest_output(session, chunk)
try:
proc = session.process
@@ -1443,9 +1196,8 @@ class ProcessRegistry:
raw_read = getattr(getattr(stdout, "buffer", None), "read1", None)
- # Resolve a real OS fd for the select() path. Mocked streams
- # (unit tests, adapters) may lack fileno() — fall back to the
- # historical blocking loop for those.
+ # select() needs a real OS fd; mocked streams (tests, adapters) may lack
+ # fileno() and use the blocking loop instead.
fd = None
if raw_read is not None and not _IS_WINDOWS:
fileno = getattr(stdout, "fileno", None)
@@ -1474,11 +1226,9 @@ class ProcessRegistry:
_append_chunk(chunk)
idle_after_exit = 0
elif proc.poll() is not None:
- # Direct child is gone and the pipe was idle for
- # ~200ms. Give it a few more cycles to catch any
- # buffered tail, then stop — otherwise we would wait
- # forever on a pipe held open by an orphaned
- # grandchild (issue #68915).
+ # Direct child gone and pipe idle ~200ms: a few more cycles
+ # for a buffered tail, then stop rather than wait forever on
+ # an orphaned grandchild's pipe.
idle_after_exit += 1
if idle_after_exit >= 3:
break
@@ -1492,8 +1242,7 @@ class ProcessRegistry:
if not chunk:
continue # partial multibyte sequence — wait for more bytes
else:
- # Fallback for mocked/alternate streams without a buffered raw
- # interface. This may be less "live", but keeps compatibility.
+ # Mocked/alternate streams without a raw buffer: less "live".
chunk = stdout.read(4096)
if not chunk:
break
@@ -1502,9 +1251,8 @@ class ProcessRegistry:
except Exception as e:
logger.debug("Process stdout reader ended: %s", e)
finally:
- # Flush any bytes still pending in the incremental decoder (a
- # truncated multibyte sequence at EOF becomes one U+FFFD instead
- # of being dropped silently).
+ # Flush the decoder: a truncated multibyte sequence at EOF becomes one
+ # U+FFFD instead of vanishing.
try:
tail = decoder.decode(b"", final=True)
if tail:
@@ -1516,11 +1264,7 @@ class ProcessRegistry:
session.process.wait(timeout=5)
except Exception as e:
logger.debug("Process wait timed out or failed: %s", e)
- session.exited = True
- if session.completion_reason != "killed":
- session.exit_code = session.process.returncode
- session.completion_reason = "exited"
- self._move_to_finished(session)
+ self._finish_exited(session, session.process.returncode)
def _env_poller_loop(
self, session: ProcessSession, env: Any, log_path: str, pid_path: str, exit_path: str
@@ -1537,13 +1281,11 @@ class ProcessRegistry:
result = env.execute(f"cat {quoted_log_path} 2>/dev/null", timeout=10)
new_output = result.get("output", "")
if new_output:
- # Compute delta for watch pattern scanning
+ # Delta since the previous read feeds watch-pattern scanning.
delta = new_output[prev_output_len:] if len(new_output) > prev_output_len else ""
prev_output_len = len(new_output)
with session._lock:
- session.output_buffer = new_output
- if len(session.output_buffer) > session.max_output_chars:
- session.output_buffer = session.output_buffer[-session.max_output_chars:]
+ session.output_buffer = new_output[-session.max_output_chars:]
if delta:
self._check_watch_patterns(session, delta)
self._emit_output(session, delta)
@@ -1583,18 +1325,10 @@ class ProcessRegistry:
def _pty_reader_loop(self, session: ProcessSession):
"""Background thread: read output from a PTY process."""
pty = session._pty
- # PTY reads can split a multibyte UTF-8 character across chunks just
- # like pipe reads — hold partial sequences until the rest arrives.
- # (Ported from openclaw/openclaw#112325.)
+ # Same split-multibyte handling as _reader_loop.
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
- def _append_text(text: str):
- with session._lock:
- session.output_buffer += text
- if len(session.output_buffer) > session.max_output_chars:
- session.output_buffer = session.output_buffer[-session.max_output_chars:]
- self._check_watch_patterns(session, text)
- self._emit_output(session, text)
+ _append_text = lambda text: self._ingest_output(session, text) # noqa: E731
try:
while pty.isalive():
@@ -1605,9 +1339,7 @@ class ProcessRegistry:
text = chunk if isinstance(chunk, str) else decoder.decode(chunk)
if text:
_append_text(text)
- except EOFError:
- break
- except Exception:
+ except Exception: # EOFError included
break
except Exception as e:
logger.debug("PTY stdout reader ended: %s", e)
@@ -1620,23 +1352,35 @@ class ProcessRegistry:
except Exception:
pass
- # Process exited
try:
pty.wait()
except Exception as e:
logger.debug("PTY wait timed out or failed: %s", e)
+ self._finish_exited(session, pty.exitstatus if hasattr(pty, 'exitstatus') else -1)
+
+ def _ingest_output(self, session: ProcessSession, text: str) -> None:
+ """Buffer a freshly-read chunk, then scan watch patterns and stream it live."""
+ session.append_output(text)
+ self._check_watch_patterns(session, text)
+ self._emit_output(session, text)
+
+ def _finish_exited(self, session: ProcessSession, exit_code) -> None:
+ """Mark a reader-observed exit and move the session to finished.
+
+ A kill that raced the reader already recorded its own exit_code/reason;
+ don't overwrite it.
+ """
session.exited = True
if session.completion_reason != "killed":
- session.exit_code = pty.exitstatus if hasattr(pty, 'exitstatus') else -1
+ session.exit_code = exit_code
session.completion_reason = "exited"
self._move_to_finished(session)
def _move_to_finished(self, session: ProcessSession):
"""Move a session from running to finished.
- Idempotent: if the session was already moved (e.g. kill_process raced
- with the reader thread), the second call is a no-op — no duplicate
- completion notification is enqueued.
+ Idempotent: kill_process() and the reader thread can both call this; only
+ the FIRST move enqueues the completion notification, so no duplicates.
"""
with self._lock:
was_running = self._running.pop(session.id, None) is not None
@@ -1644,9 +1388,6 @@ class ProcessRegistry:
session._completion_event.set()
self._write_checkpoint()
- # Only enqueue completion notification on the FIRST move. Without
- # this guard, kill_process() and the reader thread can both call
- # _move_to_finished(), producing duplicate [IMPORTANT: ...] messages.
if was_running and session.notify_on_complete:
from tools.ansi_strip import strip_ansi
output_tail = strip_ansi(session.output_buffer[-2000:]) if session.output_buffer else ""
@@ -1661,9 +1402,8 @@ class ProcessRegistry:
"completion_reason": session.completion_reason,
"termination_source": session.termination_source,
"output": output_tail,
- # Stable producer identity across checkpoint recovery; unlike
- # a consumer-observed completion timestamp, this does not vary
- # based on which watcher notices exit first.
+ # Stable producer identity across checkpoint recovery (unlike a
+ # consumer-observed completion timestamp).
"started_at": session.started_at,
}
_redact_process_result(notification)
@@ -1676,40 +1416,24 @@ class ProcessRegistry:
return session_id in self._completion_consumed
def is_session_waiting(self, session_id: str) -> bool:
- """Whether a goal loop parked on this session should still be parked.
-
- Used by the goal-loop wait barrier (``hermes_cli.goals``) to support
- waiting on a process's OWN trigger, not just its exit. A session is
- "still waiting" when:
- - it is still running, AND
- - if it has ``watch_patterns``, none has matched yet (so a
- long-lived watcher that fires a trigger mid-run — and may never
- exit — unblocks the moment its pattern hits, not on exit).
-
- Returns False (don't wait) when the session has exited, its watch
- pattern has already fired, or the session is unknown — so a stale or
- already-triggered barrier can never wedge the loop.
- """
+ """Whether a goal loop (``hermes_cli.goals`` wait barrier) should stay parked
+ on this session: still running AND, if it has ``watch_patterns``, none has
+ matched yet (a long-lived watcher unblocks on its trigger, not on exit).
+ Unknown/exited/already-fired sessions return False so a stale barrier can
+ never wedge the loop."""
if not session_id:
return False
with self._lock:
session = self._running.get(session_id) or self._finished.get(session_id)
if session is None:
return False
- # Refresh detached/remote state so .exited is current.
try:
self._refresh_detached_session(session)
except Exception:
pass
if session.exited:
return False
- # Watch-pattern process: the trigger is a pattern match, not exit.
- # Once any match has been delivered, the wait is satisfied even though
- # the process keeps running (server/daemon/watcher case).
- if session.watch_patterns and not session._watch_disabled:
- if session._watch_hits > 0:
- return False
- return True
+ return not (session.watch_patterns and not session._watch_disabled and session._watch_hits > 0)
def wait_for_pending_completions(
self,
@@ -1718,44 +1442,20 @@ class ProcessRegistry:
timeout: float | None = None,
poll_interval: float = 1.0,
) -> dict:
- """Bounded wait for tracked ``notify_on_complete`` background processes.
-
- One-shot CLI runs (``hermes -q/-Q/-z``) exit as soon as their single
- turn ends. Any background process the turn spawned with
- ``notify_on_complete=True`` — a bounded task whose completion the
- caller explicitly cares about — still holds a stdout pipe owned by
- the dying parent, so it is killed by SIGPIPE on its next write a few
- seconds later. Bot Mode handoff REPLIES are the visible casualty
- (#90879): a recipient invoked as ``hermes -p <bot> chat -Q
- --query-file ...`` dispatches its reply via ``message_agent`` /
- ``bot_relay`` exactly this way, then exits, and the reply process is
- destroyed ~3s later. The sender waits forever for a reply that was
- already killed.
-
- Called from the one-shot exit paths so the parent lingers (bounded)
- until those deliveries actually finish. This fixes the class — ANY
- bounded background task in a one-shot run, not just DMs: bot_mode_dm
- deliveries, bot_relay waiter processes, and plain
- ``terminal(background=true, notify_on_complete=true)`` jobs.
-
- Only ``notify_on_complete`` processes are waited on. Plain background
- processes (servers, daemons, watch-pattern monitors) carry no
- completion contract and are not the parent's to wait for.
-
- Args:
- task_id: restrict to processes spawned for this task; ``None``
- waits on every tracked process (a one-shot CLI process hosts
- exactly one agent, so its registry is private to that run).
- timeout: max seconds to linger. ``None`` reads
- ``terminal.oneshot_completion_wait_seconds`` from config
- (default 600). ``<= 0`` disables the wait entirely.
- poll_interval: per-pass event-wait bound; each pass re-reconciles
- child state so an orphaned-pipe exit (#17327) can't wedge the
- linger for the full timeout.
-
- Returns:
- ``{"waited": [...], "completed": [...], "timed_out": [...]}``
- (session ids). All lists empty when there was nothing to wait on.
+ """Bounded linger for ``notify_on_complete`` background processes at one-shot exit.
+
+ A one-shot CLI run (``hermes -q/-Q/-z``) exits when its turn ends; any
+ background process it spawned still holds a stdout pipe owned by the dying
+ parent and dies of SIGPIPE seconds later (Bot Mode handoff replies sent via
+ message_agent/bot_relay were the visible casualty). Only ``notify_on_complete``
+ processes carry a completion contract — servers/daemons/watchers aren't the
+ parent's to wait for.
+
+ ``task_id=None`` waits on every tracked process (a one-shot process hosts one
+ agent). ``timeout=None`` reads ``terminal.oneshot_completion_wait_seconds``;
+ ``<= 0`` disables. Each ``poll_interval`` pass re-reconciles child state so an
+ orphaned-pipe exit can't wedge the linger. Returns
+ ``{"waited": [...], "completed": [...], "timed_out": [...]}`` of session ids.
"""
if timeout is None:
timeout = self._oneshot_completion_wait_seconds()
@@ -1795,9 +1495,7 @@ class ProcessRegistry:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
- # Reconcile first: catches direct-child exits whose reader
- # is blocked on a pipe held open by a descendant (#17327)
- # and detached/env sessions, so the event actually fires.
+ # Reconcile first so orphaned-pipe and detached exits fire the event.
try:
self._reconcile_local_exit(session)
self._refresh_detached_session(session)
@@ -1807,9 +1505,8 @@ class ProcessRegistry:
break
session._completion_event.wait(min(remaining, interval))
except KeyboardInterrupt:
- # User aborted the linger — stop waiting on everything but
- # never let the interrupt skip the caller's durable teardown
- # (session flush, end_session) that follows this wait.
+ # Stop waiting, but never let the interrupt skip the caller's durable
+ # teardown (session flush, end_session) that follows.
interrupted = True
if session.exited:
result["completed"].append(session.id)
@@ -1829,54 +1526,31 @@ class ProcessRegistry:
@staticmethod
def _oneshot_completion_wait_seconds() -> float:
"""Bounded linger (s) for one-shot exits with pending notify_on_complete
- processes. Read from ``terminal.oneshot_completion_wait_seconds``;
- 0 disables. Falls back to the DEFAULT_CONFIG value (600) when config
- is unreadable so callers always get a sane bound.
- """
+ processes: ``terminal.oneshot_completion_wait_seconds`` (0 disables), 600
+ if config is unreadable."""
try:
- from hermes_cli.config import DEFAULT_CONFIG, cfg_get, read_raw_config
- cfg = read_raw_config()
- val = cfg_get(cfg, "terminal", "oneshot_completion_wait_seconds")
- if val is None:
- val = DEFAULT_CONFIG["terminal"]["oneshot_completion_wait_seconds"]
- return max(float(val), 0.0)
+ return max(float(ProcessRegistry._config_value("terminal", "oneshot_completion_wait_seconds", 600.0)), 0.0)
except Exception:
return 600.0
def _drain_should_skip(
self, session_id: str, *, skip_poll_observed: bool = True
) -> bool:
- """Whether this drain should skip a completion event for this session.
-
- Skips when the agent has either truly consumed the output (wait/log →
- ``_completion_consumed``) or observed the exit inline via poll()
- (``_poll_observed``). In both cases the CLI agent already has the
- result this turn, so injecting a [SYSTEM: ...] completion would be a
- duplicate (#8228). The gateway/tui watchers do NOT use this — they
- check only ``is_completion_consumed`` so a read-only poll never
- suppresses their autonomous delivery turn (#10156).
- """
+ """Skip a completion the CLI agent already has this turn — consumed via
+ wait/log or observed inline via poll(). Gateway/tui watchers check only
+ ``is_completion_consumed`` so a read-only poll never suppresses their
+ autonomous delivery turn."""
return session_id in self._completion_consumed or (
skip_poll_observed and session_id in self._poll_observed
)
@staticmethod
def _surface_child_process_notifications() -> bool:
- """Whether subagent-owned process notifications surface in the parent.
-
- Read from ``delegation.surface_child_process_notifications`` in
- config.yaml (default false = suppress). On any config read error the
- DEFAULT applies (suppress) — never crash the drain loop.
- """
+ """Whether subagent-owned process notifications surface in the parent
+ (``delegation.surface_child_process_notifications``; suppress on any config
+ error — never crash the drain loop)."""
try:
- from hermes_cli.config import DEFAULT_CONFIG, cfg_get, read_raw_config
- cfg = read_raw_config()
- val = cfg_get(cfg, "delegation", "surface_child_process_notifications")
- if val is None:
- val = DEFAULT_CONFIG["delegation"][
- "surface_child_process_notifications"
- ]
- return bool(val)
+ return bool(ProcessRegistry._config_value("delegation", "surface_child_process_notifications", False))
except Exception:
return False
@@ -1887,50 +1561,30 @@ class ProcessRegistry:
*,
skip_poll_observed: bool = True,
) -> "list[tuple[dict, str]]":
- """Pop all pending notification events and return formatted pairs.
-
- Returns a list of (raw_event, formatted_text) tuples.
- Skips completion events the agent already consumed via wait/log or
- observed inline via poll() (see ``_drain_should_skip``). Gateway/TUI
- callers pass ``skip_poll_observed=False`` because read-only polling must
- not suppress autonomous delivery there.
-
- When a routing filter is supplied, addressed notifications must not be
- drained into the wrong session. Async-delegation events always require
- conversation payload; ordinary notifications require routing when they
- carry ``session_key`` or ``origin_ui_session_id`` metadata. Two filter
- modes are supported, strongest first:
-
- - ``owns_event(evt) -> bool``: positive-proof ownership callback.
- When provided, a routed event is consumed ONLY if the callback
- returns True; everything else is re-queued for its owner.
- The TUI passes its compression-chain-aware ownership check here so
- a post-compression session still claims its own pre-compression
- dispatches.
- - ``session_key``: plain key equality (CLI and other single-session
- callers). Non-matching addressed events are re-queued.
-
- With neither set, all events are consumed (legacy single-session
- behavior, backward compatible). Ownerless ordinary notifications also
- retain that legacy behavior even when a filter is provided. When a
- filter is provided, ownerless async-delegation events remain
- fail-closed and require positive proof.
+ """Pop all pending events and return ``(raw_event, formatted_text)`` pairs.
+
+ Skips completions per ``_drain_should_skip``; gateway/TUI callers pass
+ ``skip_poll_observed=False``.
+
+ Routing: async-delegation events always need ownership proof; ordinary
+ events need it once they carry ``session_key`` or ``origin_ui_session_id``.
+ ``owns_event(evt)`` (strongest; the TUI passes a compression-chain-aware
+ check so a post-compression session still claims its pre-compression
+ dispatches) consumes ONLY on True; ``session_key`` uses plain equality.
+ Non-owned routed events are re-queued for their owner. With no filter every
+ event is consumed (legacy single-session), except restored delegation
+ payloads, which stay fail-closed.
"""
results: "list[tuple[dict, str]]" = []
requeue: "list[dict]" = []
- # Lazily-read flag for subagent-owned process notifications
- # (delegation.surface_child_process_notifications, default false).
- # Read at most once per drain, and only when an sa- event shows up.
+ # delegation.surface_child_process_notifications, read at most once per drain
+ # and only when an sa- event shows up.
surface_child: "bool | None" = None
while not self.completion_queue.empty():
try:
evt = self.completion_queue.get_nowait()
except Exception:
break
- # Positive-proof ownership beats bare key equality. Delegation
- # payloads always require proof; ordinary events require it once
- # they carry routing metadata. Ownerless ordinary events preserve
- # legacy single-session delivery.
is_async_delegation = evt.get("type") == "async_delegation"
evt_session_key = str(evt.get("session_key") or "")
evt_origin_sid = str(evt.get("origin_ui_session_id") or "")
@@ -1950,31 +1604,24 @@ class ProcessRegistry:
requeue.append(evt)
continue
elif is_async_delegation and evt.get("restored"):
- # Durable restore can enqueue previous-process payloads into a
- # fresh registry. An unfiltered legacy drain cannot prove
- # ownership, so leave those events queued for the owner.
+ # Restored payloads from a previous process: an unfiltered drain
+ # cannot prove ownership, so leave them for the owner.
requeue.append(evt)
continue
- # Local consumed/observed state may suppress only events this
- # session owns (or legacy ownerless ordinary events). Routing must
- # happen first so a foreign session cannot drop the owner's event.
+ # Routing happened first so a foreign session cannot drop the owner's
+ # event via its own consumed/observed state.
_evt_sid = evt.get("session_id", "")
if evt.get("type") == "completion" and self._drain_should_skip(
_evt_sid, skip_poll_observed=skip_poll_observed
):
continue
- # Subagent-owned process notifications are suppressed from the
- # parent conversation by default — the child's consolidated
- # delegation result is the deliverable; "npm ci finished" walls
- # mid-chat are noise. Ownership is judged on owner_task_id (the
- # RAW spawning task id): the container key in task_id is
- # deliberately collapsed to "default"/the session key by
- # _resolve_container_task_id, which previously let child events
- # bypass this gate. Dropped, NOT requeued (children never drain
- # notify events, so requeueing would pin them in the queue
- # forever). Type 'async_delegation' is the delegation result
- # itself and is NEVER suppressed.
+ # Subagent-owned process notifications are suppressed by default — the
+ # child's delegation result is the deliverable. Judge ownership on
+ # owner_task_id (RAW spawning id; task_id is the container key, collapsed
+ # by _resolve_container_task_id). Dropped, NOT requeued: children never
+ # drain, so a requeue would pin the event forever. 'async_delegation'
+ # is the result itself and is NEVER suppressed.
_evt_task_id = str(
evt.get("owner_task_id") or evt.get("task_id") or ""
)
@@ -2004,15 +1651,9 @@ class ProcessRegistry:
_MIN_PREFIX_CHARS = 4
def get(self, session_id: str) -> Optional[ProcessSession]:
- """Get a session by ID (running or finished).
-
- Accepts either the full ID or a unique ID prefix (inspired by Factory
- Droid's task-ID prefixes, and the same UX as ``git``/``docker`` short
- hashes): ``proc_4dae`` — or just the bare suffix ``4dae`` — resolves
- to ``proc_4dae56ca81f6`` when exactly one session matches. Ambiguous
- or too-short prefixes resolve to None (callers already report
- "No process with ID ..."), never to an arbitrary pick.
- """
+ """Get a session by full ID or unique prefix (``proc_4dae`` / bare ``4dae``,
+ like git short hashes). Ambiguous or too-short prefixes resolve to None,
+ never to an arbitrary pick."""
with self._lock:
session = self._running.get(session_id) or self._finished.get(session_id)
if session is None:
@@ -2020,13 +1661,8 @@ class ProcessRegistry:
return self._refresh_detached_session(session)
def _resolve_prefix(self, session_id: str) -> Optional[ProcessSession]:
- """Resolve a unique session-ID prefix to its session, else None.
-
- Exact lookups happen in :meth:`get` before this runs, so a full ID
- never pays the scan. Matching is prefix-only (no substring) and
- requires a unique hit; a bare suffix without the ``proc_`` lead is
- normalized so users can paste just the hex tail.
- """
+ """Resolve a unique session-ID prefix (prefix-only, unique hit; a bare hex
+ tail is normalized to ``proc_<tail>``). :meth:`get` tries exact first."""
if not session_id or not isinstance(session_id, str):
return None
query = session_id.strip()
@@ -2050,24 +1686,13 @@ class ProcessRegistry:
return None
def _reconcile_local_exit(self, session: "ProcessSession") -> None:
- """Reconcile session.exited against the real child process state.
-
- The reader thread (`_reader_loop`) sets `session.exited = True` only
- in its `finally` block, which runs when `stdout.read()` returns EOF.
- If the direct `Popen` child has exited but a descendant process (e.g.
- a daemon spawned by `hermes update` restarting the gateway) is still
- holding the stdout pipe open, the reader blocks forever and poll()
- keeps returning "running" indefinitely (issue #17327 — 74 polls over
- 7 minutes on Feishu).
-
- This helper closes that window: when `session.exited` is still False
- but the direct child's `Popen.poll()` reports an exit code, drain any
- readable bytes non-blocking and flip `session.exited`. The orphaned
- reader thread remains stuck on its blocking `read()` but is a daemon
- thread and will be reaped with the process.
-
- Safe no-op on sessions without a local `Popen` (env/PTY), already-
- exited sessions, and detached-recovered sessions.
+ """Reconcile ``session.exited`` against the real child state.
+
+ The reader flips ``exited`` only at EOF; when the direct child has exited but
+ a descendant (e.g. a daemon from ``hermes update``) holds the pipe open, poll()
+ would report "running" forever. If ``Popen.poll()`` has an exit code, drain
+ readable bytes non-blocking and flip ``exited``; the stuck daemon reader thread
+ is reaped with the process. No-op for env/PTY, exited and detached sessions.
"""
if session is None or session.exited:
return
@@ -2081,10 +1706,7 @@ class ProcessRegistry:
if rc is None:
return # Direct child still running — reader block is legitimate.
- # Direct child exited. Try to drain any bytes the reader hasn't
- # consumed yet. This is best-effort: if the pipe is held open by a
- # descendant, the non-blocking read returns what's immediately
- # available and we stop.
+ # Best-effort non-blocking drain of whatever the reader hasn't consumed.
drained = ""
stdout = getattr(proc, "stdout", None)
if stdout is not None and not _IS_WINDOWS:
@@ -2131,9 +1753,7 @@ class ProcessRegistry:
if session is None:
return {"status": "not_found", "error": f"No process with ID {session_id}"}
- # Reconcile against real child state before reading session.exited.
- # Guards against orphaned-pipe reader hangs (issue #17327).
- self._reconcile_local_exit(session)
+ self._reconcile_local_exit(session) # orphaned-pipe reader guard
with session._lock:
output_preview = strip_ansi(session.output_buffer[-1000:]) if session.output_buffer else ""
@@ -2150,16 +1770,9 @@ class ProcessRegistry:
result["exit_code"] = session.exit_code
result["completion_reason"] = session.completion_reason
result["termination_source"] = session.termination_source
- # NOTE: poll() is a read-only status query and deliberately does
- # NOT mark the session _completion_consumed. wait()/read_log()
- # represent actual output consumption and do mark it. Marking
- # consumed here would let a status check silently suppress the
- # notify_on_complete watcher's autonomous delivery turn (#10156).
- #
- # We DO record it in _poll_observed so the CLI's inline drain still
- # dedups (the agent already saw the exit in this turn's poll result)
- # without affecting the gateway/tui watchers, which only consult
- # _completion_consumed.
+ # Read-only: record in _poll_observed (CLI inline dedup) but NOT in
+ # _completion_consumed, or a status check would suppress the watcher's
+ # autonomous delivery turn. See __init__.
self._poll_observed.add(session_id)
if session.detached:
result["detached"] = True
@@ -2180,11 +1793,8 @@ class ProcessRegistry:
lines = full_output.splitlines()
total_lines = len(lines)
- # Default (offset=None): last N lines. An explicit offset=0 means
- # "start from the first line" — previously it was conflated with
- # the default and silently returned the TAIL instead of the head
- # (same falsy-coercion class as the wait() timeout guard; salvaged
- # from PR #60004, credit @isheng-eqi).
+ # offset=None -> last N lines; an explicit offset=0 means the HEAD (don't
+ # conflate the two via falsiness).
if offset is None and limit > 0:
selected = lines[-limit:]
observed_completion_output = bool(selected) or total_lines == 0
@@ -2209,16 +1819,10 @@ class ProcessRegistry:
return result
def wait(self, session_id: str, timeout: int = None) -> dict:
- """
- Block until a process exits, timeout, or interrupt.
-
- Args:
- session_id: The process to wait for.
- timeout: Max seconds to block. Falls back to TERMINAL_TIMEOUT config.
+ """Block until the process exits, the timeout elapses, or the user interrupts.
- Returns:
- dict with status ("exited", "timeout", "interrupted", "not_found")
- and output snapshot.
+ ``timeout`` defaults to (and is clamped by) TERMINAL_TIMEOUT. Returns a dict
+ with status exited|timeout|interrupted|not_found|error and an output snapshot.
"""
from tools.ansi_strip import strip_ansi
from tools.interrupt import is_interrupted as _is_interrupted
@@ -2231,11 +1835,8 @@ class ProcessRegistry:
requested_timeout = timeout
timeout_note = None
- # Reject non-positive timeouts — the schema declares minimum=1, but
- # not every caller enforces schemas before dispatch. timeout=0 is
- # falsy, so without this guard it silently fell through
- # (`0 or max_timeout`) to the DEFAULT wait instead of erroring.
- # Salvaged from PR #60004 (credit @isheng-eqi).
+ # The schema says minimum=1 but not every caller enforces it; timeout=0 is
+ # falsy and would silently fall through to the default wait.
if requested_timeout is not None and requested_timeout <= 0:
return {
"status": "error",
@@ -2261,31 +1862,20 @@ class ProcessRegistry:
session = self._refresh_detached_session(session)
if session is None:
return {"status": "not_found", "error": f"No process with ID {session_id}"}
- # Reconcile against real child state — guards against orphaned-
- # pipe reader hangs where the reader is blocked but the direct
- # child has already exited (issue #17327).
- self._reconcile_local_exit(session)
+ self._reconcile_local_exit(session) # orphaned-pipe reader guard
if session.exited:
self._completion_consumed.add(session_id)
- result = {
- "status": "exited",
- "command": session.command,
- "exit_code": session.exit_code,
- "completion_reason": session.completion_reason,
- "termination_source": session.termination_source,
- "output": strip_ansi(session.output_buffer[-2000:]),
- }
- if timeout_note:
- result["timeout_note"] = timeout_note
- return result
-
- if _is_interrupted():
+ result = self._exit_snapshot(session, "exited")
+ elif _is_interrupted():
result = {
"status": "interrupted",
"command": session.command,
"output": strip_ansi(session.output_buffer[-1000:]),
"note": "User sent a new message -- wait interrupted",
}
+ else:
+ result = None
+ if result is not None:
if timeout_note:
result["timeout_note"] = timeout_note
return result
@@ -2299,9 +1889,8 @@ class ProcessRegistry:
"status": "timeout",
"command": session.command,
"output": strip_ansi(session.output_buffer[-1000:]),
- # A wait window elapsing is NOT a failure — 511 exact-duplicate
- # process calls in a production window show models re-issuing
- # identical waits after misreading this result as an error.
+ # Not a failure — models re-issued identical waits after misreading
+ # this result as an error.
"process_running": True,
}
uptime = time.time() - session.started_at if session.started_at else None
@@ -2327,6 +1916,20 @@ class ProcessRegistry:
result["timeout_note"] = base_note
return result
+ @staticmethod
+ def _exit_snapshot(session: ProcessSession, status: str) -> dict:
+ """Result dict for an exited session: exit metadata + last 2000 chars of output."""
+ from tools.ansi_strip import strip_ansi
+
+ return {
+ "status": status,
+ "command": session.command,
+ "exit_code": session.exit_code,
+ "completion_reason": session.completion_reason,
+ "termination_source": session.termination_source,
+ "output": strip_ansi(session.output_buffer[-2000:]),
+ }
+
def kill_process(
self,
session_id: str,
@@ -2336,13 +1939,11 @@ class ProcessRegistry:
) -> dict:
"""Kill a background process and return its output snapshot.
- ``consume_output`` is true for explicit tool/RPC kills because their
- caller observes the returned output. Bulk cleanup passes false: it
- discards each result and therefore must not suppress an autonomous
- output-bearing completion notification. Exception: abandoned-turn
- reaping (``kill_started_since``) is bulk cleanup that deliberately
- passes true — a killed abandoned process must not enqueue a synthetic
- follow-up that revives work the timeout/interrupt stopped.
+ ``consume_output`` is true for explicit tool/RPC kills (the caller sees the
+ output). Bulk cleanup passes false so it doesn't suppress an autonomous
+ completion notification — except abandoned-turn reaping
+ (``kill_started_since``), which passes true so a killed abandoned process
+ can't enqueue a follow-up reviving work the timeout stopped.
"""
from tools.ansi_strip import strip_ansi
@@ -2351,89 +1952,29 @@ class ProcessRegistry:
return {"status": "not_found", "error": f"No process with ID {session_id}"}
if session.exited:
- # Even if the main process already exited, a double-forked
- # descendant may still be alive in the systemd scope (#70716,
- # reviewer gap #2 — the ``already_exited`` early return skipped
- # unit cleanup). Stop the scope to reap any survivors.
+ # A double-forked descendant may still be alive in the systemd scope even
+ # though the main process exited — stop the scope to reap survivors.
if session.systemd_unit:
_stop_systemd_unit(session.systemd_unit)
with session._lock:
- result = {
- "status": "already_exited",
- "command": session.command,
- "exit_code": session.exit_code,
- "completion_reason": session.completion_reason,
- "termination_source": session.termination_source,
- "output": strip_ansi(session.output_buffer[-2000:]),
- }
+ result = self._exit_snapshot(session, "already_exited")
# Only suppress the autonomous turn after its output is present in
# the explicit kill result, matching wait/log consumption.
if consume_output:
self._completion_consumed.add(session_id)
return result
- # Kill via PTY, Popen (local), or env execute (non-local)
try:
- if session._pty:
- # PTY process -- terminate via ptyprocess
- try:
- session._pty.terminate(force=True)
- except Exception:
- if session.pid:
- os.kill(session.pid, signal.SIGTERM)
- elif session.process:
- # Local process -- kill the process tree. On Windows this
- # must be taskkill /T /F; Popen.terminate() only kills the
- # shell wrapper and leaves Git Bash descendants behind.
- self._terminate_host_pid(session.process.pid, session.host_start_time)
- elif session.env_ref and session.pid:
- # Non-local -- kill inside sandbox
- session.env_ref.execute(f"kill {session.pid} 2>/dev/null", timeout=5)
- elif session.detached and session.pid_scope == "host" and session.pid:
- # Identity check, not bare liveness: if the PID is gone OR was
- # recycled onto an unrelated process, treat our process as
- # exited and never tree-kill the stranger. If this recovered
- # session also carries an owned systemd scope, stop that scope
- # before returning: a daemonized descendant may still be alive
- # there even though the wrapper PID exited or was recycled
- # across the gateway restart (#70716, teknium1 review).
- if not self._host_pid_is_ours(session.pid, session.host_start_time):
- if session.systemd_unit:
- _stop_systemd_unit(session.systemd_unit)
- with session._lock:
- session.exited = True
- session.exit_code = None
- output = strip_ansi(session.output_buffer[-2000:])
- if consume_output:
- self._completion_consumed.add(session_id)
- self._move_to_finished(session)
- return {
- "status": "already_exited",
- "exit_code": session.exit_code,
- "output": output,
- }
- self._terminate_host_pid(session.pid, session.host_start_time)
- else:
- return {
- "status": "error",
- "error": (
- "Recovered process cannot be killed after restart because "
- "its original runtime handle is no longer available"
- ),
- }
+ early = self._signal_kill(session, session_id, consume_output)
+ if early is not None:
+ return early
- # If the worker was spawned in its own systemd scope (#70716),
- # stop the entire unit to reap any double-forked descendants that
- # were reparented inside the scope and survived the PID signal
- # above (reviewer gap #2). ``systemctl --user stop`` sends
- # SIGTERM to every process in the cgroup and escalates to SIGKILL
- # after TimeoutStopSec. This is additive — the PID-based kill
- # above already handled the main process; this catches stragglers.
+ # Additive to the PID kill: stopping the scope reaps double-forked
+ # descendants reparented inside the cgroup.
if session.systemd_unit:
_stop_systemd_unit(session.systemd_unit)
- # Capture output before marking consumed, then mark consumed before
- # exposing ``exited`` to watcher tasks. This closes the delayed
- # notification race without discarding the terminal transcript.
+ # Capture output, mark consumed, THEN expose ``exited`` to watcher tasks —
+ # closes the delayed-notification race without losing the transcript.
with session._lock:
output = strip_ansi(session.output_buffer[-2000:])
if consume_output:
@@ -2454,16 +1995,67 @@ class ProcessRegistry:
except Exception as e:
return {"status": "error", "error": str(e)}
- def write_stdin(self, session_id: str, data: str) -> dict:
- """Send raw data to a running process's stdin (no newline appended)."""
+ def _signal_kill(self, session: ProcessSession, session_id: str, consume_output: bool) -> Optional[dict]:
+ """Deliver the kill via PTY, local Popen tree, sandbox exec or recovered host
+ PID. Returns a final result dict when the kill cannot proceed (recycled/dead
+ recovered PID, or no runtime handle), else None."""
+ from tools.ansi_strip import strip_ansi
+
+ if session._pty:
+ try:
+ session._pty.terminate(force=True)
+ except Exception:
+ if session.pid:
+ os.kill(session.pid, signal.SIGTERM)
+ elif session.process:
+ # Tree kill: on Windows Popen.terminate() only kills the shell wrapper and
+ # leaves Git Bash descendants behind.
+ self._terminate_host_pid(session.process.pid, session.host_start_time)
+ elif session.env_ref and session.pid:
+ session.env_ref.execute(f"kill {session.pid} 2>/dev/null", timeout=5)
+ elif session.detached and session.pid_scope == "host" and session.pid:
+ # Identity check, not bare liveness: a gone/recycled PID means our
+ # process exited — never tree-kill the stranger. Still stop an owned
+ # scope: a daemonized descendant may survive the wrapper PID.
+ if not self._host_pid_is_ours(session.pid, session.host_start_time):
+ if session.systemd_unit:
+ _stop_systemd_unit(session.systemd_unit)
+ with session._lock:
+ session.exited = True
+ session.exit_code = None
+ output = strip_ansi(session.output_buffer[-2000:])
+ if consume_output:
+ self._completion_consumed.add(session_id)
+ self._move_to_finished(session)
+ return {"status": "already_exited", "exit_code": session.exit_code, "output": output}
+ self._terminate_host_pid(session.pid, session.host_start_time)
+ else:
+ return {
+ "status": "error",
+ "error": (
+ "Recovered process cannot be killed after restart because "
+ "its original runtime handle is no longer available"
+ ),
+ }
+ return None
+
+ def _live_session(self, session_id: str):
+ """``(session, None)`` for a running session, else ``(None, error_result)``."""
session = self.get(session_id)
if session is None:
- return {"status": "not_found", "error": f"No process with ID {session_id}"}
+ return None, {"status": "not_found", "error": f"No process with ID {session_id}"}
if session.exited:
- return {"status": "already_exited", "error": "Process has already finished"}
+ return None, {"status": "already_exited", "error": "Process has already finished"}
+ return session, None
+
+ def write_stdin(self, session_id: str, data: str) -> dict:
+ """Send raw data to a running process's stdin (no newline appended)."""
+ session, err = self._live_session(session_id)
+ if err:
+ return err
# PTY mode -- write through pty handle.
- if hasattr(session, '_pty') and session._pty:
+ if session._pty:
try:
# pywinpty expects str on Windows; ptyprocess expects bytes on POSIX.
if _IS_WINDOWS:
@@ -2488,35 +2080,23 @@ class ProcessRegistry:
return {"status": "error", "error": str(e)}
def submit_stdin(self, session_id: str, data: str = "") -> dict:
- """Send data + newline to a running process's stdin (like pressing Enter).
-
- On a Windows PTY session the Enter key is a carriage return: ConPTY
- cooked input treats ``\\r`` as end-of-line, and a bare ``\\n`` written
- through pywinpty is NOT delivered as a line terminator — the child's
- blocking line read (Python ``readline()``, Go ``bufio.Scanner`` as in
- ``gh auth login``'s "Press Enter to open the browser" prompt) simply
- never returns and the process hangs while looking healthy. Verified
- empirically via pywinpty 2.0.15: ``\\n`` -> no line, ``\\r`` /
- ``\\r\\n`` -> line delivered. Use ``\\r\\n`` so the child sees both the
- Enter keypress and a conventional newline; POSIX PTYs and Popen pipes
- keep the plain ``\\n``.
+ """Send data + newline to stdin (like pressing Enter).
+
+ On a Windows PTY, Enter is a carriage return: ConPTY treats ``\\r`` as
+ end-of-line and a bare ``\\n`` through pywinpty is NOT a line terminator —
+ the child's blocking line read (``readline()``, Go ``bufio.Scanner`` in
+ ``gh auth login``) never returns and the process hangs looking healthy.
+ ``\\r\\n`` gives it both; POSIX PTYs and pipes keep ``\\n``.
"""
session = self.get(session_id)
- is_windows_pty = bool(
- _IS_WINDOWS and session is not None
- and getattr(session, "_pty", None)
- )
- line_ending = "\r\n" if is_windows_pty else "\n"
- return self.write_stdin(session_id, data + line_ending)
+ is_windows_pty = bool(_IS_WINDOWS and session is not None and session._pty)
+ return self.write_stdin(session_id, data + ("\r\n" if is_windows_pty else "\n"))
def request_close_terminal(self, session_id: str) -> dict:
- """Ask the desktop GUI to close the read-only terminal tab mirroring this
- background process.
+ """Ask the desktop GUI to close this process's read-only terminal tab.
- This does NOT kill the process — it only drops the view. Output keeps
- streaming into the (capped) buffer and the user can reopen the tab from
- the status stack. Desktop-only: returns an error if no UI close sink is
- wired (e.g. CLI / messaging)."""
+ Does NOT kill the process — output keeps buffering and the tab can be
+ reopened from the status stack. Errors when no UI close sink is wired."""
sink = self.on_close
if sink is None:
return {
@@ -2542,13 +2122,11 @@ class ProcessRegistry:
def close_stdin(self, session_id: str) -> dict:
"""Close a running process's stdin / send EOF without killing the process."""
- session = self.get(session_id)
- if session is None:
- return {"status": "not_found", "error": f"No process with ID {session_id}"}
- if session.exited:
- return {"status": "already_exited", "error": "Process has already finished"}
+ session, err = self._live_session(session_id)
+ if err:
+ return err
- if hasattr(session, '_pty') and session._pty:
+ if session._pty:
try:
session._pty.sendeof()
return {"status": "ok", "message": "EOF sent"}
@@ -2564,29 +2142,18 @@ class ProcessRegistry:
return {"status": "error", "error": str(e)}
def count_running(self) -> int:
- """Return the count of currently-running background processes.
-
- Cheap O(1) read of the running dict, suitable for status-bar polling
- on every render tick. CPython dict ``len()`` is atomic; callers do not
- need to hold ``self._lock``. Reflects ``_running`` only: sessions are
- moved to ``_finished`` when their subprocess exits.
- """
+ """O(1) count of running processes for status-bar polling; CPython dict
+ ``len()`` is atomic so no lock is needed."""
try:
return len(self._running)
except Exception:
return 0
def list_sessions(self, task_id: str = None, session_key: str = None) -> list:
- """List all running and recently-finished processes.
-
- When ``task_id`` is given, processes for that task are included. When
- ``session_key`` is also given, session-scoped background processes
- (``background: true``) registered under that gateway session are
- surfaced too, even if they belong to a different task — so the agent
- can discover a forgotten preview server that is blocking session
- reset (#29177). Such cross-task entries are flagged with
- ``"session_scoped": true``.
- """
+ """List running and recently-finished processes for ``task_id`` and/or
+ ``session_key``. Cross-task entries that share the gateway session (a
+ forgotten preview server blocking session reset) are flagged
+ ``"session_scoped": true``."""
with self._lock:
all_sessions = list(self._running.values()) + list(self._finished.values())
@@ -2611,14 +2178,9 @@ class ProcessRegistry:
"status": "exited" if s.exited else "running",
"output_preview": s.output_buffer[-200:] if s.output_buffer else "",
}
- # Flag processes surfaced only because they share the gateway
- # session (not the current task) — these are the long-lived
- # background processes a user may have forgotten about (#29177).
if task_id and session_key and s.task_id != task_id and s.session_key == session_key:
entry["session_scoped"] = True
- # Trigger metadata so a goal-loop judge can decide to wait on this
- # process's OWN signal (a watch-pattern match or completion), not
- # just its exit. A watcher with watch_patterns may never exit.
+ # Trigger metadata for goal-loop judges (a watcher may never exit).
if s.watch_patterns and not s._watch_disabled:
entry["watch_patterns"] = list(s.watch_patterns)
entry["watch_hit"] = s._watch_hits > 0
@@ -2633,77 +2195,42 @@ class ProcessRegistry:
# ----- Session/Task Queries (for gateway integration) -----
- def has_active_processes(self, task_id: str) -> bool:
- """Check if there are active (running) processes for a task_id."""
+ def _any_running(self, predicate) -> bool:
+ """True if any still-running session satisfies *predicate*, after refreshing
+ detached sessions so a finished-but-unreaped process reads as inactive."""
with self._lock:
sessions = list(self._running.values())
-
for session in sessions:
self._refresh_detached_session(session)
-
with self._lock:
- return any(
- s.task_id == task_id and not s.exited
- for s in self._running.values()
- )
+ return any(not s.exited and predicate(s) for s in self._running.values())
+
+ def has_active_processes(self, task_id: str) -> bool:
+ """Check if there are active (running) processes for a task_id."""
+ return self._any_running(lambda s: s.task_id == task_id)
def has_active_for_session(
self, session_key: str, max_active_age: Optional[float] = None,
) -> bool:
- """Check if there are active processes for a gateway session key.
-
- When *max_active_age* is set (seconds), processes that started more
- than that many seconds ago are **ignored** — they are still running
- but are considered stale and must not block session idle / daily
- reset. This prevents a forgotten ``http.server`` (or any long-lived
- preview process) from permanently freezing the session lifecycle.
-
- Args:
- session_key: Gateway session key to check.
- max_active_age: If set, ignore processes older than this many
- seconds. ``None`` retains the legacy behaviour (any running
- process blocks).
- """
- with self._lock:
- sessions = list(self._running.values())
-
- for session in sessions:
- self._refresh_detached_session(session)
-
+ """Active processes for a gateway session key. Processes older than
+ ``max_active_age`` seconds are ignored as stale so a forgotten
+ ``http.server`` can't freeze session idle/daily reset forever; ``None``
+ keeps legacy behaviour (any running process blocks)."""
now = time.time()
- with self._lock:
- return any(
- s.session_key == session_key
- and not s.exited
- and (max_active_age is None or (now - s.started_at) < max_active_age)
- for s in self._running.values()
- )
+ return self._any_running(
+ lambda s: s.session_key == session_key
+ and (max_active_age is None or (now - s.started_at) < max_active_age)
+ )
def has_any_active(self) -> bool:
- """Whether ANY background process is still running (across all sessions).
-
- Used by scale-to-zero idle detection (gateway/scale_to_zero): a gateway
- with a live background process (terminal background=true) is NOT idle and
- must not be suspended, or the process is lost. Refreshes detached
- sessions first so a finished-but-unreaped process reads as inactive.
- """
- with self._lock:
- sessions = list(self._running.values())
-
- for session in sessions:
- self._refresh_detached_session(session)
-
- with self._lock:
- return any(not s.exited for s in self._running.values())
+ """Whether ANY background process is running — scale-to-zero must not
+ suspend a gateway with live background work or the process is lost."""
+ return self._any_running(lambda s: True)
def snapshot_running_ids(self, task_id: str) -> frozenset[str]:
- """Capture running process IDs owned by ``task_id``.
-
- Gateway turns use this as a boundary marker: if a turn times out, only
- processes absent from its starting snapshot belong to the abandoned
- turn. Older session processes must survive because background tasks
- intentionally span successful turns.
- """
+ """Running IDs owned by ``task_id`` — a turn-boundary marker: on timeout
+ only processes absent from the starting snapshot belong to the abandoned
+ turn; older ones intentionally span turns and must survive."""
with self._lock:
return frozenset(
s.id
@@ -2718,12 +2245,9 @@ class ProcessRegistry:
*,
source: str,
) -> int:
- """Kill processes created for ``task_id`` after a prior snapshot.
-
- ``consume_output`` is forced on: abandoned-turn output must not
- enqueue a synthetic follow-up that revives work the timeout
- deliberately stopped.
- """
+ """Kill ``task_id`` processes created after ``baseline_ids``. Output is
+ consumed so an abandoned turn can't enqueue a follow-up reviving work the
+ timeout deliberately stopped."""
return self.kill_all(
task_id,
exclude_ids=frozenset(baseline_ids or ()),
@@ -2769,30 +2293,18 @@ class ProcessRegistry:
sid for sid, s in self._finished.items()
if (now - s.started_at) > FINISHED_TTL_SECONDS
]
+ if len(self._running) + len(self._finished) - len(expired) >= MAX_PROCESSES:
+ # Still over the limit: also drop the oldest surviving finished session.
+ survivors = [sid for sid in self._finished if sid not in expired]
+ if survivors:
+ expired.append(min(survivors, key=lambda sid: self._finished[sid].started_at))
for sid in expired:
del self._finished[sid]
- self._completion_consumed.discard(sid)
- self._poll_observed.discard(sid)
-
- # If still over limit, remove oldest finished
- total = len(self._running) + len(self._finished)
- if total >= MAX_PROCESSES and self._finished:
- oldest_id = min(self._finished, key=lambda sid: self._finished[sid].started_at)
- del self._finished[oldest_id]
- self._completion_consumed.discard(oldest_id)
- self._poll_observed.discard(oldest_id)
-
- # Drop any _completion_consumed / _poll_observed entries whose sessions
- # are no longer tracked at all — belt-and-suspenders against
- # module-lifetime growth on registry lookup paths that don't reach the
- # dict prunes.
+ # Belt-and-suspenders against module-lifetime growth: forget consumed /
+ # poll-observed marks for any session no longer tracked at all.
tracked = self._running.keys() | self._finished.keys()
- stale = self._completion_consumed - tracked
- if stale:
- self._completion_consumed -= stale
- stale_polls = self._poll_observed - tracked
- if stale_polls:
- self._poll_observed -= stale_polls
+ self._completion_consumed &= tracked
+ self._poll_observed &= tracked
# ----- Checkpoint (crash recovery) -----
@@ -2806,41 +2318,18 @@ class ProcessRegistry:
entries = []
for s in self._running.values():
if not s.exited:
- # Lazily backfill the kernel start time for host PIDs so
- # recovery after restart can detect PID recycling even
- # for sessions spawned before this field existed.
+ # Backfill the start time so recovery can detect PID recycling
+ # even for sessions spawned before this field existed.
if s.host_start_time is None and s.pid_scope == "host" and s.pid:
s.host_start_time = self._safe_host_start_time(s.pid)
- entries.append({
- "session_id": s.id,
- # Redact inline credentials before persisting to
- # disk — the checkpoint file lives under
- # ~/.hermes/processes.json with the raw command
- # (issue #77484). Recovery only uses command for
- # display/logging (the process is already running;
- # adoption re-validates the PID, never re-runs the
- # command), so masking is lossless.
- "command": redact_sensitive_text(s.command, code_file=True),
- "pid": s.pid,
- "pid_scope": s.pid_scope,
- "host_start_time": s.host_start_time,
- "systemd_unit": s.systemd_unit,
- "cwd": s.cwd,
- "started_at": s.started_at,
- "task_id": s.task_id,
- "owner_task_id": s.owner_task_id or s.task_id,
- "session_key": s.session_key,
- "watcher_platform": s.watcher_platform,
- "watcher_chat_id": s.watcher_chat_id,
- "watcher_user_id": s.watcher_user_id,
- "watcher_user_name": s.watcher_user_name,
- "watcher_thread_id": s.watcher_thread_id,
- "watcher_message_id": s.watcher_message_id,
- "watcher_interval": s.watcher_interval,
- "parent_session_id": s.parent_session_id,
- "notify_on_complete": s.notify_on_complete,
- "watch_patterns": s.watch_patterns,
- })
+ entry = {"session_id": s.id, **{f: getattr(s, f) for f in _CHECKPOINT_FIELDS}}
+ # Redact inline credentials before persisting: the file lives
+ # at ~/.hermes/processes.json. Recovery uses command only for
+ # display (adoption re-validates the PID, never re-runs it),
+ # so masking is lossless.
+ entry["command"] = redact_sensitive_text(s.command, code_file=True)
+ entry["owner_task_id"] = s.owner_task_id or s.task_id
+ entries.append(entry)
if extra_entries:
tracked_ids = {item.get("session_id") for item in entries}
entries.extend(
@@ -2878,9 +2367,7 @@ class ProcessRegistry:
pid_scope = entry.get("pid_scope", "host")
if pid_scope != "host":
- # Sandbox-backed processes keep only in-sandbox PIDs in the
- # checkpoint, which are not meaningful to the restarted host
- # process once the original environment handle is gone.
+ # In-sandbox PIDs mean nothing once the environment handle is gone.
logger.info(
"Skipping recovery for non-host process: %s (pid=%s, scope=%s)",
entry.get("command", "unknown")[:60],
@@ -2889,12 +2376,9 @@ class ProcessRegistry:
)
continue
- # The PID must be alive AND still the same process we spawned. A
- # bare liveness check is unsafe: across a restart (especially a
- # reboot or long uptime) the kernel may have recycled this number
- # onto an unrelated process — adopting it would let a later kill or
- # watcher tree-kill a stranger (e.g. a browser). Re-validate the
- # kernel start time recorded in the checkpoint.
+ # Alive AND the same process: across a restart the kernel may have
+ # recycled the PID onto a stranger, and adopting it would let a later
+ # kill tree-kill e.g. a browser.
recorded_start = entry.get("host_start_time")
if not self._host_pid_is_ours(pid, recorded_start):
if self._is_host_pid_alive(pid):
@@ -2915,29 +2399,19 @@ class ProcessRegistry:
unresolved_scope_entries.append(entry)
continue
- session = ProcessSession(
- id=entry["session_id"],
+ fields = {f: entry.get(f, _CHECKPOINT_DEFAULTS[f]) for f in _CHECKPOINT_FIELDS}
+ fields.update(
command=entry.get("command", "unknown"),
- task_id=entry.get("task_id", ""),
owner_task_id=entry.get("owner_task_id", "") or entry.get("task_id", ""),
- session_key=entry.get("session_key", ""),
pid=pid,
host_start_time=recorded_start,
pid_scope=pid_scope,
- systemd_unit=entry.get("systemd_unit", ""),
- cwd=entry.get("cwd"),
started_at=entry.get("started_at", time.time()),
+ )
+ session = ProcessSession(
+ id=entry["session_id"],
detached=True, # Can't read output, but can report status + kill
- watcher_platform=entry.get("watcher_platform", ""),
- watcher_chat_id=entry.get("watcher_chat_id", ""),
- watcher_user_id=entry.get("watcher_user_id", ""),
- watcher_user_name=entry.get("watcher_user_name", ""),
- watcher_thread_id=entry.get("watcher_thread_id", ""),
- watcher_message_id=entry.get("watcher_message_id", ""),
- watcher_interval=entry.get("watcher_interval", 0),
- parent_session_id=entry.get("parent_session_id", ""),
- notify_on_complete=entry.get("notify_on_complete", False),
- watch_patterns=entry.get("watch_patterns", []),
+ **fields,
)
with self._lock:
self._running[session.id] = session
@@ -2969,395 +2443,19 @@ class ProcessRegistry:
process_registry = ProcessRegistry()
-def _format_age(seconds: float) -> str:
- """Human-friendly elapsed string ('18m', '2h3m', '45s')."""
- try:
- s = int(max(0, seconds))
- except (TypeError, ValueError):
- return "?"
- if s < 60:
- return f"{s}s"
- m, s = divmod(s, 60)
- if m < 60:
- return f"{m}m" if s == 0 else f"{m}m{s}s"
- h, m = divmod(m, 60)
- return f"{h}h" if m == 0 else f"{h}h{m}m"
-
-
-def _model_not_found_patterns() -> "list[str]":
- """Model-not-found phrases from the failover classifier.
-
- Imported from ``agent.error_classifier`` so the batch renderer applies
- the SAME classification the failover path consumes — no hand-copied
- pattern list to drift. Fails open to a minimal built-in set so a
- classifier import problem never hides the per-task blocks.
- (Import approach from PR #97667 by @liuhao1024.)
- """
- try:
- from agent.error_classifier import _MODEL_NOT_FOUND_PATTERNS
-
- return list(_MODEL_NOT_FOUND_PATTERNS)
- except Exception:
- return ["is not a valid model", "model not found", "model_not_found"]
-
-
-def _delegation_config() -> dict:
- """Load the active delegation config (model/provider/fallbacks), fail-open.
-
- Mirrors ``tools.delegate_tool._load_config`` so the renderer sees the same
- ``model`` / ``provider`` the dispatcher used, without importing the heavy
- delegation module at import time. Returns ``{}`` on any error so callers
- fail open to "no notice" rather than dropping the per-task blocks.
- """
- try:
- from tools.delegate_tool import _load_config as _cfg
-
- return _cfg() or {}
- except Exception:
- return {}
-
-
-def _delegation_model_not_found(results, config) -> bool:
- """True when a result entry reflects a config-level model_not_found rejection.
-
- Matches when at least one entry's error/summary text contains both a
- model-not-found phrase AND the name of the currently-configured delegation
- model — so a stale task failing on a *different* (removed) model is not
- mis-attributed to the config-level root cause.
- """
- model = (config or {}).get("model")
- if not model:
- return False
- model = str(model).lower()
- for r in results or []:
- text = " ".join(
- str(part) for part in (r.get("error"), r.get("summary")) if part
- ).lower()
- if not text or model not in text:
- continue
- if any(p in text for p in _model_not_found_patterns()):
- return True
- return False
-
-
-def _delegation_model_not_found_notice(results) -> "list[str] | None":
- """Build the config-level model_not_found notice lines, or None.
-
- Returns ``None`` unless at least one result entry shows the configured
- delegation model being rejected by its provider, in which case a short
- actionable block is returned. Every failure path fails open to ``None`` so
- a config hiccup never hides the per-task blocks. Emit once per batch.
- """
- config = _delegation_config()
- if not _delegation_model_not_found(results, config):
- return None
- model = config.get("model") or "?"
- provider = config.get("provider") or "configured provider"
- lines = [
- "⚠ SUBAGENT MODEL REJECTED: the configured Subagent Model "
- f'"{model}" was rejected by provider "{provider}" '
- "(HTTP 400: not a valid model ID).",
- "Every task in this batch failed for this reason before doing any work.",
- "Check Settings → Advanced → Subagent Model (or: "
- "hermes config get delegation.model).",
- ]
- try:
- from hermes_cli.fallback_config import get_fallback_chain
-
- if not get_fallback_chain(config):
- lines.append(
- "No fallback chain is configured, so no failover was attempted."
- )
- except Exception:
- pass
- return lines
-
-
-def _format_async_delegation(evt: dict) -> str:
- """Format an async-delegation completion into a self-contained re-injection.
-
- Carries the FULL original task source (goal, the context the parent
- supplied, toolsets, role, model) plus dispatch time, status, and the
- complete result summary. When this re-enters the conversation the agent
- may be deep in unrelated context and won't remember why the subagent
- existed, so the block is written to stand entirely on its own — enough to
- use the result OR re-dispatch if the world has moved on.
- """
- import time as _time
-
- deleg_id = evt.get("delegation_id", "unknown")
- goal = evt.get("goal", "") or ""
- context = evt.get("context")
- toolsets = evt.get("toolsets")
- role = evt.get("role") or "leaf"
- model = evt.get("model") or "?"
- status = evt.get("status") or "completed"
- summary = evt.get("summary")
- error = evt.get("error")
- api_calls = evt.get("api_calls", 0)
- duration = evt.get("duration_seconds", "?")
- truncated = evt.get("truncated") or evt.get("exit_reason") == "max_iterations"
- dispatched_at = evt.get("dispatched_at")
- completed_at = evt.get("completed_at") or _time.time()
-
- # ----- Batch (fan-out) completion: consolidated multi-task block -----
- # A whole delegate_task fan-out dispatched as one background unit finishes
- # together and carries a per-task `results` list. Render every subagent's
- # summary in one block so the model gets the consolidated outcome at once.
- batch_results = evt.get("results")
- if evt.get("is_batch") or isinstance(batch_results, list):
- results = batch_results or []
- goals = evt.get("goals") or []
- n = len(results) if results else len(goals)
- total_dur = evt.get("total_duration_seconds", duration)
- lines = [
- f"[ASYNC DELEGATION BATCH COMPLETE — {deleg_id}]",
- f"A background fan-out of {n} subagent(s) you dispatched earlier "
- "has finished. All ran in parallel and waited on each other; their "
- "consolidated results are below. You may have moved on since "
- "dispatching — act on these or re-dispatch if things have changed.",
- "",
- ]
- if isinstance(dispatched_at, (int, float)):
- ts = _time.strftime("%Y-%m-%d %H:%M:%S", _time.localtime(dispatched_at))
- age = f" ({_format_age(completed_at - dispatched_at)} ago)"
- lines.append(f"Dispatched: {ts}{age}")
- if context:
- lines.append(f"Context you provided: {context}")
- if toolsets:
- lines.append(f"Toolsets: {', '.join(toolsets)}")
- lines.append(f"Role: {role} Model: {model} Total duration: {total_dur}s")
- if error and not results:
- lines.append("--- ERROR ---")
- lines.append(f"The batch did not complete successfully: {error}")
- return "\n".join(lines)
- # Config-level rejection notice BEFORE the per-task wall — a rejected
- # delegation model fails every task identically before doing any
- # work, and that signal must not stay buried in the task blocks.
- _notice = _delegation_model_not_found_notice(results)
- if _notice:
- lines.append("")
- lines.extend(_notice)
- for r in sorted(results, key=lambda x: x.get("task_index", 0)):
- idx = r.get("task_index", 0)
- r_status = r.get("status", "?")
- r_summary = r.get("summary")
- r_error = r.get("error")
- r_goal = goals[idx] if idx < len(goals) else r.get("goal", "")
- r_truncated = r.get("truncated") or r.get("exit_reason") == "max_iterations"
- icon = "⚠" if r_truncated else ("✓" if r_status in ("completed", "success") else "✗")
- lines.append("")
- header = f"--- {icon} TASK {idx + 1}/{n}"
- if r_goal:
- header += f": {r_goal}"
- header += f" (status={r_status}"
- if r.get("api_calls"):
- header += f", api_calls={r['api_calls']}"
- if r.get("duration_seconds") is not None:
- header += f", {r['duration_seconds']}s"
- if r_truncated:
- header += ", TRUNCATED: hit max_iterations — work may be incomplete"
- header += ") ---"
- lines.append(header)
- if r_status in ("completed", "success") and r_summary:
- if r_truncated:
- lines.append(
- "[TRUNCATED — subagent hit its iteration cap; the "
- "summary below may be incomplete. Verify before relying "
- "on it, or re-dispatch the unfinished part.]"
- )
- lines.append(r_summary)
- elif r_summary:
- if r_error:
- lines.append(f"({r_status}: {r_error})")
- lines.append("Partial output:")
- lines.append(r_summary)
- else:
- lines.append(
- f"(no summary — status={r_status}"
- + (f": {r_error}" if r_error else "")
- + ")"
- )
- r_live = r.get("live_transcript")
- if r_live:
- lines.append(
- f"Full live transcript (complete tool/assistant trace): {r_live}"
- )
- return "\n".join(lines)
-
- age = ""
- if isinstance(dispatched_at, (int, float)):
- age = f" ({_format_age(completed_at - dispatched_at)} ago)"
-
- lines = [
- f"[ASYNC DELEGATION COMPLETE — {deleg_id}]",
- "A background subagent you dispatched earlier has finished. You may "
- "have moved on since dispatching it; the full task source is below so "
- "you can act on the result or re-dispatch if things have changed.",
- "",
- ]
- if isinstance(dispatched_at, (int, float)):
- ts = _time.strftime("%Y-%m-%d %H:%M:%S", _time.localtime(dispatched_at))
- lines.append(f"Dispatched: {ts}{age}")
- lines.append(f"Original goal: {goal}")
- if context:
- lines.append(f"Context you provided: {context}")
- if toolsets:
- lines.append(f"Toolsets: {', '.join(toolsets)}")
- lines.append(f"Role: {role} Model: {model}")
- _notice = _delegation_model_not_found_notice([evt])
- if _notice:
- lines.append("")
- lines.extend(_notice)
- _trunc = " [TRUNCATED: hit max_iterations — work may be incomplete]" if truncated else ""
- lines.append(f"Status: {status} API calls: {api_calls} Duration: {duration}s{_trunc}")
- lines.append("--- RESULT ---")
- if status in ("completed", "success") and summary:
- if truncated:
- lines.append(
- "[TRUNCATED — subagent hit its iteration cap; the summary below "
- "may be incomplete. Verify before relying on it, or re-dispatch "
- "the unfinished part.]"
- )
- lines.append(summary)
- elif status == "interrupted":
- lines.append(
- "The subagent was interrupted before completing"
- + (f": {error}" if error else ".")
- )
- if summary:
- lines.append("Partial output:")
- lines.append(summary)
- else:
- # error / timeout / failed
- lines.append(
- f"The subagent did not complete successfully (status={status})."
- + (f"\n{error}" if error else "")
- )
- if summary:
- lines.append("Partial output:")
- lines.append(summary)
- return "\n".join(lines)
-
-
-def _delegation_attribution_line(evt: dict) -> "str | None":
- """One-line delegation attribution for a child-originated process event.
-
- Subagents run their terminal sessions under ``task_id == subagent_id``
- (delegate_tool._run_single_child). When a background process they started
- completes, its notification is routed to the PARENT conversation by
- design (children consume their own waits via process(wait); anything
- that outlives the child must land where a durable consumer exists).
- Without attribution the parent-facing user sees an anonymous raw output
- wall mid-conversation with no hint it came from a delegation. Resolve
- the task_id against the live + recently-finished subagent registry and
- return a short provenance line, or None for parent-owned processes.
- """
- task_id = str(evt.get("owner_task_id") or evt.get("task_id") or "")
- if not task_id.startswith("sa-"):
- return None
- try:
- from tools.delegate_tool import get_subagent_attribution
-
- info = get_subagent_attribution(task_id)
- except Exception:
- info = None
- if not info:
- # The task_id shape says "subagent" even when the registry entry has
- # aged out — still attribute generically rather than anonymously.
- return f"Started by subagent {task_id} (delegate_task)."
- goal = str(info.get("goal") or "").strip()
- if len(goal) > 120:
- goal = goal[:117] + "..."
- deleg = info.get("delegation_id")
- parts = [f"Started by subagent {task_id}"]
- if deleg:
- parts.append(f"of delegation {deleg}")
- line = " ".join(parts) + "."
- if goal:
- line += f' Task: "{goal}"'
- return line
-
-
-def format_process_notification(evt: dict) -> "str | None":
- """Format a process notification event into a [IMPORTANT: ...] message.
-
- Handles completion events (notify_on_complete), watch pattern matches,
- and watch disabled events from the unified completion_queue.
- """
- evt_type = evt.get("type", "completion")
- _sid = evt.get("session_id", "unknown")
- _cmd = evt.get("command", "unknown")
- _attribution = _delegation_attribution_line(evt)
-
- if evt_type == "watch_disabled":
- return f"[IMPORTANT: {evt.get('message', '')}]"
-
- # Overflow events carry their human-readable summary in `message` —
- # without this case they fall through to the completion formatter and
- # surface as a phantom "process exited (exit code ?)" notification.
- if evt_type in ("watch_overflow_tripped", "watch_overflow_released"):
- return f"[IMPORTANT: {evt.get('message', '')}]"
-
- if evt_type == "watch_match":
- _pat = evt.get("pattern", "?")
- _out = evt.get("output", "")
- _sup = evt.get("suppressed", 0)
- text = (
- f"[IMPORTANT: Background process {_sid} matched "
- f"watch pattern \"{_pat}\".\n"
- )
- if _attribution:
- text += f"{_attribution}\n"
- text += (
- f"Command: {_cmd}\n"
- f"Matched output:\n{_out}"
- )
- if _sup:
- text += f"\n({_sup} earlier matches were suppressed by rate limit)"
- text += "]"
- return text
-
- if evt_type == "async_delegation":
- return _format_async_delegation(evt)
-
- _exit = evt.get("exit_code", "?")
- _out = evt.get("output", "")
- _reason = evt.get("completion_reason") or "exited"
- _source = evt.get("termination_source") or ""
- _signal = ""
- if _exit in {-15, 143, "-15", "143"}:
- _signal = ", SIGTERM"
- if _reason == "killed":
- _status = f"terminated by {_source or 'Hermes'}"
- elif _reason == "lost":
- _status = "marked lost because the process backend disappeared"
- elif _reason == "failed_start":
- _status = "failed to start"
- elif _exit == 0:
- _status = "completed normally"
- else:
- _status = "exited"
- text = (
- f"[IMPORTANT: Background process {_sid} {_status} "
- f"(exit code {_exit}{_signal}).\n"
- )
- if _attribution:
- text += f"{_attribution}\n"
- # A subagent-owned process's full output belongs in the child's
- # transcript/summary, not as a raw wall in the parent conversation —
- # trim the tail hard while keeping enough to recognise failures.
- if isinstance(_out, str) and len(_out) > 600:
- _out = (
- "...(output trimmed — subagent-owned process; see the "
- "delegation's live transcript for full output)\n"
- + _out[-600:]
- )
- text += (
- f"Command: {_cmd}\n"
- f"Output:\n{_out}]"
- )
- return text
+# Notification rendering lives in tools.process_registry_notifications; the names are
+# re-exported here so `from tools.process_registry import format_process_notification`
+# and `patch("tools.process_registry._x")` keep resolving.
+from tools.process_registry_notifications import ( # noqa: F401,E402
+ _delegation_attribution_line,
+ _delegation_config,
+ _delegation_model_not_found,
+ _delegation_model_not_found_notice,
+ _format_age,
+ _format_async_delegation,
+ _model_not_found_patterns,
+ format_process_notification,
+)
# ---------------------------------------------------------------------------
@@ -3367,10 +2465,8 @@ from tools.registry import registry, tool_error
PROCESS_SCHEMA = {
"name": "process_manage",
- # Dieted (#95681): the action enum names the verbs; the description
- # keeps only non-obvious semantics. write-vs-submit is the tool's one
- # real trap (a lone \n on a Windows PTY is not a line terminator) —
- # that teaching gains emphasis rather than losing it.
+ # The enum names the verbs; the description keeps only non-obvious semantics
+ # (write-vs-submit is the one real trap: a lone \n on a Windows PTY is not Enter).
"description": (
"Poll, wait on, or kill background terminal processes (from "
"terminal(background=true)). "
@@ -3415,15 +2511,10 @@ PROCESS_SCHEMA = {
def _redact_process_result(result: dict) -> dict:
- """Redact secrets from background-process output before it reaches the
- model, session.db, and CLI display.
-
- Mirrors the foreground ``terminal`` redaction (terminal_tool.py) so the
- two surfaces can't diverge — issue #43025 (background output was returned
- verbatim). Respects ``security.redact_secrets`` (no force): output fields
- pass through ``redact_terminal_output`` which picks ``code_file`` based on
- the recorded command (env dumps get the ENV-assignment pass). The command
- string itself is also redacted in case it carried an inline credential.
+ """Redact secrets from background-process output before it reaches the model,
+ session.db and CLI, mirroring the foreground ``terminal`` redaction so the two
+ surfaces can't diverge. Respects ``security.redact_secrets``; ``redact_terminal_output``
+ picks ``code_file`` from the recorded command. The command itself is redacted too.
"""
if not isinstance(result, dict):
return result
@@ -3439,51 +2530,49 @@ def _redact_process_result(result: dict) -> dict:
return result
+def _list_processes(task_id) -> dict:
+ # Surface session-scoped background processes (e.g. a forgotten preview
+ # server) in addition to this task's own — they share the gateway
+ # session_key and can block session reset.
+ try:
+ from tools.approval import get_current_session_key
+ session_key = get_current_session_key(default="") or ""
+ except Exception:
+ session_key = ""
+ return {
+ "processes": [
+ _redact_process_result(p)
+ for p in process_registry.list_sessions(task_id=task_id, session_key=session_key or None)
+ ]
+ }
+
+
+# action -> (handler(session_id, args) -> dict, redact output?). Output-bearing
+# actions are redacted; stdin actions return only status.
+_SESSION_ACTIONS = {
+ "poll": (lambda sid, a: process_registry.poll(sid), True),
+ "log": (lambda sid, a: process_registry.read_log(sid, offset=a.get("offset"), limit=a.get("limit", 200)), True),
+ "wait": (lambda sid, a: process_registry.wait(sid, timeout=a.get("timeout")), True),
+ "kill": (lambda sid, a: process_registry.kill_process(sid), True),
+ "write": (lambda sid, a: process_registry.write_stdin(sid, str(a.get("data", ""))), False),
+ "submit": (lambda sid, a: process_registry.submit_stdin(sid, str(a.get("data", ""))), False),
+ "close": (lambda sid, a: process_registry.close_stdin(sid), False),
+}
+
+
def _handle_process(args, **kw):
- task_id = kw.get("task_id")
action = args.get("action", "")
# Coerce to string — some models send session_id as an integer
session_id = str(args.get("session_id", "")) if args.get("session_id") is not None else ""
if action == "list":
- # Surface session-scoped background processes (e.g. a forgotten
- # preview server) in addition to this task's own — they share the
- # gateway session_key and can block session reset (#29177).
- try:
- from tools.approval import get_current_session_key
- session_key = get_current_session_key(default="") or ""
- except Exception:
- session_key = ""
- return json.dumps(
- {
- "processes": [
- _redact_process_result(p)
- for p in process_registry.list_sessions(task_id=task_id, session_key=session_key or None)
- ]
- },
- ensure_ascii=False,
- )
- elif action in {"poll", "log", "wait", "kill", "write", "submit", "close"}:
+ return json.dumps(_list_processes(kw.get("task_id")), ensure_ascii=False)
+ if action in _SESSION_ACTIONS:
if not session_id:
return tool_error(f"session_id is required for {action}")
- if action == "poll":
- return json.dumps(_redact_process_result(process_registry.poll(session_id)), ensure_ascii=False)
- elif action == "log":
- return json.dumps(_redact_process_result(process_registry.read_log(
- session_id, offset=args.get("offset"), limit=args.get("limit", 200))), ensure_ascii=False)
- elif action == "wait":
- return json.dumps(_redact_process_result(process_registry.wait(session_id, timeout=args.get("timeout"))), ensure_ascii=False)
- elif action == "kill":
- return json.dumps(
- _redact_process_result(process_registry.kill_process(session_id)),
- ensure_ascii=False,
- )
- elif action == "write":
- return json.dumps(process_registry.write_stdin(session_id, str(args.get("data", ""))), ensure_ascii=False)
- elif action == "submit":
- return json.dumps(process_registry.submit_stdin(session_id, str(args.get("data", ""))), ensure_ascii=False)
- elif action == "close":
- return json.dumps(process_registry.close_stdin(session_id), ensure_ascii=False)
+ handler, redact = _SESSION_ACTIONS[action]
+ result = handler(session_id, args)
+ return json.dumps(_redact_process_result(result) if redact else result, ensure_ascii=False)
return tool_error(f"Unknown process action: {action}. Use: list, poll, log, wait, kill, write, submit, close")