The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): compact restart/drain/cache-pressure/monitor modules; extract hook-dir loader and capture-path indexer
Teknium5fa706605461
diff --git a/gateway/agent_cache_pressure.py b/gateway/agent_cache_pressure.pyindex d7d862c24fd..93413d9496e 100644--- a/gateway/agent_cache_pressure.py+++ b/gateway/agent_cache_pressure.py@@ -23,12 +23,10 @@ _AUTO_BUDGET_FRACTION = 0.65# Below this a budget is noise — small containers would evict every pass and# never keep a warm prefix._AUTO_BUDGET_FLOOR_MB = 512-_DEFAULT_MAX_EVICTIONS_PER_PASS = 16# Never shed the hottest sessions: their prompt cache is worth the most, and# evicting them just moves the cost to the next turn._DEFAULT_PROTECT_RECENT = 8-_BYTES_PER_MB = 1024 * 1024_OFF_WORDS = frozenset({"", "off", "none", "false", "disabled"})@@ -75,20 +73,15 @@ def _cgroup_limit_bytes() -> Optional[int]:"""if sys.platform != "linux":return None- candidates: list[str] = []try:from gateway.cgroup_cleanup import _own_cgroup_pathown = _own_cgroup_path()except Exception:own = None- if own and own != "/":- candidates += [f"/sys/fs/cgroup{own}/memory.high", f"/sys/fs/cgroup{own}/memory.max"]- candidates += [- "/sys/fs/cgroup/memory.high",- "/sys/fs/cgroup/memory.max",- "/sys/fs/cgroup/memory/memory.limit_in_bytes",- ]+ roots = [f"/sys/fs/cgroup{own}"] if own and own != "/" else []+ roots.append("/sys/fs/cgroup")+ candidates = [f"{r}/memory.{f}" for r in roots for f in ("high", "max")] + ["/sys/fs/cgroup/memory/memory.limit_in_bytes"]for candidate in candidates:try:limit = int(Path(candidate).read_text(encoding="utf-8").strip())@@ -144,7 +137,6 @@ def resolve_agent_cache_bounds(config: Any) -> AgentCacheBounds:section = (config.get("agent") or {}).get("agent_cache") if isinstance(config, dict) else Noneif not isinstance(section, dict):section = {}-protect_recent = section.get("protect_recent")protect_parsed = _positive(protect_recent)# 0 means "shed anything" — distinct from unset. The bool guard keeps@@ -152,7 +144,6 @@ def resolve_agent_cache_bounds(config: Any) -> AgentCacheBounds:# disabling MRU protection.if protect_parsed is None and _is_int(protect_recent) and protect_recent == 0:protect_parsed = 0-return AgentCacheBounds(max_size=_positive(section.get("max_size")),idle_ttl_secs=_positive(section.get("idle_ttl_secs"), float),@@ -179,7 +170,6 @@ def read_anon_rss_mb() -> Optional[int]:return kib // 1024except Exception:pass-try:import psutil # type: ignore@@ -223,7 +213,6 @@ def plan_pressure_evictions(protect = min(max(protect_recent, 0), len(entries) // 2)if protect:entries = entries[:-protect]-plan: List[Tuple[str, Any]] = []for key, agent in entries:if len(plan) >= max_evictions:diff --git a/gateway/drain_control.py b/gateway/drain_control.pyindex 9816f7aa909..342d89e4e27 100644--- a/gateway/drain_control.py+++ b/gateway/drain_control.py@@ -7,17 +7,13 @@ Presence of an ACTIVE marker means "external drain" (``gateway_state ->"draining"``); absence or a stale marker means "not draining".Staleness — two independent, individually-lenient signals (either suffices):- * epoch mismatch: HERMES_HOME is a durable volume on Hermes Cloud, so a- marker survives the machine restart that a drain-gated action ends in;- honouring it would park the fresh gateway in ``draining`` forever.- * expiry: a same-epoch orphan (writer never cancelled) is ignored once- ``requested_at`` is older than :data:`DRAIN_REQUEST_MAX_AGE_SECONDS`;- re-calling :func:`write_drain_request` refreshes it (long-drain keep-alive).--Reading never raises: a malformed/half-written file reads as ``{}``, which still-counts as drain-active (fail-safe toward quiescing). Both staleness checks-reject only on a *definite* verdict — a marker with no epoch/timestamp, or a-host without ``/proc``, degrades to presence-only and never fails closed.+epoch mismatch (HERMES_HOME is a durable volume on Hermes Cloud, so a marker+survives the machine restart a drain-gated action ends in and would park the+fresh gateway in ``draining`` forever) and expiry (a same-epoch orphan is+ignored past :data:`DRAIN_REQUEST_MAX_AGE_SECONDS`; re-writing refreshes it).+Reading never raises: a malformed file reads as ``{}``, still drain-active+(fail-safe toward quiescing). Staleness rejects only on a *definite* verdict —+no epoch/timestamp, or no ``/proc``, degrades to presence-only, never fail-closed."""from __future__ import annotations@@ -35,11 +31,9 @@ from utils import atomic_json_write_log = logging.getLogger(__name__)_DRAIN_REQUEST_FILENAME = ".drain_request.json"-# Drain-gated lifecycle actions complete in minutes; an hour bounds the wedge a# leaked marker can cause. Long drains refresh the marker instead of raising this.DRAIN_REQUEST_MAX_AGE_SECONDS = 3600.0-# Dedup for the expired-marker warning (the watcher re-reads every second).# Keyed by ``requested_at`` so a keep-alive re-write that later expires logs again._expiry_logged_for: Optional[str] = None@@ -55,20 +49,14 @@ def current_instantiation_epoch() -> str:time on a plain ``docker restart``. ``""`` when neither source is readable(non-Linux, no ``/proc``), which disables the epoch check — never fail-closed."""- boot_id = ""+ boot_id = pid1_start = ""with contextlib.suppress(OSError):boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="utf-8").strip()-- pid1_start = ""with contextlib.suppress(OSError, IndexError):# "<pid> (<comm>) <state> ...": comm may contain spaces/parens, so split# on the LAST ')'. starttime is field 22 (1-indexed) = tail index 19.- stat = Path("/proc/1/stat").read_text(encoding="utf-8")- pid1_start = stat.rsplit(")", 1)[1].split()[19]-- if not boot_id and not pid1_start:- return ""- return f"{boot_id}:{pid1_start}"+ pid1_start = Path("/proc/1/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split()[19]+ return f"{boot_id}:{pid1_start}" if (boot_id or pid1_start) else ""def drain_request_path(home: Optional[Path] = None) -> Path:@@ -77,10 +65,7 @@ def drain_request_path(home: Optional[Path] = None) -> Path:def write_drain_request(- *,- principal: str = "drain-control",- suppress_notification: bool = False,- home: Optional[Path] = None,+ *, principal: str = "drain-control", suppress_notification: bool = False, home: Optional[Path] = None) -> dict[str, Any]:"""Write the begin-drain marker atomically. Returns the payload written.@@ -142,10 +127,7 @@ def _marker_is_expired(body: dict[str, Any]) -> bool:"age=%.0fs > max %.0fs, principal=%s) — the drain that wrote it ""was never cancelled; treating as stale so the gateway keeps ""accepting turns.",- raw,- age,- DRAIN_REQUEST_MAX_AGE_SECONDS,- body.get("principal"),+ raw, age, DRAIN_REQUEST_MAX_AGE_SECONDS, body.get("principal"),)return True@@ -155,8 +137,7 @@ def _active_drain_body(home: Optional[Path]) -> Optional[dict[str, Any]]:body = read_drain_request(home=home)if body is None:return None- current = current_instantiation_epoch()- marker_epoch = body.get("epoch")+ current, marker_epoch = current_instantiation_epoch(), body.get("epoch")if (current and marker_epoch and marker_epoch != current) or _marker_is_expired(body):return Nonereturn bodydiff --git a/gateway/hooks.py b/gateway/hooks.pyindex b4f672d2e56..689f3a4b1ba 100644--- a/gateway/hooks.py+++ b/gateway/hooks.py@@ -1,25 +1,14 @@-"""-Event Hook System--Fires handlers at gateway lifecycle points. Hooks are discovered from-~/.hermes/hooks/<name>/ directories, each containing HOOK.yaml (name,-description, events) and handler.py (``def handle(event_type, context)``,-sync or async). Handler errors are logged and never block the pipeline.--Events:- gateway:startup, session:start, session:end (user ran /new or /reset),- session:reset, agent:start, agent:step (each tool-loop turn), agent:end,- command:* (any slash command; wildcard match).--Context passed to ``agent:start`` / ``agent:end``:- platform, user_id, chat_id, thread_id (Telegram forum-topic / thread root- id as string; empty when not in a thread), chat_type ("dm" | "group" |- "forum" | ""), session_id, message (truncated to 500 chars).-``agent:end`` adds: response (truncated to 500 chars), model, provider.--Handlers posting a follow-up into the same Telegram forum-topic should pass-``message_thread_id=int(thread_id)`` when ``chat_type == "forum"`` and-``thread_id`` is non-empty.+"""Event hook system: fires handlers at gateway lifecycle points.++Hooks live in ~/.hermes/hooks/<name>/ with HOOK.yaml (name, description, events)+and handler.py (``def handle(event_type, context)``, sync or async). Handler+errors are logged and never block the pipeline. Events: gateway:startup,+session:start/end/reset, agent:start, agent:step (each tool-loop turn),+agent:end, command:* (wildcard). ``agent:start``/``agent:end`` context: platform,+user_id, chat_id, thread_id (forum-topic/thread root as str, "" outside a thread),+chat_type ("dm"|"group"|"forum"|""), session_id, message (500 chars); ``agent:end``+adds response (500 chars), model, provider. Telegram forum follow-ups should pass+``message_thread_id=int(thread_id)`` when ``chat_type == "forum"`` and thread_id set."""import asyncio@@ -97,10 +86,8 @@ class HookRegistry:def discover_and_load(self) -> None:"""Register built-in hooks, then load every valid hook dir under HOOKS_DIR."""self._register_builtin_hooks()-if not HOOKS_DIR.exists():return-for hook_dir in sorted(HOOKS_DIR.iterdir()):if not hook_dir.is_dir():continue@@ -114,12 +101,9 @@ class HookRegistry:hook_name, events, handle_fn, description = loadedfor event in events:self._handlers.setdefault(event, []).append(handle_fn)- self._loaded_hooks.append({- "name": hook_name,- "description": description,- "events": events,- "path": str(hook_dir),- })+ self._loaded_hooks.append(+ {"name": hook_name, "description": description, "events": events, "path": str(hook_dir)}+ )print(f"[hooks] Loaded hook '{hook_name}' for events: {events}", flush=True)def _resolve_handlers(self, event_type: str) -> List[Callable]:@@ -137,11 +121,7 @@ class HookRegistry:"""Fire all handlers for an event, discarding return values."""await self.emit_collect(event_type, context)- async def emit_collect(- self,- event_type: str,- context: Optional[Dict[str, Any]] = None,- ) -> List[Any]:+ async def emit_collect(self, event_type: str, context: Optional[Dict[str, Any]] = None) -> List[Any]:"""Fire handlers and return their non-None return values in order.Used for decision-style hooks (e.g. ``command:<name>`` policies that@@ -150,7 +130,6 @@ class HookRegistry:"""if context is None:context = {}-results: List[Any] = []for fn in self._resolve_handlers(event_type):try:diff --git a/gateway/lifecycle_ledger.py b/gateway/lifecycle_ledger.pyindex f63dff5d159..0be62731879 100644--- a/gateway/lifecycle_ledger.py+++ b/gateway/lifecycle_ledger.py@@ -39,7 +39,7 @@ def _process_hermes_home() -> Path:def _home_path(home: Optional[Path], relative: tuple) -> Path:- return (home if home is not None else _process_hermes_home()).joinpath(*relative)+ return (_process_hermes_home() if home is None else home).joinpath(*relative)def get_lifecycle_sentinel_path(home: Optional[Path] = None) -> Path:@@ -123,15 +123,10 @@ def _pid_alive_with_start_time(pid: Any, start_time: Any) -> bool:"""try:pid_int = int(pid)- except (TypeError, ValueError):- return False- if pid_int <= 0:- return False- try:# NOT os.kill(pid, 0): on Windows that sends CTRL_C_EVENT to the target's console group.from gateway.status import _pid_exists, get_process_start_time- if not _pid_exists(pid_int):+ if pid_int <= 0 or not _pid_exists(pid_int):return Falseexcept Exception:return False@@ -200,9 +195,7 @@ def check_state_db_integrity(home: Optional[Path] = None) -> str:row = conn.execute("PRAGMA quick_check(1)").fetchone()except Exception as exc:return f"check-failed: {exc}"- if not row or row[0] is None:- return "check-failed: no result"- return str(row[0])+ return "check-failed: no result" if not row or row[0] is None else str(row[0])def record_startup(home: Optional[Path] = None) -> Optional[Dict[str, Any]]:diff --git a/gateway/media_repair.py b/gateway/media_repair.pyindex e0a4271eb06..3ad66cf3c09 100644--- a/gateway/media_repair.py+++ b/gateway/media_repair.py@@ -112,9 +112,7 @@ def _current_turn_messages(messages: List[Dict[str, Any]], history_offset: int)def repair_explicit_computer_use_media_paths(- response: str,- messages: List[Dict[str, Any]],- history_offset: int = 0,+ response: str, messages: List[Dict[str, Any]], history_offset: int = 0) -> str:"""Recover model-mangled paths for explicitly requested screenshots.@@ -130,30 +128,29 @@ def repair_explicit_computer_use_media_paths(return response-def _repair_explicit_computer_use_media_paths_inner(- response: str,- messages: List[Dict[str, Any]],- history_offset: int = 0,-) -> str:- if "MEDIA:" not in response:- return response-- turn_messages = _current_turn_messages(messages, history_offset)+def _canonical_capture_paths(turn_messages: List[Dict[str, Any]]) -> Dict[str, str]:+ """``{lowercase basename: absolute canonical path}`` from this turn's computer_use results."""call_id_names = tool_name_by_call_id(turn_messages)-- canonical_by_basename: Dict[str, str] = {}+ canonical: Dict[str, str] = {}for msg in turn_messages:if msg.get("role") not in {"tool", "function"}:continuecall_id = str(msg.get("tool_call_id") or msg.get("call_id") or "")- tool_name = str(msg.get("name") or msg.get("tool_name") or call_id_names.get(call_id) or "")- if tool_name != "computer_use":+ if str(msg.get("name") or msg.get("tool_name") or call_id_names.get(call_id) or "") != "computer_use":continuefor path in _iter_computer_use_capture_paths(msg.get("content")):basename = _computer_use_capture_basename(path)if basename and _ABS_PATH_PREFIX_RE.match(path):- canonical_by_basename[basename] = path+ canonical[basename] = path+ return canonical++def _repair_explicit_computer_use_media_paths_inner(+ response: str, messages: List[Dict[str, Any]], history_offset: int = 0+) -> str:+ if "MEDIA:" not in response:+ return response+ canonical_by_basename = _canonical_capture_paths(_current_turn_messages(messages, history_offset))if not canonical_by_basename:return responsediff --git a/gateway/memory_monitor.py b/gateway/memory_monitor.pyindex ddf7b502d33..04aef836efa 100644--- a/gateway/memory_monitor.py+++ b/gateway/memory_monitor.py@@ -25,7 +25,6 @@ _BYTES_TO_MB = 1024 * 1024_monitor_thread: Optional[threading.Thread] = None_stop_event: Optional[threading.Event] = None_start_time: Optional[float] = None-_interval_seconds: float = 300.0_lock = threading.Lock()@@ -50,14 +49,13 @@ def _get_rss_mb() -> Optional[int]:def log_memory_usage(prefix: str = "") -> None:"""Log ``[MEMORY] [<prefix> ]rss=... gc=... threads=... uptime=...``; safe from any thread."""rss = _get_rss_mb()- uptime = int(time.monotonic() - _start_time) if _start_time else 0logger.info("[MEMORY] %srss=%s gc=%s threads=%d uptime=%ds",f"{prefix} " if prefix else "","unavailable" if rss is None else f"{rss}MB",gc.get_count(), # (gen0, gen1, gen2)threading.active_count(),- uptime,+ int(time.monotonic() - _start_time) if _start_time else 0,)@@ -66,8 +64,7 @@ def _monitor_loop(stop_event: threading.Event, interval: float) -> None:while not stop_event.wait(interval):try:log_memory_usage()- except Exception as e:- # Never let the monitor crash the gateway.+ except Exception as e: # never let the monitor crash the gatewaylogger.debug("Memory monitor iteration failed: %s", e)@@ -77,7 +74,7 @@ def start_memory_monitoring(interval_seconds: float = 300.0) -> bool:Returns True if a fresh monitor was started; False if one is already runningor RSS introspection is unavailable (warned once)."""- global _monitor_thread, _stop_event, _start_time, _interval_seconds+ global _monitor_thread, _stop_event, _start_timewith _lock:if _monitor_thread is not None and _monitor_thread.is_alive():@@ -88,19 +85,15 @@ def start_memory_monitoring(interval_seconds: float = 300.0) -> bool:"nor psutil could read process RSS — skipping periodic logging.",)return False-_start_time = time.monotonic()- _interval_seconds = float(interval_seconds)_stop_event = threading.Event()log_memory_usage(prefix="baseline")_monitor_thread = threading.Thread(- target=_monitor_loop,- args=(_stop_event, _interval_seconds),- name="gateway-memory-monitor",- daemon=True,+ target=_monitor_loop, args=(_stop_event, float(interval_seconds)),+ name="gateway-memory-monitor", daemon=True,)_monitor_thread.start()- logger.info("[MEMORY] Periodic memory monitoring started (interval: %ds)", int(_interval_seconds))+ logger.info("[MEMORY] Periodic memory monitoring started (interval: %ds)", int(interval_seconds))return True@@ -114,14 +107,11 @@ def stop_memory_monitoring(timeout: float = 2.0) -> None:with contextlib.suppress(Exception):log_memory_usage(prefix="shutdown")_stop_event.set()- thread = _monitor_thread- _monitor_thread = None- _stop_event = None+ thread, _monitor_thread, _stop_event = _monitor_thread, None, None# Join outside the lock so a stuck log call can't deadlock shutdown.with contextlib.suppress(Exception):thread.join(timeout=timeout)-logger.info("[MEMORY] Periodic memory monitoring stopped")diff --git a/gateway/memory_status.py b/gateway/memory_status.pyindex 44c37df4dab..88b92b06991 100644--- a/gateway/memory_status.py+++ b/gateway/memory_status.py@@ -32,9 +32,7 @@ _HEARTBEAT_FRESH_TTL_S = 150.0def _nonneg_int(value: Any) -> Optional[int]:"""Return *value* if it is a non-negative int (bools rejected), else None."""- if isinstance(value, bool) or not isinstance(value, int) or value < 0:- return None- return value+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else Nonedef _mb(kib: Any) -> Optional[int]:@@ -97,14 +95,8 @@ def collect_memory_status("""moment = now or datetime.now(timezone.utc)status: Dict[str, Any] = {- "pressure": "unknown",- "gateway_rss_mb": None,- "system_total_mb": None,- "system_available_mb": None,- "swap_used_mb": None,- "sampled_at": None,- "last_boot_unclean": False,- "last_boot_suspected_oom": False,+ "pressure": "unknown", "gateway_rss_mb": None, "system_total_mb": None, "system_available_mb": None,+ "swap_used_mb": None, "sampled_at": None, "last_boot_unclean": False, "last_boot_suspected_oom": False,# Identity of the CURRENT life (sentinel started_at): the dashboard keys# banner dismissal on it so acknowledging one OOM restart does not mute the NEXT."boot_id": None,@@ -115,10 +107,9 @@ def collect_memory_status(sampled_at = _parse_iso(heartbeat.get("updated_at"))mem = heartbeat.get("mem")if isinstance(mem, dict):- status["gateway_rss_mb"] = _mb(mem.get("rss_kib"))- status["system_total_mb"] = _mb(mem.get("mem_total_kib"))- status["system_available_mb"] = _mb(mem.get("mem_available_kib"))- status["swap_used_mb"] = _mb(mem.get("swap_used_kib"))+ for dst, src in (("gateway_rss_mb", "rss_kib"), ("system_total_mb", "mem_total_kib"),+ ("system_available_mb", "mem_available_kib"), ("swap_used_mb", "swap_used_kib")):+ status[dst] = _mb(mem.get(src))if sampled_at is not None:status["sampled_at"] = sampled_at.isoformat()# Stale sample: numbers still reported (sampled_at says when) butdiff --git a/gateway/mirror.py b/gateway/mirror.pyindex 8e5bae1bad7..d652f3496a7 100644--- a/gateway/mirror.py+++ b/gateway/mirror.py@@ -1,10 +1,8 @@-"""-Session mirroring for cross-platform message delivery.+"""Session mirroring for cross-platform message delivery.-When a message is sent to a platform (send_message or cron delivery), append-a "delivery-mirror" record to the target session's transcript so the-receiving-side agent knows what was sent. Standalone: works from CLI, cron-and gateway contexts without the full SessionStore machinery.+When a message is sent to a platform (send_message or cron delivery), append a+"delivery-mirror" record to the target session's transcript so the receiving-side+agent knows what was sent. Standalone: works from CLI, cron and gateway contexts."""import json@@ -92,10 +90,9 @@ def _find_session_id(db = get_shared_session_db()try:finder = getattr(db, "find_session_by_origin", None)- if callable(finder):- session_id = finder(platform=platform, chat_id=chat_id, thread_id=thread_id, user_id=user_id)- if session_id:- return str(session_id)+ session_id = finder(platform=platform, chat_id=chat_id, thread_id=thread_id, user_id=user_id) if callable(finder) else None+ if session_id:+ return str(session_id)finally:release_or_close(db)except Exception as e:@@ -104,8 +101,7 @@ def _find_session_id(if not _SESSIONS_INDEX.exists():return Nonetry:- with open(_SESSIONS_INDEX, encoding="utf-8") as f:- data = json.load(f)+ data = json.loads(_SESSIONS_INDEX.read_text(encoding="utf-8"))except Exception:return Nonediff --git a/gateway/readiness.py b/gateway/readiness.pyindex a67ac91d7fc..54776aa56d4 100644--- a/gateway/readiness.py+++ b/gateway/readiness.py@@ -71,10 +71,8 @@ def _probe_gateway(runtime_status: dict[str, Any]) -> dict[str, Any]:platforms = runtime_status.get("platforms")platforms = platforms if isinstance(platforms, dict) else {}connected = sum(- 1- for value in platforms.values()- if isinstance(value, dict)- and str(value.get("state") or value.get("status") or "").lower() in _CONNECTED_STATES+ isinstance(v, dict) and str(v.get("state") or v.get("status") or "").lower() in _CONNECTED_STATES+ for v in platforms.values())status = "ok" if state in {"running", "draining"} else "degraded"return _check(status, state=state, connected_platforms=connected, platforms=len(platforms))diff --git a/gateway/restart.py b/gateway/restart.pyindex ccb4e9d668d..e8110a395c7 100644--- a/gateway/restart.py+++ b/gateway/restart.py@@ -9,47 +9,38 @@ from hermes_cli.config import DEFAULT_CONFIG# EX_TEMPFAIL (sysexits.h): ask the service manager to restart the gateway# after a graceful drain/reload path completes.GATEWAY_SERVICE_RESTART_EXIT_CODE = 75-# EX_CONFIG (sysexits.h): fatal configuration error (token collision, no-# platforms). The s6 finish script translates this into exit 125 (permanent-# failure) so the supervisor stops restarting the gateway.+# platforms); the s6 finish script maps it to exit 125 so the supervisor stops restarting.GATEWAY_FATAL_CONFIG_EXIT_CODE = 78-# Set by ``hermes gateway run --external-supervisor``. Unlike systemd's-# INVOCATION_ID and launchd's XPC_SERVICE_NAME, this survives wrappers that-# replace the child environment (e.g. ``sudo env -i``).+# Set by ``hermes gateway run --external-supervisor``. Unlike systemd's INVOCATION_ID+# and launchd's XPC_SERVICE_NAME, this survives wrappers that replace the child+# environment (e.g. ``sudo env -i``).EXTERNAL_GATEWAY_SUPERVISOR_ENV = "HERMES_GATEWAY_EXTERNAL_SUPERVISOR"DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT = float(DEFAULT_CONFIG["agent"]["restart_drain_timeout"])-DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT = float(- DEFAULT_CONFIG["gateway"]["signal_interrupt_grace_timeout"]-)+DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT = float(DEFAULT_CONFIG["gateway"]["signal_interrupt_grace_timeout"])DEFAULT_GATEWAY_POST_INTERRUPT_GRACE_TIMEOUT = 5.0-# In-band restart (``/restart``, SIGUSR1, self-restart) waits for active turns-# to finish *before* ``stop()`` begins. Distinct from ``restart_drain_timeout``,-# the force-interrupt budget once ``stop()`` is running (must stay short under-# systemd TimeoutStopSec).-DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUT = float(- DEFAULT_CONFIG["agent"]["restart_after_turn_timeout"]-)--# Cron-only floor under the ``stop()`` drain. ``restart_drain_timeout`` defaults-# to 0 because interrupting a *chat* turn is cheap and recoverable (user is-# told, session pre-marked resume_pending). An interrupted *cron* run has-# neither property — it lands in jobs.json as a permanent failure and a-# recurring job just waits for its next schedule — so a zero-second drain-# silently destroys work.+# In-band restart (``/restart``, SIGUSR1, self-restart) waits for active turns to+# finish *before* ``stop()`` begins. Distinct from ``restart_drain_timeout``, the+# force-interrupt budget once ``stop()`` runs (must stay short under systemd TimeoutStopSec).+DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUT = float(DEFAULT_CONFIG["agent"]["restart_after_turn_timeout"])++# Cron-only floor under the ``stop()`` drain. ``restart_drain_timeout`` defaults to 0+# because interrupting a *chat* turn is cheap and recoverable (user told, session+# pre-marked resume_pending). An interrupted *cron* run lands in jobs.json as a+# permanent failure and waits for its next schedule — a 0s drain silently destroys work.DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT = float(DEFAULT_CONFIG["agent"]["cron_drain_timeout"])-# Seconds of the shutdown watchdog leash held back for post-drain work-# (interrupt agents, kill tool subprocesses, mark jobs interrupted, disconnect-# adapters). Waiting for cron past that trades a job killed *and recorded* for-# one SIGKILLed mid-write and wedged at ``last_status=running`` forever.+# Seconds of the shutdown watchdog leash held back for post-drain work (interrupt+# agents, kill tool subprocesses, mark jobs interrupted, disconnect adapters).+# Waiting for cron past that trades a job killed *and recorded* for one SIGKILLed+# mid-write and wedged at ``last_status=running`` forever.CRON_DRAIN_CLEANUP_RESERVE_S = 10.0-# systemd TimeoutStopSec headroom after the stop-path drain budget, and the-# floor when that budget is still the default immediate (0s) chat drain.+# systemd TimeoutStopSec headroom after the stop-path drain budget, and the floor+# when that budget is still the default immediate (0s) chat drain.# Keep in lockstep with generate_systemd_unit().SYSTEMD_STOP_HEADROOM_S = 30.0SYSTEMD_TIMEOUT_STOP_SEC_FLOOR = 60.0@@ -60,11 +51,10 @@ _TRUTHY = {"1", "true", "yes", "on"}def is_global_startup_conflict(error_code: str | None) -> bool:"""True when an adapter's fatal error is a single-writer ownership conflict.- Adapters emit ``{scope}_lock`` with ``retryable=True`` so a *mid-run*- reconnect can recover once the holder exits. At startup a live foreign- holder is a configuration conflict (two gateways cannot poll one token), so- the startup router must not treat it as a transient blip. Matches by error- CODE only (``lock_conflict`` / ``*_lock``), never by message text.+ Adapters emit ``{scope}_lock`` with ``retryable=True`` so a *mid-run* reconnect+ can recover once the holder exits; at startup a live foreign holder is a+ configuration conflict (two gateways cannot poll one token), not a transient+ blip. Matches by error CODE only (``lock_conflict`` / ``*_lock``), never text."""code = (error_code or "").strip().lower()return bool(code) and (code == "lock_conflict" or code.endswith("_lock"))@@ -73,19 +63,20 @@ def is_global_startup_conflict(error_code: str | None) -> bool:def is_gateway_supervisor_process(environ: Mapping[str, str] | None = None) -> bool:"""Return whether this gateway process is owned by a supervisor."""env = os.environ if environ is None else environ- if env.get("INVOCATION_ID") or env.get("HERMES_S6_SUPERVISED_CHILD"):- return Truexpc_service = env.get("XPC_SERVICE_NAME", "")- if xpc_service and xpc_service != "0":- return True- return str(env.get(EXTERNAL_GATEWAY_SUPERVISOR_ENV, "")).strip().lower() in _TRUTHY+ return bool(+ env.get("INVOCATION_ID")+ or env.get("HERMES_S6_SUPERVISED_CHILD")+ or (xpc_service and xpc_service != "0")+ or str(env.get(EXTERNAL_GATEWAY_SUPERVISOR_ENV, "")).strip().lower() in _TRUTHY+ )def is_container_restart_context() -> bool:"""Whether the gateway runs in a container (Docker/Podman): the detached setsidrestart path dies with the cgroup, so exit-75 service restart is the only viable- path. Separate function so tests can mock container detection (a real- ``/.dockerenv`` on CI otherwise flips the routing)."""+ path. Separate function so tests can mock it (a real ``/.dockerenv`` on CI+ otherwise flips the routing)."""return os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv")@@ -112,12 +103,8 @@ def _parse_timeout_keeping_zero(raw: object, default: float, *, finite: bool = Fdef parse_restart_drain_timeout(raw: object) -> float:- """Parse a configured drain timeout, falling back to the shared default."""- try:- value = float(raw) if str(raw or "").strip() else DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT # type: ignore[arg-type]- except (TypeError, ValueError):- return DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT- return max(0.0, value)+ """Parse a configured drain timeout; falsy (incl. ``0``) falls back to the shared default."""+ return _parse_timeout_keeping_zero(raw or None, DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT)def parse_restart_after_turn_timeout(raw: object) -> float:@@ -145,22 +132,17 @@ def resolve_cron_drain_budget() -> float:"""Seconds the shutdown drain may spend waiting on in-flight cron work.- The configured floor is clamped to what this process can honour: the- shutdown watchdog hard-exits at ``watchdog_delay`` (TimeoutStopSec is sized- from the same budget), so waiting past that leash minus ``cleanup_reserve_s``- swaps a cleanly-interrupted job for a SIGKILL that leaves it wedged. Never- returns less than ``drain_timeout``: the cron floor only ever extends the- wait, so a deliberately long ``restart_drain_timeout`` is kept.+ The floor is clamped to what this process can honour: the shutdown watchdog+ hard-exits at ``watchdog_delay`` (TimeoutStopSec is sized from the same+ budget), so waiting past that leash minus ``cleanup_reserve_s`` swaps a+ cleanly-interrupted job for a SIGKILL that leaves it wedged. Never returns+ less than ``drain_timeout``: the cron floor only ever extends the wait."""drain = _seconds(drain_timeout)floor = _seconds(cron_drain_timeout)if floor <= 0.0:return drain- ceiling = (- _seconds(watchdog_delay)- - _seconds(elapsed)- - _seconds(cleanup_reserve_s, CRON_DRAIN_CLEANUP_RESERVE_S)- )+ ceiling = _seconds(watchdog_delay) - _seconds(elapsed) - _seconds(cleanup_reserve_s, CRON_DRAIN_CLEANUP_RESERVE_S)return max(drain, min(floor, ceiling))@@ -175,28 +157,20 @@ def resolve_systemd_timeout_stop_sec("""Seconds systemd ``TimeoutStopSec`` must cover the full stop budget.``restart_drain_timeout`` is only the chat-turn interrupt budget (default 0);- the stop path may first wait ``cron_drain_timeout`` + ``cleanup_reserve_s``- for cron work, so sizing from drain alone lets systemd SIGKILL an in-budget- drain. A zero cron timeout is an opt-out and does not extend the budget.- Non-numeric inputs degrade to 0.+ the stop path may first wait ``cron_drain_timeout`` + ``cleanup_reserve_s`` for+ cron work, so sizing from drain alone lets systemd SIGKILL an in-budget drain.+ A zero cron timeout is an opt-out and does not extend the budget."""drain = _seconds(drain_timeout)cron = _seconds(cron_drain_timeout)cron_budget = (cron + _seconds(cleanup_reserve_s)) if cron > 0.0 else 0.0- stop_budget = max(drain, cron_budget)- return int(max(_seconds(floor_s), stop_budget + _seconds(headroom_s)))+ return int(max(_seconds(floor_s), max(drain, cron_budget) + _seconds(headroom_s)))-def resolve_restart_exit_wait_budget(- drain_timeout: float,- after_turn_timeout: float,- *,- headroom: float = 15.0,-) -> float:+def resolve_restart_exit_wait_budget(drain_timeout: float, after_turn_timeout: float, *, headroom: float = 15.0) -> float:"""Seconds a CLI should wait for the gateway PID to exit after SIGUSR1.In-band restart may defer ``stop()`` until turns finish (``after_turn_timeout``)- and then spend ``drain_timeout`` inside ``stop()``; callers that hard-kill on- expiry must cover both phases.+ and then spend ``drain_timeout`` inside ``stop()``; hard-killing callers must cover both."""return _seconds(drain_timeout) + _seconds(after_turn_timeout) + _seconds(headroom)diff --git a/gateway/restart_loop_guard.py b/gateway/restart_loop_guard.pyindex d0978a4f2af..71c9d9a07c5 100644--- a/gateway/restart_loop_guard.py+++ b/gateway/restart_loop_guard.py@@ -1,20 +1,15 @@"""Auto-resume restart-loop breaker (defense-3).-Defenses 1 and 2 (the ``_HERMES_GATEWAY`` guard on ``hermes gateway-stop|restart`` + ``terminal_tool``, and the cron-creation lifecycle filter) stop-the agent scheduling its own restart. They do NOT cover every SIGTERM source-(raw ``launchctl kickstart``, a bad external monitor, any repeated crash): the-supervisor respawns, the gateway auto-resumes the restart-interrupted session,-whose next turn re-runs the offending logic.--Last-resort circuit breaker: each boot with restart-interrupted sessions pending-is timestamped and persisted to ``<HERMES_HOME>/gateway/restart_loop.json``-(each boot is a fresh process). Boots CHAIN while consecutive gaps stay within-``max_gap_seconds``, so a slow crash cycle (liveness watchdog every ~150s) trips-exactly like a fast ~10s respawn loop. When tripped, the caller SKIPS-auto-resume for that boot — real inbound messages are still served.-Best-effort: any read/write failure fails OPEN (a broken breaker must never-wedge a healthy gateway).+Defenses 1 and 2 (the ``_HERMES_GATEWAY`` guard on ``hermes gateway stop|restart``++ ``terminal_tool``, and the cron-creation lifecycle filter) stop the agent+scheduling its own restart but not every SIGTERM source (``launchctl kickstart``,+a bad external monitor, any repeated crash): the supervisor respawns, the gateway+auto-resumes the restart-interrupted session, whose next turn re-runs the+offending logic. Each such boot is persisted to ``<HERMES_HOME>/gateway/+restart_loop.json``; boots CHAIN while consecutive gaps stay within+``max_gap_seconds`` (a ~150s watchdog-kill cycle trips like a ~10s respawn loop).+Tripped → caller SKIPS auto-resume; inbound messages still served. Any I/O+failure fails OPEN — a broken breaker must never wedge a healthy gateway."""from __future__ import annotations