Skip to content

The agent that grows with you

refactor(gateway): collapse defensive layers, drop dead loggers, compact call sites across lifecycle/monitoring/media modules

Teknium84b868220311
diff --git a/gateway/agent_cache_pressure.py b/gateway/agent_cache_pressure.py
index 8c32a923936..bf1270128d5 100644
--- a/gateway/agent_cache_pressure.py
+++ b/gateway/agent_cache_pressure.py
@@ -16,15 +16,14 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Iterable, List, Optional, Tuple
-# Shed well under the limit: once cgroup ``memory.high`` throttling kicks in
-# (swap full), a SIGTERM flush cannot finish inside systemd's stop timeout.
+# Shed well under the limit: once cgroup ``memory.high`` throttling kicks in (swap full),
+# a SIGTERM flush cannot finish inside systemd's stop timeout.
_AUTO_BUDGET_FRACTION = 0.65
-# Below this a budget is noise — small containers would evict every pass and
-# never keep a warm prefix.
+# 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.
+# Never shed the hottest sessions: their prompt cache is worth the most; 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"})
@@ -48,13 +47,11 @@ def _is_int(value: Any) -> bool:
def _positive(value: Any, cast: Callable[[Any], Any] = int) -> Any:
"""``cast(value)`` if it is a positive number (bools rejected), else None."""
- if isinstance(value, bool) or value is None:
- return None
try:
- parsed = cast(value)
+ parsed = None if isinstance(value, bool) or value is None else cast(value)
except (TypeError, ValueError):
return None
- return parsed if parsed > 0 else None
+ return parsed if parsed is not None and parsed > 0 else None
def _cgroup_limit_bytes() -> Optional[int]:
@@ -73,10 +70,8 @@ def _cgroup_limit_bytes() -> Optional[int]:
own = _own_cgroup_path()
except Exception:
own = None
- 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:
+ roots = ([f"/sys/fs/cgroup{own}"] if own and own != "/" else []) + ["/sys/fs/cgroup"]
+ for candidate in [f"{r}/memory.{f}" for r in roots for f in ("high", "max")] + ["/sys/fs/cgroup/memory/memory.limit_in_bytes"]:
try:
limit = int(Path(candidate).read_text(encoding="utf-8").strip())
except (OSError, ValueError): # unreadable, empty, or "max"
@@ -106,12 +101,10 @@ def resolve_memory_high_mb(setting: Any) -> Optional[int]:
normalized = setting.strip().lower()
if normalized != "auto":
return None if normalized in _OFF_WORDS else _positive(normalized)
- elif isinstance(setting, bool):
- if not setting:
- return None
- else:
+ elif setting is False:
+ return None
+ elif setting is not True:
return _positive(setting)
-
limit = _cgroup_limit_bytes() or _total_memory_bytes()
if not limit:
return None
@@ -127,9 +120,8 @@ def resolve_agent_cache_bounds(config: Any) -> AgentCacheBounds:
section = {}
protect_recent = section.get("protect_recent")
protect_parsed = _positive(protect_recent)
- # 0 means "shed anything" — distinct from unset. The bool guard keeps
- # `protect_recent: false` (False == 0) on the default instead of silently
- # disabling MRU protection.
+ # 0 means "shed anything" — distinct from unset. The bool guard keeps `protect_recent: false`
+ # (False == 0) on the default instead of silently disabling MRU protection.
if protect_parsed is None and _is_int(protect_recent) and protect_recent == 0:
protect_parsed = 0
return AgentCacheBounds(
@@ -170,8 +162,7 @@ def transcript_persistence_caught_up(agent: Any) -> bool:
up. Unknown shapes are *not* caught up: a skipped eviction costs memory, a
wrong one costs the conversation.
"""
- messages = getattr(agent, "_session_messages", None)
- flushed = getattr(agent, "_last_flushed_db_idx", None)
+ messages, flushed = getattr(agent, "_session_messages", None), getattr(agent, "_last_flushed_db_idx", None)
return isinstance(messages, list) and _is_int(flushed) and flushed >= len(messages)
diff --git a/gateway/cgroup_cleanup.py b/gateway/cgroup_cleanup.py
index 3e425696ca2..8e34fc5a89b 100644
--- a/gateway/cgroup_cleanup.py
+++ b/gateway/cgroup_cleanup.py
@@ -10,6 +10,7 @@ cgroup-wide kill while per-PID signal delivery still works.
from __future__ import annotations
+import contextlib
import os
import re
import signal
@@ -34,23 +35,19 @@ def _read_cgroup_pids(cgroup_path: str) -> list[int]:
return []
pids: list[int] = []
for line in raw.splitlines():
- try:
+ with contextlib.suppress(ValueError):
pids.append(int(line.strip()))
- except ValueError:
- continue
return pids
def reap_cgroup(cgroup_path: str | None = None) -> int:
"""SIGKILL every PID in the cgroup other than the caller. Returns the count killed."""
- if cgroup_path is None:
- cgroup_path = _own_cgroup_path()
+ cgroup_path = _own_cgroup_path() if cgroup_path is None else cgroup_path
if not cgroup_path:
return 0
- own = os.getpid()
killed = 0
for pid in _read_cgroup_pids(cgroup_path):
- if pid == own:
+ if pid == os.getpid():
continue
try:
os.kill(pid, signal.SIGKILL) # windows-footgun: ok — Linux-only (reads /proc, /sys/fs/cgroup; runs from a systemd unit)
diff --git a/gateway/code_skew.py b/gateway/code_skew.py
index 3245aa158cc..a5a200142fe 100644
--- a/gateway/code_skew.py
+++ b/gateway/code_skew.py
@@ -37,16 +37,12 @@ def record_boot_fingerprint() -> None:
def _short(fingerprint: str) -> str:
"""Render a ``git:<ref>:<sha>`` fingerprint as a compact label."""
sha = fingerprint.rsplit(":", 1)[-1]
- if sha and sha != "unresolved" and len(sha) > 10:
- return sha[:10]
- return sha or fingerprint
+ return sha[:10] if sha and sha != "unresolved" and len(sha) > 10 else (sha or fingerprint)
def detect_code_skew() -> tuple[str, str] | None:
"""``(boot_rev, disk_rev)`` short labels if the checkout drifted since boot, else ``None``."""
- if _boot_fingerprint is None:
- return None
- current = _fingerprint()
+ current = _fingerprint() if _boot_fingerprint is not None else None
if current is None or current == _boot_fingerprint:
return None
return _short(_boot_fingerprint), _short(current)
diff --git a/gateway/cwd_placeholder.py b/gateway/cwd_placeholder.py
index 3d9d9dd8db7..33c1c418dd0 100644
--- a/gateway/cwd_placeholder.py
+++ b/gateway/cwd_placeholder.py
@@ -28,7 +28,6 @@ def resolve_placeholder_terminal_cwd(
"""
if configured_cwd and configured_cwd not in CWD_PLACEHOLDERS:
return configured_cwd
-
backend = (terminal_backend or "local").strip().lower()
messaging = (messaging_cwd or "").strip()
if backend == "local":
diff --git a/gateway/disk_status.py b/gateway/disk_status.py
index a27192ecc7c..897a251bc46 100644
--- a/gateway/disk_status.py
+++ b/gateway/disk_status.py
@@ -10,20 +10,16 @@ percent) and an enum. Best-effort: an unreadable filesystem degrades to
from __future__ import annotations
-import logging
import shutil
from pathlib import Path
from typing import Any, Dict, Optional
from gateway.memory_status import _nonneg_int
-logger = logging.getLogger(__name__)
-
-# Percent alone misleads both ways: 90% used on 100 GB leaves 10 GB, while 50%
-# on a tiny volume is one download from write failures. Percent triggers are
-# gated on absolute headroom also being low, and a hard absolute floor applies
-# regardless of size (below it SQLite journaling / config writes are at risk).
-# (level, free-MB floor, used-% trigger, headroom MB the % trigger is gated on); worst first.
+# Percent alone misleads both ways: 90% used on 100 GB leaves 10 GB, while 50% on a tiny
+# volume is one download from write failures. So percent triggers are gated on absolute
+# headroom also being low, and a hard floor applies regardless of size (below it SQLite
+# journaling / config writes are at risk). Rows: (level, free floor, used-%, headroom); worst first.
_PRESSURE_TIERS = (
("critical", 256, 95.0, 1024), # < 256 MB free, or >= 95% used AND < 1 GB free
("elevated", 512, 85.0, 4096), # < 512 MB free, or >= 85% used AND < 4 GB free
@@ -34,8 +30,7 @@ _BYTES_PER_MB = 1024 * 1024
def classify_disk_pressure(free_mb: Any, total_mb: Any) -> str:
"""``ok``/``elevated``/``critical`` from free/total MB; ``unknown`` when the sample
is missing/malformed — "could not read it" must never read as "fine"."""
- free = _nonneg_int(free_mb)
- total = _nonneg_int(total_mb)
+ free, total = _nonneg_int(free_mb), _nonneg_int(total_mb)
if free is None or not total:
return "unknown"
used_percent = (1 - free / total) * 100.0
@@ -59,12 +54,7 @@ def collect_disk_status(home: Optional[Path] = None) -> Dict[str, Any]:
return status
if usage.total <= 0:
return status
- total_mb = usage.total // _BYTES_PER_MB
- free_mb = usage.free // _BYTES_PER_MB
- status.update(
- total_mb=total_mb,
- free_mb=free_mb,
- used_percent=round((usage.used / usage.total) * 100, 1),
- pressure=classify_disk_pressure(free_mb, total_mb),
- )
+ total_mb, free_mb = usage.total // _BYTES_PER_MB, usage.free // _BYTES_PER_MB
+ status.update(total_mb=total_mb, free_mb=free_mb, used_percent=round((usage.used / usage.total) * 100, 1),
+ pressure=classify_disk_pressure(free_mb, total_mb))
return status
diff --git a/gateway/drain_control.py b/gateway/drain_control.py
index 112becbd671..232d45ae4ad 100644
--- a/gateway/drain_control.py
+++ b/gateway/drain_control.py
@@ -27,11 +27,11 @@ 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-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.
+# 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
@@ -48,8 +48,8 @@ def current_instantiation_epoch() -> str:
with contextlib.suppress(OSError):
boot_id = Path("/proc/sys/kernel/random/boot_id").read_text(encoding="utf-8").strip()
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.
+ # "<pid> (<comm>) <state> ...": comm may contain spaces/parens, so split on the
+ # LAST ')'. starttime is field 22 (1-indexed) = tail index 19.
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 ""
@@ -84,10 +84,9 @@ def clear_drain_request(*, home: Optional[Path] = None) -> bool:
try:
path.unlink()
return True
- except FileNotFoundError:
- return False
except OSError as e:
- _log.warning("drain-control: failed to remove %s: %s", path, e)
+ if not isinstance(e, FileNotFoundError):
+ _log.warning("drain-control: failed to remove %s: %s", path, e)
return False
@@ -146,10 +145,9 @@ def read_drain_request(*, home: Optional[Path] = None) -> Optional[dict[str, Any
path = drain_request_path(home)
try:
raw = path.read_text(encoding="utf-8")
- except FileNotFoundError:
- return None
except OSError as e:
- _log.warning("drain-control: failed to read %s: %s", path, e)
+ if not isinstance(e, FileNotFoundError):
+ _log.warning("drain-control: failed to read %s: %s", path, e)
return None
try:
data = json.loads(raw)
diff --git a/gateway/hooks.py b/gateway/hooks.py
index 168cf5abf29..c0a84aa67aa 100644
--- a/gateway/hooks.py
+++ b/gateway/hooks.py
@@ -23,34 +23,29 @@ from hermes_cli.config import get_hermes_home
HOOKS_DIR = get_hermes_home() / "hooks"
+def _skip(name: str, reason: str) -> None:
+ print(f"[hooks] Skipping {name}: {reason}", flush=True)
+
+
def _load_hook_dir(hook_dir: Path) -> Optional[tuple]:
"""``(name, events, handle_fn, description)`` for a valid hook dir, else None (reason printed)."""
- manifest_path = hook_dir / "HOOK.yaml"
- handler_path = hook_dir / "handler.py"
+ manifest_path, handler_path = hook_dir / "HOOK.yaml", hook_dir / "handler.py"
if not manifest_path.exists() or not handler_path.exists():
return None
-
manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
if not manifest or not isinstance(manifest, dict):
- print(f"[hooks] Skipping {hook_dir.name}: invalid HOOK.yaml", flush=True)
- return None
-
+ return _skip(hook_dir.name, "invalid HOOK.yaml")
hook_name = manifest.get("name", hook_dir.name)
events = manifest.get("events", [])
if not events:
- print(f"[hooks] Skipping {hook_name}: no events declared", flush=True)
- return None
-
- # Register in sys.modules BEFORE exec_module so Pydantic/dataclass forward
- # references (from ``from __future__ import annotations``) resolve; otherwise
- # a handler declaring a BaseModel fails at first dispatch with
- # "TypeAdapter ... is not fully defined".
+ return _skip(hook_name, "no events declared")
+ # Register in sys.modules BEFORE exec_module so Pydantic/dataclass forward references
+ # (``from __future__ import annotations``) resolve; otherwise a handler declaring a
+ # BaseModel fails at first dispatch with "TypeAdapter ... is not fully defined".
module_name = f"hermes_hook_{hook_name}"
spec = importlib.util.spec_from_file_location(module_name, handler_path)
if spec is None or spec.loader is None:
- print(f"[hooks] Skipping {hook_name}: could not load handler.py", flush=True)
- return None
-
+ return _skip(hook_name, "could not load handler.py")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
try:
@@ -58,11 +53,9 @@ def _load_hook_dir(hook_dir: Path) -> Optional[tuple]:
except Exception:
sys.modules.pop(module_name, None)
raise
-
handle_fn = getattr(module, "handle", None)
if handle_fn is None:
- print(f"[hooks] Skipping {hook_name}: no 'handle' function found", flush=True)
- return None
+ return _skip(hook_name, "no 'handle' function found")
return hook_name, events, handle_fn, manifest.get("description", "")
@@ -79,7 +72,6 @@ class HookRegistry:
def _register_builtin_hooks(self) -> None:
"""Extension point for always-on built-in hooks; currently none shipped."""
- return
def discover_and_load(self) -> None:
"""Register built-in hooks, then load every valid hook dir under HOOKS_DIR."""
@@ -105,11 +97,8 @@ class HookRegistry:
print(f"[hooks] Loaded hook '{hook_name}' for events: {events}", flush=True)
def _resolve_handlers(self, event_type: str) -> List[Callable]:
- """Exact-match handlers first, then ``<base>:*`` wildcard handlers.
-
- A handler registered for a bare base type ("agent") does NOT fire for
- "agent:start" — only exact matches and explicit wildcards.
- """
+ """Exact-match handlers first, then ``<base>:*`` wildcards. A bare base type
+ ("agent") does NOT fire for "agent:start" — only exact matches and explicit wildcards."""
handlers = list(self._handlers.get(event_type, []))
if ":" in event_type:
handlers.extend(self._handlers.get(f"{event_type.split(':')[0]}:*", []))
@@ -120,20 +109,15 @@ class HookRegistry:
await self.emit_collect(event_type, context)
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
- allow/deny/rewrite a command). A failing handler is logged and does not
- abort the remaining handlers.
- """
+ """Fire handlers and return their non-None return values in order (decision-style
+ hooks, e.g. ``command:<name>`` policies). A failing handler is logged, not fatal."""
if context is None:
context = {}
results: List[Any] = []
for fn in self._resolve_handlers(event_type):
try:
result = fn(event_type, context)
- if asyncio.iscoroutine(result): # sync and async handlers both supported
- result = await result
+ result = await result if asyncio.iscoroutine(result) else result # sync or async handlers
if result is not None:
results.append(result)
except Exception as e:
diff --git a/gateway/lifecycle_ledger.py b/gateway/lifecycle_ledger.py
index cb43b47f28c..a12f6c5aaea 100644
--- a/gateway/lifecycle_ledger.py
+++ b/gateway/lifecycle_ledger.py
@@ -26,12 +26,10 @@ logger = logging.getLogger(__name__)
def _process_hermes_home() -> Path:
"""HERMES_HOME for process-level identity files (ignore task overrides)."""
- val = os.environ.get("HERMES_HOME", "").strip()
- if val:
- return Path(val)
from hermes_constants import get_hermes_home
- return get_hermes_home()
+ val = os.environ.get("HERMES_HOME", "").strip()
+ return Path(val) if val else get_hermes_home()
def _home_path(home: Optional[Path], *relative: str) -> Path:
@@ -64,11 +62,8 @@ def _proc_fields(path: str, wanted: Dict[str, str]) -> Dict[str, int]:
def sample_memory() -> Dict[str, Any]:
- """Cheap /proc snapshot (KiB, kernel units): own RSS + MemTotal/MemAvailable + swap used.
-
- Linux-only (``{}`` elsewhere), never raises; embedded in the 30s loop
- heartbeat so OOM crash cycles are classifiable from the volume alone.
- """
+ """Cheap /proc snapshot (KiB): own RSS + MemTotal/MemAvailable + swap used. Linux-only
+ (``{}`` elsewhere), never raises; the 30s heartbeat embeds it so OOM cycles are classifiable."""
sample = _proc_fields("/proc/self/status", {"VmRSS": "rss_kib"})
mem = _proc_fields("/proc/meminfo", {"MemTotal": "mem_total_kib", "MemAvailable": "mem_available_kib",
"SwapTotal": "SwapTotal", "SwapFree": "SwapFree"})
@@ -88,10 +83,10 @@ def _read_json(path: Path) -> Optional[Dict[str, Any]]:
def _write_sentinel(payload: Dict[str, Any], home: Optional[Path]) -> None:
- path = get_lifecycle_sentinel_path(home)
try:
from utils import atomic_json_write
+ path = get_lifecycle_sentinel_path(home)
path.parent.mkdir(parents=True, exist_ok=True)
atomic_json_write(path, payload, indent=None)
except Exception:
@@ -100,8 +95,8 @@ def _write_sentinel(payload: Dict[str, Any], home: Optional[Path]) -> None:
def _append_exit_diag(record: Dict[str, Any], home: Optional[Path]) -> None:
"""Append a JSON line to gateway-exit-diag.log (same format as the CLI's ``_exit_diag``)."""
- path = _home_path(home, "logs", "gateway-exit-diag.log")
try:
+ path = _home_path(home, "logs", "gateway-exit-diag.log")
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as fh:
fh.write(json.dumps(record, default=str) + "\n")
@@ -110,11 +105,8 @@ def _append_exit_diag(record: Dict[str, Any], home: Optional[Path]) -> None:
def _pid_alive_with_start_time(pid: Any, start_time: Any) -> bool:
- """True when ``pid`` is a live process matching ``start_time`` (±2s).
-
- Guards the ``--replace`` takeover race: a live matching owner mid-teardown
- is a planned handover, not an unclean death.
- """
+ """True when ``pid`` is a live process matching ``start_time`` (±2s) — guards the
+ ``--replace`` race: a live matching owner mid-teardown is a handover, not a death."""
try:
pid_int = int(pid)
# NOT os.kill(pid, 0): on Windows that sends CTRL_C_EVENT to the target's console group.
@@ -124,11 +116,9 @@ def _pid_alive_with_start_time(pid: Any, start_time: Any) -> bool:
return False
except Exception:
return False
- if start_time is None:
- return True # alive; can't disambiguate PID reuse — err on "alive"
try:
- actual = get_process_start_time(pid_int)
- return actual is None or abs(float(actual) - float(start_time)) <= 2.0
+ actual = None if start_time is None else get_process_start_time(pid_int)
+ return actual is None or abs(float(actual) - float(start_time)) <= 2.0 # None: can't disambiguate PID reuse
except Exception:
return True
@@ -139,9 +129,10 @@ def _suspected_oom(mem: Dict[str, Any]) -> bool:
from gateway.memory_status import _CRITICAL_AVAILABLE_FRACTION, _CRITICAL_AVAILABLE_KIB
total, avail = mem.get("mem_total_kib"), mem.get("mem_available_kib")
- return isinstance(avail, int) and (
- avail < _CRITICAL_AVAILABLE_KIB
- or (isinstance(total, int) and total > 0 and avail / total < _CRITICAL_AVAILABLE_FRACTION)
+ if not isinstance(avail, int):
+ return False
+ return avail < _CRITICAL_AVAILABLE_KIB or (
+ isinstance(total, int) and total > 0 and avail / total < _CRITICAL_AVAILABLE_FRACTION
)
@@ -160,16 +151,16 @@ def detect_unclean_exit(home: Optional[Path] = None) -> Optional[Dict[str, Any]]
try:
from gateway.shutdown_watchdog import get_loop_heartbeat_path
- hb = _read_json(get_loop_heartbeat_path(home))
+ hb = _read_json(get_loop_heartbeat_path(home)) or {}
except Exception:
- hb = None
+ hb = {}
if hb:
evidence["last_heartbeat_at"] = hb.get("updated_at")
- mem = hb.get("mem")
- if isinstance(mem, dict):
- evidence["last_heartbeat_mem"] = mem
- if _suspected_oom(mem):
- evidence["suspected_oom"] = True
+ mem = hb.get("mem")
+ if isinstance(mem, dict):
+ evidence["last_heartbeat_mem"] = mem
+ if _suspected_oom(mem):
+ evidence["suspected_oom"] = True
return evidence
@@ -212,11 +203,8 @@ def _report_unclean_exit(evidence: Dict[str, Any], home: Optional[Path]) -> None
def record_startup(home: Optional[Path] = None) -> Optional[Dict[str, Any]]:
- """Boot entry point: report any unclean previous exit, then claim the sentinel.
-
- Returns the evidence dict (also persisted to ``gateway-exit-diag.log`` and
- logged at WARNING) or ``None``. Never raises.
- """
+ """Boot entry point: report any unclean previous exit (evidence dict, also persisted
+ to ``gateway-exit-diag.log`` and logged at WARNING) then claim the sentinel. Never raises."""
evidence: Optional[Dict[str, Any]] = None
try:
evidence = detect_unclean_exit(home)
@@ -250,20 +238,15 @@ def mark_exited(exit_code: Optional[int] = None, reason: str = "graceful_shutdow
sentinel = _read_json(get_lifecycle_sentinel_path(home))
if sentinel is not None and sentinel.get("pid") != os.getpid():
return
- _write_sentinel(
- {"phase": "exited", "pid": os.getpid(), "exit_code": exit_code, "exit_reason": reason, "exited_at": _now_iso()},
- home,
- )
+ _write_sentinel({"phase": "exited", "pid": os.getpid(), "exit_code": exit_code, "exit_reason": reason,
+ "exited_at": _now_iso()}, home)
except Exception:
logger.debug("Failed to mark lifecycle sentinel exited", exc_info=True)
def read_prior_exit_label(profile_home: Path) -> str:
- """``clean`` / ``unclean`` / ``unknown`` for how the profile's last gateway life ended.
-
- Read-only, exception-free; annotates ``container-boot.log``. ``running`` is
- unclean because the old PID namespace is gone at container boot.
- """
+ """``clean``/``unclean``/``unknown`` for the profile's last gateway life; annotates
+ ``container-boot.log``. ``running`` is unclean: the old PID namespace is gone at container boot."""
try:
phase = (_read_json(get_lifecycle_sentinel_path(profile_home)) or {}).get("phase")
return {"exited": "clean", "running": "unclean"}.get(phase, "unknown")
diff --git a/gateway/media_policy.py b/gateway/media_policy.py
index 76260892bc8..1440549b32c 100644
--- a/gateway/media_policy.py
+++ b/gateway/media_policy.py
@@ -17,9 +17,8 @@ from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
-_STRICT_ENV = "HERMES_MEDIA_DELIVERY_STRICT"
+_FLAG_ENVS = (("strict", "HERMES_MEDIA_DELIVERY_STRICT"), ("trust_recent_files", "HERMES_MEDIA_TRUST_RECENT_FILES"))
_ALLOW_DIRS_ENV = "HERMES_MEDIA_ALLOW_DIRS"
-_TRUST_RECENT_ENV = "HERMES_MEDIA_TRUST_RECENT_FILES"
def _load_gateway_cfg(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
@@ -41,25 +40,19 @@ def _set_env_default(env: str, value: str) -> None:
def _allow_dirs_str(allow_dirs: Any) -> str:
- if isinstance(allow_dirs, str):
- return allow_dirs
if isinstance(allow_dirs, (list, tuple)):
return os.pathsep.join(str(p) for p in allow_dirs if p)
- return ""
+ return allow_dirs if isinstance(allow_dirs, str) else ""
def apply_media_policy_env(config: Optional[Dict[str, Any]] = None) -> None:
- """Bridge gateway media-policy settings from config.yaml into the env.
-
- Idempotent and env-wins: a variable already present is never overwritten.
- Never raises — a policy-bridge failure must not break delivery; the
- validator falls back to its defaults exactly as before.
- """
+ """Bridge gateway media-policy settings from config.yaml into the env. Idempotent,
+ env-wins, never raises — a bridge failure must not break delivery (validator defaults apply)."""
try:
gateway_cfg = _load_gateway_cfg(config)
if not gateway_cfg:
return
- for key, env in (("strict", _STRICT_ENV), ("trust_recent_files", _TRUST_RECENT_ENV)):
+ for key, env in _FLAG_ENVS:
flag = gateway_cfg.get(key)
if flag is not None:
_set_env_default(env, "1" if flag else "0")
diff --git a/gateway/media_repair.py b/gateway/media_repair.py
index 88437e30acf..9090b2b859d 100644
--- a/gateway/media_repair.py
+++ b/gateway/media_repair.py
@@ -47,8 +47,7 @@ def tool_name_by_call_id(messages: List[Dict[str, Any]]) -> Dict[str, str]:
def _computer_use_capture_basename(path: Any) -> str:
"""Canonical (lowercased) capture basename for either separator style, or ''."""
- value = str(path or "").strip().strip("`\"'")
- basename = re.split(r"[/\\]", value)[-1]
+ basename = re.split(r"[/\\]", str(path or "").strip().strip("`\"'"))[-1]
return basename.lower() if _COMPUTER_USE_CAPTURE_BASENAME_RE.fullmatch(basename) else ""
@@ -58,32 +57,28 @@ def _iter_computer_use_capture_paths(content: Any) -> Iterator[str]:
line since the envelope's ``meta`` is not stored in the tool message)."""
if isinstance(content, str):
stripped = content.strip()
- if stripped.startswith(("{", "[")):
- # Parse JSON first, never regex-scan it: JSON escaping doubles
- # backslashes, so a raw-text hit would yield a path that exists
- # nowhere. Fail closed on unparseable (truncated) JSON.
- try:
- payload = json.loads(stripped)
- except Exception:
- return
- if isinstance(payload, (dict, list)):
- yield from _iter_computer_use_capture_paths(payload)
+ if not stripped.startswith(("{", "[")):
+ for match in _COMPUTER_USE_CAPTURE_SUMMARY_RE.finditer(content):
+ yield match.group("path").strip()
return
- for match in _COMPUTER_USE_CAPTURE_SUMMARY_RE.finditer(content):
- yield match.group("path").strip()
+ # Parse JSON, never regex-scan it: JSON escaping doubles backslashes, so a raw-text
+ # hit would yield a path that exists nowhere. Fail closed on truncated JSON.
+ try:
+ payload = json.loads(stripped)
+ except Exception:
+ return
+ if isinstance(payload, (dict, list)):
+ yield from _iter_computer_use_capture_paths(payload)
elif isinstance(content, list):
for part in content:
yield from _iter_computer_use_capture_paths(part)
elif isinstance(content, dict):
- screenshot_path = content.get("screenshot_path")
- if isinstance(screenshot_path, str):
- yield screenshot_path
meta = content.get("meta")
- if isinstance(meta, dict) and isinstance(meta.get("screenshot_path"), str):
- yield meta["screenshot_path"]
- # Producer shapes (tools/computer_use/tool.py::_capture_response):
- # content/text = multimodal parts; text_summary/summary = the line carrying
- # "(shareable screenshot saved to ...)".
+ for holder in (content, meta if isinstance(meta, dict) else {}):
+ if isinstance(holder.get("screenshot_path"), str):
+ yield holder["screenshot_path"]
+ # Producer shapes (computer_use ``_capture_response``): content/text = multimodal
+ # parts; text_summary/summary = the "(shareable screenshot saved to ...)" line.
for field in ("content", "text", "text_summary", "summary"):
nested = content.get(field)
if isinstance(nested, (str, dict, list)):
@@ -91,23 +86,18 @@ def _iter_computer_use_capture_paths(content: Any) -> Iterator[str]:
def _current_turn_messages(messages: List[Dict[str, Any]], history_offset: int) -> List[Dict[str, Any]]:
- if not history_offset:
- return messages
- if len(messages) >= history_offset:
+ if not history_offset or len(messages) >= history_offset:
return messages[history_offset:]
- # Compression can invalidate the slice boundary: recover the turn from its
- # last user message, fail closed if none remains. Deliberately narrower than
- # gateway/run.py::_collect_auto_append_media_tags' scan-everything fallback —
- # that decides whether to ATTACH; this only rewrites paths already emitted.
+ # Compression can invalidate the slice boundary: recover the turn from its last user
+ # message, fail closed if none remains. Narrower than run.py's scan-everything fallback
+ # for auto-attach — that decides whether to ATTACH; this only rewrites emitted paths.
for index in range(len(messages) - 1, -1, -1):
if messages[index].get("role") == "user":
return messages[index:]
return []
-def repair_explicit_computer_use_media_paths(
- response: str, messages: List[Dict[str, Any]], history_offset: int = 0
-) -> str:
+def repair_explicit_computer_use_media_paths(response: str, messages: List[Dict[str, Any]], history_offset: int = 0) -> str:
"""Recover model-mangled paths in explicit ``MEDIA:`` directives whose basename
matches (case-insensitively) a canonical screenshot path from this turn.
Fail-open: the repair is cosmetic, so any error returns the response unchanged."""
@@ -135,22 +125,18 @@ def _canonical_capture_paths(turn_messages: List[Dict[str, Any]]) -> Dict[str, s
return canonical
-def _repair_explicit_computer_use_media_paths_inner(
- response: str, messages: List[Dict[str, Any]], history_offset: int = 0
-) -> str:
+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 response
- # Lazy: keeps `import gateway.media_repair` cheap for standalone cron
- # processes that may never hit a MEDIA: response. No import cycle either way.
+ # Lazy: keeps the import cheap for standalone cron processes that may never hit MEDIA:.
from gateway.platforms.base import BasePlatformAdapter
- media_files, _ = BasePlatformAdapter.extract_media(response)
repaired = response
- for emitted_path, _is_voice in media_files:
+ for emitted_path, _is_voice in BasePlatformAdapter.extract_media(response)[0]:
canonical = canonical_by_basename.get(_computer_use_capture_basename(emitted_path))
if canonical and emitted_path != canonical:
repaired = repaired.replace(emitted_path, canonical)
diff --git a/gateway/memory_monitor.py b/gateway/memory_monitor.py
index d3d19ce88ca..b2154048824 100644
--- a/gateway/memory_monitor.py
+++ b/gateway/memory_monitor.py
@@ -34,8 +34,7 @@ def _get_rss_mb() -> Optional[int]:
import resource
# ru_maxrss is KB on Linux but bytes on macOS.
- maxrss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
- return int(maxrss / (_BYTES_TO_MB if sys.platform == "darwin" else 1024))
+ return int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / (_BYTES_TO_MB if sys.platform == "darwin" else 1024))
except Exception:
pass
try:
@@ -66,11 +65,8 @@ def _monitor_loop(stop_event: threading.Event, interval: float) -> None:
def start_memory_monitoring(interval_seconds: float = 300.0) -> bool:
- """Start periodic memory logging in a daemon thread (baseline logged immediately).
-
- Returns True if a fresh monitor was started; False if one is already running
- or RSS introspection is unavailable (warned once).
- """
+ """Start periodic logging in a daemon thread (baseline logged immediately). False if
+ already running or RSS introspection is unavailable (warned once)."""
global _monitor_thread, _stop_event, _start_time
with _lock:
@@ -104,9 +100,7 @@ def stop_memory_monitoring(timeout: float = 2.0) -> None:
log_memory_usage(prefix="shutdown")
_stop_event.set()
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):
+ with contextlib.suppress(Exception): # join outside the lock so a stuck log call can't deadlock the stop path
thread.join(timeout=timeout)
logger.info("[MEMORY] Periodic memory monitoring stopped")
diff --git a/gateway/memory_status.py b/gateway/memory_status.py
index 289e48782ae..e6a4600a644 100644
--- a/gateway/memory_status.py
+++ b/gateway/memory_status.py
@@ -9,13 +9,10 @@ coarse numbers (MB), enums and booleans. A missing/corrupt file degrades to
from __future__ import annotations
-import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional
-logger = logging.getLogger(__name__)
-
# Thresholds on system MemAvailable. ``critical`` doubles as the lifecycle
# ledger's OOM-suspicion heuristic: a level that makes a later unclean death
# "suspected OOM" already warns while the process is alive.
@@ -39,27 +36,23 @@ def _nonneg_int(value: Any) -> Optional[int]:
def _mb(kib: Any) -> Optional[int]:
- kib = _nonneg_int(kib)
- return None if kib is None else kib // 1024
+ return None if _nonneg_int(kib) is None else kib // 1024
def _parse_iso(value: Any) -> Optional[datetime]:
- if not isinstance(value, str) or not value:
- return None
try:
- parsed = datetime.fromisoformat(value)
+ parsed = datetime.fromisoformat(value) if isinstance(value, str) and value else None
except ValueError:
return None
- return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc)
+ return parsed.replace(tzinfo=timezone.utc) if parsed is not None and parsed.tzinfo is None else parsed
def classify_pressure(available_kib: Any, total_kib: Any) -> str:
"""``ok``/``elevated``/``critical`` from MemAvailable/MemTotal; ``unknown`` when the
sample is missing/malformed — "could not read it" must never read as "fine"."""
- available = _nonneg_int(available_kib)
+ available, total = _nonneg_int(available_kib), _nonneg_int(total_kib)
if available is None:
return "unknown"
- total = _nonneg_int(total_kib)
fraction = available / total if total else None
for level, kib_floor, frac_floor in _PRESSURE_TIERS:
if available < kib_floor or (fraction is not None and fraction < frac_floor):
@@ -97,8 +90,7 @@ def collect_memory_status(
heartbeat, sentinel = _read_state_files(home)
if heartbeat:
- sampled_at = _parse_iso(heartbeat.get("updated_at"))
- mem = heartbeat.get("mem")
+ sampled_at, mem = _parse_iso(heartbeat.get("updated_at")), heartbeat.get("mem")
if isinstance(mem, dict):
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")):
@@ -115,7 +107,6 @@ def collect_memory_status(
status["last_boot_unclean"] = bool(sentinel.get("prior_unclean_exit"))
status["last_boot_suspected_oom"] = bool(sentinel.get("prior_suspected_oom"))
started_at = sentinel.get("started_at")
- if isinstance(started_at, str) and started_at:
- status["boot_id"] = started_at
+ status["boot_id"] = started_at if isinstance(started_at, str) and started_at else None
return status
diff --git a/gateway/message_timestamps.py b/gateway/message_timestamps.py
index 62999c02a4c..9f353b60bb2 100644
--- a/gateway/message_timestamps.py
+++ b/gateway/message_timestamps.py
@@ -35,14 +35,12 @@ def _localize(dt: datetime, tz) -> float:
def _parse_iso(text: str, tz=None) -> Optional[float]:
"""Parse an ISO-8601 string (incl. ``+0200`` offsets fromisoformat rejects)."""
- try:
- dt = datetime.fromisoformat(text)
- except (TypeError, ValueError):
+ for parse in (datetime.fromisoformat, lambda t: datetime.strptime(t, "%Y-%m-%dT%H:%M:%S%z")):
try:
- dt = datetime.strptime(text, "%Y-%m-%dT%H:%M:%S%z")
+ return _localize(parse(text), tz)
except (TypeError, ValueError):
- return None
- return _localize(dt, tz)
+ continue
+ return None
def _parse_timestamp_match(match: re.Match, tz=None) -> Optional[float]:
@@ -58,8 +56,6 @@ def _parse_timestamp_match(match: re.Match, tz=None) -> Optional[float]:
def coerce_message_timestamp(ts_value: Any, tz=None) -> Optional[float]:
"""Epoch seconds from a number, datetime, ISO string, or the gateway's bracketed
format; ``None`` when uninterpretable."""
- if ts_value is None:
- return None
if isinstance(ts_value, (int, float)):
return float(ts_value)
if hasattr(ts_value, "timestamp"):
@@ -67,16 +63,13 @@ def coerce_message_timestamp(ts_value: Any, tz=None) -> Optional[float]:
return float(ts_value.timestamp())
except Exception:
return None
- if not isinstance(ts_value, str):
- return None
- text = ts_value.strip()
+ text = ts_value.strip() if isinstance(ts_value, str) else ""
if not text:
return None
match = _TIMESTAMP_PREFIX_RE.match(text)
- if match is not None:
- parsed = _parse_timestamp_match(match, tz=tz)
- if parsed is not None:
- return parsed
+ parsed = _parse_timestamp_match(match, tz=tz) if match is not None else None
+ if parsed is not None:
+ return parsed
try:
return float(text)
except (TypeError, ValueError):
@@ -89,7 +82,7 @@ def format_message_timestamp(ts_value: Any, tz=None) -> str:
if epoch is None:
return ""
dt = datetime.fromtimestamp(epoch, tz=tz) if tz is not None else datetime.fromtimestamp(epoch).astimezone()
- return "[" + dt.strftime("%a %Y-%m-%d %H:%M:%S %Z") + "]"
+ return f"[{dt.strftime('%a %Y-%m-%d %H:%M:%S %Z')}]"
def strip_leading_message_timestamps(content: str, tz=None) -> Tuple[str, Optional[float]]:
@@ -98,8 +91,7 @@ def strip_leading_message_timestamps(content: str, tz=None) -> Tuple[str, Option
time of legacy rows like ``[processing time] [platform time] [sender] message``."""
if not isinstance(content, str) or not content:
return content, None
- text = content
- embedded_epoch: Optional[float] = None
+ text, embedded_epoch = content, None
while (match := _TIMESTAMP_PREFIX_RE.match(text)) is not None:
parsed = _parse_timestamp_match(match, tz=tz)
if parsed is not None:
@@ -112,8 +104,5 @@ def render_user_content_with_timestamp(content: str, ts_value: Any = None, tz=No
"""Render a user message for LLM context with exactly one timestamp prefix; an
existing prefix is stripped and its parsed time wins over ``ts_value``."""
clean_content, embedded_epoch = strip_leading_message_timestamps(content, tz=tz)
- effective_ts = embedded_epoch if embedded_epoch is not None else ts_value
- prefix = format_message_timestamp(effective_ts, tz=tz)
- if not prefix:
- return clean_content
- return f"{prefix} {clean_content}" if clean_content else prefix
+ prefix = format_message_timestamp(ts_value if embedded_epoch is None else embedded_epoch, tz=tz)
+ return f"{prefix} {clean_content}" if prefix and clean_content else (prefix or clean_content)
diff --git a/gateway/mirror.py b/gateway/mirror.py
index 552858e0601..908c53b847f 100644
--- a/gateway/mirror.py
+++ b/gateway/mirror.py
@@ -89,11 +89,9 @@ def _find_session_id(platform: str, chat_id: str, thread_id: Optional[str] = Non
def _matches(entry: dict) -> bool:
origin = entry.get("origin") or {}
- return (
- (origin.get("platform") or entry.get("platform", "")).lower() == platform.lower()
- and str(origin.get("chat_id", "")) == str(chat_id)
- and (thread_id is None or str(origin.get("thread_id") or "") == str(thread_id))
- )
+ return ((origin.get("platform") or entry.get("platform", "")).lower() == platform.lower()
+ and str(origin.get("chat_id", "")) == str(chat_id)
+ and (thread_id is None or str(origin.get("thread_id") or "") == str(thread_id)))
# Keys starting with "_" (e.g. the gateway's "_README") are metadata sentinels.
candidates = [e for k, e in data.items() if not str(k).startswith("_") and isinstance(e, dict) and _matches(e)]
@@ -105,11 +103,8 @@ def _find_session_id(platform: str, chat_id: str, thread_id: Optional[str] = Non
candidates = exact_user_matches
elif len(candidates) > 1:
return None
- elif len(candidates) > 1:
- distinct_user_ids = {uid.strip() for uid in map(_origin_user_id, candidates) if uid.strip()}
- if len(distinct_user_ids) > 1:
- return None
-
+ elif len(candidates) > 1 and len({u.strip() for u in map(_origin_user_id, candidates) if u.strip()}) > 1:
+ return None
return max(candidates, key=lambda entry: entry.get("updated_at", "")).get("session_id")
@@ -117,6 +112,7 @@ def _append_to_sqlite(session_id: str, message: dict) -> None:
"""Append a message to the SQLite session database."""
try:
from hermes_state import get_shared_session_db, release_or_close
+
db = get_shared_session_db()
try:
db.append_message(session_id=session_id, role=message.get("role", "assistant"), content=message.get("content"))
diff --git a/gateway/readiness.py b/gateway/readiness.py
index 29bd8236e0d..266f093732d 100644
--- a/gateway/readiness.py
+++ b/gateway/readiness.py
@@ -18,11 +18,7 @@ _CONNECTED_STATES = {"connected", "running", "ok"}
def _check(status: str, detail: str | None = None, **extra: Any) -> dict[str, Any]:
- result: dict[str, Any] = {"status": status}
- if detail:
- result["detail"] = detail
- result.update(extra)
- return result
+ return {"status": status, **({"detail": detail} if detail else {}), **extra}
def _probe_state_db(home: Path) -> dict[str, Any]:
@@ -30,12 +26,10 @@ def _probe_state_db(home: Path) -> dict[str, Any]:
if not path.exists():
return _check("ok", "not initialized")
try:
- # Read-only schema query: catches unreadable/corrupt DBs without competing
- # with state writers. ``closing`` is required — sqlite3's connection
- # context manager only commits/rolls back, never closes, so a bare
- # ``with connect()`` would leak one connection (and fds) per health poll.
- uri = f"file:{path.as_posix()}?mode=ro"
- with closing(sqlite3.connect(uri, uri=True, timeout=1.0)) as conn:
+ # Read-only schema query: catches unreadable/corrupt DBs without competing with
+ # writers. ``closing`` is required — sqlite3's context manager only commits/rolls
+ # back, never closes, so a bare ``with connect()`` leaks a connection per poll.
+ with closing(sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True, timeout=1.0)) as conn:
conn.execute("PRAGMA query_only = ON")
conn.execute("SELECT name FROM sqlite_master LIMIT 1").fetchone()
return _check("ok")
@@ -60,8 +54,7 @@ def _probe_disk(home: Path) -> dict[str, Any]:
except Exception as exc:
return _check("degraded", type(exc).__name__)
used_pct = round((usage.used / usage.total) * 100, 1) if usage.total else 0.0
- status = "degraded" if used_pct >= _DISK_DEGRADED_PERCENT else "ok"
- return _check(status, used_percent=used_pct, free_bytes=usage.free)
+ return _check("degraded" if used_pct >= _DISK_DEGRADED_PERCENT else "ok", used_percent=used_pct, free_bytes=usage.free)
def _probe_gateway(runtime_status: dict[str, Any]) -> dict[str, Any]:
@@ -72,8 +65,8 @@ def _probe_gateway(runtime_status: dict[str, Any]) -> dict[str, Any]:
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))
+ return _check("ok" if state in {"running", "draining"} else "degraded", state=state,
+ connected_platforms=connected, platforms=len(platforms))
def _probe_session_store(runtime_status: dict[str, Any], state_db_probe: dict[str, Any]) -> dict[str, Any]:
@@ -108,8 +101,7 @@ def collect_runtime_readiness(
active_delegations=max(0, int(active_delegations)),
),
}
- overall = "ok" if all(item.get("status") == "ok" for item in checks.values()) else "degraded"
- return {"status": overall, "checks": checks}
+ return {"status": "ok" if all(c.get("status") == "ok" for c in checks.values()) else "degraded", "checks": checks}
__all__ = ["collect_runtime_readiness"]
diff --git a/gateway/response_filters.py b/gateway/response_filters.py
index acc9c306308..6f293935447 100644
--- a/gateway/response_filters.py
+++ b/gateway/response_filters.py
@@ -39,16 +39,12 @@ def _strip_edge_silence_punctuation(text: str) -> str:
def _canonical_silence_candidates(text: Any) -> tuple[str, ...]:
"""Canonical forms of a short marker-sized response; ``()`` when not a candidate at all."""
- if not isinstance(text, str):
- return ()
- stripped = text.strip()
+ stripped = text.strip() if isinstance(text, str) else ""
if not 0 < len(stripped) <= _MARKER_LENGTH_CAP:
return ()
- exact = _canonical_silence_candidate(stripped)
depunctuated = _strip_edge_silence_punctuation(stripped)
- if depunctuated == stripped:
- return (exact,)
- return (exact, _canonical_silence_candidate(depunctuated))
+ forms = (stripped,) if depunctuated == stripped else (stripped, depunctuated)
+ return tuple(_canonical_silence_candidate(f) for f in forms)
def is_intentional_silence_response(response: Any) -> bool:
@@ -69,29 +65,19 @@ def is_autonomous_silence_response(response: Any) -> bool:
changes detected``). A token buried mid-sentence is still delivered.
Shares :data:`LIVE_GATEWAY_SILENT_MARKERS` so the two sets cannot drift.
"""
- if not isinstance(response, str):
- return False
- stripped = response.strip()
+ stripped = response.strip() if isinstance(response, str) else ""
if not stripped:
return False
-
- def _is_token(line: str) -> bool:
- return _canonical_silence_candidate(line) in LIVE_GATEWAY_SILENT_MARKERS
-
- if _is_token(stripped):
- return True
lines = [ln for ln in stripped.splitlines() if ln.strip()]
- if lines and (_is_token(lines[0]) or _is_token(lines[-1])):
- return True
- # Bracketed form only, so a bare "Silent retry succeeded" is NOT swallowed.
- return stripped.upper().startswith("[SILENT]")
+ # Bracketed form only for the prefix rule, so a bare "Silent retry succeeded" is NOT swallowed.
+ return stripped.upper().startswith("[SILENT]") or any(
+ _canonical_silence_candidate(c) in LIVE_GATEWAY_SILENT_MARKERS for c in (stripped, lines[0], lines[-1])
+ )
def is_intentional_silence_agent_result(agent_result: dict | None, response: Any) -> bool:
"""Silence markers suppress delivery only for successful agent turns."""
- if not isinstance(agent_result, dict) or agent_result.get("failed"):
- return False
- return is_intentional_silence_response(response)
+ return isinstance(agent_result, dict) and not agent_result.get("failed") and is_intentional_silence_response(response)
def is_partial_silence_marker(text: Any) -> bool:
diff --git a/gateway/restart.py b/gateway/restart.py
index 74673228a2f..9b36120ac33 100644
--- a/gateway/restart.py
+++ b/gateway/restart.py
@@ -25,21 +25,16 @@ DEFAULT_GATEWAY_POST_INTERRUPT_GRACE_TIMEOUT = 5.0
# ``restart_drain_timeout``, the force-interrupt budget once ``stop()`` runs (short under 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.
+# 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 resume_pending); an
+# interrupted *cron* run is a permanent failure in jobs.json — 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.
+# Watchdog leash held back for post-drain work (interrupt agents, kill subprocesses, mark jobs,
+# 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.
-# Keep in lockstep with generate_systemd_unit().
+# 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.0
SYSTEMD_TIMEOUT_STOP_SEC_FLOOR = 60.0
@@ -49,10 +44,9 @@ _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), not a transient
- blip. Matches by error CODE only (``lock_conflict`` / ``*_lock``), never text.
+ Adapters emit ``{scope}_lock`` with ``retryable=True`` so a *mid-run* reconnect can
+ recover; 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, never text.
"""
code = (error_code or "").strip().lower()
return bool(code) and (code == "lock_conflict" or code.endswith("_lock"))
@@ -62,19 +56,13 @@ def is_gateway_supervisor_process(environ: Mapping[str, str] | None = None) -> b
"""Return whether this gateway process is owned by a supervisor."""
env = os.environ if environ is None else environ
xpc_service = env.get("XPC_SERVICE_NAME", "")
- 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
- )
+ 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 setsid
- restart path dies with the cgroup, so exit-75 service restart is the only viable
- path. Separate function so tests can mock it (a real ``/.dockerenv`` on CI
- otherwise flips the routing)."""
+ """In a container (Docker/Podman) the detached setsid restart path dies with the cgroup,
+ so exit-75 service restart is the only viable path. Own function so tests can mock it."""
return os.path.exists("/.dockerenv") or os.path.exists("/run/.containerenv")
@@ -95,9 +83,7 @@ def _parse_timeout_keeping_zero(raw: object, default: float, *, finite: bool = F
value = float(raw) # type: ignore[arg-type]
except (TypeError, ValueError):
return default
- if finite and not math.isfinite(value):
- return default
- return max(0.0, value)
+ return default if finite and not math.isfinite(value) else max(0.0, value)
def parse_restart_drain_timeout(raw: object) -> float:
@@ -124,13 +110,11 @@ def resolve_cron_drain_budget(
drain_timeout: float, cron_drain_timeout: float, *, watchdog_delay: float, elapsed: float = 0.0,
cleanup_reserve_s: float = CRON_DRAIN_CLEANUP_RESERVE_S,
) -> float:
- """Seconds the shutdown drain may spend waiting on in-flight cron work.
+ """Seconds the stop drain may wait on in-flight cron work.
- 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.
+ Clamped to what this process can honour: the watchdog hard-exits at ``watchdog_delay``,
+ so waiting past that leash minus ``cleanup_reserve_s`` swaps a cleanly-interrupted job
+ for a SIGKILL that leaves it wedged. Never less than ``drain_timeout`` (only extends).
"""
drain = _seconds(drain_timeout)
floor = _seconds(cron_drain_timeout)
@@ -145,13 +129,9 @@ def resolve_systemd_timeout_stop_sec(
cleanup_reserve_s: float = CRON_DRAIN_CLEANUP_RESERVE_S, headroom_s: float = SYSTEMD_STOP_HEADROOM_S,
floor_s: float = SYSTEMD_TIMEOUT_STOP_SEC_FLOOR,
) -> int:
- """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.
- """
+ """Seconds systemd ``TimeoutStopSec`` must cover: the stop path may first wait
+ ``cron_drain_timeout`` + ``cleanup_reserve_s`` for cron work, so sizing from the chat drain
+ alone lets systemd SIGKILL an in-budget drain. A zero cron timeout is an opt-out."""
drain = _seconds(drain_timeout)
cron = _seconds(cron_drain_timeout)
cron_budget = (cron + _seconds(cleanup_reserve_s)) if cron > 0.0 else 0.0
@@ -159,9 +139,6 @@ def resolve_systemd_timeout_stop_sec(
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()``; hard-killing callers must cover both.
- """
+ """Seconds a CLI should wait for the gateway PID to exit after SIGUSR1: in-band restart may
+ defer ``stop()`` until turns finish, then spend ``drain_timeout`` inside it — 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.py
index 6ecfed5243c..09f47b3d4a5 100644
--- a/gateway/restart_loop_guard.py
+++ b/gateway/restart_loop_guard.py
@@ -54,7 +54,7 @@ def _save_boots(boots: List[float]) -> None:
def _chain_gap(window_seconds: int, max_gap_seconds: int) -> float:
- """Inter-boot gap that still links two boots. Floored by ``window_seconds`` so
+ """Inter-boot gap that still links two boots; floored by ``window_seconds`` so
widening the window never makes the breaker *less* sensitive."""
return float(max(1, window_seconds, max_gap_seconds))
@@ -67,17 +67,14 @@ def _chain_ending_at(boots: List[float], ts: float, gap: float) -> List[float]:
chain: List[float] = []
prev = ts
for t in sorted(boots, reverse=True):
- if t > ts:
- # Clock moved backwards (NTP step, restored state file): treat the
- # future entry as adjacent rather than dropping the whole chain.
+ if t > ts: # clock moved backwards (NTP step, restored file): future entry is adjacent, not a break
chain.append(t)
continue
if prev - t > gap:
break
chain.append(t)
prev = t
- chain.reverse()
- return chain
+ return chain[::-1]
def record_restart_interrupted_boot(
@@ -87,8 +84,7 @@ def record_restart_interrupted_boot(
"""Record a restart-interrupted boot; return the pruned chain + now (most recent
last). A persistence failure returns the in-memory list without raising."""
ts = time.time() if now is None else now
- boots = _chain_ending_at(_load_boots(), ts, _chain_gap(window_seconds, max_gap_seconds))
- boots.append(ts)
+ boots = _chain_ending_at(_load_boots(), ts, _chain_gap(window_seconds, max_gap_seconds)) + [ts]
_save_boots(boots[-_MAX_STORED_BOOTS:])
return boots