The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): trim footer/phrases/scale-to-zero/wake/systemd helpers
Teknium5025182f4eed
diff --git a/gateway/runtime_footer.py b/gateway/runtime_footer.pyindex d2ba7991f74..2f2014bcf51 100644--- a/gateway/runtime_footer.py+++ b/gateway/runtime_footer.py@@ -54,28 +54,20 @@ def _env_cwd() -> str:return terminal_env("TERMINAL_CWD", "")-def _apply_footer_section(resolved: dict[str, Any], section: Any) -> None:- if not isinstance(section, dict):- return- if "enabled" in section:- resolved["enabled"] = bool(section.get("enabled"))- if isinstance(section.get("fields"), list) and section["fields"]:- resolved["fields"] = [str(f) for f in section["fields"]]---def resolve_footer_config(- user_config: dict[str, Any] | None,- platform_key: str | None = None,-) -> dict[str, Any]:+def resolve_footer_config(user_config: dict[str, Any] | None, platform_key: str | None = None) -> dict[str, Any]:"""Resolve effective footer config: defaults (enabled=False) <``display.runtime_footer`` < ``display.platforms.<platform_key>.runtime_footer``."""resolved = {"enabled": False, "fields": list(_DEFAULT_FIELDS)}cfg = (user_config or {}).get("display") or {}- _apply_footer_section(resolved, cfg.get("runtime_footer"))- if platform_key:- plat_cfg = (cfg.get("platforms") or {}).get(platform_key)- if isinstance(plat_cfg, dict):- _apply_footer_section(resolved, plat_cfg.get("runtime_footer"))+ plat_cfg = (cfg.get("platforms") or {}).get(platform_key) if platform_key else None+ sections = [cfg.get("runtime_footer"), plat_cfg.get("runtime_footer") if isinstance(plat_cfg, dict) else None]+ for section in sections:+ if not isinstance(section, dict):+ continue+ if "enabled" in section:+ resolved["enabled"] = bool(section.get("enabled"))+ if isinstance(section.get("fields"), list) and section["fields"]:+ resolved["fields"] = [str(f) for f in section["fields"]]return resolved@@ -90,12 +82,6 @@ def _format_latency(seconds: float) -> str:return f"{m}m{sec:02d}s"-def _context_pct(context_tokens: int, context_length: Optional[int]) -> str:- if context_length and context_length > 0 and context_tokens >= 0:- return f"{max(0, min(100, round((context_tokens / context_length) * 100)))}%"- return ""--def format_runtime_footer(*,model: Optional[str],@@ -110,9 +96,14 @@ def format_runtime_footer(Fields whose data is missing (and unknown field names) are skipped silently —a partial footer beats ``?%`` or empty slots."""+ def context_pct() -> str:+ if context_length and context_length > 0 and context_tokens >= 0:+ return f"{max(0, min(100, round((context_tokens / context_length) * 100)))}%"+ return ""+renderers = {"model": lambda: _model_short(model),- "context_pct": lambda: _context_pct(context_tokens, context_length),+ "context_pct": context_pct,# Skipped when the caller did not measure (None) or the value is negative."latency": lambda: _format_latency(turn_seconds) if turn_seconds is not None and turn_seconds >= 0 else "","cwd": lambda: _home_relative_cwd(cwd or _env_cwd()),@@ -142,10 +133,6 @@ def build_footer_line(if not cfg.get("enabled"):return ""return format_runtime_footer(- model=model,- context_tokens=context_tokens,- context_length=context_length,- cwd=cwd,- turn_seconds=turn_seconds,- fields=cfg.get("fields") or _DEFAULT_FIELDS,+ model=model, context_tokens=context_tokens, context_length=context_length,+ cwd=cwd, turn_seconds=turn_seconds, fields=cfg.get("fields") or _DEFAULT_FIELDS,)diff --git a/gateway/scale_to_zero.py b/gateway/scale_to_zero.pyindex 875e868b4d9..f438bb0b13c 100644--- a/gateway/scale_to_zero.py+++ b/gateway/scale_to_zero.py@@ -51,21 +51,18 @@ FLY_API_SOCKET = "/.fly/api"# config.yaml default (behavioural setting -> config, not env). Short is safe# because real work always blocks the suspend and resume is sub-second; longer-# windows just bill idle RAM. Raise per-instance via-# gateway.scale_to_zero.idle_timeout_minutes.+# windows just bill idle RAM. Raise via gateway.scale_to_zero.idle_timeout_minutes.DEFAULT_IDLE_TIMEOUT_MINUTES = 2_TRUTHY = {"1", "true", "yes", "on"}# Dashboard-client liveness marker. The dashboard process (tui_gateway/ws.py, a-# DIFFERENT process on hosted instances) touches this on every /api/ws connect-# and inbound frame (clients ping every 15s). The gateway folds the mtime into-# its inbound clock so an open client holds the box awake like a chat message-# does (and gets the same idle_timeout grace after it disconnects) — otherwise-# the box suspends under the client, whose reconnect re-pokes-# the wake URL and the instance flaps every ~60s. Deliberately NO staleness-# cutoff: the mtime is a real inbound timestamp and is_idle already decides-# whether it is recent enough.+# DIFFERENT process on hosted instances) touches this on every /api/ws connect and+# inbound frame (clients ping every 15s). The gateway folds the mtime into its+# inbound clock so an open client holds the box awake like a chat message does —+# otherwise the box suspends under the client, whose reconnect re-pokes the wake+# URL and the instance flaps every ~60s. Deliberately NO staleness cutoff: the+# mtime is a real inbound timestamp and is_idle decides whether it is recent enough.DASHBOARD_CLIENT_HEARTBEAT_REL = os.path.join("state", "dashboard_clients.heartbeat")@@ -90,9 +87,7 @@ def parse_idle_timeout_seconds(minutes = float(cfg_value)except (TypeError, ValueError):minutes = float(default_minutes)- if minutes <= 0:- minutes = float(default_minutes)- return minutes * 60.0+ return (float(default_minutes) if minutes <= 0 else minutes) * 60.0def messaging_is_relay_only_or_absent(platforms: Iterable[Any]) -> bool:@@ -101,21 +96,12 @@ def messaging_is_relay_only_or_absent(platforms: Iterable[Any]) -> bool:A directly-connected platform holds a live socket and cannot scale to zero.Compared by ``.value``/name so this module stays enum-import-free."""- names = {_platform_name(p) for p in platforms}+ names = {str(getattr(p, "value", p)).strip().lower() for p in platforms}names.discard("relay")return not names-def _platform_name(platform: Any) -> str:- return str(getattr(platform, "value", platform)).strip().lower()---def should_arm(- *,- enabled: bool,- relay_only_or_absent: bool,- wake_url: Optional[str],-) -> bool:+def should_arm(*, enabled: bool, relay_only_or_absent: bool, wake_url: Optional[str]) -> bool:"""Start the idle watcher only if ALL hold: flag on, relay-only/absent messaging,wakeUrl registered (a suspended instance with no wake target is a black hole).Any unmet -> the watcher never starts (no idle timer, no dormancy), so a@@ -139,9 +125,7 @@ def is_idle(mid-cron-job suspend hole. Callers that cannot read a work source must failAWAKE (pass a positive sentinel), never fail to 0."""- if active_work_count > 0 or has_live_background_work:- return False- return seconds_since_last_inbound >= idle_timeout_seconds+ return active_work_count <= 0 and not has_live_background_work and seconds_since_last_inbound >= idle_timeout_secondsdef dashboard_client_heartbeat_path(hermes_home: Optional[os.PathLike | str] = None):@@ -168,9 +152,7 @@ def touch_dashboard_client_heartbeat(path: Optional[os.PathLike | str] = None) -def dashboard_client_last_seen(- path: Optional[os.PathLike | str] = None,- *,- now: Optional[float] = None,+ path: Optional[os.PathLike | str] = None, *, now: Optional[float] = None) -> Optional[float]:"""Epoch seconds a dashboard client last sent a WS frame, or None if never.@@ -197,18 +179,11 @@ def self_suspend_available(environ: Optional[dict] = None) -> bool:the platform owns the freeze, so the gateway stays connected until it lands."""return bool(- _env_str(environ, FLY_APP_NAME_ENV)- and _env_str(environ, FLY_MACHINE_ID_ENV)- and os.path.exists(FLY_API_SOCKET)+ _env_str(environ, FLY_APP_NAME_ENV) and _env_str(environ, FLY_MACHINE_ID_ENV) and os.path.exists(FLY_API_SOCKET))-def suspend_self(- environ: Optional[dict] = None,- *,- socket_path: str = FLY_API_SOCKET,- timeout: float = 10.0,-) -> bool:+def suspend_self(environ: Optional[dict] = None, *, socket_path: str = FLY_API_SOCKET, timeout: float = 10.0) -> bool:"""POST /v1/apps/{app}/machines/{id}/suspend on the local flaps socket.No token needed — the socket is the credential. Returns True when flaps@@ -224,10 +199,7 @@ def suspend_self(return Falserequest = (f"POST /v1/apps/{app}/machines/{machine_id}/suspend HTTP/1.1\r\n"- "Host: flaps\r\n"- "Content-Length: 0\r\n"- "Connection: close\r\n"- "\r\n"+ "Host: flaps\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")try:with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:@@ -250,9 +222,5 @@ def suspend_self(logger.info("scale-to-zero: machine suspend accepted by flaps (%s)", status_line)else:body = response.split(b"\r\n\r\n", 1)[-1][:500].decode("utf-8", "replace")- logger.warning(- "scale-to-zero: flaps suspend rejected: %s %s",- status_line,- json.dumps(body)[:500],- )+ logger.warning("scale-to-zero: flaps suspend rejected: %s %s", status_line, json.dumps(body)[:500])return okdiff --git a/gateway/startup_watchdog.py b/gateway/startup_watchdog.pyindex 229315ad914..5e1a7cc7081 100644--- a/gateway/startup_watchdog.py+++ b/gateway/startup_watchdog.py@@ -22,18 +22,3 @@ from hermes_startup_watchdog import ( # noqa: F401resolve_startup_watchdog_timeout,startup_watchdog_disabled,)--__all__ = [- "DEFAULT_STARTUP_WATCHDOG_TIMEOUT_S",- "ENV_STARTUP_WATCHDOG",- "ENV_STARTUP_WATCHDOG_TIMEOUT_S",- "SERVICE_RESTART_EXIT_CODE",- "StartupWatchdogHandle",- "arm_startup_watchdog",- "disarm_startup_watchdog",- "get_startup_watchdog_dump_path",- "kick_startup_watchdog",- "report_startup_progress",- "resolve_startup_watchdog_timeout",- "startup_watchdog_disabled",-]diff --git a/gateway/status_phrases.py b/gateway/status_phrases.pyindex c7d64b898d1..5a831a89a3a 100644--- a/gateway/status_phrases.py+++ b/gateway/status_phrases.py@@ -54,7 +54,9 @@ def _clean_phrase_list(value: Any) -> list[str]:return cleaned-def _merge_phrase_mapping(catalog: dict[str, list[str]], section: Mapping[str, Any], *, inherited_mode: str | None = None) -> None:+def _merge_phrase_mapping(+ catalog: dict[str, list[str]], section: Mapping[str, Any], *, inherited_mode: str | None = None+) -> None:replace = str(section.get("mode") or inherited_mode or "append").strip().lower() == "replace"phrase_map = section.get("phrases") if isinstance(section.get("phrases"), Mapping) else sectionfor surface in _STATUS_SURFACES:@@ -72,23 +74,20 @@ def _merge_phrase_file(catalog: dict[str, list[str]], path: Path, *, inherited_m_merge_phrase_mapping(catalog, loaded, inherited_mode=inherited_mode)-def _relative_path_under(base_dir: Path, raw_path: Any) -> Path | None:+def _iter_phrase_files(base_dir: Path, raw_path: Any) -> list[Path]:+ """YAML files under ``base_dir/raw_path``; [] for absolute / ``..`` / escaping paths."""raw = str(raw_path or "").strip()if not raw:- return None+ return []candidate = Path(raw).expanduser()if candidate.is_absolute() or ".." in candidate.parts:- return None+ return []base = base_dir.resolve()- resolved = (base / candidate).resolve()+ path = (base / candidate).resolve()try:- resolved.relative_to(base)+ path.relative_to(base)except ValueError:- return None- return resolved---def _iter_phrase_files(path: Path) -> list[Path]:+ return []if path.is_file() and path.suffix.lower() in _YAML_SUFFIXES:return [path]if path.is_dir():@@ -96,27 +95,24 @@ def _iter_phrase_files(path: Path) -> list[Path]:return []-def _merge_phrase_paths(catalog: dict[str, list[str]], paths: Any, *, base_dir: Path, inherited_mode: str | None = None) -> None:+def _merge_phrase_paths(+ catalog: dict[str, list[str]], paths: Any, *, base_dir: Path, inherited_mode: str | None = None+) -> None:if paths is None:returnfor raw_path in paths if isinstance(paths, list) else [paths]:- resolved = _relative_path_under(base_dir, raw_path)- if resolved is not None:- for phrase_file in _iter_phrase_files(resolved):- _merge_phrase_file(catalog, phrase_file, inherited_mode=inherited_mode)+ for phrase_file in _iter_phrase_files(base_dir, raw_path):+ _merge_phrase_file(catalog, phrase_file, inherited_mode=inherited_mode)def _copy_catalog(catalog: Mapping[str, list[str]]) -> dict[str, list[str]]:return {surface: list(phrases) for surface, phrases in catalog.items()}-def _load_builtin_catalog() -> dict[str, list[str]]:- catalog = _copy_catalog(_FALLBACK_PHRASES)- _merge_phrase_file(catalog, Path(__file__).resolve().parent / "assets" / "status_phrases.yaml", inherited_mode="replace")- return catalog---_DEFAULT_PHRASES: dict[str, list[str]] = _load_builtin_catalog()+_DEFAULT_PHRASES: dict[str, list[str]] = _copy_catalog(_FALLBACK_PHRASES)+_merge_phrase_file(+ _DEFAULT_PHRASES, Path(__file__).resolve().parent / "assets" / "status_phrases.yaml", inherited_mode="replace"+)def _merge_phrase_config(catalog: dict[str, list[str]], section: Any, *, base_dir: Path) -> None:@@ -129,7 +125,9 @@ def _merge_phrase_config(catalog: dict[str, list[str]], section: Any, *, base_di_merge_phrase_mapping(catalog, section)-def resolve_status_phrase_catalog(user_config: Mapping[str, Any] | None, platform_key: str | None = None) -> dict[str, list[str]]:+def resolve_status_phrase_catalog(+ user_config: Mapping[str, Any] | None, platform_key: str | None = None+) -> dict[str, list[str]]:"""Resolve built-in + user-configured generic status phrases.Resolution order mirrors gateway display settings: built-ins, conventionaldiff --git a/gateway/systemd_notify.py b/gateway/systemd_notify.pyindex f3e973171a9..1fa71737b29 100644--- a/gateway/systemd_notify.py+++ b/gateway/systemd_notify.py@@ -10,14 +10,20 @@ import socketfrom typing import Optional+def _notify_socket() -> str:+ """``NOTIFY_SOCKET`` address, or "" when systemd did not configure one / no AF_UNIX."""+ address = os.environ.get("NOTIFY_SOCKET", "").strip()+ return address if address and hasattr(socket, "AF_UNIX") else ""++def notify(message: str) -> bool:"""Send one nonblocking sd_notify datagram when systemd configured it.Failures are non-fatal: a missing socket or an older platform must neverprevent the gateway from starting."""- address = os.environ.get("NOTIFY_SOCKET", "").strip()- if not address or not isinstance(message, str) or not message or not hasattr(socket, "AF_UNIX"):+ address = _notify_socket()+ if not address or not isinstance(message, str) or not message:return Falsetry:payload = message.encode("utf-8")@@ -34,11 +40,7 @@ def notify(message: str) -> bool:def watchdog_interval_seconds() -> Optional[float]:"""Return systemd's configured watchdog interval in seconds."""- if not os.environ.get("NOTIFY_SOCKET", "").strip() or not hasattr(socket, "AF_UNIX"):- return None- raw = os.environ.get("WATCHDOG_USEC", "").strip()- if not raw:- return None+ raw = os.environ.get("WATCHDOG_USEC", "").strip() if _notify_socket() else ""try:interval = float(raw) / 1_000_000.0except (TypeError, ValueError):@@ -72,8 +74,6 @@ class SystemdWatchdog:def _lag_tolerance(self) -> float:default = max(0.1, (self.interval_seconds or 0.0) * 0.25)- if self._lag_tolerance_seconds is None:- return defaulttry:value = float(self._lag_tolerance_seconds)except (TypeError, ValueError):@@ -90,9 +90,7 @@ class SystemdWatchdog:asyncio.get_running_loop()except RuntimeError:return False- self._stopping = False- self._unhealthy = False- self._stopping_notified = False+ self._stopping = self._unhealthy = self._stopping_notified = Falseself._task = asyncio.create_task(self._run(), name="hermes-systemd-watchdog")return True@@ -119,10 +117,9 @@ class SystemdWatchdog:return Trueasync def _run(self) -> None:- interval = self.interval_seconds- if interval is None:+ if self.interval_seconds is None:return- cadence = max(0.01, interval / 2.0)+ cadence = max(0.01, self.interval_seconds / 2.0)loop = asyncio.get_running_loop()scheduled_at = loop.time() + cadencewith contextlib.suppress(asyncio.CancelledError):diff --git a/gateway/wake.py b/gateway/wake.pyindex 618c250c013..d2e82d84935 100644--- a/gateway/wake.py+++ b/gateway/wake.py@@ -1,30 +1,16 @@"""Wake an existing agent session from a background completion event.-Two delivery strategies, selected by the adapter's ``supports_async_delivery``-capability flag:--* Push-capable adapters (telegram, discord, plugin platforms, ...): inject a- synthetic ``MessageEvent(internal=True)`` through ``adapter.handle_message``.--* Stateless request/response adapters (the API server,- ``supports_async_delivery = False``): ``handle_message`` would run the wake- under a ``build_session_key()``-derived key that never matches the raw- ``X-Hermes-Session-Id`` key real turns run under, landing in an invisible- parallel session. Instead we self-POST ``/v1/chat/completions`` on the- in-pod API server with the raw session id header — the exact entry point- real turns use — so the wake resumes the REAL session with full history.--Async-delegation completions are the exception on the stateless path: after-the parent turn ends the CLIENT owns the next turn, so a completion must never-be self-POSTed as a new ``role=user`` prompt (that starts an unauthorized agent-turn that can cross a pending human-confirmation gate). Instead-``persist_delegation_delivery`` writes it into the session transcript as a-durable DELIVERY row (``role=user`` + ``display_kind="async_delegation_complete"``,-the shape the TUI/desktop pollers use) so pollers see it immediately and the-next REAL client turn carries it as context, without any model turn running.--Failures RAISE (after bounded retries on transient errors) so callers can-rewind cursors / retry instead of silently losing the event.+Delivery is selected by the adapter's ``supports_async_delivery`` flag. Push-capable+adapters get a synthetic ``MessageEvent(internal=True)`` via ``handle_message``.+Stateless adapters (API server) would run that under a ``build_session_key()`` key+that never matches the raw ``X-Hermes-Session-Id`` real turns use (invisible parallel+session), so we self-POST ``/v1/chat/completions`` with the raw session id header and+resume the REAL session. Async-delegation completions are the exception there: the+CLIENT owns the next turn, so a completion is never self-POSTed as a new ``role=user``+prompt (it could cross a pending human-confirmation gate); ``persist_delegation_delivery``+writes a durable DELIVERY row (``display_kind="async_delegation_complete"``, the shape the+TUI/desktop pollers read) instead. Failures RAISE (after bounded retries on transient+errors) so callers can rewind cursors / retry instead of silently losing the event."""from __future__ import annotations@@ -123,12 +109,10 @@ async def persist_delegation_delivery(adapter: Any, *, text: str, session_id: st)await asyncio.to_thread(db.append_message, session_id, "user", content=text,- display_kind="async_delegation_complete",- display_metadata=_delegation_display_metadata(evt or {}),+ display_kind="async_delegation_complete", display_metadata=_delegation_display_metadata(evt or {}),)logger.info(- "async delegation completion persisted as delivery row for api_server session %s (no wake turn)",- session_id,+ "async delegation completion persisted as delivery row for api_server session %s (no wake turn)", session_id)@@ -180,8 +164,8 @@ async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: strlogger.warning("%s; attempt %d/%d", last_err, attempt + 1, attempts)continueif resp.status >= 400:- body = (await resp.text())[:300]# Non-transient (auth/validation) — fail immediately.+ body = (await resp.text())[:300]raise RuntimeError(f"wake self-post failed for session {session_id}: HTTP {resp.status}: {body}")@@ -194,7 +178,6 @@ async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: str"wake self-post transient failure for session %s (attempt %d/%d): %s",session_id, attempt + 1, attempts, exc,)- continueraise RuntimeError(f"wake self-post gave up for session {session_id} after {attempts} attempts: {last_err}") from last_err