The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): drop intra-function blank lines in g1-status files
Teknium5c140be05634
diff --git a/gateway/scale_to_zero.py b/gateway/scale_to_zero.pyindex 572d44530df..8f45f759581 100644--- a/gateway/scale_to_zero.py+++ b/gateway/scale_to_zero.py@@ -100,7 +100,6 @@ def dashboard_client_heartbeat_path(hermes_home: Optional[os.PathLike | str] = N"""Path of the dashboard-client liveness marker under HERMES_HOME."""if hermes_home is None:from hermes_constants import get_hermes_home-hermes_home = get_hermes_home()return Path(hermes_home) / DASHBOARD_CLIENT_HEARTBEAT_RELdiff --git a/gateway/shutdown_forensics.py b/gateway/shutdown_forensics.pyindex e6784a5d48d..ba9ff4f331a 100644--- a/gateway/shutdown_forensics.py+++ b/gateway/shutdown_forensics.py@@ -266,6 +266,7 @@ def parse_systemd_duration_to_us(raw: str) -> Optional[int]:units = {"us": 1, "ms": 1_000, "s": 1_000_000, "sec": 1_000_000,"min": 60_000_000, "h": 3_600_000_000, "hr": 3_600_000_000}total_us, token, digits = 0, "", ""+def _flush() -> bool: # fold the pending digits/token pair into total_usnonlocal total_us, token, digitsmultiplier = units.get(token.lower()) if token else 1_000_000diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.pyindex edf2981bc2d..00efda81f9b 100644--- a/gateway/shutdown_watchdog.py+++ b/gateway/shutdown_watchdog.py@@ -95,6 +95,7 @@ def start_loop_liveness_watchdog((``GatewayRunner._start_loop_liveness_guards``)."""stop_event = threading.Event()+def _wait_for_probe(probe_event: threading.Event) -> Optional[bool]:"""True/False = probe answered / timed out; None = stop requested mid-wait."""deadline = time.monotonic() + probe_timeout@@ -105,6 +106,7 @@ def start_loop_liveness_watchdog(if probe_event.wait(timeout=min(remaining, 0.05)):return Truereturn None+def _watchdog() -> None:strikes = 0while not stop_event.wait(timeout=probe_interval):@@ -271,6 +273,7 @@ def arm_shutdown_watchdog(delay = _coerce_float(delay_s, DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S)if delay <= 0:return done+def _watchdog() -> None:deadline = time.monotonic() + delay # chunked wait so a late disarm is observed within ~1swhile time.monotonic() < deadline:@@ -383,6 +386,7 @@ async def loop_heartbeat_forever("loop-scheduling witness and will not escalate on a stale heartbeat",exc_info=True,)+async def _write_off_loop() -> None:# write_loop_heartbeat never raises, so a failure here is an executor problem and must not# kill the task.diff --git a/gateway/status.py b/gateway/status.pyindex c74cf9cabdd..8006de9cc3f 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -150,7 +150,6 @@ def _profile_label_for_home(home: Path | str) -> Optional[str]:if canonical.parent.name == "profiles" and _PROFILE_LABEL_RE.match(canonical.name):return canonical.nameimport hermes_constants-default_homes = (hermes_constants.get_default_hermes_root, _get_platform_default_hermes_home)for default_home in default_homes:with contextlib.suppress(Exception):@@ -264,7 +263,6 @@ def terminate_pid(# Hide flags: a bare taskkill spawn from windowless pythonw.exe would# flash a conhost window on every force-kill.from hermes_cli._subprocess_compat import windows_hide_flags-try:result = subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, text=True,@@ -299,7 +297,6 @@ def _get_process_start_time(pid: int) -> Optional[int]:return int(Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").split()[21])try:import psutil # type: ignore-return int(round(psutil.Process(pid).create_time() * 100))except Exception:return None@@ -328,7 +325,6 @@ def _read_process_cmdline(pid: int) -> Optional[str]:return result.stdout.strip()with contextlib.suppress(Exception):import psutil # type: ignore-cmdline_parts = psutil.Process(pid).cmdline()if cmdline_parts:return " ".join(cmdline_parts)@@ -481,7 +477,6 @@ def _get_code_identity_fields() -> dict[str, Any]:"""try:from hermes_cli.build_info import get_code_identity-identity = get_code_identity()return {"code_sha": identity.get("sha"), "code_version": identity.get("version")}except Exception:@@ -644,7 +639,6 @@ def _pid_exists(pid: int) -> bool:pid = int(pid)try:import psutil # type: ignore-# Best-effort zombie check: status-read failures fall through to pid_exists().try:if psutil.Process(pid).status() == psutil.STATUS_ZOMBIE:@@ -688,7 +682,6 @@ def _pid_exists_win32_ctypes(pid: int) -> bool:"""psutil-free Windows liveness probe via OpenProcess/WaitForSingleObject."""try:import ctypes-kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]# Pin restypes: default c_int mangles WAIT_* DWORDs into negatives.kernel32.OpenProcess.restype = ctypes.c_void_p@@ -921,7 +914,6 @@ def write_runtime_status(_write_json_file(path, payload)with contextlib.suppress(Exception):from agent.monitoring.gateway_health import emit_runtime_status_transition-emit_runtime_status_transition(previous_payload, payload)@@ -1033,7 +1025,6 @@ def resolve_gateway_liveness(pid = guarded(_pid_probe, profile_dir / "gateway.pid") if scoped else guarded(_pid_probe)if pid is not None:return GatewayLiveness(running=True, pid=pid, source="pid")-health_body: Optional[dict[str, Any]] = Noneif health_probe is not None:alive, health_body = guarded(health_probe, fallback=(False, None))@@ -1043,7 +1034,6 @@ def resolve_gateway_liveness(return GatewayLiveness(running=True, pid=remote_pid, source="health", health_body=health_body)-if runtime is _UNSET:reader_kwargs = {"path": profile_dir / "gateway_state.json"} if scoped else {}runtime = guarded(_runtime_reader, **reader_kwargs)@@ -1415,7 +1405,6 @@ def _snapshot_gateway_children(pid: int) -> list:return []try:import psutil # type: ignore-return psutil.Process(int(pid)).children(recursive=True)except Exception:logger.debug("Could not snapshot children of gateway PID %d", pid, exc_info=True)@@ -1436,7 +1425,6 @@ def reap_gateway_children(children: list, *, parent_pid: int, timeout: float = 5reaped = 0try:import psutil # type: ignore-live = []for child in children:try:@@ -1650,7 +1638,6 @@ def get_running_pid_identity_strict(pid_path: Path) -> Optional[tuple[int, floatif _IS_WINDOWS:try:import psutil # type: ignore-exact_create_time = float(psutil.Process(pid).create_time())except Exception as exc:raise RuntimeError("exact gateway creation time is unavailable") from excdiff --git a/gateway/status_phrases.py b/gateway/status_phrases.pyindex 9a42a209764..9070298056e 100644--- a/gateway/status_phrases.py+++ b/gateway/status_phrases.py@@ -138,11 +138,9 @@ def resolve_status_phrase_catalog(catalog = _copy_catalog(_DEFAULT_PHRASES)hermes_home = get_hermes_home()_merge_phrase_paths(catalog, list(_CONVENTIONAL_RELATIVE_PATHS), base_dir=hermes_home)-display = (user_config or {}).get("display") if isinstance(user_config, Mapping) else Noneif not isinstance(display, Mapping):return catalog-sections = [display]platforms = display.get("platforms")if platform_key and isinstance(platforms, Mapping) and isinstance(platforms.get(platform_key), Mapping):diff --git a/gateway/wake.py b/gateway/wake.pyindex d2e82d84935..feaafa9a391 100644--- a/gateway/wake.py+++ b/gateway/wake.py@@ -53,11 +53,9 @@ async def deliver_wake(adapter: Any, *, text: str, session_id: str = "", source:if source is None:raise ValueError("deliver_wake: push-capable adapter requires a SessionSource")from gateway.platforms.base import MessageEvent, MessageType-synth_event = MessageEvent(text=text, message_type=MessageType.TEXT, source=source, internal=True)await adapter.handle_message(synth_event)return-if not session_id:raise ValueError("deliver_wake: non-push adapter (supports_async_delivery=False) "@@ -124,7 +122,6 @@ async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: strkey is a hard error rather than a wake in a fresh session nobody watches."""import aiohttp-host = str(getattr(adapter, "_host", "") or "127.0.0.1")if host in ("0.0.0.0", "::", "*"):host = "127.0.0.1" # wildcard bind — connect over loopback@@ -136,7 +133,6 @@ async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: str"X-Hermes-Session-Id is rejected (403) on an unauthenticated API ""server, so the wake cannot reach the target session")-if ":" in host and not host.startswith("["):host = f"[{host}]" # bare IPv6 literalurl = f"http://{host}:{port}/v1/chat/completions"@@ -146,7 +142,6 @@ async def _self_post_chat_completion(adapter: Any, *, text: str, session_id: str"messages": [{"role": "user", "content": text}],"stream": False,}-last_err: Optional[BaseException] = Noneattempts = 1 + len(_RETRY_DELAYS_SECONDS)for attempt in range(attempts):