The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): stay alive on all-adapters-down when no service manager supervises
xiaodu91617521c6be
diff --git a/apps/desktop/electron/guest-onboarding.ts b/apps/desktop/electron/guest-onboarding.tsindex 24ad95e49f7..d6507a9045c 100644--- a/apps/desktop/electron/guest-onboarding.ts+++ b/apps/desktop/electron/guest-onboarding.ts@@ -9,5 +9,15 @@ export function guestOnboardingEnabled(}export function desktopBackendSpawnEnv(base: NodeJS.ProcessEnv, guestOnboarding: boolean): NodeJS.ProcessEnv {- return { ...base, [GUEST_ONBOARDING_ENV]: guestOnboarding ? '1' : '0' }+ return {+ ...base,+ [GUEST_ONBOARDING_ENV]: guestOnboarding ? '1' : '0',+ // The desktop spawns `hermes serve` directly — no systemd/launchd supervisor will+ // revive a failure exit, so EX_TEMPFAIL only severs the UI's websockets and drops+ // in-flight assistant messages (#118080). Tell the gateway to stay alive on+ // all-adapters-down and let the reconnect watcher recover instead. Written LAST+ // (same rule as GUEST_ONBOARDING_ENV) so no earlier spread can override it. Older+ // runtimes ignore the unknown variable and keep the historical exit behavior.+ GATEWAY_ON_ALL_ADAPTERS_DOWN: 'stay_alive'+ }}diff --git a/gateway/config.py b/gateway/config.pyindex 97613384d33..f744bc92406 100644--- a/gateway/config.py+++ b/gateway/config.py@@ -64,6 +64,32 @@ def _env_multiplex_profiles_override() -> "bool | None":return parsed+# What the runner does when the last messaging adapter goes down (GatewayConfig.on_all_adapters_down).+ON_ALL_ADAPTERS_DOWN_POLICIES = ("exit", "stay_alive")+++def _env_on_all_adapters_down_override() -> "str | None":+ """GATEWAY_ON_ALL_ADAPTERS_DOWN operator override: 'exit'/'stay_alive' for a recognized token.++ ``None`` when unset, blank, or unrecognized so the caller keeps the config.yaml value+ (env > config > default). Launchers without a supervising service manager (the desktop app+ spawns ``hermes serve`` directly) set ``stay_alive``: a failure exit there only severs the+ UI's websocket connections and drops in-flight assistant messages (#118080).+ """+ raw = os.getenv("GATEWAY_ON_ALL_ADAPTERS_DOWN")+ if not (raw or "").strip():+ return None+ token = raw.strip().lower()+ if token in ON_ALL_ADAPTERS_DOWN_POLICIES:+ return token+ logger.warning(+ "Ignoring unrecognized GATEWAY_ON_ALL_ADAPTERS_DOWN=%r "+ "(expected one of %s); falling back to config.yaml.",+ raw, list(ON_ALL_ADAPTERS_DOWN_POLICIES),+ )+ return None++def _normalize_transport_token(value: Any) -> str:"""Canonical streaming transport token. YAML 1.1 parses bare ``on``/``off`` asbooleans (``mode: off`` → ``False`` → ``"false"`` would ENABLE streaming), so@@ -603,6 +629,13 @@ class GatewayConfig:loop_watchdog_probe_interval_s: float = DEFAULT_LOOP_WATCHDOG_INTERVAL_Sloop_watchdog_probe_timeout_s: float = DEFAULT_LOOP_WATCHDOG_TIMEOUT_Sloop_watchdog_max_strikes: int = DEFAULT_LOOP_WATCHDOG_MAX_STRIKES+ # What happens when the LAST messaging adapter goes down. ``exit`` (default) shuts the gateway+ # down with the failure verdict so a supervising service manager (systemd/launchd) restarts it;+ # ``stay_alive`` keeps the process running and leaves recovery to the reconnect watcher — for+ # launchers with no supervisor (the desktop app spawns ``hermes serve`` directly), where a+ # failure exit only severs the UI's websockets and drops in-flight assistant messages (#118080).+ # Retryable failures are recoverable in both modes; non-retryable adapter loss always exits.+ on_all_adapters_down: str = "exit" # "exit" | "stay_alive"; GATEWAY_ON_ALL_ADAPTERS_DOWN overridesunauthorized_dm_behavior: str = "pair" # UNAUTHORIZED_DM_BEHAVIORSunauthorized_dm_decline_message: str = "" # "decline" reply text; empty → DEFAULT_UNAUTHORIZED_DM_DECLINE_MESSAGEstreaming: StreamingConfig = field(default_factory=StreamingConfig)@@ -615,6 +648,7 @@ class GatewayConfig:"write_sessions_json", "always_log_local", "filter_silence_narration", "stt_enabled","stt_echo_transcripts", "group_sessions_per_user", "thread_sessions_per_user","max_concurrent_sessions", "multiplex_profiles",+ "on_all_adapters_down","room_link_url", "systemd_watchdog_seconds", "loop_watchdog","loop_watchdog_probe_interval_s", "loop_watchdog_probe_timeout_s","loop_watchdog_max_strikes", "unauthorized_dm_behavior", "unauthorized_dm_decline_message",@@ -739,6 +773,14 @@ class GatewayConfig:env_multiplex = _env_multiplex_profiles_override()if env_multiplex is not None:multiplex_profiles = env_multiplex+ # env > config.yaml > default: GATEWAY_ON_ALL_ADAPTERS_DOWN wins for launchers that know+ # whether a service manager is watching (the desktop launcher sets stay_alive); anything+ # unrecognized (env or yaml) falls back to "exit", the historical behavior (#118080).+ on_all_adapters_down = _env_on_all_adapters_down_override()+ if on_all_adapters_down is None:+ on_all_adapters_down = _normalize_choice(+ pick("on_all_adapters_down"), ON_ALL_ADAPTERS_DOWN_POLICIES, "exit"+ )max_concurrent_sessions = _coerce_optional_positive_int(pick("max_concurrent_sessions"), key_label("max_concurrent_sessions"))@@ -765,6 +807,7 @@ class GatewayConfig:loop_watchdog_probe_interval_s=bounded_float("loop_watchdog_probe_interval_s", DEFAULT_LOOP_WATCHDOG_INTERVAL_S, 1.0, 3600.0),loop_watchdog_probe_timeout_s=bounded_float("loop_watchdog_probe_timeout_s", DEFAULT_LOOP_WATCHDOG_TIMEOUT_S, 1.0, 600.0),loop_watchdog_max_strikes=max_strikes,+ on_all_adapters_down=on_all_adapters_down,max_concurrent_sessions=max_concurrent_sessions,unauthorized_dm_behavior=_normalize_choice(data.get("unauthorized_dm_behavior"), UNAUTHORIZED_DM_BEHAVIORS, "pair"),unauthorized_dm_decline_message=str(data.get("unauthorized_dm_decline_message") or "").strip(),diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex 5daa88e9842..576cd8f897f 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -19,7 +19,12 @@ import weakref as _weakreffrom agent.async_utils import consume_detached_task_resultfrom contextvars import Contextfrom datetime import datetime, timedelta, timezone-from gateway.config import SHARED_LISTENER_MIRROR_PLATFORMS, Platform, platform_binds_port as _platform_binds_port+from gateway.config import (+ ON_ALL_ADAPTERS_DOWN_POLICIES,+ SHARED_LISTENER_MIRROR_PLATFORMS,+ Platform,+ platform_binds_port as _platform_binds_port,+)from gateway.platforms.base import BasePlatformAdapterfrom gateway.platforms.helpers import carry_inbound_dedup, inbound_dedup_cachesfrom gateway.restart import is_global_startup_conflict@@ -269,6 +274,14 @@ class GatewayAdapterLifecycleMixin:self._ensure_reconnect_watcher_running()return True+ def _on_all_adapters_down(self) -> str:+ """Normalized ``GatewayConfig.on_all_adapters_down``: ``"exit"`` (default — a supervising+ service manager restarts the process) or ``"stay_alive"`` (launchers with no supervisor,+ e.g. the desktop app's direct ``hermes serve`` child, where a failure exit only severs the+ UI's websockets and drops in-flight assistant messages; #118080)."""+ value = getattr(getattr(self, "config", None), "on_all_adapters_down", None)+ return value if value in ON_ALL_ADAPTERS_DOWN_POLICIES else "exit"+async def _handle_adapter_fatal_error_detached(self, adapter: BasePlatformAdapter) -> None:"""Run the fatal handler; a platform left stranded (not reconnected, not queued, notintentionally disabled) exits the gateway with failure so the service manager restarts it."""@@ -311,13 +324,25 @@ class GatewayAdapterLifecycleMixin:and platform not in getattr(self, "_failed_platforms", {})and not (shutdown_event is not None and shutdown_event.is_set())):- logger.error(- "%s adapter was lost without entering the reconnection "- "queue; exiting gateway so the service manager restarts it.", platform.value,- )- self._exit_reason = f"{platform.value} adapter lost without reconnection queue"- self._exit_with_failure = True- await self.stop()+ if self._on_all_adapters_down() == "stay_alive":+ # No supervisor will revive this process, so exiting only severes the UI's+ # connections and drops in-flight assistant messages (#118080). Stay alive and+ # hand recovery to the reconnect watcher; the messaging platform stays down+ # either way, but cron / api_server / dashboard keep serving.+ logger.warning(+ "%s adapter was lost without entering the reconnection queue; "+ "on_all_adapters_down=stay_alive — gateway staying alive, reconnect "+ "watcher owns recovery.", platform.value,+ )+ self._ensure_reconnect_watcher_running()+ else:+ logger.error(+ "%s adapter was lost without entering the reconnection "+ "queue; exiting gateway so the service manager restarts it.", platform.value,+ )+ self._exit_reason = f"{platform.value} adapter lost without reconnection queue"+ self._exit_with_failure = True+ await self.stop()def _queue_retryable_best_effort(self, adapter: BasePlatformAdapter, why: str) -> None:with _log_suppressed(@@ -365,6 +390,17 @@ class GatewayAdapterLifecycleMixin:# after.await self._safe_adapter_disconnect(adapter, adapter.platform)if not self.adapters and not self._failed_platforms:+ if adapter.fatal_error_retryable and self._on_all_adapters_down() == "stay_alive":+ # No supervising service manager to revive the process (#118080): stay alive and+ # keep serving cron / api_server / dashboard while the reconnect watcher owns+ # recovery of the lost platform.+ logger.warning(+ "No connected messaging platforms remain; on_all_adapters_down=stay_alive — "+ "gateway staying alive, reconnect watcher owns recovery of %s.",+ adapter.platform.value,+ )+ self._ensure_reconnect_watcher_running()+ returnself._exit_reason = adapter.fatal_error_message or "All messaging adapters disconnected"if adapter.fatal_error_retryable:self._exit_with_failure = Truediff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.pyindex 14648888881..15d62db3c1f 100644--- a/tests/gateway/test_config.py+++ b/tests/gateway/test_config.py@@ -1586,3 +1586,35 @@ class TestWebhookEnvOverride:config.platforms[Platform.WEBHOOK].extra.get("secret")== "shared-secret")+++class TestOnAllAdaptersDown:+ """gateway.on_all_adapters_down: what the runner does when the last messaging+ adapter goes down (#118080). Default 'exit' preserves the service-restart+ contract; 'stay_alive' is for launchers with no supervising service manager+ (the desktop app's direct `hermes serve` child)."""++ def test_default_is_exit(self):+ config = GatewayConfig.from_dict({})+ assert config.on_all_adapters_down == "exit"++ def test_yaml_value_accepted_and_roundtrips(self):+ config = GatewayConfig.from_dict({"gateway": {"on_all_adapters_down": "stay_alive"}})+ assert config.on_all_adapters_down == "stay_alive"+ assert GatewayConfig.from_dict(config.to_dict()).on_all_adapters_down == "stay_alive"++ def test_unrecognized_yaml_falls_back_to_exit(self):+ config = GatewayConfig.from_dict({"gateway": {"on_all_adapters_down": "yolo"}})+ assert config.on_all_adapters_down == "exit"++ def test_env_override_wins_and_invalid_env_falls_back(self, monkeypatch):+ monkeypatch.setenv("GATEWAY_ON_ALL_ADAPTERS_DOWN", "stay_alive")+ assert GatewayConfig.from_dict(+ {"gateway": {"on_all_adapters_down": "exit"}}+ ).on_all_adapters_down == "stay_alive"+ monkeypatch.setenv("GATEWAY_ON_ALL_ADAPTERS_DOWN", "whatever")+ assert GatewayConfig.from_dict(+ {"gateway": {"on_all_adapters_down": "exit"}}+ ).on_all_adapters_down == "exit"+ monkeypatch.delenv("GATEWAY_ON_ALL_ADAPTERS_DOWN")+ assert GatewayConfig.from_dict({}).on_all_adapters_down == "exit"diff --git a/tests/gateway/test_runner_fatal_adapter.py b/tests/gateway/test_runner_fatal_adapter.pyindex 9e1382af664..f314060b81a 100644--- a/tests/gateway/test_runner_fatal_adapter.py+++ b/tests/gateway/test_runner_fatal_adapter.py@@ -241,3 +241,43 @@ async def test_fatal_handler_outer_timeout_still_queues_platform(monkeypatch, tmawait asyncio.wait({operation}, timeout=0.2)+++async def test_stay_alive_policy_keeps_gateway_up_on_stranded_retryable_fatal(tmp_path):+ """on_all_adapters_down='stay_alive' (the desktop launcher's mode): a retryable fatal+ on the LAST adapter must not produce the exit-with-failure verdict — no service manager+ will revive the process, so exiting only severs the UI's websockets and drops in-flight+ assistant messages (#118080). The platform has no config entry here, so the reconnection+ queue cannot take it and the stranded check is reached with empty _failed_platforms."""+ config = GatewayConfig(sessions_dir=tmp_path / "sessions", on_all_adapters_down="stay_alive")+ runner = GatewayRunner(config)+ adapter = _RuntimeRetryableAdapter()+ adapter._set_fatal_error("email_imap_fetch_failed", "IMAP read timeout", retryable=True)+ runner.adapters = {Platform.WHATSAPP: adapter}+ runner.delivery_router.adapters = runner.adapters+ runner.stop = AsyncMock()++ await runner._handle_adapter_fatal_error(adapter)++ runner.stop.assert_not_awaited()+ assert runner._exit_with_failure is False+++async def test_default_exit_policy_keeps_service_restart_verdict_on_stranded_retryable_fatal(tmp_path):+ """Without the stay_alive policy (service-managed deployments), the stranded retryable+ fatal still exits with the failure verdict so the service manager restarts the gateway+ — the pre-#118080 contract is unchanged."""+ config = GatewayConfig(sessions_dir=tmp_path / "sessions")+ runner = GatewayRunner(config)+ adapter = _RuntimeRetryableAdapter()+ adapter._set_fatal_error("email_imap_fetch_failed", "IMAP read timeout", retryable=True)+ runner.adapters = {Platform.WHATSAPP: adapter}+ runner.delivery_router.adapters = runner.adapters+ runner.stop = AsyncMock()++ await runner._handle_adapter_fatal_error(adapter)++ runner.stop.assert_awaited()+ assert runner._exit_with_failure is True