The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): process_registry — mark_exited/_output_tail/_stdin_op helpers, unified watch_disabled emitter, compact docs
Teknium60e90090798a
diff --git a/tools/process_registry.py b/tools/process_registry.pyindex 950329e38e6..1a392416618 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -1,12 +1,8 @@-"""-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.+"""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. Nothing runs on the host unless TERMINAL_ENV=local; other backends run+the command inside their sandbox through the environment interface."""import codecs@@ -23,9 +19,8 @@ import uuidfrom pathlib import Path_IS_WINDOWS = platform.system() == "Windows"-# systemd transient scopes exist only on Linux. Gate every scope-path branch-# on this constant (not merely "not Windows") so macOS and other POSIX-# platforms provably never touch systemd code (#70716 cross-platform audit).+# systemd transient scopes exist only on Linux; gate every scope-path branch on this+# (not merely "not Windows") so macOS and other POSIX platforms never touch systemd._IS_LINUX = platform.system() == "Linux"from tools.environments.local import _find_shell, _resolve_safe_cwd, _sanitize_subprocess_envfrom hermes_cli._subprocess_compat import windows_hide_flags@@ -38,45 +33,37 @@ from agent.redact import redact_sensitive_textlogger = logging.getLogger(__name__)--# Checkpoint file for crash recovery (gateway only)+# Crash-recovery checkpoint (gateway only)CHECKPOINT_PATH = get_hermes_home() / "processes.json"-# Limits-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_OUTPUT_CHARS = 200_000 # rolling output buffer+FINISHED_TTL_SECONDS = 1800 # keep finished processes 30 minutes+MAX_PROCESSES = 64 # max tracked processes (LRU pruning)-# 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-pattern rate limiting, PER SESSION: at most one watch-match notification per+# 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 watching is+# permanently disabled and the session falls back to notify_on_complete semantics.WATCH_MIN_INTERVAL_SECONDS = 15WATCH_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.+# Lifetime cap, independent of strikes: a pattern recurring just above the cooldown+# never strikes yet forces a full-context agent turn each time; watch_patterns is+# documented as "ONLY for rare one-shot signals", so after this many deliveries 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-# siblings can't collectively flood the user even when each is under its own cap.+# Global circuit breaker across all sessions so concurrent siblings can't collectively+# flood the user even when each is under its own cap.WATCH_GLOBAL_MAX_PER_WINDOW = 15WATCH_GLOBAL_WINDOW_SECONDS = 10WATCH_GLOBAL_COOLDOWN_SECONDS = 30-# ----------------------------------------------------------------------------# systemd cgroup isolation for gateway-spawned local executors-# ---------------------------------------------------------------------------+# --- systemd cgroup isolation for gateway-spawned local executors ------------------# 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-oomd. ``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()_SYSTEMD_SCOPE_PROBED_AT = 0.0@@ -106,8 +93,7 @@ def _worker_memory_max_bytes() -> int:logger.warning("Ignoring invalid TERMINAL_LOCAL_MEMORY_MAX_MB=%r; ""expected an integer representing at least %d MiB",- override,- _MIN_WORKER_MEMORY_MAX_BYTES // (1024 * 1024),+ override, _MIN_WORKER_MEMORY_MAX_BYTES // (1024 * 1024),)candidates: List[int] = []@@ -115,21 +101,15 @@ def _worker_memory_max_bytes() -> int:for line in Path("/proc/self/cgroup").read_text(encoding="utf-8").splitlines():if line.startswith("0::"):relative = line.partition("::")[2].lstrip("/")- raw_limit = (- Path("/sys/fs/cgroup") / relative / "memory.max"- ).read_text(encoding="utf-8").strip()+ raw_limit = (Path("/sys/fs/cgroup") / relative / "memory.max").read_text(encoding="utf-8").strip()if raw_limit.isdigit() and int(raw_limit) >= _MIN_WORKER_MEMORY_MAX_BYTES:candidates.append(int(raw_limit))breakexcept (OSError, ValueError):pass-try: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(min(_WORKER_MEMORY_MAX_CAP_BYTES, max(_MIN_WORKER_MEMORY_MAX_BYTES, physical_bytes // 2)))except (OSError, ValueError, TypeError):pass@@ -138,58 +118,44 @@ def _worker_memory_max_bytes() -> int: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.-- ``--collect`` makes the transient scope self-clean after exit; ``--unit`` gives it- a recognisable name for ``systemctl --user status`` / journalctl.- """+ """``systemd-run --user --scope`` argv shared by the probe and real spawns.+ ``--collect`` self-cleans the scope after exit; ``--unit`` names it for systemctl."""return [- binary, "--user", "--scope", "--quiet",- "--unit", unit_name,- "--collect",+ binary, "--user", "--scope", "--quiet", "--unit", unit_name, "--collect","--property", "MemoryAccounting=yes","--property", f"MemoryMax={_worker_memory_max_bytes()}","--property", "OOMPolicy=kill",- "--",- *argv,+ "--", *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.- """- cached = _SYSTEMD_SCOPE_AVAILABLE- if cached is True:+ """Cached probe verdict, or None when a (re)probe is due. True is permanent; False+ expires after ``_SYSTEMD_SCOPE_FAILURE_TTL_SECONDS`` so a D-Bus blip isn't sticky."""+ if _SYSTEMD_SCOPE_AVAILABLE is True:return True- if cached is False and time.monotonic() - _SYSTEMD_SCOPE_PROBED_AT < _SYSTEMD_SCOPE_FAILURE_TTL_SECONDS:+ if _SYSTEMD_SCOPE_AVAILABLE is False and time.monotonic() - _SYSTEMD_SCOPE_PROBED_AT < _SYSTEMD_SCOPE_FAILURE_TTL_SECONDS:return Falsereturn Nonedef _systemd_run_user_scope_available() -> bool:- """Return True if ``systemd-run --user --scope`` can create a cgroup.+ """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.+ ``shutil.which`` alone is insufficient: system services and containers may lack+ the user D-Bus bus even with the binary on PATH (every spawn would fail with+ ``Failed to connect to user bus``), so a cheap ``/bin/true`` probe is run and cached."""global _SYSTEMD_SCOPE_AVAILABLE, _SYSTEMD_SCOPE_PROBED_ATverdict = _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: a concurrent first-use spawn must not observe a temporary+ # False mid-probe, or it would launch back inside the gateway cgroup.with _SYSTEMD_SCOPE_PROBE_LOCK:verdict = _systemd_scope_cached()if verdict is not None:return verdict-available = Falseif _IS_LINUX:try:@@ -197,23 +163,19 @@ def _systemd_run_user_scope_available() -> bool:binary = shutil.which("systemd-run")if binary:- # A unique unit avoids collisions; the timeout bounds D-Bus.+ # Unique unit avoids collisions; the timeout bounds D-Bus.probe_unit = f"hermes-probe-scope-{os.getpid()}-{uuid.uuid4().hex[:8]}"result = subprocess.run(- _systemd_scope_argv(binary, probe_unit, "/bin/true"),- capture_output=True,- timeout=3,+ _systemd_scope_argv(binary, probe_unit, "/bin/true"), capture_output=True, timeout=3,)available = result.returncode == 0if not available:logger.debug("systemd-run --user --scope probe failed (rc=%s): %s",- result.returncode,- (result.stderr or b"").decode("utf-8", "replace").strip(),+ result.returncode, (result.stderr or b"").decode("utf-8", "replace").strip(),)except Exception as exc:logger.debug("systemd-run --user --scope probe error: %s", exc)-_SYSTEMD_SCOPE_AVAILABLE = available_SYSTEMD_SCOPE_PROBED_AT = time.monotonic()return available@@ -222,39 +184,30 @@ def _systemd_run_user_scope_available() -> bool:def _is_supervised_gateway_process() -> bool:"""Whether this process is the live, supervised Hermes gateway itself.- 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.+ 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 — scopes are for the gateway, not terminal children or CLIs."""if os.environ.get("_HERMES_GATEWAY") != "1":return False-try:from gateway.restart import is_gateway_supervisor_processfrom gateway.status import get_running_pid- return (- is_gateway_supervisor_process()- and get_running_pid(cleanup_stale=False) == os.getpid()- )+ return is_gateway_supervisor_process() and get_running_pid(cleanup_stale=False) == os.getpid()except Exception as exc:logger.debug("Could not verify supervised gateway process identity: %s", exc)return False-def _build_systemd_scope_argv(- shell_argv: List[str],- unit_suffix: str,-) -> List[str]:+def _build_systemd_scope_argv(shell_argv: List[str], unit_suffix: str) -> List[str]:"""Wrap *shell_argv* in a ``systemd-run --user --scope`` invocation with its ownmemory accounting, so an OOM in the worker cannot kill the gateway cgroup."""import shutilbinary = shutil.which("systemd-run")if binary is None:- # Caller should have checked _systemd_run_user_scope_available();- # guard anyway so we never pass None into Popen.+ # Caller should have probed availability; never pass None into Popen anyway.return shell_argvreturn _systemd_scope_argv(binary, f"hermes-worker-{unit_suffix}", *shell_argv)@@ -262,13 +215,10 @@ def _build_systemd_scope_argv(def _stop_systemd_unit(unit_name: str) -> bool:"""Stop a transient systemd user scope by unit name.- 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 stopped (or was already gone), False if- ``systemctl`` is unavailable or the stop command failed.+ Reaps the *entire* cgroup — catching double-forked descendants reparented to init+ inside the scope that survive a plain PID signal (SIGTERM all, SIGKILL after+ ``TimeoutStopSec``). True if stopped or already gone; False if ``systemctl`` is+ unavailable or the stop failed."""import shutil@@ -276,24 +226,12 @@ def _stop_systemd_unit(unit_name: str) -> bool:if binary is None:return Falsetry:- result = subprocess.run(- [binary, "--user", "stop", unit_name],- capture_output=True,- timeout=15,- )+ result = subprocess.run([binary, "--user", "stop", unit_name], capture_output=True, timeout=15)if result.returncode != 0:stderr = (result.stderr or b"").decode(errors="replace").strip()- stderr_lower = stderr.lower()- if any(- marker in stderr_lower- for marker in ("not loaded", "not found", "does not exist")- ):+ if any(marker in stderr.lower() for marker in ("not loaded", "not found", "does not exist")):return True- logger.debug(- "systemctl --user stop %s exited %d: %s",- unit_name, result.returncode,- stderr,- )+ logger.debug("systemctl --user stop %s exited %d: %s", unit_name, result.returncode, stderr)return Falsereturn Trueexcept Exception as exc:@@ -312,31 +250,42 @@ def format_uptime_short(seconds: int) -> str:return f"{hours}h {mins}m"+def _not_found(session_id: str) -> dict:+ return {"status": "not_found", "error": f"No process with ID {session_id}"}+++def _output_tail(session: "ProcessSession", n: int) -> str:+ """Last *n* chars of the session output with ANSI sequences stripped."""+ from tools.ansi_strip import strip_ansi++ return strip_ansi(session.output_buffer[-n:])++@dataclassclass ProcessSession:"""A tracked background process with output buffering."""- 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. "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+ id: str # "proc_xxxxxxxxxxxx"+ command: str+ task_id: str = "" # Task/sandbox isolation key (CONTAINER key,+ # may be collapsed by _resolve_container_task_id)+ owner_task_id: str = "" # RAW spawning task id ("sa-..."); ownership+ # checks must use this, not task_id+ session_key: str = "" # Gateway session key (reset protection)+ pid: Optional[int] = Noneprocess: Optional[subprocess.Popen] = None # Popen handle (local only)- env_ref: Any = None # Reference to the environment object- cwd: Optional[str] = None # Working directory- started_at: float = 0.0 # time.time() of spawn (wall clock)+ env_ref: Any = None # Environment object (sandbox spawns)+ cwd: Optional[str] = None+ started_at: float = 0.0 # time.time() of spawnhost_start_time: Optional[int] = None # kernel start ticks (/proc/<pid>/stat f22) — PID-reuse guard- exited: bool = False # Whether the process has finished- exit_code: Optional[int] = None # Exit code (None if still running)+ exited: bool = False+ exit_code: Optional[int] = None # None while runningcompletion_reason: str = "exited" # exited|killed|lost|failed_start|already_exitedtermination_source: str = "" # process.kill|kill_all|backend_lost|failed_start- output_buffer: str = "" # Rolling output (last MAX_OUTPUT_CHARS)+ output_buffer: str = "" # Rolling tail (last max_output_chars)max_output_chars: int = MAX_OUTPUT_CHARS- detached: bool = False # True if recovered from crash (no pipe)+ detached: bool = False # Recovered from checkpoint (no pipe)pid_scope: str = "host" # "host" for local/PTY PIDs, "sandbox" for env-local PIDs- systemd_unit: str = "" # transient scope unit name when spawned under systemd-run (#70716)+ systemd_unit: str = "" # transient scope unit name when spawned under systemd-run# Watcher/notification metadata (persisted for crash recovery)watcher_platform: str = ""watcher_chat_id: str = ""@@ -345,11 +294,10 @@ class ProcessSession:watcher_thread_id: str = ""watcher_message_id: str = "" # Triggering message id — reply anchor for topic routingwatcher_interval: int = 0 # 0 = no watcher configured- # 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.+ # Session-db id of the spawning conversation; lets the gateway drop completions whose+ # session was closed at a user boundary (/new) instead of injecting into the NEW one.parent_session_id: str = ""- notify_on_complete: bool = False # Queue agent notification on exit+ notify_on_complete: bool = False # Queue agent notification on exitwatch_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@@ -363,7 +311,7 @@ class ProcessSession:_completion_event: threading.Event = field(default_factory=threading.Event, repr=False)_lock: threading.Lock = field(default_factory=threading.Lock)_reader_thread: Optional[threading.Thread] = field(default=None, repr=False)- _pty: Any = field(default=None, repr=False) # ptyprocess handle (when use_pty=True)+ _pty: Any = field(default=None, repr=False) # ptyprocess handle (use_pty=True)def append_output(self, text: str) -> None:"""Append to the rolling output buffer under the session lock, keeping the tail."""@@ -372,6 +320,16 @@ class ProcessSession:if len(self.output_buffer) > self.max_output_chars:self.output_buffer = self.output_buffer[-self.max_output_chars:]+ def mark_exited(self, exit_code, reason: str = "exited", source: str = "") -> None:+ """Record an exit. A kill that raced the observer already recorded its own+ exit_code/reason; never overwrite it."""+ self.exited = True+ if self.completion_reason != "killed":+ self.exit_code = exit_code+ self.completion_reason = reason+ if source:+ self.termination_source = source+# Session fields persisted verbatim in the crash-recovery checkpoint (plus# ``session_id``; ``command`` is redacted and ``owner_task_id`` defaulted on write).@@ -408,10 +366,8 @@ class ProcessRegistry:self._running: Dict[str, ProcessSession] = {}self._finished: Dict[str, ProcessSession] = {}self._lock = threading.Lock()-# Side-channel for check_interval watchers (gateway reads after agent run)self.pending_watchers: List[Dict[str, Any]] = []-# 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.@@ -423,7 +379,6 @@ class ProcessRegistry:restore_undelivered_completions(self.completion_queue)except Exception as exc:logger.warning("Could not restore async delegation completions: %s", exc)-# 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()@@ -433,7 +388,6 @@ class ProcessRegistry:# 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.self._global_watch_lock = threading.Lock()self._global_watch_window_start: float = 0.0@@ -455,8 +409,7 @@ class ProcessRegistry:return "\n".join(lines)def _emit_output(self, session: ProcessSession, chunk: str) -> None:- """Forward a freshly-read chunk to the live-output sink, if one is set.- Called from reader threads; never raise into the read loop."""+ """Forward a chunk to the live-output sink; called from reader threads, never raises."""sink = self.on_outputif sink is None or not chunk:return@@ -468,10 +421,10 @@ class ProcessRegistry:def _check_watch_patterns(self, session: ProcessSession, new_text: str) -> None:"""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.+ Per-session rate limiting (see 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@@ -479,8 +432,6 @@ class ProcessRegistry:# avoids stale notifications minutes after the process ended.if session.exited:return-- # Scan new text line-by-line for pattern matchesmatched_lines = []matched_pattern = Nonefor line in new_text.splitlines():@@ -490,7 +441,6 @@ class ProcessRegistry:if matched_pattern is None:matched_pattern = patbreak # one match per line is enough-if not matched_lines:return@@ -498,29 +448,26 @@ class ProcessRegistry:should_disable = Falselifetime_exhausted = Falsewith session._lock:- # Case 1: inside the cooldown — drop, count one strike per window, and- # disable + promote once the strike limit is hit.+ # Inside the cooldown: drop, count one strike per window, 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:- # First drop in this window — count one strike.session._watch_strike_candidate = Truesession._watch_consecutive_strikes += 1if session._watch_consecutive_strikes >= WATCH_STRIKE_LIMIT:session._watch_disabled = True- # Promote to notify_on_complete so the agent still gets- # exactly one notification when the process actually ends.+ # Promote so the agent still gets exactly one notification on exit.session.notify_on_complete = Trueshould_disable = Truereturn_early = Trueelse:- # Case 2: cooldown expired. A prior window with no drops resets the+ # 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 = 0session._watch_strike_candidate = False-- # Emit the notification and start a new cooldown window.+ # Emit and start a new cooldown window.session._watch_last_emit_at = nowsession._watch_cooldown_until = now + WATCH_MIN_INTERVAL_SECONDSsession._watch_hits += 1@@ -536,54 +483,41 @@ class ProcessRegistry:if return_early:if should_disable:# Exactly one summary so the agent/user sees why things went quiet.- self.completion_queue.put({- **self._watch_event_base(session),- "type": "watch_disabled",- "suppressed": session._watch_suppressed,- "message": (- f"Watch patterns disabled for process {session.id} — "- f"{WATCH_STRIKE_LIMIT} consecutive rate-limit windows triggered "- f"(min spacing {WATCH_MIN_INTERVAL_SECONDS}s). "- f"Falling back to notify_on_complete semantics; you'll get "- f"exactly one notification when the process exits."- ),- })+ self._emit_watch_disabled(+ session, session._watch_suppressed,+ f"{WATCH_STRIKE_LIMIT} consecutive rate-limit windows triggered "+ f"(min spacing {WATCH_MIN_INTERVAL_SECONDS}s). ",+ )return- # Trim matched output to a reasonable sizeoutput = "\n".join(matched_lines[:20])if len(output) > 2000:output = output[:2000] + "\n...(truncated)"-- if not self._global_watch_admit(now):- # Even when the breaker drops the final match, still explain the silence.- if lifetime_exhausted:- self._emit_lifetime_watch_disabled(session)- return-- notification = {- **self._watch_event_base(session),- "type": "watch_match",- "pattern": matched_pattern,- "output": output,- "suppressed": suppressed,- }- _redact_process_result(notification)- self.completion_queue.put(notification)-+ if self._global_watch_admit(now):+ notification = {+ **self._watch_event_base(session),+ "type": "watch_match",+ "pattern": matched_pattern,+ "output": output,+ "suppressed": suppressed,+ }+ _redact_process_result(notification)+ self.completion_queue.put(notification)+ # Even when the breaker drops the final match, still explain the silence.if lifetime_exhausted:- self._emit_lifetime_watch_disabled(session)+ self._emit_watch_disabled(+ session, 0, f"reached the lifetime cap of {WATCH_LIFETIME_MAX_HITS} delivered matches. ",+ )- def _emit_lifetime_watch_disabled(self, session: ProcessSession) -> None:- """Queue the watch_disabled summary for the lifetime-cap path."""+ def _emit_watch_disabled(self, session: ProcessSession, suppressed: int, why: str) -> None:+ """Queue the one-shot watch_disabled summary (strike-limit or lifetime-cap path)."""self.completion_queue.put({**self._watch_event_base(session),"type": "watch_disabled",- "suppressed": 0,+ "suppressed": suppressed,"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"Watch patterns disabled for process {session.id} — {why}"+ f"Falling back to notify_on_complete semantics; you'll get "f"exactly one notification when the process exits."),})@@ -609,17 +543,9 @@ class ProcessRegistry: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,+ "session_id": "", "session_key": "", "command": "", "type": type_, **extra,"message": message,- "platform": "",- "chat_id": "",- "user_id": "",- "user_name": "",- "thread_id": "",+ "platform": "", "chat_id": "", "user_id": "", "user_name": "", "thread_id": "",}def _global_watch_admit(self, now: float) -> bool:@@ -629,7 +555,7 @@ class ProcessRegistry: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+ release_msg = trip_msg = Nonewith 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:@@ -639,47 +565,37 @@ class ProcessRegistry:self._global_watch_window_start = nowself._global_watch_window_hits = 0if suppressed > 0:- # 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:+ # Still in cooldown — drop and count.self._global_watch_suppressed_during_trip += 1admit = False- trip_now = Noneelse:- # Slide the window.if now - self._global_watch_window_start >= WATCH_GLOBAL_WINDOW_SECONDS:self._global_watch_window_start = nowself._global_watch_window_hits = 0-- if self._global_watch_window_hits >= WATCH_GLOBAL_MAX_PER_WINDOW:- # Trip the breaker.+ admit = self._global_watch_window_hits < WATCH_GLOBAL_MAX_PER_WINDOW+ if admit:+ self._global_watch_window_hits += 1+ else:self._global_watch_tripped_until = now + WATCH_GLOBAL_COOLDOWN_SECONDSself._global_watch_suppressed_during_trip += 1- trip_now = now- admit = False- else:- self._global_watch_window_hits += 1- trip_now = None- admit = True-+ trip_msg = 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.",+ )# Queue summary events outside the lock.- if release_msg is not None:- self.completion_queue.put(release_msg)- if trip_now is not None:- 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.",- ))+ for msg in (release_msg, trip_msg):+ if msg is not None:+ self.completion_queue.put(msg)return admit@staticmethod@@ -687,8 +603,8 @@ class ProcessRegistry:"""Best-effort liveness check for host-visible PIDs."""if not pid:return False- # ``os.kill(pid, 0)`` is NOT a no-op on Windows (bpo-14484) — use- # the cross-platform existence check.+ # ``os.kill(pid, 0)`` is NOT a no-op on Windows (bpo-14484) — use the+ # cross-platform existence check.from gateway.status import _pid_existsreturn _pid_exists(pid)@@ -714,37 +630,28 @@ class ProcessRegistry:"""if not cls._is_host_pid_alive(pid):return False- if expected_start is None:- return True- return cls._safe_host_start_time(pid) == expected_start+ return expected_start is None or cls._safe_host_start_time(pid) == expected_startdef _refresh_detached_session(self, session: Optional[ProcessSession]) -> Optional[ProcessSession]:"""Update recovered host-PID sessions when the underlying process has exited."""if session is None or session.exited or not session.detached or session.pid_scope != "host":return session-# 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-with session._lock:if session.exited:return sessionsession.exited = True- # Recovered sessions no longer have a waitable handle, so the real- # exit code is unavailable once the original process object is gone.+ # No waitable handle survives recovery, so the real exit code is unknown.session.exit_code = None-self._move_to_finished(session)return session@staticmethoddef _proc_alive(proc) -> bool:- """True if a psutil.Process is running and not a zombie.-- A zombie is already dead (just unreaped), so there's nothing to SIGKILL.- """+ """True if a psutil.Process is running and not a zombie (already dead, just unreaped)."""try:import psutilif not proc.is_running():@@ -767,9 +674,8 @@ class ProcessRegistry:@staticmethoddef _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."""+ """Grace (s) between SIGTERM and escalated SIGKILL, floored at 0 (0 disables+ escalation): ``terminal.daemon_term_grace_seconds``; 2.0 if config is unreadable."""try:return max(float(ProcessRegistry._config_value("terminal", "daemon_term_grace_seconds", 2.0)), 0.0)except Exception:@@ -783,17 +689,15 @@ class ProcessRegistry:mismatch or dead PID means the number was recycled onto a stranger and werefuse 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).+ POSIX: psutil SIGTERMs children before the parent so subprocess trees+ (Chromium renderers under an agent-browser daemon) aren't reparented to init+ and survive; survivors are SIGKILLed after ``terminal.daemon_term_grace_seconds``.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``.+ ``gateway.status.terminate_pid``). psutil is unusable there: PPID links go+ stale so ``children(recursive=True)`` misses orphans, and ``terminate()`` is+ ``TerminateProcess()`` on one handle — nothing cascades like a process-group+ SIGTERM. Bare ``os.kill`` covers OSError/PermissionError and a missing taskkill."""if expected_start is not None and not cls._host_pid_is_ours(pid, expected_start):logger.warning(@@ -801,6 +705,7 @@ class ProcessRegistry:"PID was recycled onto an unrelated process.", pid,)return+def _sigterm_quietly():try:os.kill(pid, signal.SIGTERM)@@ -811,11 +716,8 @@ class ProcessRegistry:try:subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"],- capture_output=True,- text=True, encoding='utf-8', errors='replace',- timeout=10,- creationflags=windows_hide_flags(),- stdin=subprocess.DEVNULL,+ capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10,+ creationflags=windows_hide_flags(), stdin=subprocess.DEVNULL,)except (FileNotFoundError, subprocess.TimeoutExpired, OSError):_sigterm_quietly()@@ -829,32 +731,27 @@ class ProcessRegistry:except (OSError, PermissionError):_sigterm_quietly()return-# Snapshot the whole tree (children before parent) and SIGTERM each.try:targets = parent.children(recursive=True)except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):targets = []targets.append(parent)-for proc in targets:try:proc.terminate()except (psutil.NoSuchProcess, psutil.AccessDenied, OSError):pass-- # 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.+ # Escalate to SIGKILL for anything that ignored SIGTERM within the grace window.+ # ``psutil.wait_procs``' gone/alive partition is deliberately NOT trusted: it+ # reaps via ``Process.wait()`` and mis-partitions across zombie transitions in a+ # parent/child tree, leaving survivors un-killed. Re-probing every target is+ # deterministic.grace = cls._daemon_term_grace_seconds()if grace <= 0:returndeadline = time.monotonic() + grace- while time.monotonic() < deadline:- if not any(cls._proc_alive(_p) for _p in targets):- break+ while time.monotonic() < deadline and any(cls._proc_alive(_p) for _p in targets):time.sleep(0.05)for proc in targets:try:@@ -883,31 +780,28 @@ 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).- """+ def _scope_argv(self, session: ProcessSession, safe_command: str, unit_suffix: str, label: str) -> List[str]:+ """Login-shell argv for *safe_command*, wrapped in a transient systemd scope when+ we are the supervised gateway (own cgroup: an OOM kills only the worker, not the+ gateway and its messaging control plane)."""+ argv = [_find_shell(), "-lic", f"set +m; {safe_command}"]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+ return _build_systemd_scope_argv(argv, unit_suffix=unit_suffix)if in_supervised_gateway:- # Under a supervisor but no private cgroup: an OOM in the worker can- # still take the whole gateway down.+ # Under a supervisor but no private cgroup: a worker OOM 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+ return argvdef _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,- )+ reader = threading.Thread(target=reader_target, args=(session,), daemon=True, name=reader_name)session._reader_thread = readerreader.start()with self._lock:@@ -925,22 +819,14 @@ class ProcessRegistry:from winpty import PtyProcess as _PtyProcessClselse: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),- )+ pty_argv = self._scope_argv(session, safe_command, session.id, "PTY")+ pty_proc = _PtyProcessCls.spawn(pty_argv, cwd=session.cwd, env=pty_env, dimensions=(30, 120))session.pid = pty_proc.pidsession.host_start_time = self._safe_host_start_time(session.pid)session._pty = pty_proc@@ -957,19 +843,15 @@ class ProcessRegistry:use_pty: bool = False,owner_task_id: str = "",) -> ProcessSession:- """Spawn a background process locally (TERMINAL_ENV=local only; other- backends use spawn_via_env()).-- ``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.- """+ """Spawn a background process locally (TERMINAL_ENV=local; other backends use+ spawn_via_env()). ``use_pty`` requests a pseudo-terminal via ptyprocess/pywinpty+ for interactive CLIs, falling back to a plain pipe when unavailable or failing."""# 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_bgsafe_command = _rewrite_bg(command)-session = ProcessSession(id=f"proc_{uuid.uuid4().hex[:12]}",command=command,@@ -1000,39 +882,24 @@ class ProcessRegistry:# 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()bg_env = _sanitize_subprocess_env(os.environ, env_vars)bg_env["PYTHONUNBUFFERED"] = "1"_popen_kwargs = {"creationflags": windows_hide_flags()} if _IS_WINDOWS else {}-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",- )-+ spawn_argv = self._scope_argv(session, safe_command, unit_suffix, "Local")# 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,- cwd=session.cwd,- env=bg_env,- encoding="utf-8",- errors="replace",- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- stdin=subprocess.DEVNULL,- start_new_session=True,- **_popen_kwargs,+ spawn_argv, text=True, cwd=session.cwd, env=bg_env, encoding="utf-8", errors="replace",+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,+ start_new_session=True, **_popen_kwargs,)-session.process = procsession.pid = proc.pidsession.host_start_time = self._safe_host_start_time(session.pid)-try:self._track_started(session, self._reader_loop, f"proc-reader-{session.id}")except Exception:@@ -1059,7 +926,6 @@ class ProcessRegistry:except Exception:passraise-return sessiondef spawn_via_env(@@ -1074,9 +940,9 @@ class ProcessRegistry:) -> ProcessSession:"""Spawn a background process inside a non-local backend's sandbox.- 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.+ The command is wrapped to capture its in-sandbox PID and redirect output to a+ log file that later execute() calls poll. No live pipe or stdin, but it runs in+ the correct sandbox context."""session = ProcessSession(id=f"proc_{uuid.uuid4().hex[:12]}",@@ -1089,32 +955,18 @@ class ProcessRegistry:env_ref=env,pid_scope="sandbox",)-- # Run the command in the sandbox with output capturetemp_dir = self._env_temp_dir(env)- log_path = f"{temp_dir}/hermes_bg_{session.id}.log"- pid_path = f"{temp_dir}/hermes_bg_{session.id}.pid"- exit_path = f"{temp_dir}/hermes_bg_{session.id}.exit"- quoted_command = shlex.quote(command)- quoted_temp_dir = shlex.quote(temp_dir)- quoted_log_path = shlex.quote(log_path)- quoted_pid_path = shlex.quote(pid_path)- quoted_exit_path = shlex.quote(exit_path)+ log_path, pid_path, exit_path = (f"{temp_dir}/hermes_bg_{session.id}.{ext}" for ext in ("log", "pid", "exit"))+ q = shlex.quotebg_command = (- f"mkdir -p {quoted_temp_dir} && "- f"( nohup bash -lc {quoted_command} > {quoted_log_path} 2>&1; "- f"rc=$?; printf '%s\\n' \"$rc\" > {quoted_exit_path} ) & "- f"echo $! > {quoted_pid_path} && cat {quoted_pid_path}"+ f"mkdir -p {q(temp_dir)} && "+ f"( nohup bash -lc {q(command)} > {q(log_path)} 2>&1; "+ f"rc=$?; printf '%s\\n' \"$rc\" > {q(exit_path)} ) & "+ f"echo $! > {q(pid_path)} && cat {q(pid_path)}")-try:- result = env.execute(- bg_command,- timeout=timeout,- rewrite_compound_background=False,- )+ result = env.execute(bg_command, timeout=timeout, rewrite_compound_background=False)output = result.get("output", "").strip()- # Try to extract the PID from the outputfor line in output.splitlines():line = line.strip()if line.isdigit():@@ -1123,39 +975,27 @@ class ProcessRegistry:# 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))- if session.exit_code == 0:- session.exit_code = -1- session.completion_reason = "failed_start"- session.termination_source = "failed_start"- session.output_buffer = result.get("output", "").strip()+ session.mark_exited(int(result.get("returncode", -1)) or -1, "failed_start", "failed_start")+ session.output_buffer = outputexcept Exception as e:- session.exited = True- session.exit_code = -1- session.completion_reason = "failed_start"- session.termination_source = "failed_start"+ session.mark_exited(-1, "failed_start", "failed_start")session.output_buffer = f"Failed to start: {e}"- if not session.exited:- # Start a poller thread that periodically reads the log file- reader = threading.Thread(- target=self._env_poller_loop,- args=(session, env, log_path, pid_path, exit_path),- daemon=True,- name=f"proc-poller-{session.id}",- )- session._reader_thread = reader- reader.start()-+ if session.exited:+ with self._lock:+ self._prune_if_needed()+ return session+ # Poller thread periodically reads the log file+ reader = threading.Thread(+ target=self._env_poller_loop, args=(session, env, log_path, pid_path, exit_path),+ daemon=True, name=f"proc-poller-{session.id}",+ )+ session._reader_thread = reader+ reader.start()with self._lock:self._prune_if_needed()- if not session.exited:- self._running[session.id] = session-- if not session.exited:- self._write_checkpoint()-+ self._running[session.id] = session+ self._write_checkpoint()return session# ----- Reader / Poller Threads -----@@ -1166,19 +1006,18 @@ class ProcessRegistry:Uses ``buffer.read1(4096)`` not ``TextIOWrapper.read(4096)``: on pipes thelatter 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.+ 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`` 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 (mirrors ``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- # 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.+ # A multibyte UTF-8 char split across read1() chunks would become U+FFFD with+ # stateless decoding; the incremental decoder holds the partial sequence.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")def _append_chunk(chunk: str):@@ -1193,9 +1032,7 @@ class ProcessRegistry:if proc is None or proc.stdout is None:returnstdout = proc.stdout-raw_read = getattr(getattr(stdout, "buffer", None), "read1", None)-# select() needs a real OS fd; mocked streams (tests, adapters) may lack# fileno() and use the blocking loop instead.fd = None@@ -1226,9 +1063,9 @@ class ProcessRegistry:_append_chunk(chunk)idle_after_exit = 0elif proc.poll() is not None:- # 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.+ # 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 += 1if idle_after_exit >= 3:break@@ -1246,7 +1083,6 @@ class ProcessRegistry:chunk = stdout.read(4096)if not chunk:break-_append_chunk(chunk)except Exception as e:logger.debug("Process stdout reader ended: %s", e)@@ -1266,22 +1102,15 @@ class ProcessRegistry:logger.debug("Process wait timed out or failed: %s", e)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- ):+ def _env_poller_loop(self, session: ProcessSession, env: Any, log_path: str, pid_path: str, exit_path: str):"""Background thread: poll a sandbox log file for non-local backends."""- quoted_log_path = shlex.quote(log_path)- quoted_pid_path = shlex.quote(pid_path)- quoted_exit_path = shlex.quote(exit_path)- prev_output_len = 0 # track delta for watch pattern scanning+ q = shlex.quote+ prev_output_len = 0 # delta tracking for watch-pattern scanningwhile not session.exited:- time.sleep(2) # Poll every 2 seconds+ time.sleep(2)try:- # Read new output from the log file- result = env.execute(f"cat {quoted_log_path} 2>/dev/null", timeout=10)- new_output = result.get("output", "")+ new_output = env.execute(f"cat {q(log_path)} 2>/dev/null", timeout=10).get("output", "")if new_output:- # 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:@@ -1289,30 +1118,21 @@ class ProcessRegistry:if delta:self._check_watch_patterns(session, delta)self._emit_output(session, delta)-- # Check if process is still runningcheck = env.execute(- f"kill -0 \"$(cat {quoted_pid_path} 2>/dev/null)\" 2>/dev/null; echo $?",- timeout=5,+ f"kill -0 \"$(cat {q(pid_path)} 2>/dev/null)\" 2>/dev/null; echo $?", timeout=5,)check_output = check.get("output", "").strip()if check_output and check_output.splitlines()[-1].strip() != "0":- # Process has exited -- get exit code captured by the wrapper shell.- exit_result = env.execute(- f"cat {quoted_exit_path} 2>/dev/null",- timeout=5,- )- exit_str = exit_result.get("output", "").strip()+ # Exited -- read the exit code captured by the wrapper shell.+ exit_str = env.execute(f"cat {q(exit_path)} 2>/dev/null", timeout=5).get("output", "").strip()try:- session.exit_code = int(exit_str.splitlines()[-1].strip())+ exit_code = int(exit_str.splitlines()[-1].strip())except (ValueError, IndexError):- session.exit_code = -1- session.exited = True- if session.completion_reason != "killed":- session.completion_reason = "exited"- self._move_to_finished(session)+ exit_code = -1+ # Unlike mark_exited, a raced kill keeps its reason but takes this code.+ session.exit_code = exit_code+ self._finish_exited(session, exit_code)return-except Exception:# Environment might be gone (sandbox reaped, etc.)session.exited = True@@ -1327,9 +1147,6 @@ class ProcessRegistry:pty = session._pty# Same split-multibyte handling as _reader_loop.decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")-- _append_text = lambda text: self._ingest_output(session, text) # noqa: E731-try:while pty.isalive():try:@@ -1338,20 +1155,18 @@ class ProcessRegistry:# ptyprocess returns bytes; pywinpty returns strtext = chunk if isinstance(chunk, str) else decoder.decode(chunk)if text:- _append_text(text)+ self._ingest_output(session, text)except Exception: # EOFError includedbreakexcept Exception as e:logger.debug("PTY stdout reader ended: %s", e)-# Flush any partial multibyte sequence held by the decoder.try:tail = decoder.decode(b"", final=True)if tail:- _append_text(tail)+ self._ingest_output(session, tail)except Exception:pass-try:pty.wait()except Exception as e:@@ -1365,15 +1180,8 @@ class ProcessRegistry: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 = exit_code- session.completion_reason = "exited"+ """Mark a reader-observed exit (a raced kill keeps its own code/reason) and finish."""+ session.mark_exited(exit_code)self._move_to_finished(session)def _move_to_finished(self, session: ProcessSession):@@ -1387,10 +1195,7 @@ class ProcessRegistry:self._finished[session.id] = sessionsession._completion_event.set()self._write_checkpoint()-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 ""notification = {"type": "completion","session_id": session.id,@@ -1401,7 +1206,7 @@ class ProcessRegistry:"exit_code": session.exit_code,"completion_reason": session.completion_reason,"termination_source": session.termination_source,- "output": output_tail,+ "output": _output_tail(session, 2000),# Stable producer identity across checkpoint recovery (unlike a# consumer-observed completion timestamp)."started_at": session.started_at,@@ -1444,29 +1249,24 @@ class ProcessRegistry:) -> dict:"""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.+ 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 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. ``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"}`` id lists."""if timeout is None:timeout = self._oneshot_completion_wait_seconds()result: dict = {"waited": [], "completed": [], "timed_out": []}with self._lock:pending = [- s- for s in self._running.values()- if s.notify_on_complete- and not s.exited- and (task_id is None or s.task_id == task_id)+ s for s in self._running.values()+ if s.notify_on_complete and not s.exited and (task_id is None or s.task_id == task_id)]if not pending or timeout <= 0:return result@@ -1474,9 +1274,7 @@ class ProcessRegistry:logger.info("One-shot exit lingering (bounded %ss) for %d notify_on_complete ""background process(es): %s",- timeout,- len(pending),- ", ".join(s.id for s in pending),+ timeout, len(pending), ", ".join(s.id for s in pending),)deadline = time.monotonic() + max(float(timeout), 0.0)interval = max(float(poll_interval), 0.05)@@ -1508,47 +1306,35 @@ class ProcessRegistry:# 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)- else:- result["timed_out"].append(session.id)+ result["completed" if session.exited else "timed_out"].append(session.id)if result["timed_out"]:logger.warning("One-shot exit linger timed out after %ss with %d background ""process(es) still running: %s — they may be killed when this ""process exits.",- timeout,- len(result["timed_out"]),- ", ".join(result["timed_out"]),+ timeout, len(result["timed_out"]), ", ".join(result["timed_out"]),)return result@staticmethoddef _oneshot_completion_wait_seconds() -> float:- """Bounded linger (s) for one-shot exits with pending notify_on_complete- processes: ``terminal.oneshot_completion_wait_seconds`` (0 disables), 600- if config is unreadable."""+ """Linger (s) for one-shot exits with pending notify_on_complete processes:+ ``terminal.oneshot_completion_wait_seconds`` (0 disables), 600 if unreadable."""try: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:- """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- )+ def _drain_should_skip(self, session_id: str, *, skip_poll_observed: bool = True) -> bool:+ """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 turn."""+ return session_id in self._completion_consumed or (skip_poll_observed and session_id in self._poll_observed)@staticmethoddef _surface_child_process_notifications() -> bool:- """Whether subagent-owned process notifications surface in the parent- (``delegation.surface_child_process_notifications``; suppress on any config- error — never crash the drain loop)."""+ """``delegation.surface_child_process_notifications``; False on any config+ error — never crash the drain loop."""try:return bool(ProcessRegistry._config_value("delegation", "surface_child_process_notifications", False))except Exception:@@ -1587,9 +1373,8 @@ class ProcessRegistry:breakis_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 "")requires_positive_proof = is_async_delegation or bool(- evt_session_key or evt_origin_sid+ evt_session_key or evt.get("origin_ui_session_id"))if owns_event is not None and requires_positive_proof:try:@@ -1611,20 +1396,15 @@ class ProcessRegistry:# 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- ):+ 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 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 ""- )+ _evt_task_id = str(evt.get("owner_task_id") or evt.get("task_id") or "")if not is_async_delegation and _evt_task_id.startswith("sa-"):if surface_child is None:surface_child = self._surface_child_process_notifications()@@ -1633,12 +1413,9 @@ class ProcessRegistry:"Suppressed subagent-owned process notification ""(delegation.surface_child_process_notifications=false): ""type=%s session_id=%s task_id=%s",- evt.get("type", "completion"),- _evt_sid,- _evt_task_id,+ evt.get("type", "completion"), _evt_sid, _evt_task_id,)continue-text = format_process_notification(evt)if text:results.append((evt, text))@@ -1668,22 +1445,16 @@ class ProcessRegistry:query = session_id.strip()if not query:return None- # Allow the bare suffix form: "4dae56" -> "proc_4dae56".if not query.startswith("proc_"):query = f"proc_{query}"- suffix = query[len("proc_"):]- if len(suffix) < self._MIN_PREFIX_CHARS:+ if len(query) - len("proc_") < self._MIN_PREFIX_CHARS:return Nonewith self._lock:matches = [- s- for store in (self._running, self._finished)- for sid, s in store.items()- if sid.startswith(query)+ s for store in (self._running, self._finished)+ for sid, s in store.items() if sid.startswith(query)]- if len(matches) == 1:- return matches[0]- return None+ return matches[0] if len(matches) == 1 else Nonedef _reconcile_local_exit(self, session: "ProcessSession") -> None:"""Reconcile ``session.exited`` against the real child state.@@ -1705,7 +1476,6 @@ class ProcessRegistry:returnif rc is None:return # Direct child still running — reader block is legitimate.-# Best-effort non-blocking drain of whatever the reader hasn't consumed.drained = ""stdout = getattr(proc, "stdout", None)@@ -1728,16 +1498,12 @@ class ProcessRegistry:passexcept Exception as e:logger.debug("Non-blocking drain failed for %s: %s", session.id, e)-with session._lock:if drained:session.output_buffer += drainedif len(session.output_buffer) > session.max_output_chars:session.output_buffer = session.output_buffer[-session.max_output_chars:]- session.exited = True- if session.completion_reason != "killed":- session.exit_code = rc- session.completion_reason = "exited"+ session.mark_exited(rc)logger.info("Reconciled session %s: direct child exited with code %s but reader ""was still blocked (orphaned pipe). Flipped to exited.",@@ -1747,17 +1513,12 @@ class ProcessRegistry:def poll(self, session_id: str) -> dict:"""Check status and get new output for a background process."""- from tools.ansi_strip import strip_ansi-session = self.get(session_id)if session is None:- return {"status": "not_found", "error": f"No process with ID {session_id}"}-+ return _not_found(session_id)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 ""-+ output_preview = _output_tail(session, 1000)result = {"session_id": session.id,"command": session.command,@@ -1785,14 +1546,11 @@ class ProcessRegistry:session = self.get(session_id)if session is None:- return {"status": "not_found", "error": f"No process with ID {session_id}"}-+ return _not_found(session_id)with session._lock:full_output = strip_ansi(session.output_buffer)-lines = full_output.splitlines()total_lines = len(lines)-# 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:@@ -1802,10 +1560,7 @@ class ProcessRegistry:offset = offset or 0selected = lines[offset:offset + limit]stop = slice(offset, offset + limit).indices(total_lines)[1]- observed_completion_output = (- total_lines == 0 or (bool(selected) and stop == total_lines)- )-+ observed_completion_output = total_lines == 0 or (bool(selected) and stop == total_lines)result = {"session_id": session.id,"command": session.command,@@ -1824,44 +1579,31 @@ class ProcessRegistry:``timeout`` defaults to (and is clamped by) TERMINAL_TIMEOUT. Returns a dictwith status exited|timeout|interrupted|not_found|error and an output snapshot."""- from tools.ansi_strip import strip_ansifrom tools.interrupt import is_interrupted as _is_interruptedtry:- default_timeout = int(os.getenv("TERMINAL_TIMEOUT", "180"))+ max_timeout = int(os.getenv("TERMINAL_TIMEOUT", "180"))except (ValueError, TypeError):- default_timeout = 180- max_timeout = default_timeout- requested_timeout = timeout+ max_timeout = 180timeout_note = None-# 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",- "error": f"timeout must be positive (got {requested_timeout})",- }-- if requested_timeout and requested_timeout > max_timeout:+ if timeout is not None and timeout <= 0:+ return {"status": "error", "error": f"timeout must be positive (got {timeout})"}+ if timeout and timeout > max_timeout:effective_timeout = max_timeout- timeout_note = (- f"Requested wait of {requested_timeout}s was clamped "- f"to configured limit of {max_timeout}s"- )+ timeout_note = f"Requested wait of {timeout}s was clamped to configured limit of {max_timeout}s"else:- effective_timeout = requested_timeout or max_timeout+ effective_timeout = timeout or max_timeoutsession = self.get(session_id)if session is None:- return {"status": "not_found", "error": f"No process with ID {session_id}"}-+ return _not_found(session_id)deadline = time.monotonic() + effective_timeout-while time.monotonic() < deadline:session = self._refresh_detached_session(session)if session is None:- return {"status": "not_found", "error": f"No process with ID {session_id}"}+ return _not_found(session_id)self._reconcile_local_exit(session) # orphaned-pipe reader guardif session.exited:self._completion_consumed.add(session_id)@@ -1870,7 +1612,7 @@ class ProcessRegistry:result = {"status": "interrupted","command": session.command,- "output": strip_ansi(session.output_buffer[-1000:]),+ "output": _output_tail(session, 1000),"note": "User sent a new message -- wait interrupted",}else:@@ -1879,7 +1621,6 @@ class ProcessRegistry:if timeout_note:result["timeout_note"] = timeout_notereturn result-remaining = deadline - time.monotonic()if remaining <= 0:break@@ -1888,46 +1629,34 @@ class ProcessRegistry:result = {"status": "timeout","command": session.command,- "output": strip_ansi(session.output_buffer[-1000:]),+ "output": _output_tail(session, 1000),# 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- base_note = (- f"Wait window of {effective_timeout}s elapsed — the process is "- "still running. This is not an error."- )- if uptime is not None:- base_note += f" Uptime: {int(uptime)}s."+ base_note = f"Wait window of {effective_timeout}s elapsed — the process is still running. This is not an error."+ if session.started_at:+ base_note += f" Uptime: {int(time.time() - session.started_at)}s."if session.notify_on_complete:- base_note += (- " notify_on_complete is set: you will be notified on exit — "- "do more work instead of waiting again."- )+ base_note += " notify_on_complete is set: you will be notified on exit — do more work instead of waiting again."else:base_note += (" Poll again later or use terminal(background=true, ""notify_on_complete=true) next time for automatic notification.")- if timeout_note:- result["timeout_note"] = f"{timeout_note}. {base_note}"- else:- result["timeout_note"] = base_note+ result["timeout_note"] = f"{timeout_note}. {base_note}" if timeout_note else base_notereturn result@staticmethoddef _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:]),+ "output": _output_tail(session, 2000),}def kill_process(@@ -1945,12 +1674,9 @@ class ProcessRegistry:(``kill_started_since``), which passes true so a killed abandoned processcan't enqueue a follow-up reviving work the timeout stopped."""- from tools.ansi_strip import strip_ansi-session = self.get(session_id)if session is None:- return {"status": "not_found", "error": f"No process with ID {session_id}"}-+ return _not_found(session_id)if session.exited:# A double-forked descendant may still be alive in the systemd scope even# though the main process exited — stop the scope to reap survivors.@@ -1963,12 +1689,10 @@ class ProcessRegistry:if consume_output:self._completion_consumed.add(session_id)return result-try:early = self._signal_kill(session, session_id, consume_output)if early is not None:return early-# Additive to the PID kill: stopping the scope reaps double-forked# descendants reparented inside the cgroup.if session.systemd_unit:@@ -1976,7 +1700,7 @@ class ProcessRegistry:# 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:])+ output = _output_tail(session, 2000)if consume_output:self._completion_consumed.add(session_id)session.exited = True@@ -1999,8 +1723,6 @@ class ProcessRegistry:"""Deliver the kill via PTY, local Popen tree, sandbox exec or recovered hostPID. Returns a final result dict when the kill cannot proceed (recycled/deadrecovered PID, or no runtime handle), else None."""- from tools.ansi_strip import strip_ansi-if session._pty:try:session._pty.terminate(force=True)@@ -2023,7 +1745,7 @@ class ProcessRegistry:with session._lock:session.exited = Truesession.exit_code = None- output = strip_ansi(session.output_buffer[-2000:])+ output = _output_tail(session, 2000)if consume_output:self._completion_consumed.add(session_id)self._move_to_finished(session)@@ -2039,45 +1761,42 @@ class ProcessRegistry:}return None- def _live_session(self, session_id: str):- """``(session, None)`` for a running session, else ``(None, error_result)``."""+ def _stdin_op(self, session_id: str, pty_op, pipe_op) -> dict:+ """Run a stdin operation on a running session: ``pty_op(pty)`` under PTY mode,+ else ``pipe_op(stdin)`` on the Popen pipe. Each returns the ok-result dict."""session = self.get(session_id)if session is None:- return None, {"status": "not_found", "error": f"No process with ID {session_id}"}+ return _not_found(session_id)if session.exited:- return None, {"status": "already_exited", "error": "Process has already finished"}- return session, None+ return {"status": "already_exited", "error": "Process has already finished"}+ try:+ if session._pty:+ return pty_op(session._pty)+ if not session.process or not session.process.stdin:+ return {"status": "error", "error": "Process stdin not available (non-local backend or stdin closed)"}+ return pipe_op(session.process.stdin)+ 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)."""- session, err = self._live_session(session_id)- if err:- return err-- # PTY mode -- write through pty handle.- if session._pty:- try:- # pywinpty expects str on Windows; ptyprocess expects bytes on POSIX.- if _IS_WINDOWS:- pty_data = data.decode("utf-8") if isinstance(data, bytes) else str(data)- else:- # surrogateescape: a PTY is a byte stream — round-trip the- # original bytes instead of crashing on surrogate content.- pty_data = data.encode("utf-8", "surrogateescape") if isinstance(data, str) else data- session._pty.write(pty_data)- return {"status": "ok", "bytes_written": len(data)}- except Exception as e:- return {"status": "error", "error": str(e)}+ def via_pty(pty):+ # pywinpty expects str on Windows; ptyprocess expects bytes on POSIX.+ if _IS_WINDOWS:+ pty_data = data.decode("utf-8") if isinstance(data, bytes) else str(data)+ else:+ # surrogateescape: a PTY is a byte stream — round-trip the original+ # bytes instead of crashing on surrogate content.+ pty_data = data.encode("utf-8", "surrogateescape") if isinstance(data, str) else data+ pty.write(pty_data)+ return {"status": "ok", "bytes_written": len(data)}- # Popen mode -- write through stdin pipe- if not session.process or not session.process.stdin:- return {"status": "error", "error": "Process stdin not available (non-local backend or stdin closed)"}- try:- session.process.stdin.write(data)- session.process.stdin.flush()+ def via_pipe(stdin):+ stdin.write(data)+ stdin.flush()return {"status": "ok", "bytes_written": len(data)}- except Exception as e:- return {"status": "error", "error": str(e)}++ return self._stdin_op(session_id, via_pty, via_pipe)def submit_stdin(self, session_id: str, data: str = "") -> dict:"""Send data + newline to stdin (like pressing Enter).@@ -2122,28 +1841,18 @@ class ProcessRegistry:def close_stdin(self, session_id: str) -> dict:"""Close a running process's stdin / send EOF without killing the process."""- session, err = self._live_session(session_id)- if err:- return err+ def via_pty(pty):+ pty.sendeof()+ return {"status": "ok", "message": "EOF sent"}- if session._pty:- try:- session._pty.sendeof()- return {"status": "ok", "message": "EOF sent"}- except Exception as e:- return {"status": "error", "error": str(e)}-- if not session.process or not session.process.stdin:- return {"status": "error", "error": "Process stdin not available (non-local backend or stdin closed)"}- try:- session.process.stdin.close()+ def via_pipe(stdin):+ stdin.close()return {"status": "ok", "message": "stdin closed"}- except Exception as e:- return {"status": "error", "error": str(e)}++ return self._stdin_op(session_id, via_pty, via_pipe)def count_running(self) -> int:- """O(1) count of running processes for status-bar polling; CPython dict- ``len()`` is atomic so no lock is needed."""+ """O(1) running count for status-bar polling; dict ``len()`` is atomic, no lock."""try:return len(self._running)except Exception:@@ -2156,16 +1865,12 @@ class ProcessRegistry:``"session_scoped": true``."""with self._lock:all_sessions = list(self._running.values()) + list(self._finished.values())-all_sessions = [self._refresh_detached_session(s) for s in all_sessions]-if task_id or session_key:all_sessions = [s for s in all_sessions- if (task_id and s.task_id == task_id)- or (session_key and s.session_key == session_key)+ if (task_id and s.task_id == task_id) or (session_key and s.session_key == session_key)]-result = []for s in all_sessions:entry = {@@ -2209,13 +1914,11 @@ class ProcessRegistry:"""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:+ def has_active_for_session(self, session_key: str, max_active_age: Optional[float] = None) -> bool:"""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)."""+ ``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()return self._any_running(lambda s: s.session_key == session_key@@ -2232,28 +1935,13 @@ class ProcessRegistry:only processes absent from the starting snapshot belong to the abandonedturn; older ones intentionally span turns and must survive."""with self._lock:- return frozenset(- s.id- for s in self._running.values()- if s.task_id == task_id and not s.exited- )+ return frozenset(s.id for s in self._running.values() if s.task_id == task_id and not s.exited)- def kill_started_since(- self,- task_id: str,- baseline_ids,- *,- source: str,- ) -> int:+ def kill_started_since(self, task_id: str, baseline_ids, *, source: str) -> int:"""Kill ``task_id`` processes created after ``baseline_ids``. Output isconsumed so an abandoned turn can't enqueue a follow-up reviving work thetimeout deliberately stopped."""- return self.kill_all(- task_id,- exclude_ids=frozenset(baseline_ids or ()),- source=source,- consume_output=True,- )+ return self.kill_all(task_id, exclude_ids=frozenset(baseline_ids or ()), source=source, consume_output=True)def kill_all(self,@@ -2267,18 +1955,11 @@ class ProcessRegistry:with self._lock:targets = [s for s in self._running.values()- if (task_id is None or s.task_id == task_id)- and s.id not in exclude_ids- and not s.exited+ if (task_id is None or s.task_id == task_id) and s.id not in exclude_ids and not s.exited]-killed = 0for session in targets:- result = self.kill_process(- session.id,- source=source,- consume_output=consume_output,- )+ result = self.kill_process(session.id, source=source, consume_output=consume_output)if result.get("status") in {"killed", "already_exited"}:killed += 1return killed@@ -2286,13 +1967,10 @@ class ProcessRegistry:# ----- Cleanup / Pruning -----def _prune_if_needed(self):- """Remove oldest finished sessions if over MAX_PROCESSES. Must hold _lock."""- # First prune expired finished sessions+ """Drop expired finished sessions, then the oldest survivor while over+ MAX_PROCESSES. Must hold _lock."""now = time.time()- expired = [- sid for sid, s in self._finished.items()- if (now - s.started_at) > FINISHED_TTL_SECONDS- ]+ expired = [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]@@ -2308,74 +1986,56 @@ class ProcessRegistry:# ----- Checkpoint (crash recovery) ------ def _write_checkpoint(- self,- extra_entries: Optional[List[Dict[str, Any]]] = None,- ):- """Write running process metadata to checkpoint file atomically."""+ def _write_checkpoint(self, extra_entries: Optional[List[Dict[str, Any]]] = None):+ """Write running process metadata to the checkpoint file atomically."""try:with self._lock:entries = []for s in self._running.values():- if not s.exited:- # 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)- 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 s.exited:+ continue+ # 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)+ entry = {"session_id": s.id, **{f: getattr(s, f) for f in _CHECKPOINT_FIELDS}}+ # Redact inline credentials before persisting (~/.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(- item- for item in extra_entries- if item.get("session_id") not in tracked_ids- )-- # Atomic write to avoid corruption on crash+ entries.extend(item for item in extra_entries if item.get("session_id") not in tracked_ids)from utils import atomic_json_writeatomic_json_write(CHECKPOINT_PATH, entries)except Exception as e:logger.debug("Failed to write checkpoint file: %s", e, exc_info=True)def recover_from_checkpoint(self) -> int:- """- On gateway startup, probe PIDs from checkpoint file.-- Returns the number of processes recovered as detached.- """+ """On gateway startup, probe PIDs from the checkpoint file; returns how many+ were recovered as detached sessions."""if not CHECKPOINT_PATH.exists():return 0-try:entries = json.loads(CHECKPOINT_PATH.read_text(encoding="utf-8"))except Exception:return 0-recovered = 0unresolved_scope_entries: List[Dict[str, Any]] = []for entry in entries:pid = entry.get("pid")if not pid:continue-pid_scope = entry.get("pid_scope", "host")if pid_scope != "host":# 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],- pid,- pid_scope,+ entry.get("command", "unknown")[:60], pid, pid_scope,)continue-# 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.@@ -2393,12 +2053,10 @@ class ProcessRegistry:logger.warning("Could not reap persisted scope %s for dead wrapper pid %s; ""retaining checkpoint entry for the next startup",- systemd_unit,- pid,+ systemd_unit, pid,)unresolved_scope_entries.append(entry)continue-fields = {f: entry.get(f, _CHECKPOINT_DEFAULTS[f]) for f in _CHECKPOINT_FIELDS}fields.update(command=entry.get("command", "unknown"),@@ -2408,16 +2066,12 @@ class ProcessRegistry:pid_scope=pid_scope,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- **fields,- )+ # detached: can't read output, but can report status + kill+ session = ProcessSession(id=entry["session_id"], detached=True, **fields)with self._lock:self._running[session.id] = sessionrecovered += 1logger.info("Recovered detached process: %s (pid=%d)", session.command[:60], pid)-# Re-enqueue watcher so gateway can resume notificationsif session.watcher_interval > 0:self.pending_watchers.append({@@ -2433,19 +2087,16 @@ class ProcessRegistry:"notify_on_complete": session.notify_on_complete,"parent_session_id": session.parent_session_id,})-self._write_checkpoint(extra_entries=unresolved_scope_entries)-return recovered-# Module-level singletonprocess_registry = ProcessRegistry()-# 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.+# Notification rendering lives in tools.process_registry_notifications; re-exported 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,@@ -2458,9 +2109,7 @@ from tools.process_registry_notifications import ( # noqa: F401,E402)-# ----------------------------------------------------------------------------# Registry -- the "process" tool schema + handler-# ---------------------------------------------------------------------------+# --- the "process_manage" tool schema + handler -----------------------------------from tools.registry import registry, tool_errorPROCESS_SCHEMA = {@@ -2521,19 +2170,18 @@ def _redact_process_result(result: dict) -> dict:from agent.redact import redact_sensitive_text, redact_terminal_outputcommand = result.get("command") or ""- for field in ("output", "output_preview"):- value = result.get(field)+ for key in ("output", "output_preview"):+ value = result.get(key)if isinstance(value, str) and value:- result[field] = redact_terminal_output(value, command)- if isinstance(result.get("command"), str) and result["command"]:- result["command"] = redact_sensitive_text(result["command"], code_file=True)+ result[key] = redact_terminal_output(value, command)+ if isinstance(command, str) and command:+ result["command"] = redact_sensitive_text(command, code_file=True)return resultdef _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.+ # Also surface session-scoped background processes (e.g. a forgotten preview+ # server): they share the gateway session_key and can block session reset.try:from tools.approval import get_current_session_keysession_key = get_current_session_key(default="") or ""diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.pyindex ccd8d2fd604..0887f7bca31 100644--- a/tools/process_registry_notifications.py+++ b/tools/process_registry_notifications.py@@ -25,13 +25,9 @@ def _format_age(seconds: float) -> str:def _model_not_found_patterns() -> "list[str]":- """Model-not-found phrases shared with the failover classifier.-- Imported from ``agent.error_classifier`` so the batch renderer applies the- same classification the failover path uses (no hand-copied list to drift).- Fails open to a minimal built-in set so an import problem never hides the- per-task blocks.- """+ """Model-not-found phrases from ``agent.error_classifier`` (same classification+ the failover path uses, no hand-copied list to drift); a minimal built-in set+ if the import fails so per-task blocks are never hidden."""try:from agent.error_classifier import _MODEL_NOT_FOUND_PATTERNS@@ -42,11 +38,8 @@ def _model_not_found_patterns() -> "list[str]":def _delegation_config() -> dict:"""Active delegation config (model/provider/fallbacks); ``{}`` on any error.-- Mirrors ``tools.delegate_tool._load_config`` lazily so the renderer sees the- same model/provider the dispatcher used without importing the heavy- delegation module at import time.- """+ Lazy ``tools.delegate_tool._load_config`` so the renderer sees the dispatcher's+ model/provider without importing the heavy delegation module at import time."""try:from tools.delegate_tool import _load_config as _cfg@@ -67,12 +60,8 @@ def _delegation_model_not_found(results, config) -> bool:return Falsemodel = 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()):+ text = " ".join(str(part) for part in (r.get("error"), r.get("summary")) if part).lower()+ if text and model in text and any(p in text for p in _model_not_found_patterns()):return Truereturn False@@ -96,9 +85,7 @@ def _delegation_model_not_found_notice(results) -> "list[str] | None":from hermes_cli.fallback_config import get_fallback_chainif not get_fallback_chain(config):- lines.append(- "No fallback chain is configured, so no failover was attempted."- )+ lines.append("No fallback chain is configured, so no failover was attempted.")except Exception:passreturn lines@@ -115,11 +102,14 @@ def _is_truncated(entry: dict) -> bool:return bool(entry.get("truncated") or entry.get("exit_reason") == "max_iterations")-def _dispatched_line(dispatched_at, completed_at) -> "str | None":- if not isinstance(dispatched_at, (int, float)):- return None- ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(dispatched_at))- return f"Dispatched: {ts} ({_format_age(completed_at - dispatched_at)} ago)"+def _header_lines(evt: dict, title: str, intro: str, completed_at: float) -> "list[str]":+ """Shared preamble: title, intro, blank, dispatch time and task-source lines."""+ lines = [title, intro, ""]+ dispatched_at = evt.get("dispatched_at")+ if isinstance(dispatched_at, (int, float)):+ ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(dispatched_at))+ lines.append(f"Dispatched: {ts} ({_format_age(completed_at - dispatched_at)} ago)")+ return linesdef _task_source_lines(evt: dict) -> "list[str]":@@ -131,6 +121,10 @@ def _task_source_lines(evt: dict) -> "list[str]":return lines+def _role_model(evt: dict) -> str:+ return f"Role: {evt.get('role') or 'leaf'} Model: {evt.get('model') or '?'}"++def _format_batch_delegation(evt: dict, deleg_id: str, completed_at: float) -> str:"""Consolidated block for a delegate_task fan-out that finished as one unit."""results = evt.get("results") or []@@ -138,22 +132,17 @@ def _format_batch_delegation(evt: dict, deleg_id: str, completed_at: float) -> sn = len(results) if results else len(goals)total_dur = evt.get("total_duration_seconds", evt.get("duration_seconds", "?"))error = evt.get("error")- lines = [+ lines = _header_lines(+ evt,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.",- "",- ]- dispatched = _dispatched_line(evt.get("dispatched_at"), completed_at)- if dispatched:- lines.append(dispatched)- lines.extend(_task_source_lines(evt))- lines.append(- f"Role: {evt.get('role') or 'leaf'} Model: {evt.get('model') or '?'}"- f" Total duration: {total_dur}s"+ completed_at,)+ lines.extend(_task_source_lines(evt))+ lines.append(f"{_role_model(evt)} Total duration: {total_dur}s")if error and not results:lines.append("--- ERROR ---")lines.append(f"The batch did not complete successfully: {error}")@@ -195,16 +184,10 @@ def _format_batch_delegation(evt: dict, deleg_id: str, completed_at: float) -> slines.append("Partial output:")lines.append(r_summary)else:- lines.append(- f"(no summary — status={r_status}"- + (f": {r_error}" if r_error 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}"- )+ lines.append(f"Full live transcript (complete tool/assistant trace): {r_live}")return "\n".join(lines)@@ -226,19 +209,17 @@ def _format_async_delegation(evt: dict) -> str:summary = evt.get("summary")error = evt.get("error")truncated = _is_truncated(evt)- lines = [+ lines = _header_lines(+ evt,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.",- "",- ]- dispatched = _dispatched_line(evt.get("dispatched_at"), completed_at)- if dispatched:- lines.append(dispatched)+ completed_at,+ )lines.append(f"Original goal: {evt.get('goal', '') or ''}")lines.extend(_task_source_lines(evt))- lines.append(f"Role: {evt.get('role') or 'leaf'} Model: {evt.get('model') or '?'}")+ lines.append(_role_model(evt))_notice = _delegation_model_not_found_notice([evt])if _notice:lines.append("")@@ -255,14 +236,10 @@ def _format_async_delegation(evt: dict) -> str:lines.append(summary)else:if status == "interrupted":- lines.append(- "The subagent was interrupted before completing"- + (f": {error}" if error else ".")- )+ lines.append("The subagent was interrupted before completing" + (f": {error}" if error else "."))else: # error / timeout / failedlines.append(- f"The subagent did not complete successfully (status={status})."- + (f"\n{error}" if error else "")+ f"The subagent did not complete successfully (status={status})." + (f"\n{error}" if error else ""))if summary:lines.append("Partial output:")@@ -273,9 +250,8 @@ def _format_async_delegation(evt: dict) -> str:def _delegation_attribution_line(evt: dict) -> "str | None":"""One-line provenance for a subagent-owned process event, else None.- Subagents run terminal sessions under ``task_id == subagent_id``; a- background process they started outlives the child and is routed to the- PARENT conversation, which otherwise sees an anonymous raw output wall.+ A background process a subagent started outlives the child and is routed to+ the PARENT conversation, which otherwise sees an anonymous raw output wall.Judged on ``owner_task_id`` (the raw spawning id) — ``task_id`` is thecontainer key and may be collapsed to the session key."""@@ -304,18 +280,19 @@ def _delegation_attribution_line(evt: dict) -> "str | None":return line+_REASON_STATUS = {+ "lost": "marked lost because the process backend disappeared",+ "failed_start": "failed to start",+}++def _completion_status(evt: dict) -> str:- _exit = evt.get("exit_code", "?")- _reason = evt.get("completion_reason") or "exited"- if _reason == "killed":+ reason = evt.get("completion_reason") or "exited"+ if reason == "killed":return f"terminated by {evt.get('termination_source') or 'Hermes'}"- if _reason == "lost":- return "marked lost because the process backend disappeared"- if _reason == "failed_start":- return "failed to start"- if _exit == 0:- return "completed normally"- return "exited"+ if reason in _REASON_STATUS:+ return _REASON_STATUS[reason]+ return "completed normally" if evt.get("exit_code", "?") == 0 else "exited"def format_process_notification(evt: dict) -> "str | None":@@ -325,40 +302,32 @@ def format_process_notification(evt: dict) -> "str | None":_cmd = evt.get("command", "unknown")_attribution = _delegation_attribution_line(evt)- # watch_disabled and overflow events carry their own human-readable- # `message`; without this branch overflow events would fall through to the- # completion formatter as a phantom "process exited (exit code ?)".+ # watch_disabled and overflow events carry their own human-readable `message`;+ # otherwise overflow events would fall through to the completion formatter as a+ # phantom "process exited (exit code ?)".if evt_type in ("watch_disabled", "watch_overflow_tripped", "watch_overflow_released"):return f"[IMPORTANT: {evt.get('message', '')}]"-if evt_type == "watch_match":_sup = evt.get("suppressed", 0)- text = (- f"[IMPORTANT: Background process {_sid} matched "- f"watch pattern \"{evt.get('pattern', '?')}\".\n"- )+ text = f"[IMPORTANT: Background process {_sid} matched watch pattern \"{evt.get('pattern', '?')}\".\n"if _attribution:text += f"{_attribution}\n"text += f"Command: {_cmd}\nMatched output:\n{evt.get('output', '')}"if _sup:text += f"\n({_sup} earlier matches were suppressed by rate limit)"return text + "]"-if evt_type == "async_delegation":return _format_async_delegation(evt)_exit = evt.get("exit_code", "?")_out = evt.get("output", "")_signal = ", SIGTERM" if _exit in {-15, 143, "-15", "143"} else ""- text = (- f"[IMPORTANT: Background process {_sid} {_completion_status(evt)} "- f"(exit code {_exit}{_signal}).\n"- )+ text = f"[IMPORTANT: Background process {_sid} {_completion_status(evt)} (exit code {_exit}{_signal}).\n"if _attribution:text += f"{_attribution}\n"- # A subagent-owned process's full output belongs in the child's- # transcript, not as a raw wall in the parent — trim hard but keep- # enough tail to recognise failures.+ # A subagent-owned process's full output belongs in the child's transcript,+ # not as a raw wall in the parent — trim hard but keep enough tail to+ # recognise failures.if isinstance(_out, str) and len(_out) > 600:_out = ("...(output trimmed — subagent-owned process; see the "