The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): fold wait-or-detach tails, cron-count/interrupt-log/hasattr-clear ladders, connect-abort teardown loop
Teknium10500e1a626b
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex ba6e146dca6..9ace375554c 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -41,17 +41,14 @@ class GatewayAdapterLifecycleMixin:"""Wait up to ``timeout`` for ``task``; on deadline (or our own cancellation) detach it. Not``asyncio.wait_for``: that WAITS for the cancelled child, so a connect()/close() swallowing``CancelledError`` blocks recovery forever. True if it finished in time."""+ done: set = set()try:done, _pending = await asyncio.wait({task}, timeout=timeout)- except asyncio.CancelledError:- task.cancel()- task.add_done_callback(consume_detached_task_result)- raise- if task in done:- return True- task.cancel()- task.add_done_callback(consume_detached_task_result)- return False+ finally:+ if task not in done: # timed out, or our own cancellation+ task.cancel()+ task.add_done_callback(consume_detached_task_result)+ return task in doneasync def _await_adapter_cleanup_with_timeout(self, awaitable: Awaitable[Any], timeout: float) -> bool:"""Await adapter cleanup with a detach-on-deadline bound; True when it completed."""diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex 90f65723f2b..aefc59568c8 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -138,11 +138,15 @@ class GatewayShutdownMixin:+ self._active_deferred_agent_worker_count())+ @staticmethod+ def _running_cron_job_count() -> int:+ from cron.scheduler import get_running_job_ids+ return len(get_running_job_ids())+def _active_cron_job_count(self) -> int:"""Cron jobs currently executing — they run outside ``_running_agents``; 0 if cron can't import."""try:- from cron.scheduler import get_running_job_ids- return len(get_running_job_ids())+ return self._running_cron_job_count()except Exception:return 0@@ -341,11 +345,7 @@ class GatewayShutdownMixin:logger.debug("scale-to-zero: %s unreadable — staying awake", label, exc_info=True)return busy_sentinel- def _cron_count() -> int:- from cron.scheduler import get_running_job_ids- return len(get_running_job_ids())-- cron_count = _read_or_awake("cron work count", _cron_count, 1)+ cron_count = _read_or_awake("cron work count", self._running_cron_job_count, 1)api_count = _read_or_awake("api work count", lambda: self._api_server_hook("active_agent_work_count"), 1)# An attached dashboard/desktop/TUI client (heartbeat file mtime from the dashboard process) is# inbound activity too — folded into the inbound clock, not a conjunct, so disconnect gets the@@ -623,12 +623,12 @@ class GatewayShutdownMixin:logger.debug("Interrupted running agent for session %s during shutdown", session_key)# API-server / desk turns are adapter-owned and never enter _running_agents, so the loop above# cannot see them even though _drain_active_agents() waited for them.- interrupted_api = self._interrupt_api_server_runs(reason)- if interrupted_api:- logger.debug("Interrupted %d api_server run(s) during shutdown", interrupted_api)- interrupted_deferred = self._interrupt_deferred_agent_workers(reason)- if interrupted_deferred:- logger.debug("Interrupted %d deferred agent worker(s) during shutdown", interrupted_deferred)+ for count, what in (+ (self._interrupt_api_server_runs(reason), "api_server run(s)"),+ (self._interrupt_deferred_agent_workers(reason), "deferred agent worker(s)"),+ ):+ if count:+ logger.debug("Interrupted %d %s during shutdown", count, what)def _shutdown_interrupt_reason(self) -> str:from gateway.run import _INTERRUPT_REASON_GATEWAY_RESTART, _INTERRUPT_REASON_GATEWAY_SHUTDOWN@@ -844,9 +844,9 @@ class GatewayShutdownMixin:)continue# Home channels omit ``metadata=`` when empty (adapter doubles may not accept the kwarg).- send_kwargs = {"metadata": metadata} if metadata else {}if await self._send_shutdown_notice(- adapter, str(home.chat_id), msg, "home channel", platform.value, **send_kwargs+ adapter, str(home.chat_id), msg, "home channel", platform.value,+ **({"metadata": metadata} if metadata else {}),):notified.add(dedup_key)@@ -1533,12 +1533,11 @@ class GatewayShutdownMixin:# session (never a wholesale dict swap that could lose a concurrent writer's entry).self._running_agents.clear()self._running_agents_ts.clear()- if hasattr(self, "_active_session_leases"):- self._active_session_leases.clear()self._pending_messages.clear()self._pending_approvals.clear()- if hasattr(self, "_busy_ack_ts"):- self._busy_ack_ts.clear()+ for _attr in ("_active_session_leases", "_busy_ack_ts"): # absent on bare shutdown-path doubles+ if hasattr(self, _attr):+ getattr(self, _attr).clear()self._shutdown_event.set()# Global catch-all subprocess kill (safe to repeat): covers the graceful path and# anything respawned since the drain-timeout path's post-interrupt kill.diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 086b87dcd3e..00d5c21f6b2 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -23,7 +23,7 @@ from gateway.session import SessionSource, build_session_keyfrom gateway.restart import (DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT, GATEWAY_FATAL_CONFIG_EXIT_CODE, is_global_startup_conflict)-from gateway.run_shutdown import _log_suppressed+from gateway.run_shutdown import _log_suppressed, _send_errorfrom gateway.shutdown_watchdog import (DEFAULT_HEARTBEAT_INTERVAL_S, DEFAULT_LOOP_WATCHDOG_INTERVAL_S,DEFAULT_LOOP_WATCHDOG_MAX_STRIKES, DEFAULT_LOOP_WATCHDOG_TIMEOUT_S, loop_heartbeat_forever,@@ -725,14 +725,12 @@ class GatewayStartupMixin:# Log any active supply-chain security advisories. Deliberately does NOT block startup or# surface inline to users — only the operator can act (uninstall, rotate credentials).- try:+ with _log_suppressed(logging.DEBUG, "security advisory check failed at gateway startup", exc_info=True):from hermes_cli.security_advisories import detect_compromised, gateway_log_message_adv_msg = gateway_log_message(detect_compromised())if _adv_msg:logger.warning("%s", _adv_msg)logger.warning("Run `hermes doctor` on the gateway host for full remediation steps.")- except Exception:- logger.debug("security advisory check failed at gateway startup", exc_info=True)def _start_log_systemd_timing_alignment(self) -> None:"""Warn when systemd's TimeoutStopSec does not cover the drain window (a unit file from before@@ -784,9 +782,9 @@ class GatewayStartupMixin:entries = platform_registry.plugin_entries()allowed_vars += [e.allowed_users_env for e in entries if e.allowed_users_env]allow_all_vars += [e.allow_all_env for e in entries if e.allow_all_env]- _any_allowlist = any(os.getenv(v) for v in allowed_vars)- _allow_all = any(os.getenv(v, "").lower() in {"true", "1", "yes"} for v in allow_all_vars)- if not _any_allowlist and not _allow_all:+ if not any(os.getenv(v) for v in allowed_vars) and not any(+ os.getenv(v, "").lower() in {"true", "1", "yes"} for v in allow_all_vars+ ):logger.warning("No env user allowlists configured. Messaging platforms default to ""pairing/allowlist policies and will deny unknown senders unless you "@@ -985,12 +983,10 @@ class GatewayStartupMixin:# stop() won't reach them._connected_ok = [_t for _t in _task_map- if _t not in _pending_tasks and not _t.cancelled()- and _t.exception() is None and _t.result()[3] == "ok"+ if _t not in _pending_tasks and not _t.cancelled() and _t.exception() is None and _t.result()[3] == "ok"]for _t in [*_pending_tasks, *_connected_ok]:- _p, _c, _a = _task_map[_t]- await self._startup_teardown_adapter(_a, _p)+ await self._startup_teardown_adapter(_task_map[_t][2], _task_map[_t][0])await self._abort_startup_if_shutdown_requested()return None@@ -1519,5 +1515,4 @@ class GatewayStartupMixin:except Exception as exc:raise RuntimeError(f"adapter.send failed: {exc}") from excif not getattr(result, "success", True):- err = getattr(result, "error", "send returned success=False")- raise RuntimeError(f"adapter.send failed: {err}")+ raise RuntimeError(f"adapter.send failed: {_send_error(result)}")