diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py index 1c15a1d9aa..608f260da8 100644 --- a/gateway/run_adapters.py +++ b/gateway/run_adapters.py @@ -1,8 +1,8 @@ -"""Adapter connect/disconnect, fatal-error recovery, reconnect watcher and multiplex profile adapter methods for GatewayRunner. +"""Adapter connect/disconnect, fatal-error recovery, reconnect watcher and multiplex profile +adapters for GatewayRunner (mixin bound via the MRO). -Split out of ``gateway/run.py``; bound onto ``GatewayRunner`` via the MRO. -``gateway.run`` internals are imported lazily inside method bodies (import cycle), -so ``patch("gateway.run.X")`` keeps intercepting them at call time. +``gateway.run`` internals are imported lazily inside method bodies (import cycle), so +``patch("gateway.run.X")`` keeps intercepting them at call time. """ from __future__ import annotations @@ -10,6 +10,8 @@ from __future__ import annotations import logging from typing import TYPE_CHECKING import asyncio +import contextlib +import functools import os import time import weakref as _weakref @@ -31,22 +33,15 @@ logger = logging.getLogger("gateway.run") class GatewayAdapterLifecycleMixin: - """Adapter connect/disconnect, fatal-error recovery, reconnect watcher and multiplex profile adapter methods for GatewayRunner.""" + """Adapter lifecycle: connect/teardown, fatal recovery, reconnect watcher, multiplex profiles.""" - async def _await_adapter_cleanup_with_timeout( - self, awaitable: Awaitable[Any], timeout: float - ) -> bool: - """Wait for adapter cleanup without letting cancellation swallowing hang us. + @staticmethod + async def _wait_or_detach(task: "asyncio.Future", timeout: float) -> bool: + """Wait up to ``timeout`` for ``task``; on deadline (or our own cancellation) detach it. - ``asyncio.wait_for`` cancels an overdue child but then waits for it to exit. An adapter - close path that catches ``CancelledError`` can therefore block recovery forever. Keep - ownership of the old task through its done callback, but release the runner at the deadline. + Not ``asyncio.wait_for``: that WAITS for the cancelled child to exit, so a connect()/close() + that swallows ``CancelledError`` blocks recovery forever. Returns True if it finished in time. """ - if timeout <= 0: - await awaitable - return True - - task = asyncio.ensure_future(awaitable) try: done, _pending = await asyncio.wait({task}, timeout=timeout) except asyncio.CancelledError: @@ -54,56 +49,52 @@ class GatewayAdapterLifecycleMixin: task.add_done_callback(consume_detached_task_result) raise if task in done: - await task return True - task.cancel() task.add_done_callback(consume_detached_task_result) return False - async def _safe_adapter_disconnect(self, adapter, platform) -> None: - """Call adapter.disconnect() defensively, swallowing any error. + async 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.""" + if timeout <= 0: + await awaitable + return True + task = asyncio.ensure_future(awaitable) + if not await self._wait_or_detach(task, timeout): + return False + await task + return True - For a failed/raised connect(): partial resources (aiohttp.ClientSession, poll tasks, child - subprocesses) would otherwise leak. Must tolerate partial-init state and never raise. + async def _safe_adapter_disconnect(self, adapter, platform) -> None: + """Call adapter.disconnect() defensively (bounded, never raises). + + After a failed connect() partial resources (ClientSession, poll tasks, subprocesses) would + otherwise leak; must tolerate partial-init state. """ timeout = self._adapter_disconnect_timeout_secs() + label = platform.value if platform is not None else "adapter" try: - completed = await self._await_adapter_cleanup_with_timeout( - adapter.disconnect(), timeout - ) - if not completed: + if not await self._await_adapter_cleanup_with_timeout(adapter.disconnect(), timeout): logger.warning( "Timed out after %.1fs while disconnecting %s adapter; continuing shutdown", - timeout, - platform.value if platform is not None else "adapter", + timeout, label, ) except Exception as e: - logger.debug( - "Defensive %s disconnect after failed connect raised: %s", - platform.value if platform is not None else "adapter", - e, - ) + logger.debug("Defensive %s disconnect after failed connect raised: %s", label, e) - async def _bounded_adapter_teardown( - self, adapter, platform, *, profile: Optional[str] = None - ) -> None: - """Tear down one adapter on the shutdown path with bounded awaits. + async def _bounded_adapter_teardown(self, adapter, platform, *, profile: Optional[str] = None) -> None: + """Tear down one adapter on the shutdown path with bounded awaits (never raises). - ``cancel_background_tasks()`` and ``disconnect()`` can block forever on half-dead network - state (e.g. a wedged WebSocket thread), stalling shutdown past systemd's ``TimeoutStopSec``; - the SIGKILL skips ``atexit`` PID-file cleanup and the next start dies with "PID file race - lost". Each await uses ``HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT``; on timeout the task is - cancelled and detached so a cancellation-swallowing adapter can't hang the loop. Never raises. + Unbounded, a half-dead transport stalls shutdown past systemd's ``TimeoutStopSec``; the + SIGKILL skips ``atexit`` PID-file cleanup and the next start dies with "PID file race lost". """ timeout = self._adapter_disconnect_timeout_secs() suffix = f" (profile: {profile})" if profile else "" started_at = time.monotonic() try: - cancelled = await self._await_adapter_cleanup_with_timeout( + if not await self._await_adapter_cleanup_with_timeout( adapter.cancel_background_tasks(), timeout - ) - if not cancelled: + ): logger.warning( "✗ %s background-task cancel timed out after %.1fs - forcing continue%s", platform.value, timeout, suffix, @@ -111,13 +102,9 @@ class GatewayAdapterLifecycleMixin: except Exception as e: logger.debug("✗ %s background-task cancel error%s: %s", platform.value, suffix, e) try: - disconnected = await self._await_adapter_cleanup_with_timeout( - adapter.disconnect(), timeout - ) - if disconnected: + if await self._await_adapter_cleanup_with_timeout(adapter.disconnect(), timeout): logger.info( - "✓ %s disconnected (%.2fs)%s", - platform.value, time.monotonic() - started_at, suffix, + "✓ %s disconnected (%.2fs)%s", platform.value, time.monotonic() - started_at, suffix, ) else: logger.warning( @@ -130,109 +117,62 @@ class GatewayAdapterLifecycleMixin: platform.value, time.monotonic() - started_at, suffix, e, ) + @staticmethod + def _env_timeout_override(name: str) -> Optional[float]: + """Non-negative float from env var ``name``; None when unset or unparseable (warned).""" + raw = os.getenv(name, "").strip() + if not raw: + return None + try: + return max(0.0, float(raw)) + except ValueError: + logger.warning("Ignoring invalid %s=%r", name, raw) + return None + def _adapter_disconnect_timeout_secs(self) -> float: """Return the per-adapter disconnect timeout used during shutdown.""" from gateway.run import _ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT - raw = os.getenv("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT", "").strip() - if raw: - try: - timeout = float(raw) - except ValueError: - logger.warning( - "Ignoring invalid HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT=%r", - raw, - ) - else: - return max(0.0, timeout) - return _ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT + override = self._env_timeout_override("HERMES_GATEWAY_ADAPTER_DISCONNECT_TIMEOUT") + return _ADAPTER_DISCONNECT_TIMEOUT_SECS_DEFAULT if override is None else override def _platform_connect_timeout_secs(self, platform=None, *, initial: bool = False) -> float: - """Return the per-platform connect timeout used during startup/retry. - - Telegram's full 180s connect budget is deliberately NOT spent at cold start: an unreachable - Telegram would hold the gateway out of ``running`` for the whole budget. The cold-start wait - is capped and the platform handed to the reconnect watcher, which retries with the full - budget and ``is_reconnect=True`` (preserving the offline update queue). - """ + """Per-platform connect timeout. Telegram's full 180s is NOT spent at cold start (it would + hold the gateway out of ``running``); the watcher retries with the full budget.""" from gateway.run import ( - _PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT, - _TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT, + _PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT, _TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT, _TELEGRAM_INITIAL_CONNECT_TIMEOUT_SECS_DEFAULT, ) - raw = os.getenv("HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT", "").strip() - if raw: - try: - timeout = float(raw) - except ValueError: - logger.warning( - "Ignoring invalid HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT=%r", - raw, - ) - else: - return max(0.0, timeout) - if platform == Platform.TELEGRAM: - if initial: - return _TELEGRAM_INITIAL_CONNECT_TIMEOUT_SECS_DEFAULT - return _TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT - return _PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT + override = self._env_timeout_override("HERMES_GATEWAY_PLATFORM_CONNECT_TIMEOUT") + if override is not None: + return override + if platform != Platform.TELEGRAM: + return _PLATFORM_CONNECT_TIMEOUT_SECS_DEFAULT + return _TELEGRAM_INITIAL_CONNECT_TIMEOUT_SECS_DEFAULT if initial else _TELEGRAM_CONNECT_TIMEOUT_SECS_DEFAULT async def _connect_adapter_with_timeout( self, adapter, platform, *, is_reconnect: bool = False, initial: bool = False ) -> bool: - """Connect an adapter without allowing one platform to block others. - - ``is_reconnect`` lets adapters distinguish a cold first boot (drop any stale server-side - queue) from a watcher reconnect (preserve the queue so interim messages aren't dropped). - ``initial`` selects the capped cold-start budget for platforms whose full connect budget is - too long to spend before the gateway reaches ``running`` (Telegram's 180s). - """ + """Connect with a bound so one platform can't block others. ``is_reconnect``: cold boot + drops the stale server-side queue, a reconnect keeps it. ``initial``: capped budget.""" timeout = self._platform_connect_timeout_secs(platform, initial=initial) if timeout <= 0: return await adapter.connect(is_reconnect=is_reconnect) - # Detach-on-timeout rather than plain asyncio.wait_for: wait_for cancels the overdue task but - # then waits for it to exit, so a connect() that catches CancelledError blocks recovery - # forever (watcher never retries). Keep ownership via its done callback; release at deadline. - task = asyncio.ensure_future( - adapter.connect(is_reconnect=is_reconnect) - ) - 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: - result = await task - return bool(result) - task.cancel() - task.add_done_callback(consume_detached_task_result) - raise TimeoutError( - f"{platform.value} connect timed out after {timeout:g}s" - ) + task = asyncio.ensure_future(adapter.connect(is_reconnect=is_reconnect)) + if await self._wait_or_detach(task, timeout): + return bool(await task) + raise TimeoutError(f"{platform.value} connect timed out after {timeout:g}s") async def _connect_initial_adapter_with_timeout(self, adapter, platform) -> bool: - """Connect one cold-start adapter with tightly scoped replace intent. - - The capability is visible only while this initial connect is awaited. Reconnects call - ``_connect_adapter_with_timeout`` directly and adapters also default to deny, so a later - network recovery can never evict a healthy token holder. - """ - adapter._platform_lock_takeover_allowed = bool( - self._platform_lock_takeover_on_start - ) + """Cold-start connect with replace intent visible ONLY during this await, so a later + network recovery can never evict a healthy token holder.""" + adapter._platform_lock_takeover_allowed = bool(self._platform_lock_takeover_on_start) try: - return await self._connect_adapter_with_timeout( - adapter, platform, initial=True - ) + return await self._connect_adapter_with_timeout(adapter, platform, initial=True) finally: adapter._platform_lock_takeover_allowed = False async def _handle_reaction_event(self, ctx: Dict[str, Any]) -> None: - """Fan a normalised platform reaction event out to the HookRegistry. - - The adapter-supplied ``event_name`` ("reaction:added"/"reaction:removed") is the hook event, - matching the ``agent:*`` naming scheme. Errors never block the adapter's event loop. - """ + """Fan a normalised reaction event out to the HookRegistry; errors never block the adapter.""" event_name = str(ctx.get("event_name") or "reaction:added") try: await self.hooks.emit(event_name, ctx) @@ -240,13 +180,10 @@ class GatewayAdapterLifecycleMixin: logger.debug("[Gateway] reaction hook emit failed", exc_info=True) async def _handle_adapter_fatal_error(self, adapter: BasePlatformAdapter) -> None: - """React to an adapter failure after startup. + """React to an adapter failure after startup (retryable → background reconnect queue). - Retryable errors (network blip, DNS) queue the platform for background reconnection. - The notification arrives on the failing adapter's own polling task, and the disconnect in - the handler can cancel that task mid-flight (disconnect()'s current-task guard misses it - because _safe_adapter_disconnect closes in a wrapper task), stranding the platform between - the fatal log and the reconnect queue — so the real work runs in a detached task. + Detached task: the notification arrives on the failing adapter's own polling task, which + the handler's disconnect can cancel mid-flight, stranding the platform half-handled. """ tasks = getattr(self, "_fatal_handler_tasks", None) if tasks is None: @@ -254,17 +191,14 @@ class GatewayAdapterLifecycleMixin: task = asyncio.create_task(self._handle_adapter_fatal_error_detached(adapter)) tasks.add(task) task.add_done_callback(tasks.discard) - # Await so callers that expect completion still get it — but through shield(): Task.cancel() - # on the caller also cancels the future it is awaiting (_fut_waiter), so a plain `await - # task` would tunnel the cancellation straight into the "detached" task. shield() absorbs - # it: the caller sees CancelledError, the handler runs to completion. + # shield(): a plain `await task` would tunnel the caller's cancellation into the detached + # task; with shield the caller sees CancelledError and the handler runs to completion. await asyncio.shield(task) def _queue_retryable_fatal_platform(self, adapter: BasePlatformAdapter) -> bool: - """Queue a retryable fatal adapter for background reconnection. + """Queue a retryable fatal adapter for background reconnection (True when newly queued). - Returns True when newly queued; idempotent if already queued. Must not await: callers - invoke this *before* any disconnect await so a wedged close cannot strand the platform. + Must not await: callers run this BEFORE any disconnect so a wedged close can't strand it. """ if not adapter.fatal_error_retryable: return False @@ -272,11 +206,9 @@ class GatewayAdapterLifecycleMixin: if not platform_config: return False if adapter.platform in self._failed_platforms: - # Nothing to enqueue — but "already queued" is exactly when the watcher may have died, - # and the enqueue branch below holds the ONLY _ensure_reconnect_watcher_running() call. - # _spawn_supervised gives up after _MAX_SUPERVISED_RESTARTS; without this backstop a - # queued platform is a silent permanent outage (nothing retries, and the stranded check - # treats a queued platform as safe so the process never restarts either). + # Already queued is exactly when the watcher may have died (_spawn_supervised gives up + # after _MAX_SUPERVISED_RESTARTS); without this backstop the platform is a silent + # permanent outage — nothing retries and the stranded check treats "queued" as safe. self._ensure_reconnect_watcher_running() return False self._failed_platforms[adapter.platform] = { @@ -284,148 +216,103 @@ class GatewayAdapterLifecycleMixin: "attempts": 0, "next_retry": time.monotonic(), "queued_at": time.monotonic(), - "credential_claim": self._adapter_credential_claim( - adapter.platform, adapter - ), - "listener_claim": self._adapter_listener_claim( - adapter.platform, adapter - ), + "credential_claim": self._adapter_credential_claim(adapter.platform, adapter), + "listener_claim": self._adapter_listener_claim(adapter.platform, adapter), } - logger.info( - "%s queued for background reconnection", - adapter.platform.value, - ) - # Ensure the reconnect watcher is alive — respawn if it died (e.g. restart budget exhausted) - # so queued platforms are not permanently stranded. + logger.info("%s queued for background reconnection", adapter.platform.value) self._ensure_reconnect_watcher_running() return True - async def _handle_adapter_fatal_error_detached( - self, adapter: BasePlatformAdapter - ) -> None: - """Run the fatal handler; if the platform still ends up stranded (not reconnected, not - queued, not intentionally disabled), exit the gateway with failure so the service manager - restarts it instead of leaving a silent partial outage.""" + async def _handle_adapter_fatal_error_detached(self, adapter: BasePlatformAdapter) -> None: + """Run the fatal handler; a platform left stranded (not reconnected, not queued, not + intentionally disabled) exits the gateway with failure so the service manager restarts it.""" try: - # Outer hard deadline: even with queue-before-disconnect, a hang anywhere in the impl - # (status write side effects, detach races, etc.) must not leave this task wedged - # forever — the stranded check in ``finally`` only runs when we return. + # Outer hard deadline: a hang anywhere in the impl must not wedge this task — the + # stranded check in ``finally`` only runs when we return. timeout = self._adapter_disconnect_timeout_secs() if timeout <= 0: await self._handle_adapter_fatal_error_impl(adapter) else: - # Disconnect budget plus a little queue/status bookkeeping overhead; keep the extra - # proportional so tests that shrink the disconnect timeout still finish promptly. + # Disconnect budget + proportional bookkeeping overhead (tests shrink the timeout). outer = timeout + min(2.0, max(0.05, timeout)) - completed = await self._await_adapter_cleanup_with_timeout( - self._handle_adapter_fatal_error_impl(adapter), - outer, - ) - if not completed: + if not await self._await_adapter_cleanup_with_timeout( + self._handle_adapter_fatal_error_impl(adapter), outer + ): logger.error( "Fatal-error handling for %s timed out after %.1fs; " - "ensuring reconnect queue is populated", - adapter.platform.value, - outer, + "ensuring reconnect queue is populated", adapter.platform.value, outer, ) self._queue_retryable_fatal_platform(adapter) except asyncio.CancelledError: - # Best-effort queue before re-raising: a cancelled fatal handler - # must not strand a retryable platform (#80598). - try: - self._queue_retryable_fatal_platform(adapter) - except Exception: - logger.debug( - "Failed to queue %s after fatal-handler cancellation", - adapter.platform.value, - exc_info=True, - ) + # A cancelled or raising fatal handler must not strand a retryable platform. + self._queue_retryable_best_effort(adapter, "cancellation") raise except Exception: - logger.exception( - "Fatal-error handling for %s raised unexpectedly", - adapter.platform.value, - ) - # Best-effort queue so an unexpected raise mid-handler cannot - # leave a retryable platform permanently deaf (#80598). - try: - self._queue_retryable_fatal_platform(adapter) - except Exception: - logger.debug( - "Failed to queue %s after fatal-handler exception", - adapter.platform.value, - exc_info=True, - ) + logger.exception("Fatal-error handling for %s raised unexpectedly", adapter.platform.value) + self._queue_retryable_best_effort(adapter, "exception") finally: platform = adapter.platform shutdown_event = getattr(self, "_shutdown_event", None) - stranded = ( + if ( adapter.fatal_error_retryable and platform not in self.adapters and platform not in getattr(self, "_failed_platforms", {}) and not (shutdown_event is not None and shutdown_event.is_set()) - ) - if stranded: + ): 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" + "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: + try: + self._queue_retryable_fatal_platform(adapter) + except Exception: + logger.debug( + "Failed to queue %s after fatal-handler %s", adapter.platform.value, why, exc_info=True, + ) + async def _handle_adapter_fatal_error_impl(self, adapter: BasePlatformAdapter) -> None: - # Snapshot this platform slot's current owner first: acting on a stale notification would - # overwrite a healthy platform's runtime status and wrongly re-queue it for reconnection. + # Snapshot the slot owner first: a stale notification must not overwrite a healthy + # platform's runtime status or re-queue it. existing = self.adapters.get(adapter.platform) if existing is not None and existing is not adapter: logger.debug( "Ignoring stale fatal error from a superseded %s adapter instance: %s", - adapter.platform.value, - adapter.fatal_error_code or "unknown", + adapter.platform.value, adapter.fatal_error_code or "unknown", ) return logger.error( - "Fatal %s adapter error (%s): %s", - adapter.platform.value, - adapter.fatal_error_code or "unknown", - adapter.fatal_error_message or "unknown error", + "Fatal %s adapter error (%s): %s", adapter.platform.value, + adapter.fatal_error_code or "unknown", adapter.fatal_error_message or "unknown error", ) - # A relay credential revoked by opt-out is not an error to retry: render a clean "disabled" - # state, not red "fatal"/"retrying" (non-retryable code, so it also leaves the queue below). - if adapter.fatal_error_code == "relay_disabled": - platform_state = "disabled" - elif adapter.fatal_error_retryable: - platform_state = "retrying" - else: - platform_state = "fatal" + # relay_disabled (credential revoked by opt-out) renders "disabled", not red fatal/retrying. self._update_platform_runtime_status( adapter.platform.value, - platform_state=platform_state, + platform_state=( + "disabled" if adapter.fatal_error_code == "relay_disabled" + else "retrying" if adapter.fatal_error_retryable else "fatal" + ), error_code=adapter.fatal_error_code, error_message=adapter.fatal_error_message, ) if existing is adapter: - # Claim this adapter for teardown before awaiting disconnect(): a second fatal-error - # notification for the same adapter (e.g. a concurrent recovery path) would otherwise - # still see itself as "existing" during the await and disconnect() the same object twice. + # Claim for teardown BEFORE awaiting disconnect(), else a concurrent second fatal + # notification for the same adapter would disconnect() it twice. self.adapters.pop(adapter.platform, None) self.delivery_router.adapters = self.adapters - # Queue retryable failures BEFORE any disconnect await: a half-dead transport can wedge - # native close() (or swallow CancelledError), so "disconnect then queue" left platforms - # permanently deaf in a live process after the network recovered. Populate the queue first so the - # reconnect watcher always has work; teardown is best-effort after. + # Queue BEFORE any disconnect await: a half-dead transport can wedge native close() (or + # swallow CancelledError), and "disconnect then queue" left platforms permanently deaf. self._queue_retryable_fatal_platform(adapter) if existing is adapter: - # A half-closed transport can wedge native close() indefinitely; reuse the shutdown-path - # timeout so this runtime fatal handler always returns to the stay-alive / stranded path. + # Bounded by the shutdown-path timeout so this always returns to the stranded check. await self._safe_adapter_disconnect(adapter, adapter.platform) if not self.adapters and not self._failed_platforms: @@ -437,16 +324,23 @@ class GatewayAdapterLifecycleMixin: logger.error("No connected messaging platforms remain. Shutting down gateway cleanly.") await self.stop() elif not self.adapters and self._failed_platforms: - # All platforms are down and queued for reconnection. Keep the gateway alive so cron jobs - # still run and the watcher can recover platforms when the problem clears; exiting for a - # systemd restart would turn a transient outage into a state-killing restart loop. + # Everything is down but queued: stay alive (cron still runs, watcher recovers) rather + # than turn a transient outage into a state-killing systemd restart loop. logger.warning( "No connected messaging platforms remain, but %d platform(s) " "queued for reconnection — gateway staying alive, watcher will " - "retry in background.", - len(self._failed_platforms), + "retry in background.", len(self._failed_platforms), ) + def _retain_background_task(self, task: "asyncio.Task") -> "asyncio.Task": + """Register ``task`` in ``_background_tasks`` (created lazily for bare test runners).""" + tasks = getattr(self, "_background_tasks", None) + if not isinstance(tasks, set): + tasks = self._background_tasks = set() + tasks.add(task) + task.add_done_callback(tasks.discard) + return task + def _request_clean_exit(self, reason: str) -> None: self._exit_cleanly = True self._exit_reason = reason @@ -454,45 +348,34 @@ class GatewayAdapterLifecycleMixin: @staticmethod def _supervised_backoff(attempt: int) -> float: - """Delay before the supervisor's next respawn, in seconds (capped exponential). - - A method so tests can collapse the schedule instead of sleeping through the real curve. - """ + """Capped exponential respawn delay (a method so tests can collapse the schedule).""" return min(60, 2 ** min(attempt, 6)) def _spawn_supervised( - self, coro_factory, name, *, restart=True, _attempt=0, on_spawn=None, - on_give_up=None, + self, coro_factory, name, *, restart=True, _attempt=0, on_spawn=None, on_give_up=None ): """Launch a long-lived background task with task-level supervision. - Catches what a per-iteration try/except cannot — exceptions in the OUTER loop or pre-try - setup — which a bare ``asyncio.create_task`` drops silently. Restarts with capped backoff up - to ``_MAX_SUPERVISED_RESTARTS`` rapid failures; the counter resets after a run healthy for - ``_SUPERVISED_HEALTHY_SECS``. Each spawn uses a fresh ``Context``: an inherited - delegated-child marker would make the Kanban dispatcher reject its own writes. - ``on_spawn`` fires on EVERY spawn incl. respawns; callers tracking the handle elsewhere - (e.g. ``_reconnect_watcher_task``) MUST pass it or a respawn leaves a stale handle and a - SECOND watcher. ``on_give_up(name)`` fires when the restart budget is spent. + Catches outer-loop/pre-try exceptions a bare ``create_task`` drops silently. Restarts with + capped backoff up to ``_MAX_SUPERVISED_RESTARTS`` rapid failures; the counter resets after + ``_SUPERVISED_HEALTHY_SECS`` of healthy running. Each spawn uses a fresh ``Context`` (an + inherited delegated-child marker would make the Kanban dispatcher reject its own writes). + ``on_spawn`` fires on EVERY spawn incl. respawns — callers tracking the handle elsewhere + MUST pass it or a respawn leaves a stale handle and a SECOND watcher. ``on_give_up(name)`` + fires when the restart budget is spent. """ - if getattr(self, "_background_tasks", None) is None: - self._background_tasks = set() - - # Monotonic spawn timestamp captured per spawn: the ``_done`` callback - # uses it to distinguish a rapid crash-loop from a healthy-run-then-crash. + # Spawn timestamp lets ``_done`` tell a rapid crash-loop from a healthy-run-then-crash. _started = time.monotonic() - # Deliberately no kwargs to create_task (some test doubles mock a narrow signature); calling - # it from a fresh Context gives the same isolation as create_task(..., context=Context()). + # No create_task kwargs (test doubles mock a narrow signature); running it from a fresh + # Context gives the same isolation as create_task(..., context=Context()). task = Context().run(lambda: asyncio.create_task(coro_factory())) - # PERMANENT supervised watcher, not transient background WORK: the scale-to-zero idle check - # must ignore process-lifetime watchers or the gateway counts itself busy forever. Transient - # tasks added to _background_tasks elsewhere (startup-resume events etc.) stay counted. + # Marks a PERMANENT watcher so the scale-to-zero idle check ignores it (else the gateway + # counts itself busy forever); transient _background_tasks stay counted. task._hermes_supervised_watcher = True # type: ignore[attr-defined] - self._background_tasks.add(task) + self._retain_background_task(task) if on_spawn is not None: - # Record the live handle NOW so an external tracker (e.g. _reconnect_watcher_task) - # points at the current task, not a dead one left by a prior supervised respawn. + # Record the live handle NOW so external trackers don't point at a dead prior task. try: on_spawn(task) except Exception: # pragma: no cover - defensive; a tracker must never kill the spawn @@ -504,106 +387,74 @@ class GatewayAdapterLifecycleMixin: return exc = t.exception() if exc is None: - # Clean return == deliberate shutdown or a self-disabling watcher (e.g. a gated - # no-op returning at once); respawning would busy-spin it — NEVER restart on it. + # Clean return = deliberate shutdown or a self-disabling watcher; NEVER respawn. return logger.error("Supervised task %s died: %r", name, exc, exc_info=exc) - if restart and self._running: - ran_for = time.monotonic() - _started - if ran_for >= self._SUPERVISED_HEALTHY_SECS: - # Ran healthily before crashing — a FRESH failure, not a rapid crash-loop. Reset - # the counter so a daemon crashing a few times over days is never abandoned. - effective_attempt = 0 - else: - effective_attempt = _attempt - if effective_attempt >= self._MAX_SUPERVISED_RESTARTS: - logger.error( - "Supervised task %s died %d times in rapid succession " - "(each within %ds of restart) — giving up restarts", - name, - effective_attempt, - self._SUPERVISED_HEALTHY_SECS, + if not (restart and self._running): + return + # A healthy run before the crash is a FRESH failure, not a crash-loop: reset so a + # daemon crashing a few times over days is never abandoned. + healthy = time.monotonic() - _started >= self._SUPERVISED_HEALTHY_SECS + effective_attempt = 0 if healthy else _attempt + if effective_attempt >= self._MAX_SUPERVISED_RESTARTS: + logger.error( + "Supervised task %s died %d times in rapid succession " + "(each within %ds of restart) — giving up restarts", name, + effective_attempt, self._SUPERVISED_HEALTHY_SECS, + ) + if on_give_up is not None: + try: + on_give_up(name) + except Exception: # pragma: no cover - defensive + logger.debug("on_give_up callback for %s raised", name, exc_info=True) + return + backoff = self._supervised_backoff(effective_attempt) + + async def _respawn(): + await asyncio.sleep(backoff) + if self._running: + self._spawn_supervised( + coro_factory, name, restart=restart, _attempt=effective_attempt + 1, + on_spawn=on_spawn, on_give_up=on_give_up, # only the LAST give-up matters ) - if on_give_up is not None: - try: - on_give_up(name) - except Exception: # pragma: no cover - defensive - logger.debug( - "on_give_up callback for %s raised", - name, exc_info=True, - ) - return - backoff = self._supervised_backoff(effective_attempt) - async def _respawn(): - await asyncio.sleep(backoff) - if self._running: - self._spawn_supervised( - coro_factory, - name, - restart=restart, - _attempt=effective_attempt + 1, - on_spawn=on_spawn, - # Threaded through the recursion like on_spawn: only the LAST respawn's give-up - # matters, and dropping the callback leaves the exhaustion branch with no owner. - on_give_up=on_give_up, - ) - - # The done callback retains its registration context, so isolate the backoff task - # too; otherwise a restart could reintroduce the original caller's turn scope. - respawn_task = Context().run(lambda: asyncio.create_task(_respawn())) - self._background_tasks.add(respawn_task) - respawn_task.add_done_callback(self._background_tasks.discard) + # The done callback runs in its registration context; isolate the backoff task too. + self._retain_background_task(Context().run(lambda: asyncio.create_task(_respawn()))) task.add_done_callback(_done) return task - async def _handoff_watcher( - self, interval: float = 2.0, drain_timeout: float = 30.0, - ) -> None: - """Background task that processes pending CLI→gateway session handoffs. + async def _handoff_watcher(self, interval: float = 2.0, drain_timeout: float = 30.0) -> None: + """Process pending CLI→gateway session handoffs from ``state.db``. - Polls ``state.db`` for ``handoff_state='pending'`` rows: claim atomically (pending → - running), re-bind the home channel's session_key to the CLI session_id via - ``switch_session``, dispatch a synthetic ``MessageEvent``, mark ``completed``/``failed``. + Claim atomically (pending → running), re-bind the home channel to the CLI session_id, + dispatch a synthetic ``MessageEvent``, mark ``completed``/``failed``. """ from gateway.run import _async_profile_runtime_scope, _handoff_watch_scopes, _reclaim_stale - # Initial delay so the gateway is fully connected to its platforms - # before we try to dispatch handoffs through them. - await asyncio.sleep(5) + await asyncio.sleep(5) # let platforms connect before dispatching through them - # Does _process_handoff accept the profile argument? The real one does; test stand-ins bind - # a one-parameter callable. Probed once, outside the loop. + # Does _process_handoff accept the profile argument? Test stand-ins bind a one-arg callable. try: import inspect as _inspect - _process_takes_profile = len( - _inspect.signature(self._process_handoff).parameters - ) >= 2 + _process_takes_profile = len(_inspect.signature(self._process_handoff).parameters) >= 2 except Exception: _process_takes_profile = False - # In-flight dispatches keyed by session id. A handoff runs a FULL agent turn plus delivery - # (far longer than the CLI's 60s wait); inline processing would let one slow handoff block - # every other profile's poll and time them out. Fire-and-forget; the poll loop only claims. + # In-flight dispatches keyed by session id: a handoff runs a FULL agent turn, so inline + # processing would let one slow handoff time out every other profile's poll. inflight: Dict[str, "asyncio.Task"] = {} async def _dispatch(row, session_id, session_db, profile_name) -> None: """Run one claimed handoff to a terminal state, off the poll path.""" try: - if _process_takes_profile: - await self._process_handoff(row, profile_name) - else: - await self._process_handoff(row) + await self._process_handoff(*((row, profile_name) if _process_takes_profile else (row,))) await session_db.complete_handoff(session_id) except asyncio.CancelledError: # Gateway shutting down: leave the row 'running' so the next # start's reclaim marks it failed with a clear reason. raise except Exception as exc: - logger.warning( - "Handoff for session %s failed: %s", - session_id, exc, exc_info=True, - ) + logger.warning("Handoff for session %s failed: %s", session_id, exc, exc_info=True) try: await session_db.fail_handoff(session_id, str(exc)) except Exception: @@ -612,12 +463,11 @@ class GatewayAdapterLifecycleMixin: inflight.pop(session_id, None) async def _tick(profile_name: Optional[str] = None) -> None: - """One poll of the CURRENTLY-SCOPED session store. + """One poll of the CURRENTLY-SCOPED store; ``profile_name`` (None = root) routes + delivery to that profile's OWN adapter. - A closure over ``self``, not a method: unit tests bind ``_handoff_watcher`` onto a - ``SimpleNamespace`` exposing only ``_session_db``, ``_running`` and ``_process_handoff``; - any other ``self.`` would raise, be swallowed by the loop, and silently no-op the - watcher. ``profile_name`` (``None`` = root) makes delivery use that profile's OWN adapter. + A closure, not a method: tests bind ``_handoff_watcher`` onto a ``SimpleNamespace`` + with only ``_session_db``/``_running``/``_process_handoff``. """ session_db = getattr(self, "_session_db", None) if session_db is None: @@ -630,8 +480,6 @@ class GatewayAdapterLifecycleMixin: if not await session_db.claim_handoff(session_id): # Another tick or another gateway already claimed it. continue - # Positional, not keyword: tests bind a one-arg ``_process_handoff(row)`` stand-in and a - # keyword call would TypeError into the failure branch (arity probed above). # INVARIANT (do not weaken): this task is created inside _profile_runtime_scope but # typically RUNS after it exits; it sees the profile's home/secret scope only because # those seams are ContextVar-based and ensure_future copies the Context. @@ -639,15 +487,17 @@ class GatewayAdapterLifecycleMixin: _dispatch(row, session_id, session_db, profile_name) ) - # A row still 'running' at startup belongs to a gateway that died mid-dispatch: it can never - # reach a terminal state, and request_handoff refuses new requests while it sits there. + # A row still 'running' at startup belongs to a gateway that died mid-dispatch; it blocks + # request_handoff until reclaimed. + def _scope(profile_home): + if profile_home is None: + return contextlib.nullcontext() + return _async_profile_runtime_scope(profile_home) + for _pname, _phome in _handoff_watch_scopes(self): try: - if _phome is None: + async with _scope(_phome): await _reclaim_stale(self) - else: - async with _async_profile_runtime_scope(_phome): - await _reclaim_stale(self) except Exception: logger.debug("Stale-handoff reclaim failed", exc_info=True) @@ -655,19 +505,15 @@ class GatewayAdapterLifecycleMixin: while self._running: try: for profile_name, profile_home in _handoff_watch_scopes(self): - if profile_home is None: + async with _scope(profile_home): await _tick(profile_name) - else: - async with _async_profile_runtime_scope(profile_home): - await _tick(profile_name) except asyncio.CancelledError: raise except Exception as exc: logger.debug("Handoff watcher tick error: %s", exc, exc_info=True) await asyncio.sleep(interval) finally: - # Drain in-flight dispatches before returning: cancelling would strand their rows in - # 'running'; a bounded grace period lets an almost-done handoff record its own state. + # Bounded drain: cancelling would strand in-flight rows in 'running'. pending_tasks = [t for t in inflight.values() if not t.done()] if pending_tasks: try: @@ -679,25 +525,19 @@ class GatewayAdapterLifecycleMixin: task.cancel() def _on_reconnect_watcher_gave_up(self, name: str = "") -> None: - """Own the reconnect invariant once supervision has abandoned it. - - Invariant: while running and ``_failed_platforms`` is non-empty, a reconnect watcher is live - or a bounded respawn is scheduled. Event-coupled recovery is not enough: the failed adapter - is dropped from the live map, so no later event may ever arrive to notice a dead watcher. - Deliberately NOT done here: requesting a process restart when the slow tier is exhausted — - a blast-radius policy call; a single loud error names the still-queued platforms instead. - """ + """Own the reconnect invariant once supervision gives up: while running with queued + platforms, a watcher is live or a bounded respawn is scheduled (no later event can notice + a dead watcher). Slow-tier exhaustion logs loudly; deliberately NOT a process restart.""" if not getattr(self, "_running", False): return - if not getattr(self, "_failed_platforms", None): - # No queued work depends on the watcher; leaving it dead is correct — the enqueue path - # spawns a fresh one the moment a platform is queued again. + if getattr(self, "_failed_platforms", None): + self._schedule_slow_reconnect_watcher_respawn(attempt=0) + else: + # Nothing depends on the watcher; the enqueue path spawns a fresh one when needed. logger.warning( "Reconnect watcher supervision exhausted with an empty retry " "queue — leaving it down until a platform is queued." ) - return - self._schedule_slow_reconnect_watcher_respawn(attempt=0) def _schedule_slow_reconnect_watcher_respawn(self, *, attempt: int) -> None: """Bounded slow-tier respawn of the reconnect watcher.""" @@ -705,69 +545,47 @@ class GatewayAdapterLifecycleMixin: logger.error( "Reconnect watcher could not be kept alive after %d slow " "respawns; %d platform(s) remain queued and unattended: %s. " - "Manual intervention or a gateway restart is required.", - attempt, - len(self._failed_platforms), - ", ".join(str(p) for p in self._failed_platforms), + "Manual intervention or a gateway restart is required.", attempt, + len(self._failed_platforms), ", ".join(str(p) for p in self._failed_platforms), ) return async def _slow_respawn() -> None: await asyncio.sleep(self._RECONNECT_WATCHER_SLOW_RETRY_SECS) - if not getattr(self, "_running", False): - return - if not getattr(self, "_failed_platforms", None): - # The queue drained while we waited -- something else healed - # it. Nothing to own any more. - return task = getattr(self, "_reconnect_watcher_task", None) - if task is not None and not task.done(): - return # a watcher came back on its own; stand down + if ( + not getattr(self, "_running", False) + or not getattr(self, "_failed_platforms", None) # queue drained while waiting + or (task is not None and not task.done()) # a watcher came back; stand down + ): + return logger.warning( "Reconnect watcher still down with %d platform(s) queued — " - "slow respawn %d/%d", - len(self._failed_platforms), - attempt + 1, + "slow respawn %d/%d", len(self._failed_platforms), attempt + 1, self._MAX_SLOW_WATCHER_RESPAWNS, ) self._spawn_reconnect_watcher( - on_give_up=lambda _name: self._schedule_slow_reconnect_watcher_respawn( - attempt=attempt + 1 - ) + on_give_up=lambda _name: self._schedule_slow_reconnect_watcher_respawn(attempt=attempt + 1) ) - respawn_task = asyncio.create_task(_slow_respawn()) - if getattr(self, "_background_tasks", None) is None: - self._background_tasks = set() - self._background_tasks.add(respawn_task) - respawn_task.add_done_callback(self._background_tasks.discard) + self._retain_background_task(asyncio.create_task(_slow_respawn())) def _spawn_reconnect_watcher(self, *, on_give_up=None): - """Single place that knows how to launch the reconnect watcher. - - ``on_spawn`` is load-bearing: without it the supervisor's own respawn leaves - ``_reconnect_watcher_task`` at a dead handle and ``_ensure_...`` spawns a second watcher. - """ + """Launch the reconnect watcher. ``on_spawn`` is load-bearing: without it a supervised + respawn leaves ``_reconnect_watcher_task`` dead and ``_ensure_...`` spawns a second one.""" self._reconnect_watcher_task = self._spawn_supervised( - self._platform_reconnect_watcher, - "platform_reconnect_watcher", + self._platform_reconnect_watcher, "platform_reconnect_watcher", on_spawn=lambda t: setattr(self, "_reconnect_watcher_task", t), on_give_up=on_give_up or self._on_reconnect_watcher_gave_up, ) return self._reconnect_watcher_task def _ensure_reconnect_watcher_running(self) -> None: - """Ensure the platform reconnect watcher background task is alive. - - Respawns a dead watcher (exhausted restart budget, unrecoverable exception) so queued - platforms are not stranded. Called on BOTH _queue_retryable_fatal_platform paths: the - re-fatal of an already-queued platform is the only case where the budget can be exhausted. - """ - if not getattr(self, "_running", False): - return + """Respawn a dead reconnect watcher (called on BOTH _queue_retryable_fatal_platform paths: + the re-fatal of an already-queued platform is the only case that exhausts the budget).""" task = getattr(self, "_reconnect_watcher_task", None) - if task is not None and not task.done(): - return # already alive + if not getattr(self, "_running", False) or (task is not None and not task.done()): + return # not running, or already alive logger.warning( "Reconnect watcher task is dead (done=%s) — respawning", task.done() if task is not None else "N/A", @@ -775,248 +593,185 @@ class GatewayAdapterLifecycleMixin: self._spawn_reconnect_watcher() async def _platform_reconnect_watcher(self) -> None: - """Background task that periodically retries connecting failed platforms. + """Periodically retry failed platforms: backoff 30s → 300s cap, retryable failures retry + forever (self-heal), non-retryable drop out. Pausing is manual only (``/platform pause``).""" + async def _idle(seconds: int, until_queued: bool = False) -> bool: + """Sleep in 1s steps; False once the runner stops (or, if asked, once work is queued).""" + for _ in range(seconds): + if not self._running: + return False + if until_queued and self._failed_platforms: + break + await asyncio.sleep(1) + return True - Exponential backoff 30s → 300s cap; retryable failures (network/DNS) retry at the cap - indefinitely so transient outages self-heal, non-retryable (bad auth) drop out immediately. - The circuit breaker (``/platform pause``) is manual only — auto-pausing left bots dead. - """ - from gateway.run import ( - _dispose_unused_adapter, - _platform_has_bot_credential, - _reconnect_backoff, - _reconnect_needs_attention, - ) await asyncio.sleep(10) # initial delay — let startup finish while self._running: if not self._failed_platforms: - # Nothing to reconnect — sleep and check again - for _ in range(30): - if not self._running: - return - if self._failed_platforms: - break - await asyncio.sleep(1) + if not await _idle(30, until_queued=True): + return continue - now = time.monotonic() for platform in list(self._failed_platforms.keys()): if not self._running: return - info = self._failed_platforms.get(platform) - if info is None: - # Removed concurrently (/platform resume, reconnect via another path) between - # the snapshot above and this lookup — not an error, nothing to do this pass. - continue - # Skip paused platforms entirely — they need explicit - # /platform resume to come back. - if info.get("paused"): - continue - # Long-lived retry escalation: past the attention threshold flag the platform - # NEEDS_ATTENTION in runtime status so a dead token/revoked intent doesn't look - # like ordinary "retrying" forever. A signal, NOT a circuit breaker — retries continue. - if not info.get("attention_flagged") and _reconnect_needs_attention(info, now): - info["attention_flagged"] = True - queued_for = now - info.get("queued_at", now) - retrying_since_iso = ( - datetime.now(timezone.utc) - timedelta(seconds=queued_for) - ).isoformat() - logger.warning( - "%s has been failing/reconnecting continuously for " - "%.1f hours (%d attempts) — flagging NEEDS_ATTENTION. " - "Retries continue, but this usually means a permanent " - "problem (revoked credentials, missing intents, broken " - "sidecar). Check `hermes status` / `/platform list`.", - platform.value, - queued_for / 3600.0, - info.get("attempts", 0), - ) - self._update_platform_runtime_status( - platform.value, - platform_state="retrying", - needs_attention=True, - retrying_since=retrying_since_iso, - ) - if now < info["next_retry"]: - continue # not time yet + await self._reconnect_failed_platform(platform, now) + if not await _idle(10): # re-check every 10 seconds + return - platform_config = info["config"] - attempt = info["attempts"] + 1 - # Empty-token primary configs can never reconnect; drop them so multiplex setups - # where a secondary profile owns the bot do not spin forever. - if not _platform_has_bot_credential(platform, platform_config): - logger.warning( - "Reconnect %s: no bot credential on queued config, " - "removing from retry queue", - platform.value, - ) - del self._failed_platforms[platform] - continue - logger.info( - "Reconnecting %s (attempt %d)...", - platform.value, attempt, + def _flag_reconnect_needs_attention(self, platform, info: dict, now: float) -> None: + """Flag NEEDS_ATTENTION (once) past the threshold — a signal, NOT a circuit breaker.""" + from gateway.run import _reconnect_needs_attention + if info.get("attention_flagged") or not _reconnect_needs_attention(info, now): + return + info["attention_flagged"] = True + queued_for = now - info.get("queued_at", now) + retrying_since_iso = (datetime.now(timezone.utc) - timedelta(seconds=queued_for)).isoformat() + logger.warning( + "%s has been failing/reconnecting continuously for " + "%.1f hours (%d attempts) — flagging NEEDS_ATTENTION. " + "Retries continue, but this usually means a permanent " + "problem (revoked credentials, missing intents, broken " + "sidecar). Check `hermes status` / `/platform list`.", platform.value, + queued_for / 3600.0, info.get("attempts", 0), + ) + self._update_platform_runtime_status( + platform.value, platform_state="retrying", needs_attention=True, + retrying_since=retrying_since_iso, + ) + + def _bump_reconnect_backoff( + self, platform, info: dict, attempt: int, error_code, error_message: str + ) -> int: + """Mark the platform retrying and record the failed attempt; returns the backoff applied.""" + from gateway.run import _reconnect_backoff + self._update_platform_runtime_status( + platform.value, platform_state="retrying", error_code=error_code, error_message=error_message, + ) + backoff = _reconnect_backoff(attempt) + info["attempts"] = attempt + info["next_retry"] = time.monotonic() + backoff + return backoff + + async def _reconnect_failed_platform(self, platform, now: float) -> None: + """One watcher pass for a queued platform: gate, attempt, and record the outcome.""" + from gateway.run import _dispose_unused_adapter, _platform_has_bot_credential + info = self._failed_platforms.get(platform) + # None: removed concurrently since the caller's snapshot. Paused needs /platform resume. + if info is None or info.get("paused"): + return + self._flag_reconnect_needs_attention(platform, info, now) + if now < info["next_retry"]: + return # not time yet + + platform_config = info["config"] + attempt = info["attempts"] + 1 + # Empty-token primary configs can never reconnect; drop them so multiplex setups + # where a secondary profile owns the bot do not spin forever. + if not _platform_has_bot_credential(platform, platform_config): + self._drop_from_reconnect_queue(platform, "no bot credential on queued config") + return + logger.info("Reconnecting %s (attempt %d)...", platform.value, attempt) + + adapter = None + try: + adapter = self._create_adapter(platform, platform_config) + if not adapter: + self._drop_from_reconnect_queue(platform, "adapter creation returned None") + return + + self._wire_adapter_handlers(adapter) + # Reconnect after outage: keep the platform's server-side update queue so + # messages sent while the bot was offline are delivered rather than dropped. + success = await self._connect_adapter_with_timeout(adapter, platform, is_reconnect=True) + if success: + await self._install_reconnected_adapter(platform, adapter) + elif adapter.has_fatal_error and not adapter.fatal_error_retryable: + self._update_platform_runtime_status( + platform.value, platform_state="fatal", error_code=adapter.fatal_error_code, + error_message=adapter.fatal_error_message, ) + logger.warning( + "Reconnect %s: non-retryable error (%s), removing from retry queue", + platform.value, adapter.fatal_error_message, + ) + # Never installed on self.adapters, so nothing else will disconnect() it: dispose or + # the resource owners built in __init__ leak ~2 fds each (fd limit in ~12h at the cap). + await _dispose_unused_adapter(adapter) + del self._failed_platforms[platform] + else: + # Retryable failures retry at the backoff cap forever; never auto-pause them — a + # transient outage must not need `/platform resume`. Same fd-leak dispose as above. + backoff = self._bump_reconnect_backoff( + platform, info, attempt, adapter.fatal_error_code, + adapter.fatal_error_message or "failed to reconnect", + ) + logger.info("Reconnect %s failed, next retry in %ds", platform.value, backoff) + await _dispose_unused_adapter(adapter) + except Exception as e: + if adapter is not None: + # An exception escaping connect leaves the adapter in the same unowned state. + await _dispose_unused_adapter(adapter) + # A reconnect exception is transient; keep retrying at the cap rather than auto-pausing. + backoff = self._bump_reconnect_backoff(platform, info, attempt, None, str(e)) + logger.warning("Reconnect %s error: %s, next retry in %ds", platform.value, e, backoff) - adapter = None - try: - adapter = self._create_adapter(platform, platform_config) - if not adapter: - logger.warning( - "Reconnect %s: adapter creation returned None, removing from retry queue", - platform.value, - ) - del self._failed_platforms[platform] - continue + def _drop_from_reconnect_queue(self, platform, reason: str) -> None: + logger.warning("Reconnect %s: %s, removing from retry queue", platform.value, reason) + del self._failed_platforms[platform] - adapter.set_message_handler(self._primary_message_handler()) - adapter.set_fatal_error_handler(self._handle_adapter_fatal_error) - adapter.set_session_store(self.session_store) - adapter.set_busy_session_handler(self._handle_active_session_busy_message) - _set_reaction = getattr(adapter, "set_reaction_handler", None) - if callable(_set_reaction): - _set_reaction(self._handle_reaction_event) - adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id) - adapter.set_authorization_check(self._make_adapter_auth_check(adapter.platform)) - adapter.set_platform_event_handler(self._primary_platform_event_handler()) - adapter._busy_text_mode = self._busy_text_mode + async def _install_reconnected_adapter(self, platform, adapter) -> None: + """Publish a freshly reconnected primary adapter and replay what it missed while down.""" + self.adapters[platform] = adapter + self._sync_voice_mode_state_to_adapter(adapter) + self._bind_voice_input_callback(adapter) + self.delivery_router.adapters = self.adapters + del self._failed_platforms[platform] + self._update_platform_runtime_status( + platform.value, platform_state="connected", error_code=None, error_message=None, + needs_attention=False, retrying_since=None, + ) + logger.info("✓ %s reconnected successfully", platform.value) - # Reconnect after outage: keep the platform's server-side update queue so - # messages sent while the bot was offline are delivered rather than dropped. - success = await self._connect_adapter_with_timeout( - adapter, platform, is_reconnect=True - ) - if success: - self.adapters[platform] = adapter - self._sync_voice_mode_state_to_adapter(adapter) - # Wire voice input callback on reconnect as well (#60623). - self._bind_voice_input_callback(adapter) - self.delivery_router.adapters = self.adapters - del self._failed_platforms[platform] - self._update_platform_runtime_status( - platform.value, - platform_state="connected", - error_code=None, - error_message=None, - needs_attention=False, - retrying_since=None, - ) - logger.info("✓ %s reconnected successfully", platform.value) + # Final responses rejected while this adapter was down are still owned by this live + # process, so startup recovery cannot claim them. Replay the transient subset now. + try: + await self._redeliver_failed_obligations_for_platform(platform) + except Exception: + logger.debug( + "failed-obligation redelivery after %s reconnect failed", platform.value, exc_info=True, + ) - # Final responses rejected while this adapter was down are still owned by - # this live process, so startup recovery cannot claim them. Replay the - # explicitly transient subset now that the platform is usable. - try: - await self._redeliver_failed_obligations_for_platform( - platform - ) - except Exception: - logger.debug( - "failed-obligation redelivery after %s reconnect failed", - platform.value, - exc_info=True, - ) + # Rebuild channel directory with the new adapter + try: + from gateway.channel_directory import build_channel_directory + await build_channel_directory(self.adapters) + except Exception: + pass - # Rebuild channel directory with the new adapter - try: - from gateway.channel_directory import build_channel_directory - await build_channel_directory(self.adapters) - except Exception: - pass - - # A platform that was offline at gateway startup never got its restart- - # interrupted sessions auto-resumed — the startup pass skips sessions whose - # adapter isn't connected yet. - try: - self._schedule_resume_pending_sessions(platform=platform) - except Exception: - logger.debug( - "resume-pending reschedule after %s reconnect failed", - platform.value, - exc_info=True, - ) - # Check if the failure is non-retryable - elif adapter.has_fatal_error and not adapter.fatal_error_retryable: - self._update_platform_runtime_status( - platform.value, - platform_state="fatal", - error_code=adapter.fatal_error_code, - error_message=adapter.fatal_error_message, - ) - logger.warning( - "Reconnect %s: non-retryable error (%s), removing from retry queue", - platform.value, adapter.fatal_error_message, - ) - # The adapter is about to be dropped from the queue without ever being - # installed on self.adapters, so nothing else will call disconnect() on it. - # Dispose here or the resource owners built in __init__ (ResponseStore etc.) - # leak ~2 fds each; at the 300s cap the gateway hits the fd limit in ~12h. - await _dispose_unused_adapter(adapter) - del self._failed_platforms[platform] - else: - self._update_platform_runtime_status( - platform.value, - platform_state="retrying", - error_code=adapter.fatal_error_code, - error_message=adapter.fatal_error_message or "failed to reconnect", - ) - backoff = _reconnect_backoff(attempt) - info["attempts"] = attempt - info["next_retry"] = time.monotonic() + backoff - logger.info( - "Reconnect %s failed, next retry in %ds", - platform.value, backoff, - ) - # Same fd-leak concern as the non-retryable branch above: the adapter failed - # to connect and is being thrown away. - await _dispose_unused_adapter(adapter) - # Retryable failures (network/DNS blips) retry at the backoff cap forever, - # self-healing when connectivity returns. Never auto-pause them: a transient - # outage must not need `/platform resume`. Everything here is retryable. - except Exception as e: - if adapter is not None: - # An exception escaping connect (DNS timeout, aiohttp server.start() crash, - # etc.) leaves the adapter in the same unowned state as the branches above. - await _dispose_unused_adapter(adapter) - self._update_platform_runtime_status( - platform.value, - platform_state="retrying", - error_code=None, - error_message=str(e), - ) - backoff = _reconnect_backoff(attempt) - info["attempts"] = attempt - info["next_retry"] = time.monotonic() + backoff - logger.warning( - "Reconnect %s error: %s, next retry in %ds", - platform.value, e, backoff, - ) - # A reconnect exception (connect timeout, DNS failure, ...) is transient; keep - # retrying at the backoff cap rather than auto-pausing. - - # Check every 10 seconds for platforms that need reconnection - for _ in range(10): - if not self._running: - return - await asyncio.sleep(1) + # A platform offline at gateway startup never got its restart-interrupted sessions + # auto-resumed — the startup pass skips sessions whose adapter isn't connected yet. + try: + self._schedule_resume_pending_sessions(platform=platform) + except Exception: + logger.debug( + "resume-pending reschedule after %s reconnect failed", platform.value, exc_info=True + ) async def _cancel_secondary_profile_reconnect_tasks(self) -> None: - """Cancel profile-scoped reconnects before tearing down their registry. - - A reconnect can be waiting in adapter setup while shutdown begins. It must not republish - an adapter after the secondary registry is drained. Waiting is bounded by the adapter- - cleanup budget; a task that overruns is still blocked by the stopped runner state. - """ + """Cancel profile-scoped reconnects before tearing down their registry, so a reconnect + mid-setup cannot republish an adapter after the registry drains (bounded wait).""" pending = self._profile_failed_platforms if not isinstance(pending, dict): return current = asyncio.current_task() - tasks: list[asyncio.Task] = [] - for profile_pending in pending.values(): - if not isinstance(profile_pending, dict): - continue - for task in profile_pending.values(): - if isinstance(task, asyncio.Task) and task is not current and not task.done(): - tasks.append(task) + tasks = [ + task + for profile_pending in pending.values() + if isinstance(profile_pending, dict) + for task in profile_pending.values() + if isinstance(task, asyncio.Task) and task is not current and not task.done() + ] for task in tasks: task.cancel() timeout = self._adapter_disconnect_timeout_secs() @@ -1030,18 +785,13 @@ class GatewayAdapterLifecycleMixin: pending.clear() async def _start_secondary_profile_adapters(self) -> int: - """Bring up adapters for every non-active profile this gateway serves. + """Bring up adapters for every non-active profile (multiplex only); returns connected count. - Returns the count of connected secondary adapters; 0 unless ``gateway.multiplex_profiles``. - Each profile's adapters connect under its HERMES_HOME + secret scope, live in - ``self._profile_adapters[profile]``, and get a handler stamping ``source.profile``. Same- - platform credential collisions are refused here — the only point seeing every profile's - resolved credentials together. + Each profile connects under its own HERMES_HOME + secret scope; credential/listener + collisions are refused here — the only point seeing every profile's credentials together. """ from gateway.run import ( - MultiplexConfigError, - SecondaryPortBindingConfigError, - _multiplex_profile_homes, + MultiplexConfigError, SecondaryPortBindingConfigError, _multiplex_profile_homes ) if not getattr(self.config, "multiplex_profiles", False): return 0 @@ -1053,117 +803,94 @@ class GatewayAdapterLifecycleMixin: active = get_active_profile_name() or "default" connected = 0 - # Resource claim -> owning profile. Credential claims stop two profiles polling the same - # account; listener claims stop sidecars with distinct credentials binding one endpoint. - claimed: Dict[tuple, str] = {} - for _plat, _ad in self.adapters.items(): - fp = self._adapter_credential_fingerprint(_ad) - if fp is not None: - claimed[(_plat, fp)] = active - listener_claim = self._adapter_listener_claim(_plat, _ad) - if listener_claim is not None: - claimed[listener_claim] = active - # A retryable primary still owns its credential and listener; reserve both while queued - # so a secondary cannot take the endpoint before the reconnect watcher retries it. - for retry_info in getattr(self, "_failed_platforms", {}).values(): - for claim_name in ("credential_claim", "listener_claim"): - retry_claim = retry_info.get(claim_name) - if isinstance(retry_claim, tuple): - claimed[retry_claim] = active - + claimed = self._primary_resource_claims(active) profile_homes = _multiplex_profile_homes(self.config) for profile_name, profile_home in profile_homes: if profile_name == active: continue # handled by the primary startup loop try: - connected += await self._start_one_profile_adapters( - profile_name, profile_home, claimed - ) + connected += await self._start_one_profile_adapters(profile_name, profile_home, claimed) except SecondaryPortBindingConfigError as e: logger.warning( - "Skipping secondary profile '%s' due to port-binding config error: %s", - profile_name, - e, + "Skipping secondary profile '%s' due to port-binding config error: %s", profile_name, e, ) except MultiplexConfigError: raise except Exception as e: logger.error( - "Failed to start adapters for profile '%s': %s", - profile_name, e, exc_info=True, + "Failed to start adapters for profile '%s': %s", profile_name, e, exc_info=True ) - # Record the authoritative served set in runtime status for `hermes status`. "Served" - # means eligible for shared routing, HTTP prefixes, cron, and profile runtime scope — - # intentionally broader than profiles with a connected (or any) secondary adapter. + self._record_served_profiles(active, profile_homes) + return connected + + def _primary_resource_claims(self, active: str) -> Dict[tuple, str]: + """Resource claim -> owning profile for every live or queued primary adapter (credential: + one account polled once; listener: one bind+port). A queued retryable primary owns both.""" + claimed: Dict[tuple, str] = {} + for _plat, _ad in self.adapters.items(): + fp = self._adapter_credential_fingerprint(_ad) + for claim in ((_plat, fp) if fp is not None else None, self._adapter_listener_claim(_plat, _ad)): + if claim is not None: + claimed[claim] = active + for retry_info in getattr(self, "_failed_platforms", {}).values(): + for claim_name in ("credential_claim", "listener_claim"): + retry_claim = retry_info.get(claim_name) + if isinstance(retry_claim, tuple): + claimed[retry_claim] = active + return claimed + + def _record_served_profiles(self, active: str, profile_homes) -> None: + """Record the served set (eligible for routing/HTTP prefixes/cron/runtime scope — broader + than "has a connected adapter") for `hermes status`; seed per-profile PairingStores.""" try: from gateway.status import write_runtime_status from gateway.pairing import PairingStore - served = [active] + sorted( - name for name, _home in profile_homes if name != active - ) - # Per-profile PairingStores so authz_mixin routes pairing checks to the right whitelist; - # the active profile's store is at its HERMES_HOME, other served profiles at their own. + served = [active] + sorted(name for name, _home in profile_homes if name != active) for name in served: if name and name not in self.pairing_stores: self.pairing_stores[name] = ( - self.pairing_store - if name == active - else PairingStore(profile=name) + self.pairing_store if name == active else PairingStore(profile=name) ) write_runtime_status(served_profiles=served) except Exception: logger.debug("could not record served_profiles", exc_info=True) - return connected + async def _load_secondary_profile_config(self, profile_name: str, profile_home: "Path"): + """Hydrate + enter ``profile_home``'s scope once; return its gateway config. - async def _start_one_profile_adapters( - self, profile_name: str, profile_home: "Path", claimed: Dict[tuple, str] - ) -> int: - """Create+connect one profile's adapters under its runtime scope.""" + Raises ``MultiplexConfigError`` (open dm/group policy) or ``SecondaryPortBindingConfigError`` + (the default profile owns the single shared HTTP listener). + """ from gateway.run import ( - MultiplexConfigError, - SecondaryPortBindingConfigError, - _load_gateway_runtime_config, - _own_policy_open_startup_violation, - _platform_has_bot_credential, - _profile_runtime_scope, + MultiplexConfigError, SecondaryPortBindingConfigError, _load_gateway_runtime_config, + _own_policy_open_startup_violation, _profile_runtime_scope, ) from gateway.config import load_gateway_config from hermes_cli.env_loader import hydrate_profile_secret_sources - # Hydrate external secret sources (1Password/vault/...) off-loop ONCE, then enter the scope - # without re-hydrating: the sync hydration is network-bound and would otherwise stall every - # other profile's heartbeat while this one boots (same class as the reconnect path). + # Hydrate external secret sources (1Password/vault/...) off-loop ONCE: the sync hydration is + # network-bound and would stall every other profile's heartbeat while this one boots. await asyncio.to_thread(hydrate_profile_secret_sources, profile_home) with _profile_runtime_scope(profile_home, hydrate_secrets=False): profile_runtime_cfg = _load_gateway_runtime_config() from hermes_cli.plugins import discover_plugins - discover_plugins() - # Register this profile's own declarative shell hooks and outbound webhooks. The - # registration in start() runs before any profile scope exists and only sees the root - # profile's config, so without this a secondary profile's `hooks:` block is silently - # inert (its turns use a plugin manager keyed by resolved home). + # Register this profile's shell hooks / outbound webhooks: start() registers before any + # profile scope exists, so a secondary profile's `hooks:` block would be silently inert. try: from hermes_cli.config import load_config as _load_profile_config - from agent.shell_hooks import ( - register_from_config as _register_shell_hooks, - ) - from agent.outbound_webhooks import ( - register_from_config as _register_outbound_webhooks, - ) + from agent.shell_hooks import register_from_config as _register_shell_hooks + from agent.outbound_webhooks import (register_from_config as _register_outbound_webhooks) _profile_hooks_cfg = _load_profile_config() _register_shell_hooks(_profile_hooks_cfg, accept_hooks=False) _register_outbound_webhooks(_profile_hooks_cfg) except Exception: logger.warning( - "shell-hook/webhook registration failed for profile '%s'", - profile_name, - exc_info=True, + "shell-hook/webhook registration failed for profile '%s'", profile_name, exc_info=True, ) profile_cfg = load_gateway_config() @@ -1180,286 +907,252 @@ class GatewayAdapterLifecycleMixin: port_binding_platforms = sorted( platform.value for platform, platform_config in profile_cfg.platforms.items() - if platform_config.enabled - and _platform_binds_port(platform.value, platform_config.extra) + if platform_config.enabled and _platform_binds_port(platform.value, platform_config.extra) ) if port_binding_platforms: - joined = ", ".join(port_binding_platforms) raise SecondaryPortBindingConfigError( f"Profile '{profile_name}' enables port-binding platform(s) " - f"{joined}, but gateway.multiplex_profiles is on. The default " + f"{', '.join(port_binding_platforms)}, but gateway.multiplex_profiles is on. The default " f"profile owns the single shared HTTP listener and serves every " f"profile through the /p/{profile_name}/ URL prefix. Remove " f"these platform entries from profile '{profile_name}'s config.yaml " f"or configure them only on the default profile." ) + return profile_cfg + def _refuse_duplicate_claim( + self, claim, claimed: Dict[tuple, str], profile_name: str, platform: Platform, kind: str + ) -> bool: + """Log + park a secondary adapter whose credential/listener another profile owns (True when + refused). NOT disconnected: it never connected, and for a same-credential Photon adapter + disconnect() would shut down the primary profile's live sidecar.""" + owner = claimed.get(claim) if claim is not None else None + if owner is None: + return False + if kind == "credential": + message = ( + f"Profile '{owner}' and '{profile_name}' both configure " + f"{platform.value} with the same credential. Give each " + f"profile its own {platform.value} credential." + ) + logger.error( + "Profile '%s' and '%s' both configure %s with the same " + "credential — refusing to start the duplicate (one " + "credential cannot be consumed twice). Give each profile " + "its own %s credential.", owner, profile_name, platform.value, platform.value, + ) + else: + bind, port = claim[-2:] + message = ( + f"Profile '{owner}' and '{profile_name}' both configure " + f"{platform.value} sidecars on the same listener. Configure " + f"a distinct listener for profile '{profile_name}'." + ) + logger.error( + "Profile '%s' and '%s' both configure %s sidecars on " + "%s:%s — refusing to start the duplicate listener. " + "Set platforms.%s.extra.sidecar_port to a distinct port " + "for profile '%s'.", + owner, profile_name, platform.value, bind, port, platform.value, profile_name, + ) + self._update_platform_runtime_status( + f"{profile_name}:{platform.value}", platform_state="fatal", + error_code=f"duplicate_{kind}", error_message=message, + ) + return True + + async def _start_one_profile_adapters( + self, profile_name: str, profile_home: "Path", claimed: Dict[tuple, str] + ) -> int: + """Create+connect one profile's adapters under its runtime scope.""" + from gateway.run import _platform_has_bot_credential, _profile_runtime_scope + profile_cfg = await self._load_secondary_profile_config(profile_name, profile_home) + multiplex = getattr(self.config, "multiplex_profiles", False) profile_map = self._profile_adapters.setdefault(profile_name, {}) connected = 0 for platform, platform_config in profile_cfg.platforms.items(): if not platform_config.enabled: continue - # A platform enabled in a secondary profile's config.yaml may have no credential in that - # profile's secret scope — the shared YAML enables it for the default profile only. - # Building an adapter anyway would fan one inbound message out across every - # credential-less profile; mirror the primary loop's credential gate and skip. - if ( - getattr(self.config, "multiplex_profiles", False) - and not _platform_has_bot_credential(platform, platform_config) - ): + # Enabled in the shared YAML but no credential in THIS profile's scope: building an + # adapter anyway would fan one inbound message out across every credential-less profile. + if multiplex and not _platform_has_bot_credential(platform, platform_config): logger.info( "[MULTIPLEX] Profile '%s': skipping %s - no bot credential " - "in this profile's secrets", - profile_name, - platform.value, + "in this profile's secrets", profile_name, platform.value, ) continue - # Relay and WhatsApp are shared process-level ingress in multiplex mode (one connection - # owned by the active profile, route-stamped source.profile fans out). WhatsApp is one - # session per phone number; a secondary adapter would only retry-loop and stall startup. - if ( - getattr(self.config, "multiplex_profiles", False) - and platform in (Platform.RELAY, Platform.WHATSAPP) - ): + # Relay/WhatsApp are shared process-level ingress under multiplex (the active profile's + # one connection fans out by route); a secondary would only retry-loop and stall startup. + if multiplex and platform in (Platform.RELAY, Platform.WHATSAPP): continue try: with _profile_runtime_scope(profile_home, hydrate_secrets=False): adapter = self._create_adapter(platform, platform_config) except Exception as e: logger.error( - "[MULTIPLEX] Profile '%s': _create_adapter('%s') raised %s", - profile_name, - platform.value, - e, - exc_info=True, + "[MULTIPLEX] Profile '%s': _create_adapter('%s') raised %s", profile_name, + platform.value, e, exc_info=True, ) continue if not adapter: logger.warning( "[MULTIPLEX] Profile '%s': skipping platform '%s' - adapter creation returned None", - profile_name, - platform.value, + profile_name, platform.value, ) continue - - # Same-token conflict detection — refuse a duplicate poll. + # Same-token / same-listener conflict detection — refuse a duplicate poll or bind. credential_claim = self._adapter_credential_claim(platform, adapter) - if credential_claim is not None: - owner = claimed.get(credential_claim) - if owner is not None: - message = ( - f"Profile '{owner}' and '{profile_name}' both configure " - f"{platform.value} with the same credential. Give each " - f"profile its own {platform.value} credential." - ) - logger.error( - "Profile '%s' and '%s' both configure %s with the same " - "credential — refusing to start the duplicate (one " - "credential cannot be consumed twice). Give each profile " - "its own %s credential.", - owner, profile_name, platform.value, platform.value, - ) - self._update_platform_runtime_status( - f"{profile_name}:{platform.value}", - platform_state="fatal", - error_code="duplicate_credential", - error_message=message, - ) - # This adapter has not connected and therefore owns no resources to clean up. - # Calling disconnect here can mutate the shared platform state and, for a same- - # credential Photon adapter, shut down the primary profile's live sidecar. - continue - listener_claim = self._adapter_listener_claim(platform, adapter) - if listener_claim is not None: - owner = claimed.get(listener_claim) - if owner is not None: - bind, port = listener_claim[-2:] - message = ( - f"Profile '{owner}' and '{profile_name}' both configure " - f"{platform.value} sidecars on the same listener. Configure " - f"a distinct listener for profile '{profile_name}'." - ) - logger.error( - "Profile '%s' and '%s' both configure %s sidecars on " - "%s:%s — refusing to start the duplicate listener. " - "Set platforms.%s.extra.sidecar_port to a distinct port " - "for profile '%s'.", - owner, - profile_name, - platform.value, - bind, - port, - platform.value, - profile_name, - ) - self._update_platform_runtime_status( - f"{profile_name}:{platform.value}", - platform_state="fatal", - error_code="duplicate_listener", - error_message=message, - ) - # Like credential conflicts, this adapter never connected - # and owns no resources that should be disconnected. - continue - + if self._refuse_duplicate_claim( + credential_claim, claimed, profile_name, platform, "credential" + ) or self._refuse_duplicate_claim(listener_claim, claimed, profile_name, platform, "listener"): + continue self._configure_profile_adapter(adapter, profile_name, platform) - try: with _profile_runtime_scope(profile_home, hydrate_secrets=False): - success = await self._connect_initial_adapter_with_timeout( - adapter, platform - ) - if success: - profile_map[platform] = adapter - # Restore persisted /voice state for this bot (#84872) — - # primary startup and every reconnect path already do. - self._sync_voice_mode_state_to_adapter(adapter) - if credential_claim is not None: - claimed[credential_claim] = profile_name - if listener_claim is not None: - claimed[listener_claim] = profile_name - connected += 1 - logger.info("✓ %s connected (profile: %s)", platform.value, profile_name) - else: + success = await self._connect_initial_adapter_with_timeout(adapter, platform) + if not success: logger.warning("✗ %s failed to connect (profile: %s)", platform.value, profile_name) - await self._safe_adapter_disconnect(adapter, platform) - self._schedule_secondary_profile_startup_reconnect( - profile_name, platform, adapter - ) except Exception as e: logger.error("✗ %s error (profile: %s): %s", platform.value, profile_name, e) + success = False + if not success: await self._safe_adapter_disconnect(adapter, platform) - self._schedule_secondary_profile_startup_reconnect( - profile_name, platform, adapter - ) + self._schedule_secondary_profile_startup_reconnect(profile_name, platform, adapter) + continue + profile_map[platform] = adapter + # Restore persisted /voice state for this bot (primary startup and reconnects do too). + self._sync_voice_mode_state_to_adapter(adapter) + for claim in (credential_claim, listener_claim): + if claim is not None: + claimed[claim] = profile_name + connected += 1 + logger.info("✓ %s connected (profile: %s)", platform.value, profile_name) return connected - def _configure_profile_adapter( - self, - adapter: BasePlatformAdapter, - profile_name: str, - platform: Platform, + def _wire_adapter_handlers( + self, adapter: BasePlatformAdapter, *, message_handler=None, fatal_error_handler=None, + busy_session_handler=None, authorization_check=None, platform_event_handler=None, + busy_text_mode: Optional[str] = None, ) -> None: - """Install the profile-scoped handlers shared by startup and reconnect.""" - # Runtime status is process-scoped while message/config work is profile-scoped. Keep both - # dimensions in the key so dashboard/NAS health aggregation sees which secondary failed. - adapter._runtime_status_platform_key = f"{profile_name}:{platform.value}" - adapter.set_message_handler(self._make_profile_message_handler(profile_name)) - adapter.set_fatal_error_handler( - self._make_profile_fatal_error_handler(profile_name, platform) - ) + """Install the runner callbacks every adapter needs (defaults = primary handlers; + secondary wiring passes profile-scoped variants). ``set_reaction_handler`` is optional.""" + adapter.set_message_handler(message_handler or self._primary_message_handler()) + adapter.set_fatal_error_handler(fatal_error_handler or self._handle_adapter_fatal_error) adapter.set_session_store(self.session_store) - # Declare credential ownership BEFORE any inbound event can be handled: adapter-level - # session keys (batching, _active_sessions, busy guard) are derived at ingress, before the - # handler stamps source.profile — without this every secondary bot would key into the - # default profile's `agent:main:` lane (see BasePlatformAdapter._session_key_profile). - _set_owner = getattr(adapter, "set_owner_profile", None) - if callable(_set_owner): - _set_owner(profile_name) - adapter.set_busy_session_handler( - self._make_profile_busy_session_handler(profile_name) - ) + adapter.set_busy_session_handler(busy_session_handler or self._handle_active_session_busy_message) _set_reaction = getattr(adapter, "set_reaction_handler", None) if callable(_set_reaction): _set_reaction(self._handle_reaction_event) adapter.set_topic_recovery_fn(self._recover_telegram_topic_thread_id) adapter.set_authorization_check( - self._make_adapter_auth_check(platform, profile_name=profile_name) + authorization_check or self._make_adapter_auth_check(adapter.platform) ) - adapter.set_platform_event_handler( - self._make_profile_platform_event_handler(profile_name) - ) - # Voice transcripts from this bot's channels dispatch through THIS - # adapter (primary wiring lives at connect time; see #75198). - self._bind_voice_input_callback(adapter) + adapter.set_platform_event_handler(platform_event_handler or self._primary_platform_event_handler()) + adapter._busy_text_mode = (self._busy_text_mode if busy_text_mode is None else busy_text_mode) + + def _configure_profile_adapter( + self, adapter: BasePlatformAdapter, profile_name: str, platform: Platform + ) -> None: + """Install the profile-scoped handlers shared by startup and reconnect.""" + # Runtime status is process-scoped while message/config work is profile-scoped. Keep both + # dimensions in the key so dashboard/NAS health aggregation sees which secondary failed. + adapter._runtime_status_platform_key = f"{profile_name}:{platform.value}" + # Declare ownership BEFORE any inbound event: adapter-level session keys are derived at + # ingress, before the handler stamps source.profile — without this every secondary bot + # would key into the default profile's `agent:main:` lane. + _set_owner = getattr(adapter, "set_owner_profile", None) + if callable(_set_owner): + _set_owner(profile_name) text_modes = getattr(self, "_busy_text_modes_by_profile", None) - adapter._busy_text_mode = ( - text_modes.get(profile_name, self._busy_text_mode) - if isinstance(text_modes, dict) - else self._busy_text_mode + self._wire_adapter_handlers( + adapter, + message_handler=self._make_profile_message_handler(profile_name), + fatal_error_handler=self._make_profile_fatal_error_handler(profile_name, platform), + busy_session_handler=self._make_profile_busy_session_handler(profile_name), + authorization_check=self._make_adapter_auth_check(platform, profile_name=profile_name), + platform_event_handler=self._make_profile_platform_event_handler(profile_name), + busy_text_mode=( + text_modes.get(profile_name, self._busy_text_mode) + if isinstance(text_modes, dict) + else self._busy_text_mode + ), ) - # Secondary adapters always carry the profile they serve so prune - # paths namespace topic bindings correctly under multiplex (#76423). + # Voice transcripts from this bot's channels dispatch through THIS adapter (primary + # wiring lives at connect time). + self._bind_voice_input_callback(adapter) + # Secondary adapters always carry the profile they serve so prune paths namespace topic + # bindings correctly under multiplex. adapter._hermes_profile_name = profile_name - async def _run_secondary_profile_reconnect( - self, profile_name: str, platform: Platform - ) -> None: + async def _secondary_reconnect_attempt(self, profile_name: str, platform: Platform): + """One scoped attempt to rebuild+connect a secondary adapter → ``(adapter, success)``. + + ``(None, None)`` = give up for good (disabled, credential removed, adapter unavailable). + Caller tears down a RETURNED adapter; one whose configure/connect raised is torn down here. + """ + from gateway.run import _platform_has_bot_credential, _profile_runtime_scope + # Lazy + per-attempt: keeps test monkeypatches on these modules live. + from hermes_cli.profiles import get_profile_dir + from hermes_cli.env_loader import hydrate_profile_secret_sources + from gateway.config import load_gateway_config + profile_home = get_profile_dir(profile_name) + # Hydrate external secret sources off-loop so they cannot starve heartbeats. + await asyncio.to_thread(hydrate_profile_secret_sources, profile_home) + with _profile_runtime_scope(profile_home, hydrate_secrets=False): + profile_config = load_gateway_config().platforms.get(platform) + if profile_config is None or not profile_config.enabled: + return None, None + # Startup credential gate mirror: a removed credential must not rebuild. + if not _platform_has_bot_credential(platform, profile_config): + logger.info( + "Secondary %s reconnect skipped: no bot credential (profile: %s)", + platform.value, profile_name, + ) + return None, None + adapter = self._create_adapter(platform, profile_config) + if adapter is None: + logger.warning( + "Secondary %s reconnect skipped: adapter unavailable (profile: %s)", + platform.value, profile_name, + ) + return None, None + try: + self._configure_profile_adapter(adapter, profile_name, platform) + success = await self._connect_adapter_with_timeout(adapter, platform, is_reconnect=True) + except BaseException: + # Caller never sees this adapter; release its partial resources here. + await self._safe_adapter_disconnect(adapter, platform) + raise + return adapter, success + + async def _run_secondary_profile_reconnect(self, profile_name: str, platform: Platform) -> None: """Reconnect a retryable secondary adapter under its own profile scope.""" - from gateway.run import _platform_has_bot_credential, _profile_runtime_scope, _reconnect_backoff + from gateway.run import _reconnect_backoff attempts = 0 current_task = asyncio.current_task() try: while self._running: adapter = None try: - from hermes_cli.profiles import get_profile_dir - from hermes_cli.env_loader import hydrate_profile_secret_sources - from gateway.config import load_gateway_config - - profile_home = get_profile_dir(profile_name) - # Like the #16856 MCP discovery path, hydrate external secret - # sources off-loop so they cannot starve platform heartbeats. - await asyncio.to_thread( - hydrate_profile_secret_sources, profile_home - ) - with _profile_runtime_scope(profile_home, hydrate_secrets=False): - profile_config = load_gateway_config().platforms.get(platform) - if profile_config is None or not profile_config.enabled: - return - # Mirrors the startup credential gate: a credential removed from this - # profile's scope must not rebuild an adapter that would fan out turns. - if not _platform_has_bot_credential(platform, profile_config): - logger.info( - "Secondary %s reconnect skipped: no bot credential " - "(profile: %s)", - platform.value, - profile_name, - ) - return - adapter = self._create_adapter(platform, profile_config) - if adapter is None: - logger.warning( - "Secondary %s reconnect skipped: adapter unavailable (profile: %s)", - platform.value, - profile_name, - ) - return - self._configure_profile_adapter( - adapter, profile_name, platform - ) - success = await self._connect_adapter_with_timeout( - adapter, platform, is_reconnect=True - ) - + adapter, success = await self._secondary_reconnect_attempt(profile_name, platform) + if adapter is None: + return if success and self._running: profile_map = self._profile_adapters.setdefault(profile_name, {}) if platform not in profile_map: profile_map[platform] = adapter self._sync_voice_mode_state_to_adapter(adapter) - logger.info( - "✓ %s reconnected (profile: %s)", - platform.value, - profile_name, - ) + logger.info("✓ %s reconnected (profile: %s)", platform.value, profile_name) await self._redeliver_failed_obligations_for_platform( platform, profile=profile_name ) return - # A newer reconnect already won the slot while this - # attempt was awaiting connect; do not replace it. - await self._safe_adapter_disconnect(adapter, platform) - return - - # Shutdown can begin mid-connect(): never republish a newly connected adapter - # after the registry has been drained; release its partial resources instead. - if success: - await self._safe_adapter_disconnect(adapter, platform) - return - + # Not installed: a newer reconnect won the slot mid-connect (never replace it), + # shutdown began mid-connect (never republish after the registry drained), or + # connect failed. Release partial resources; stop only for a non-retryable fatal. await self._safe_adapter_disconnect(adapter, platform) - if ( + if success or ( getattr(adapter, "has_fatal_error", False) and not getattr(adapter, "fatal_error_retryable", True) ): @@ -1472,10 +1165,8 @@ class GatewayAdapterLifecycleMixin: if adapter is not None: await self._safe_adapter_disconnect(adapter, platform) logger.debug( - "Secondary %s reconnect attempt failed (profile: %s)", - platform.value, - profile_name, - exc_info=True, + "Secondary %s reconnect attempt failed (profile: %s)", platform.value, + profile_name, exc_info=True, ) if not self._running: @@ -1483,100 +1174,67 @@ class GatewayAdapterLifecycleMixin: attempts += 1 backoff = _reconnect_backoff(attempts) logger.info( - "Secondary %s reconnect retry in %ds (profile: %s)", - platform.value, - backoff, + "Secondary %s reconnect retry in %ds (profile: %s)", platform.value, backoff, profile_name, ) await asyncio.sleep(backoff) finally: + # Release our slot unless a newer task already owns it. pending = self._profile_failed_platforms - if isinstance(pending, dict): - profile_pending = pending.get(profile_name) - task = profile_pending.get(platform) if isinstance(profile_pending, dict) else None + profile_pending = pending.get(profile_name) if isinstance(pending, dict) else None + if isinstance(profile_pending, dict): + task = profile_pending.get(platform) if not isinstance(task, asyncio.Task) or task is current_task: - if isinstance(profile_pending, dict): - profile_pending.pop(platform, None) - if not profile_pending: - pending.pop(profile_name, None) + profile_pending.pop(platform, None) + if not profile_pending: + pending.pop(profile_name, None) def _schedule_secondary_profile_startup_reconnect( self, profile_name: str, platform: Platform, adapter: BasePlatformAdapter ) -> None: - """Queue a cold-start reconnect for a secondary adapter. - - Startup failures happen BEFORE ``self._running`` flips True, so the regular scheduler's - guard would drop the request. Park a task across startup and hand off to the scheduler once - live (``_profile_failed_platforms`` dedupes); release it if shutdown begins first. - Non-retryable failures are dropped as the regular scheduler would. - """ + """Queue a cold-start reconnect: startup failures happen BEFORE ``_running`` flips True (the + regular scheduler would drop them), so park a task and hand off once live.""" if not getattr(adapter, "fatal_error_retryable", True): return if is_global_startup_conflict(getattr(adapter, "fatal_error_code", None)): - # Same startup contract as the primary path: a live foreign holder of this profile's - # token/identity is an ownership conflict, not a transient blip. Park it fatal (like - # ``duplicate_credential``) instead of retry-storming the token every backoff. + # A live foreign holder of this profile's token is an ownership conflict, not a blip: + # park it fatal (like ``duplicate_credential``) instead of retry-storming. logger.error( "[MULTIPLEX] Profile '%s': %s credential is held by another " - "gateway (%s) — parked, not retried. %s", - profile_name, - platform.value, - adapter.fatal_error_code, - adapter.fatal_error_message or "", + "gateway (%s) — parked, not retried. %s", profile_name, platform.value, + adapter.fatal_error_code, adapter.fatal_error_message or "", ) self._update_platform_runtime_status( - f"{profile_name}:{platform.value}", - platform_state="fatal", - error_code=adapter.fatal_error_code, - error_message=adapter.fatal_error_message, + f"{profile_name}:{platform.value}", platform_state="fatal", + error_code=adapter.fatal_error_code, error_message=adapter.fatal_error_message, ) return + def _handoff() -> None: + try: + self._schedule_secondary_profile_reconnect(profile_name, platform, adapter) + except Exception: + # The handoff touches live registries; if it raises, the parked task dies as an + # unretrieved-task exception logged only at GC. Surface it where operators look. + logger.exception( + "secondary-startup-reconnect handoff failed (profile=%s platform=%s)", + profile_name, platform.value, + ) + async def _await_running_then_schedule() -> None: if self._running: - try: - self._schedule_secondary_profile_reconnect( - profile_name, platform, adapter - ) - except Exception: - # Same GC-time-exception hazard as the post-poll handoff - # below; surface it in gateway.log instead. - logger.exception( - "secondary-startup-reconnect handoff failed " - "(profile=%s platform=%s)", - profile_name, - platform.value, - ) + _handoff() return - # Modest poll: startup completion has no dedicated event, and the reconnect runner's own - # backoff makes sub-100ms precision irrelevant. Bounded so a wedged startup cannot spin. + # Poll (startup completion has no event); bounded so a wedged startup cannot spin. while not self._running and not self._shutdown_event.is_set(): await asyncio.sleep(0.1) if self._running and not self._shutdown_event.is_set(): - try: - self._schedule_secondary_profile_reconnect( - profile_name, platform, adapter - ) - except Exception: - # The handoff touches live registries; if it raises, the parked task dies as an - # unretrieved-task exception logged only at GC. Surface it where operators look. - logger.exception( - "secondary-startup-reconnect handoff failed " - "(profile=%s platform=%s)", - profile_name, - platform.value, - ) + _handoff() - task = asyncio.create_task( + self._retain_background_task(asyncio.create_task( _await_running_then_schedule(), name=f"secondary-startup-reconnect:{profile_name}:{platform.value}", - ) - background_tasks = getattr(self, "_background_tasks", None) - if not isinstance(background_tasks, set): - background_tasks = set() - self._background_tasks = background_tasks - background_tasks.add(task) - task.add_done_callback(background_tasks.discard) + )) def _schedule_secondary_profile_reconnect( self, profile_name: str, platform: Platform, adapter: BasePlatformAdapter @@ -1586,49 +1244,30 @@ class GatewayAdapterLifecycleMixin: return pending = self._profile_failed_platforms if not isinstance(pending, dict): - pending = {} - self._profile_failed_platforms = pending + pending = self._profile_failed_platforms = {} profile_pending = pending.setdefault(profile_name, {}) if platform in profile_pending: return - task = asyncio.create_task( + profile_pending[platform] = self._retain_background_task(asyncio.create_task( self._run_secondary_profile_reconnect(profile_name, platform), name=f"secondary-reconnect:{profile_name}:{platform.value}", - ) - profile_pending[platform] = task - background_tasks = getattr(self, "_background_tasks", None) - if not isinstance(background_tasks, set): - background_tasks = set() - self._background_tasks = background_tasks - background_tasks.add(task) - task.add_done_callback(background_tasks.discard) + )) def _make_profile_fatal_error_handler( self, profile_name: str, platform: Platform ) -> Callable[[BasePlatformAdapter], Awaitable[None]]: """Route a secondary-profile fatal error to that profile's reconnect slot.""" - async def _handler(adapter: BasePlatformAdapter) -> None: - await self._handle_profile_adapter_fatal_error(profile_name, platform, adapter) - - return _handler + return functools.partial(self._handle_profile_adapter_fatal_error, profile_name, platform) async def _handle_profile_adapter_fatal_error( - self, - profile_name: str, - platform: Platform, - adapter: BasePlatformAdapter, + self, profile_name: str, platform: Platform, adapter: BasePlatformAdapter ) -> None: - """Remove a failed multiplexed adapter without touching the primary slot. - - Secondaries live in ``_profile_adapters``, which the primary-only fatal handler ignores; - without this route a fatal secondary Discord client stayed live forever. - """ + """Remove a failed multiplexed adapter (the primary-only fatal handler ignores them).""" profile_map = getattr(self, "_profile_adapters", {}).get(profile_name) if not isinstance(profile_map, dict) or profile_map.get(platform) is not adapter: logger.debug( "Ignoring stale fatal error from secondary %s adapter (profile: %s)", - platform.value, - profile_name, + platform.value, profile_name, ) return profile_map.pop(platform, None) @@ -1637,94 +1276,87 @@ class GatewayAdapterLifecycleMixin: return self._schedule_secondary_profile_reconnect(profile_name, platform, adapter) logger.error( - "Fatal %s adapter error for multiplexed profile %s (%s)", - platform.value, - profile_name, + "Fatal %s adapter error for multiplexed profile %s (%s)", platform.value, profile_name, adapter.fatal_error_code or "unknown", ) - def _make_profile_message_handler(self, profile_name: str): - """Return a message handler that stamps source.profile then delegates. - - Auth runs inside ``_handle_message`` *before* the agent-turn scope is installed. For - secondary profiles under multiplex, wrap the whole handler in ``_profile_runtime_scope`` - so allowlists/tokens from that profile's ``.env`` are visible to ``get_secret`` / authz. - """ - from gateway.run import _async_profile_runtime_scope + @staticmethod + def _profile_home_or_none(profile_name: str): from hermes_cli.profiles import get_profile_dir - try: - profile_home = get_profile_dir(profile_name) + return get_profile_dir(profile_name) except Exception: - profile_home = None + return None + + @staticmethod + def _stamp_event_profile(event, profile_name: str) -> None: + """Best-effort: stamp ``source.profile`` on an inbound event that has none yet.""" + try: + if getattr(event, "source", None) is not None and not event.source.profile: + event.source.profile = profile_name + except Exception: + pass + + def _make_profile_message_handler(self, profile_name: str): + """Message handler that stamps source.profile, then delegates under the profile scope + (auth runs BEFORE the agent-turn scope, so the profile's ``.env`` must be visible here).""" + from gateway.run import _async_profile_runtime_scope + profile_home = self._profile_home_or_none(profile_name) async def _handler(event): - try: - if getattr(event, "source", None) is not None and not event.source.profile: - event.source.profile = profile_name - except Exception: - pass - if profile_home is not None: - async with _async_profile_runtime_scope(profile_home): - return await self._handle_message(event) - return await self._handle_message(event) + self._stamp_event_profile(event, profile_name) + async with ( + _async_profile_runtime_scope(profile_home) if profile_home is not None + else contextlib.nullcontext() + ): + return await self._handle_message(event) return _handler def _make_profile_busy_session_handler(self, profile_name: str): """Stamp an owning adapter's profile before resolving busy policy.""" async def _handler(event, _session_key): - try: - if getattr(event, "source", None) is not None and not event.source.profile: - event.source.profile = profile_name - except Exception: - pass + self._stamp_event_profile(event, profile_name) routed_session_key = self._session_key_for_source(event.source) - return await self._handle_active_session_busy_message( - event, routed_session_key - ) + return await self._handle_active_session_busy_message(event, routed_session_key) return _handler def _make_default_profile_message_handler(self): - """Scope primary-adapter messages to their routed multiplex profile. - - Resolve the home per event so session lookup and transcript loading use the same profile - store as the agent run. Authorization stays with the transport profile (a routed profile - may intentionally have no bot credential/allowlist): the transport home is preserved on the - live source and never re-checked against the routed scope. Unrouted events keep the default. - """ + """Scope primary-adapter messages to their routed multiplex profile. Authorization stays + with the transport profile (a routed profile may have no credential/allowlist).""" from gateway.run import _async_profile_runtime_scope, get_hermes_home default_home = Path(get_hermes_home()) async def _handler(event): source = event.source - # In-process only (SessionSource serialization ignores dynamic attrs). The route selects - # agent/session state, not which bot admitted the message — separate trust domains. + # In-process only (serialization ignores dynamic attrs); route ≠ admitting bot. source._authorization_profile_home = default_home if ( not getattr(source, "profile", None) and getattr(source, "profile_route_rejected", False) is not True + and not self._stamp_routed_profile(source) ): - from gateway.profile_routing import ProfileRouteRejected - - try: - source.profile = self._profile_name_for_source(source) - except ProfileRouteRejected: - # NOT write-only: the ``_handle_message`` ingress gate reads this exact marker - # and drops the message fail-closed (explicit route to an unserved profile). - source.profile_route_rejected = True - + # Read by the ``_handle_message`` ingress gate, which drops fail-closed. + source.profile_route_rejected = True profile_home = ( self._resolve_profile_home_for_source(source) - if getattr(source, "profile", None) - else default_home + if getattr(source, "profile", None) else default_home ) async with _async_profile_runtime_scope(profile_home): return await self._handle_message(event) return _handler + def _stamp_routed_profile(self, source) -> bool: + """Stamp ``source.profile`` from ``profile_routes``; False when the route is rejected.""" + from gateway.profile_routing import ProfileRouteRejected + try: + source.profile = self._profile_name_for_source(source) + except ProfileRouteRejected: + return False + return True + def _primary_message_handler(self): """Return the correctly scoped handler for a primary adapter.""" if getattr(self.config, "multiplex_profiles", False): @@ -1735,12 +1367,8 @@ class GatewayAdapterLifecycleMixin: """Authorize and publish one normalized adapter event to plugin hooks.""" try: from hermes_cli.lifecycle import has_hook, invoke_hook - - if not has_hook("gateway_platform_event"): - return - if not self._is_user_authorized_for_source(source): - return - invoke_hook("gateway_platform_event", **event) + if has_hook("gateway_platform_event") and self._is_user_authorized_for_source(source): + invoke_hook("gateway_platform_event", **event) except Exception: # Observer failures must never break the adapter's update loop. logger.debug("gateway_platform_event hook dispatch failed", exc_info=True) @@ -1748,20 +1376,16 @@ class GatewayAdapterLifecycleMixin: def _make_profile_platform_event_handler(self, profile_name: str): """Bind platform-event auth and hook dispatch to one multiplex profile.""" from gateway.run import _profile_runtime_scope - from hermes_cli.profiles import get_profile_dir - - try: - profile_home = get_profile_dir(profile_name) - except Exception: - profile_home = None + profile_home = self._profile_home_or_none(profile_name) async def _handler(event, source): if getattr(source, "profile", None) is None: source.profile = profile_name - if profile_home is not None: - with _profile_runtime_scope(profile_home): - return await self._handle_gateway_platform_event(event, source) - return await self._handle_gateway_platform_event(event, source) + with ( + _profile_runtime_scope(profile_home) if profile_home is not None + else contextlib.nullcontext() + ): + return await self._handle_gateway_platform_event(event, source) return _handler @@ -1783,188 +1407,103 @@ class GatewayAdapterLifecycleMixin: return self._handle_gateway_platform_event @staticmethod - def _adapter_credential_claim( - platform: Platform, adapter: Any - ) -> Optional[tuple]: + def _adapter_credential_claim(platform: Platform, adapter: Any) -> Optional[tuple]: """Return the exclusive credential resource claimed by an adapter.""" from gateway.run import GatewayRunner fingerprint = GatewayRunner._adapter_credential_fingerprint(adapter) - if fingerprint is None: - return None - return (platform, fingerprint) + return None if fingerprint is None else (platform, fingerprint) @staticmethod def _adapter_listener_claim(platform: Platform, adapter: Any) -> Optional[tuple]: - """Return the exclusive listener resource claimed by an adapter. - - Sidecars with different credentials still cannot share a bind+port; expose it as a claim so - multiplex startup rejects the later adapter before connect()/disconnect() disturb the first. - """ - if getattr(platform, "value", None) != "photon": - return None + """Exclusive listener claim (Photon sidecar bind+port): distinct credentials still cannot + share a port, so the later adapter is rejected before connect() disturbs the first.""" bind = getattr(adapter, "_sidecar_bind", None) - port = getattr(adapter, "_sidecar_port", None) - if not isinstance(bind, str) or not bind.strip(): + if getattr(platform, "value", None) != "photon" or not isinstance(bind, str) or not bind.strip(): return None try: - port = int(port) + port = int(getattr(adapter, "_sidecar_port", None)) except (TypeError, ValueError): return None return ("listener", "photon", bind.strip().lower(), port) @staticmethod def _adapter_credential_fingerprint(adapter: Any) -> Optional[str]: - """Return a stable, log-safe fingerprint of an adapter's credential. - - Salted hash (never the credential) used to detect two profiles sharing one platform - credential; None when no credential is discoverable (conflict detection is then skipped). - """ - token = None - for attr in ( - "token", - "bot_token", - "_token", - "api_token", - "_bot_token", - # Photon/Spectrum authenticates with project credentials, not a bot token; including - # its secret stops multiplexed profiles spawning rival sidecars for one account/port. - "_project_secret", - # Feishu/Lark authenticates with an app_id/app_secret pair (one WebSocket per app). - # app_id is stable, log-safe and already the adapter's _app_lock_identity, so including - # it lets the multiplex guard refuse cloned profiles competing for the same app. - "_app_id", - # Same class: Teams (client_id/client_secret) and WeCom - # (bot_id/secret) authenticate with an app-style id pair too. - "_client_id", - "_bot_id", - ): - val = getattr(adapter, attr, None) + """Salted, log-safe hash of an adapter's credential; None when none is discoverable + (conflict detection is then skipped).""" + # Many adapters (e.g. Discord) keep the token on `config`; without that fallback the + # same-token check is silently skipped and every profile polls the same bot. + candidates = [ + (adapter, attr) for attr in ( + "token", "bot_token", "_token", "api_token", "_bot_token", + "_project_secret", # Photon/Spectrum: project credentials, not a bot token + "_app_id", # Feishu/Lark app_id — stable, log-safe, already the _app_lock_identity + "_client_id", "_bot_id", # Teams / WeCom app-style id pairs + ) + ] + [(getattr(adapter, "config", None), attr) for attr in ("token", "bot_token")] + for obj, attr in candidates: + val = getattr(obj, attr, None) if isinstance(val, str) and val.strip(): - token = val.strip() - break - # Many adapters (e.g. Discord) store the token on their `config` sub-object. Without this - # lookup they return None, the same-token check is silently skipped, and every profile's - # adapter polls the same bot token — a per-message race over which one answers. - if not token: - cfg = getattr(adapter, "config", None) - if cfg is not None: - for attr in ("token", "bot_token"): - val = getattr(cfg, attr, None) - if isinstance(val, str) and val.strip(): - token = val.strip() - break - if not token: - config = getattr(adapter, "config", None) - val = getattr(config, "token", None) - if isinstance(val, str) and val.strip(): - token = val.strip() - if not token: - return None - import hashlib - return hashlib.sha256(("hermes-mux:" + token).encode("utf-8")).hexdigest()[:16] + import hashlib + return hashlib.sha256(("hermes-mux:" + val.strip()).encode("utf-8")).hexdigest()[:16] + return None - def _create_adapter( - self, - platform: Platform, - config: Any, - ) -> Optional[BasePlatformAdapter]: - """Create an adapter and bind it to this gateway runner. - - Every lifecycle path (primary/secondary startup, reconnect) uses this method; keep runner - binding here so adapters can resolve inbound profile routes before handlers or connect(). - """ + def _create_adapter(self, platform: Platform, config: Any) -> Optional[BasePlatformAdapter]: + """Create an adapter bound to this runner (every lifecycle path goes through here so + adapters can resolve inbound profile routes before handlers or connect()).""" adapter = self._instantiate_adapter(platform, config) if adapter is not None: adapter.gateway_runner = self return adapter - def _instantiate_adapter( - self, - platform: Platform, - config: Any, - ) -> Optional[BasePlatformAdapter]: - """Instantiate the appropriate adapter for a platform. - - Checks platform_registry (plugin adapters) first, then the built-in table of core platforms. - """ + def _instantiate_adapter(self, platform: Platform, config: Any) -> Optional[BasePlatformAdapter]: + """Instantiate the adapter for a platform: plugin registry first, then built-ins.""" from gateway.run import _instantiate_builtin_adapter if hasattr(config, "extra") and isinstance(config.extra, dict): + config.extra.setdefault("group_sessions_per_user", self.config.group_sessions_per_user) config.extra.setdefault( - "group_sessions_per_user", - self.config.group_sessions_per_user, - ) - config.extra.setdefault( - "thread_sessions_per_user", - getattr(self.config, "thread_sessions_per_user", False), + "thread_sessions_per_user", getattr(self.config, "thread_sessions_per_user", False) ) - # ── Plugin-registered platforms (checked first) ─────────────────── try: from gateway.platform_registry import platform_registry if platform_registry.is_registered(platform.value): adapter = platform_registry.create_adapter(platform.value, config) - if adapter is not None: - return adapter - # Registered but failed to instantiate — don't silently fall - # through to built-ins (there are none for plugin platforms). - logger.error( - "Platform '%s' is registered but adapter creation failed " - "(check dependencies and config)", - platform.value, - ) - return None + if adapter is None: # registered but failed — never fall through to built-ins + logger.error( + "Platform '%s' is registered but adapter creation failed " + "(check dependencies and config)", platform.value, + ) + return adapter except Exception as e: logger.debug("Platform registry lookup for '%s' failed: %s", platform.value, e) - # Fall through to built-in adapters below - return _instantiate_builtin_adapter(platform, config) def _make_adapter_auth_check( - self, - platform: Platform, - profile_name: Optional[str] = None, + self, platform: Platform, profile_name: Optional[str] = None ) -> Callable[[str, Optional[str], Optional[str]], bool]: - """Build a platform-bound auth callback for adapter use. - - Adapters fetching external context (e.g. Slack ``conversations.replies``) use it via - ``_is_sender_authorized`` to mark non-allowlisted senders unverified (prompt-injection - mitigation). Delegates to :meth:`_is_user_authorized` so the full auth chain stays the single - source of truth. ``profile_name`` binds a secondary adapter to its own secret scope; for the - shared primary (None) the ``profile_routes`` match is stamped on the source so the routed - profile's pairing store is consulted while allowlist reads stay under the transport home. - """ + """Platform-bound auth callback for adapters (prompt-injection mitigation for fetched + context); delegates to :meth:`_is_user_authorized`. ``profile_name`` binds a secondary to + its scope; for the shared primary (None) the routed profile is stamped so its pairing store + is consulted while allowlist reads stay under the transport home.""" from gateway.run import get_hermes_home multiplex = bool(getattr(self.config, "multiplex_profiles", False)) - transport_home = ( - Path(get_hermes_home()) if multiplex and profile_name is None else None - ) + transport_home = (Path(get_hermes_home()) if multiplex and profile_name is None else None) def check( - user_id: str, - chat_type: Optional[str] = None, - chat_id: Optional[str] = None, - *, - is_bot: bool = False, - thread_id: Optional[str] = None, + user_id: str, chat_type: Optional[str] = None, chat_id: Optional[str] = None, *, + is_bot: bool = False, thread_id: Optional[str] = None, ) -> bool: if not user_id: return False source = SessionSource( - platform=platform, - chat_id=chat_id or "", - chat_type=chat_type or "group", - user_id=user_id, - thread_id=thread_id, - is_bot=bool(is_bot), - profile=profile_name, + platform=platform, chat_id=chat_id or "", chat_type=chat_type or "group", + user_id=user_id, thread_id=thread_id, is_bot=bool(is_bot), profile=profile_name, ) - # Same in-process transport provenance ``build_source`` retains, so adapter-level policy - # reads (config.yaml group_allowed_chats, allow_from) resolve the receiving adapter even - # once the routed profile is stamped below. + # Same transport provenance ``build_source`` retains, so adapter-level policy reads + # resolve the receiving adapter even once the routed profile is stamped below. registry = ( (getattr(self, "_profile_adapters", None) or {}).get(profile_name) - if profile_name - else getattr(self, "adapters", None) + if profile_name else getattr(self, "adapters", None) ) or {} adapter = registry.get(platform) if adapter is not None: @@ -1972,13 +1511,7 @@ class GatewayAdapterLifecycleMixin: if transport_home is None: return self._is_user_authorized(source) source._authorization_profile_home = transport_home - from gateway.profile_routing import ProfileRouteRejected - - try: - source.profile = self._profile_name_for_source(source) - except ProfileRouteRejected: - # Same fail-closed outcome as the ingress gate in - # ``_handle_message`` for a route to an unserved profile. - return False + if not self._stamp_routed_profile(source): + return False # fail-closed, like the ``_handle_message`` ingress gate return self._is_user_authorized_for_source(source) return check diff --git a/gateway/run_busy.py b/gateway/run_busy.py index 53946c7587..a332b66504 100644 --- a/gateway/run_busy.py +++ b/gateway/run_busy.py @@ -1,8 +1,8 @@ -"""Busy-session queueing, slot claims, slash dispatch tables and destructive-slash confirmation for GatewayRunner. +"""Busy-session queueing, slot claims, slash dispatch tables and destructive-slash confirmation +for GatewayRunner (mixin bound via the MRO). -Split out of ``gateway/run.py``; bound onto ``GatewayRunner`` via the MRO. -``gateway.run`` internals are imported lazily inside method bodies (import cycle), -so ``patch("gateway.run.X")`` keeps intercepting them at call time. +``gateway.run`` internals are imported lazily inside method bodies (import cycle), so +``patch("gateway.run.X")`` keeps intercepting them at call time. """ from __future__ import annotations @@ -10,6 +10,7 @@ from __future__ import annotations import logging from typing import TYPE_CHECKING import asyncio +import contextlib import json import os import time @@ -27,105 +28,83 @@ logger = logging.getLogger("gateway.run") class GatewayBusySessionMixin: - """Busy-session queueing, slot claims, slash dispatch tables and destructive-slash confirmation for GatewayRunner.""" + """Busy-session queueing, slot claims, slash dispatch tables, destructive-slash confirmation.""" - def _queue_during_drain_enabled( - self, busy_input_mode: Optional[str] = None - ) -> bool: - # "queue" and "steer" both mean messages must not be lost across restart: queue them for - # the newly-spawned gateway process to pick up. "interrupt" mode drops them. + def _queue_during_drain_enabled(self, busy_input_mode: Optional[str] = None) -> bool: + # "queue"/"steer" mean messages survive a restart (queued for the new process); "interrupt" drops. mode = busy_input_mode or self._busy_input_mode return self._restart_requested and mode in {"queue", "steer"} + def _overflow_queue(self, session_key: str): + """The session's FIFO overflow list, or None when no session state exists yet.""" + state = self._peek_session_state(session_key) + return state.conversation.queued_events if state else None + def _enqueue_fifo(self, session_key: str, queued_event: "MessageEvent", adapter: Any) -> None: """Append a /queue event to the FIFO chain for a session.""" - if adapter is None: - return - pending_slot = getattr(adapter, "_pending_messages", None) + pending_slot = getattr(adapter, "_pending_messages", None) if adapter is not None else None if pending_slot is None: return if session_key in pending_slot: - self._session_state(session_key).conversation.queued_events.append( - queued_event - ) + self._session_state(session_key).conversation.queued_events.append(queued_event) else: pending_slot[session_key] = queued_event def _promote_queued_event( - self, - session_key: str, - adapter: Any, - pending_event: Optional["MessageEvent"], + self, session_key: str, adapter: Any, pending_event: Optional["MessageEvent"] ) -> Optional["MessageEvent"]: - """Promote the next overflow item after the slot was drained. + """Promote the next overflow item after the slot drained. - If pending_event is None, return the overflow head as the new pending_event; if the slot is - already populated (interrupt follow-up etc.), stage the head there for the NEXT recursion. - Returns the (possibly updated) pending_event. + ``pending_event`` None → the overflow head becomes the pending event; otherwise the head is + staged into the slot for the NEXT recursion. Returns the (possibly updated) pending_event. """ - _q_state = self._peek_session_state(session_key) - overflow = _q_state.conversation.queued_events if _q_state else None + overflow = self._overflow_queue(session_key) if not overflow: return pending_event - next_queued = overflow.pop(0) if pending_event is None: - return next_queued + return overflow.pop(0) if adapter is not None and hasattr(adapter, "_pending_messages"): - adapter._pending_messages[session_key] = next_queued - else: - # No adapter — push back so we don't silently drop the item. - overflow.insert(0, next_queued) + adapter._pending_messages[session_key] = overflow.pop(0) + # else: no adapter — leave the head in place so we don't silently drop it. return pending_event def _queue_depth(self, session_key: str, *, adapter: Any = None) -> int: """Total pending /queue items for a session — slot + overflow.""" - _q_state = self._peek_session_state(session_key) - depth = len(_q_state.conversation.queued_events) if _q_state else 0 + depth = len(self._overflow_queue(session_key) or ()) if adapter is not None and session_key in getattr(adapter, "_pending_messages", {}): depth += 1 return depth - def _rescue_orphaned_overflow( - self, session_key: str, adapter: Any - ) -> Optional["MessageEvent"]: - """Pop the oldest orphaned FIFO overflow event for an idle session. + def _rescue_orphaned_overflow(self, session_key: str, adapter: Any) -> Optional["MessageEvent"]: + """Pop the oldest orphaned FIFO overflow event for an idle session (None if nothing to rescue). - ``queued_events`` drains only at the post-turn promotion site in ``_run_agent``; if a busy - window ends without that drain (early recursion exit, exception/interrupt/generation-bump), - the overflow is silently orphaned. Called when a NEW event arrives for a NON-busy session: - the oldest orphan is returned to run as THIS turn, the next is staged into the slot so the - chain continues in arrival order, and the caller enqueues the incoming event behind it. The - returned event is REMOVED from both stores, else the post-turn dequeue would run it twice. - Returns ``None`` when there is nothing to rescue (no overflow, slot occupied, or no slot). + ``queued_events`` drains only at the post-turn promotion site; a busy window ending without + it (early exit, exception/interrupt/generation-bump) orphans the overflow. On a NEW event for + a NON-busy session the oldest orphan runs as THIS turn, the next is staged into the slot so + arrival order holds, and the caller enqueues the incoming event behind it. The returned + event is REMOVED from both stores, else the post-turn dequeue would run it twice. """ try: - _q_state = self._peek_session_state(session_key) - overflow = _q_state.conversation.queued_events if _q_state else None + overflow = self._overflow_queue(session_key) if not overflow: return None pending_slot = getattr(adapter, "_pending_messages", None) if not isinstance(pending_slot, dict) or pending_slot.get(session_key): - # Slot occupied (busy) or no slot storage — promotion owns - # this; do not fight it from the idle path. - return None + return None # slot occupied (busy) or no slot storage — promotion owns this head = overflow.pop(0) - # Keep the slot occupied for the rest of the chain so the drain promotes in order and - # any mid-chain arrival routes to overflow instead of jumping the queue (same invariant - # as the drain's own _promote_queued_event). Only ONE event fits the slot. + # Keep the slot occupied so the drain promotes in order and a mid-chain arrival routes + # to overflow instead of jumping the queue (same invariant as _promote_queued_event). if overflow: pending_slot[session_key] = overflow.pop(0) logger.warning( "Rescued orphaned FIFO overflow event for idle session " "%s — it was queued during a busy window but the post-turn " - "drain never promoted it (#99882)", - session_key, + "drain never promoted it (#99882)", session_key, ) if overflow: logger.warning( "%d overflow event(s) still queued for session %s after " - "rescue staging (will drain via normal promotion)", - len(overflow), - session_key, + "rescue staging (will drain via normal promotion)", len(overflow), session_key, ) return head except Exception: @@ -134,20 +113,12 @@ class GatewayBusySessionMixin: @staticmethod def _is_goal_continuation_event(event_or_text: Any) -> bool: - """Return True for synthetic /goal continuation turns. - - Goal continuations are normal queued user-role events, so pause/clear must distinguish - them from real user /queue messages before removing or suppressing them. - """ + """True for synthetic /goal continuation turns (so pause/clear can spare real /queue items).""" text = getattr(event_or_text, "text", event_or_text) or "" return str(text).startswith("[Continuing toward your standing goal]\nGoal:") def _clear_goal_pending_continuations(self, session_key: str, adapter: Any) -> int: - """Remove queued synthetic /goal continuations for one session. - - User /goal pause/clear can race a judge-queued continuation; only synthetic goal - continuations are removed, normal /queue and user follow-up events are preserved. - """ + """Remove queued synthetic /goal continuations for one session; real /queue items are kept.""" removed = 0 pending_slot = getattr(adapter, "_pending_messages", None) if adapter is not None else None if isinstance(pending_slot, dict): @@ -156,16 +127,11 @@ class GatewayBusySessionMixin: pending_slot.pop(session_key, None) removed += 1 - _q_state = self._peek_session_state(session_key) - overflow = _q_state.conversation.queued_events if _q_state else [] + overflow = self._overflow_queue(session_key) if overflow: - kept = [] - for queued_event in overflow: - if self._is_goal_continuation_event(queued_event): - removed += 1 - else: - kept.append(queued_event) - _q_state.conversation.queued_events = kept + kept = [e for e in overflow if not self._is_goal_continuation_event(e)] + removed += len(overflow) - len(kept) + self._peek_session_state(session_key).conversation.queued_events = kept return removed def _goal_still_active_for_session(self, session_id: str) -> bool: @@ -183,7 +149,6 @@ class GatewayBusySessionMixin: """Return the configured active chat session cap, if enabled.""" try: from hermes_cli.active_sessions import resolve_max_concurrent_sessions - return resolve_max_concurrent_sessions(getattr(self, "config", None)) except Exception: return None @@ -191,31 +156,25 @@ class GatewayBusySessionMixin: def _active_session_limit_message(self, session_key: str) -> Optional[str]: """Return a user-facing rejection when starting a new session exceeds the cap.""" max_sessions = self._get_max_concurrent_sessions() - if max_sessions is None: - return None - if self._is_session_running(session_key): + if max_sessions is None or self._is_session_running(session_key): return None active_count = self._running_agent_count() if active_count < max_sessions: return None from hermes_cli.active_sessions import active_session_limit_message - return active_session_limit_message(active_count, max_sessions) def _claim_active_session_slot( - self, - session_key: str, - source: SessionSource, + self, session_key: str, source: SessionSource ) -> tuple[Any, Optional[str]]: """Claim a cross-process active-session slot for a new gateway turn.""" if self._is_session_running(session_key): return None, None - local_limit_message = self._active_session_limit_message(session_key) - if local_limit_message is not None: - return None, local_limit_message + limit_message = self._active_session_limit_message(session_key) + if limit_message is not None: + return None, limit_message try: from hermes_cli.active_sessions import try_acquire_active_session - platform = source.platform.value if source and source.platform else "gateway" return try_acquire_active_session( session_id=session_key, @@ -225,9 +184,8 @@ class GatewayBusySessionMixin: "platform": platform, "chat_id": getattr(source, "chat_id", "") or "", "user_id": getattr(source, "user_id", "") or "", - # Writer identity for re-entrancy: if this process leaks a lease for this session - # (exception path skipped release), the next turn re-acquires its own entry rather - # than being fenced out forever — pruning only reclaims entries whose PROCESS died. + # Writer identity: a leaked lease from this process is re-acquired by the next + # turn rather than fencing it out forever (pruning only reclaims dead PROCESSES). "live_session_id": str(session_key), }, ) @@ -237,43 +195,36 @@ class GatewayBusySessionMixin: @staticmethod def _agent_has_active_subagents(running_agent: Any) -> bool: - """Return True when *running_agent* is driving subagents via ``delegate_task``. - - ``AIAgent.interrupt()`` cascades through ``_active_children`` and aborts in-flight subagent - work, so callers demote ``busy_input_mode='interrupt'`` to ``queue`` while this is True; - explicit ``/stop`` is untouched. Fail-safe: returns False on any attribute/lock error. - """ + """True when *running_agent* is driving subagents (callers demote interrupt → queue; + ``interrupt()`` would cascade through ``_active_children``). Fail-safe False on any error.""" from gateway.run import _AGENT_PENDING_SENTINEL if running_agent is None or running_agent is _AGENT_PENDING_SENTINEL: return False children = getattr(running_agent, "_active_children", None) - # AIAgent always initialises this as a concrete list. Reject anything that isn't a real - # collection — guards against ``MagicMock()._active_children`` auto-creating a truthy stub - # in tests and triggering the demotion for an agent with no subagents. - if not isinstance(children, (list, tuple, set)): - return False - if not children: + # Real collections only — a ``MagicMock()._active_children`` auto-attr must not demote. + if not isinstance(children, (list, tuple, set)) or not children: return False lock = getattr(running_agent, "_active_children_lock", None) try: - if lock is not None: - with lock: - return bool(children) - return bool(children) + with lock if lock is not None else contextlib.nullcontext(): + return bool(children) except Exception: return False async def _session_has_compression_in_flight(self, session_key: str) -> bool: - """Return True when a compression lock is held for this session's id. - - Gateway ``interrupt`` busy mode could start a follow-up against the pre-rotation parent while - compression is mid-flight, producing orphaned compression siblings; callers demote interrupt - to queue when True. Both blocking sources (``session_store`` lock + JSON load, SQLite lock - holder SELECT) run in a worker thread so a large state.db never freezes the event loop. - """ + """True when a compression lock is held for this session's id (callers demote interrupt → + queue, else a follow-up against the pre-rotation parent orphans compression siblings). + Both blocking reads run in a worker thread so a large state.db never freezes the loop.""" session_store = getattr(self, "session_store", None) if not session_key or session_store is None: return False + def _assume_active(what: str, ident) -> bool: + logger.warning( + "Compression in-flight check failed while reading %s %s; treating compression as " + "active to avoid interrupting a possible parent-session rotation", what, ident, exc_info=True, + ) + return True + try: session_id = await asyncio.to_thread( self._lookup_session_id_under_store_lock, session_store, session_key @@ -281,38 +232,20 @@ class GatewayBusySessionMixin: except (AttributeError, TypeError): return False except Exception: - logger.warning( - "Compression in-flight check failed while reading session %s; " - "treating compression as active to avoid interrupting a possible " - "parent-session rotation", - session_key, - exc_info=True, - ) - return True - if not session_id: - return False + return _assume_active("session", session_key) session_db = getattr(self, "_session_db", None) - if session_db is None: + if not session_id or session_db is None: return False raw_db = getattr(session_db, "_db", session_db) try: - holder = await asyncio.to_thread( - raw_db.get_compression_lock_holder, str(session_id) - ) + holder = await asyncio.to_thread(raw_db.get_compression_lock_holder, str(session_id)) # Production returns Optional[str]. Reject non-strings so a MagicMock auto-attr (or any # unexpected truthy) cannot look like a held lock and skip hygiene. return isinstance(holder, str) and bool(holder) except (AttributeError, TypeError): return False except Exception: - logger.warning( - "Compression in-flight check failed while reading lock holder " - "for session %s; treating compression as active to avoid " - "interrupting a possible parent-session rotation", - session_id, - exc_info=True, - ) - return True + return _assume_active("lock holder for session", session_id) @staticmethod def _lookup_session_id_under_store_lock(session_store, session_key: str): @@ -323,23 +256,21 @@ class GatewayBusySessionMixin: entry = session_store._entries.get(session_key) # noqa: SLF001 return getattr(entry, "session_id", None) if entry is not None else None + # Metadata that must match for two pending events to merge into one slot. + _SECURITY_METADATA_KEYS = ( + "hermes_plugin_id", "hermes_plugin_injection", "gateway_session_key", + "gateway_session_id", "gateway_session_strict", + ) + def _queue_or_replace_pending_event(self, session_key: str, event: MessageEvent) -> None: from gateway.run import merge_pending_message_event adapter = self._adapter_for_source(event.source) if not adapter: return - # Route through the ``/queue`` FIFO infrastructure so each follow-up gets its own turn in - # arrival order (merge_text=False silently OVERWROTE the single pending slot). Photo bursts - # still merge into the head slot (album semantics); everything else appends to the tail. + # FIFO so each follow-up gets its own turn in arrival order (the single pending slot used to + # be silently OVERWRITTEN). Photo bursts still merge into the head slot (album semantics). pending_slot = getattr(adapter, "_pending_messages", None) existing = pending_slot.get(session_key) if isinstance(pending_slot, dict) else None - security_metadata_keys = ( - "hermes_plugin_id", - "hermes_plugin_injection", - "gateway_session_key", - "gateway_session_id", - "gateway_session_strict", - ) same_security_context = existing is not None and ( getattr(existing, "internal", False) == getattr(event, "internal", False) and getattr(existing, "allow_gateway_control", True) @@ -347,7 +278,7 @@ class GatewayBusySessionMixin: and all( (getattr(existing, "metadata", None) or {}).get(key) == (getattr(event, "metadata", None) or {}).get(key) - for key in security_metadata_keys + for key in self._SECURITY_METADATA_KEYS ) ) if same_security_context and ( @@ -358,9 +289,7 @@ class GatewayBusySessionMixin: ): # Preserve photo-burst / media-merge semantics for the head slot. merge_pending_message_event( - adapter._pending_messages, - session_key, - event, + adapter._pending_messages, session_key, event, merge_text=event.message_type == MessageType.TEXT, ) return @@ -368,37 +297,26 @@ class GatewayBusySessionMixin: if self._queue_depth(session_key, adapter=adapter) >= self._BUSY_QUEUE_MAX_PENDING: logger.warning( "Dropping busy-mode follow-up for session %s — pending queue at cap (%d).", - session_key, - self._BUSY_QUEUE_MAX_PENDING, + session_key, self._BUSY_QUEUE_MAX_PENDING, ) return self._enqueue_fifo(session_key, event, adapter) async def _prepare_busy_steer_text(self, event: MessageEvent) -> str: - """Return steerable text for a busy follow-up, transcribing voice first. + """Steerable text for a busy follow-up, transcribing voice-message media first. - Successful steer messages bypass the inbound STT queue, so without this a media-only voice - follow-up has empty text and steer silently degrades to queue mode. Only voice-message media - (not audio file attachments) is transcribed; on failure keep any caption and let the steer - fallback handle it. Goes through ``_transcribe_and_echo_pending_voice`` — the single - out-of-band STT choke point — so STT runs at most once per message (cached on the event). + Steer bypasses the inbound STT queue, so a media-only voice follow-up would otherwise + silently degrade to queue mode. Uses the single out-of-band STT choke point, so STT runs at + most once per message; on failure the caption (if any) is kept. """ text = (event.text or "").strip() if not self._pending_event_audio_paths(event): return text - - adapter = self._adapter_for_source(event.source) enriched_text, successful_transcripts = await self._transcribe_and_echo_pending_voice( - event, - adapter, - event.source, - text, - log_context="Busy-steer", + event, self._adapter_for_source(event.source), event.source, text, log_context="Busy-steer" ) - if not successful_transcripts: - return text - return (enriched_text or text).strip() + return (enriched_text or text).strip() if successful_transcripts else text @staticmethod def _busy_reply_to(event: MessageEvent, reply_anchor): @@ -411,64 +329,57 @@ class GatewayBusySessionMixin: else (None if event.source.platform == Platform.TELEGRAM and event.source.thread_id else event.message_id) ) + async def _send_busy_reply(self, event: MessageEvent, adapter, content: str, *, plain_anchor: bool = False) -> None: + """Send a busy-path reply anchored to the event (thread metadata included).""" + reply_anchor = self._reply_anchor_for_event(event) + await adapter._send_with_retry( + chat_id=event.source.chat_id, content=content, + reply_to=reply_anchor if plain_anchor else self._busy_reply_to(event, reply_anchor), + metadata=self._thread_metadata_for_source(event.source, reply_anchor), + ) + async def _send_busy_drain_notice(self, event: MessageEvent, session_key: str, effective_mode: str) -> None: """Busy path while the gateway is restarting/stopping: queue (if allowed) and tell the user.""" adapter = self._adapter_for_source(event.source) if not adapter: return - - reply_anchor = self._reply_anchor_for_event(event) - thread_meta = self._thread_metadata_for_source(event.source, reply_anchor) if self._queue_during_drain_enabled(effective_mode): self._queue_or_replace_pending_event(session_key, event) message = f"⏳ Gateway {self._status_action_gerund()} — queued for the next turn after it comes back." else: message = f"⏳ Gateway is {self._status_action_gerund()} and is not accepting another turn right now." + await self._send_busy_reply(event, adapter, message) - await adapter._send_with_retry( - chat_id=event.source.chat_id, - content=message, - reply_to=self._busy_reply_to(event, reply_anchor), - metadata=thread_meta, - ) + # Bare-word approval replies → (verb, args) for the synthesized slash command. + _PLAINTEXT_APPROVAL_WORDS: Dict[str, tuple] = { + **{w: ("approve", "") for w in ("approve", "yes", "ok", "okay", "confirm", "y", "👍")}, + **{w: ("deny", "") for w in ("deny", "no", "reject", "cancel", "n", "👎")}, + **{w: ("approve", "always") for w in ("always", "approve always", "always approve")}, + **{w: ("approve", "session") for w in ("session", "approve session", "session approve")}, + } async def _route_plaintext_approval_while_busy(self, event: MessageEvent, session_key: str) -> bool: """Route a bare "yes"/"no" to the approval handlers while a dangerous-command approval blocks. Returns True when the message was consumed as an approval response. """ - # Approval routing: while blocked on a dangerous-command approval, a bare "yes" must reach the - # approval handler, not be steered/queued/interrupted (else it queues behind a turn that can't - # start until the approval resolves -> auto-deny deadlock). Slash forms already bypass at the - # base-adapter guard. Gated on has_blocking_approval so a conversational "yes" never fires a - # command. Reuse the /approve and /deny handlers; the busy path does not auto-send their return. + # A bare "yes" while blocked on a dangerous-command approval must reach the approval handler, + # not queue behind a turn that can't start until it resolves (auto-deny deadlock). Gated on + # has_blocking_approval so a conversational "yes" never fires a command. try: from tools.approval import has_blocking_approval if event.allow_gateway_control and has_blocking_approval(session_key): _raw_text = (event.text or "").strip().lower() - _approve_words = {"approve", "yes", "ok", "okay", "confirm", "y", "👍"} - _deny_words = {"deny", "no", "reject", "cancel", "n", "👎"} - _approval_handler = None - _normalized_args = "" - if _raw_text in _approve_words: - _approval_handler = self._handle_approve_command - elif _raw_text in _deny_words: - _approval_handler = self._handle_deny_command - elif _raw_text in {"always", "approve always", "always approve"}: - _approval_handler = self._handle_approve_command - _normalized_args = "always" - elif _raw_text in {"session", "approve session", "session approve"}: - _approval_handler = self._handle_approve_command - _normalized_args = "session" - if _approval_handler is not None: + _match = self._PLAINTEXT_APPROVAL_WORDS.get(_raw_text) + if _match is not None: + _verb, _normalized_args = _match + _approval_handler = ( + self._handle_approve_command if _verb == "approve" else self._handle_deny_command + ) # Synthesize "/approve [args]" / "/deny" so the slash handlers parse modifiers via # event.get_command_args(). Always a literal "/": is_command()/get_command_args() # don't recognize per-platform display prefixes ("!" on Slack/Matrix). - _verb = "approve" if _approval_handler is self._handle_approve_command else "deny" - _synth = f"/{_verb}" - if _normalized_args: - _synth = f"{_synth} {_normalized_args}" - event.text = _synth + event.text = f"/{_verb} {_normalized_args}".rstrip() _reply = await _approval_handler(event) logger.info( "Approval response via plain text: session=%s verb=%s args=%r", @@ -478,113 +389,76 @@ class GatewayBusySessionMixin: if _adapter and _reply: _text, _eph_ttl = _adapter._unwrap_ephemeral(_reply) if _text: - _anchor = self._reply_anchor_for_event(event) - await _adapter._send_with_retry( - chat_id=event.source.chat_id, - content=_text, - reply_to=_anchor, - metadata=self._thread_metadata_for_source(event.source, _anchor), - ) + await self._send_busy_reply(event, _adapter, _text, plain_anchor=True) return True except Exception: logger.warning( "Plain-text approval routing failed for session %s; " - "falling through to busy handling", - session_key, exc_info=True, + "falling through to busy handling", session_key, exc_info=True, ) return False async def _resolve_busy_steer_or_redirect( - self, - event: MessageEvent, - session_key: str, - effective_mode: str, - running_agent: Any, + self, event: MessageEvent, session_key: str, effective_mode: str, running_agent: Any ) -> "GatewayRunner._BusySteerOutcome": """Apply interrupt->queue demotions, then attempt steer (steer mode) or redirect (interrupt mode).""" from gateway.run import _AGENT_PENDING_SENTINEL - # Steer mode injects mid-run via running_agent.steer(); fall back to queue (nothing lost) if the - # agent isn't running yet (sentinel), lacks steer(), or the payload is empty. interrupt() - # cascades to ``_active_children`` and aborts delegate_task work, so demote ``interrupt`` to - # ``queue`` while the parent drives subagents; explicit /stop and /new still force-cancel all. + # Steer injects mid-run via running_agent.steer(), falling back to queue (nothing lost) when + # the agent isn't running yet, lacks steer(), or the payload is empty. Interrupt is demoted + # to queue while subagents run (interrupt() would abort them); /stop and /new still cancel all. demoted_for_subagents = ( - effective_mode == "interrupt" - and self._agent_has_active_subagents(running_agent) + effective_mode == "interrupt" and self._agent_has_active_subagents(running_agent) ) if demoted_for_subagents: - logger.info( - "Demoting busy_input_mode 'interrupt' to 'queue' for session %s " - "because the running agent has active subagents (#30170)", - session_key, - ) - effective_mode = "queue" + effective_mode = self._demote_interrupt(session_key, "the running agent has active subagents (#30170)") demoted_for_compression = ( - effective_mode == "interrupt" - and await self._session_has_compression_in_flight(session_key) + effective_mode == "interrupt" and await self._session_has_compression_in_flight(session_key) ) if demoted_for_compression: - logger.info( - "Demoting busy_input_mode 'interrupt' to 'queue' for session %s " - "because context compression is in flight (#56391)", - session_key, - ) - effective_mode = "queue" - steered = False - redirected = False + effective_mode = self._demote_interrupt(session_key, "context compression is in flight (#56391)") + steered = redirected = False + agent_live = running_agent is not None and running_agent is not _AGENT_PENDING_SENTINEL + plain_text = ( + event.message_type == MessageType.TEXT and not event.media_urls and not event.media_types + ) if effective_mode == "steer": steer_text = await self._prepare_busy_steer_text(event) - # Steerable: plain text, OR every attachment is STT-eligible voice media whose transcript - # was folded into steer_text — else a voice note in steer mode silently degrades to queue. + # Steerable: plain text, OR every attachment is voice media folded into steer_text. _steer_media_urls = getattr(event, "media_urls", None) or [] _steer_all_voice = bool(_steer_media_urls) and ( len(self._pending_event_audio_paths(event)) == len(_steer_media_urls) ) - can_steer = ( - steer_text - and ( - ( - event.message_type == MessageType.TEXT - and not event.media_urls - and not event.media_types - ) - or _steer_all_voice - ) - and running_agent is not None - and running_agent is not _AGENT_PENDING_SENTINEL - and hasattr(running_agent, "steer") - ) - if can_steer: - try: - steered = bool(running_agent.steer(steer_text)) - except Exception as exc: - logger.warning("Gateway steer failed for session %s: %s", session_key, exc) - steered = False + if steer_text and (plain_text or _steer_all_voice) and agent_live and hasattr(running_agent, "steer"): + steered = self._try_agent_verb(running_agent, "steer", steer_text, session_key) if not steered: - # Fall back to queue (merge into pending messages, no interrupt) effective_mode = "queue" elif ( - effective_mode == "interrupt" - and event.message_type == MessageType.TEXT - and not event.media_urls - and not event.media_types - and running_agent is not None - and running_agent is not _AGENT_PENDING_SENTINEL + effective_mode == "interrupt" and plain_text and agent_live and getattr(running_agent, "_supports_active_turn_redirect", False) is True and hasattr(running_agent, "redirect") ): - try: - redirected = bool(running_agent.redirect((event.text or "").strip())) - except Exception as exc: - logger.warning("Gateway redirect failed for session %s: %s", session_key, exc) - redirected = False + redirected = self._try_agent_verb( + running_agent, "redirect", (event.text or "").strip(), session_key + ) return self._BusySteerOutcome( - effective_mode=effective_mode, - demoted_for_subagents=demoted_for_subagents, - demoted_for_compression=demoted_for_compression, - steered=steered, - redirected=redirected, + effective_mode=effective_mode, demoted_for_subagents=demoted_for_subagents, + demoted_for_compression=demoted_for_compression, steered=steered, redirected=redirected, ) + @staticmethod + def _demote_interrupt(session_key: str, why: str) -> str: + logger.info("Demoting busy_input_mode 'interrupt' to 'queue' for session %s because %s", session_key, why) + return "queue" + + @staticmethod + def _try_agent_verb(running_agent, verb: str, text: str, session_key: str) -> bool: + """Call ``running_agent.(text)`` (steer/redirect); False + warning on failure.""" + try: + return bool(getattr(running_agent, verb)(text)) + except Exception as exc: + logger.warning("Gateway %s failed for session %s: %s", verb, session_key, exc) + return False + async def _interrupt_running_agent_for_busy_event(self, event: MessageEvent, adapter, running_agent) -> None: """Interrupt mode: abort in-flight tool calls; the agent loop exits at its next check point.""" from gateway.run import _build_media_placeholder @@ -593,11 +467,7 @@ class GatewayBusySessionMixin: _media_urls = getattr(event, "media_urls", None) or [] if self._pending_event_audio_paths(event): _interrupt_text, _ = await self._transcribe_and_echo_pending_voice( - event, - adapter, - event.source, - event.text or "", - log_context="Voice-busy-interrupt", + event, adapter, event.source, event.text or "", log_context="Voice-busy-interrupt", ) elif not _interrupt_text and _media_urls: _interrupt_text = _build_media_placeholder(event) @@ -606,244 +476,161 @@ class GatewayBusySessionMixin: pass # don't let interrupt failure block the ack def _busy_steer_ack_enabled(self, event: MessageEvent, session_key: str) -> bool: - # Steer mode already injected the text; some mobile chat setups want silent steering (like STT - # echo suppression) — keep the behavior, drop only the confirmation bubble. + # Some mobile chat setups want silent steering — keep the behavior, drop the bubble. from gateway.run import _load_gateway_config, _platform_config_key from gateway.display_config import resolve_display_setting - platform_key = _platform_config_key(event.source.platform) steer_ack_env = os.environ.get("HERMES_GATEWAY_BUSY_STEER_ACK_ENABLED") if steer_ack_env is not None: steer_ack_enabled = steer_ack_env.strip().lower() in {"1", "true", "yes", "on"} else: steer_ack_enabled = bool( resolve_display_setting( - _load_gateway_config(), - platform_key, - "busy_steer_ack_enabled", - True, + _load_gateway_config(), _platform_config_key(event.source.platform), + "busy_steer_ack_enabled", True, ) ) if not steer_ack_enabled: logger.debug("Busy steer ack suppressed for session %s", session_key) return steer_ack_enabled + _BUSY_DEMOTED_TAIL = ( + " — your message is queued for when it finishes (use /stop to cancel everything)." + ) + def _compose_busy_ack_message( - self, - event: MessageEvent, - now: float, - _busy_state, - running_agent: Any, - *, - is_steer_mode: bool, - is_queue_mode: bool, - is_redirect_mode: bool, - demoted_for_subagents: bool, - demoted_for_compression: bool, + self, event: MessageEvent, now: float, _busy_state, running_agent: Any, *, + is_steer_mode: bool, is_queue_mode: bool, is_redirect_mode: bool, + demoted_for_subagents: bool, demoted_for_compression: bool, ) -> str: from gateway.run import ( - _AGENT_PENDING_SENTINEL, - _hermes_home, - _load_gateway_config, - _platform_config_key, + _AGENT_PENDING_SENTINEL, _hermes_home, _load_gateway_config, _platform_config_key ) from gateway.display_config import resolve_display_setting - # Mobile chat defaults keep the ack terse; iteration/tool detail stays in logs and can be opted - # in per platform via display.platforms..busy_ack_detail. + # Terse by default; iteration/tool detail opts in via display.platforms.

.busy_ack_detail. status_parts = [] busy_ack_detail_enabled = bool( resolve_display_setting( - _load_gateway_config(), - _platform_config_key(event.source.platform), - "busy_ack_detail", - True, + _load_gateway_config(), _platform_config_key(event.source.platform), + "busy_ack_detail", True, ) ) - if busy_ack_detail_enabled and running_agent and running_agent is not _AGENT_PENDING_SENTINEL: try: summary = running_agent.get_activity_summary() - iteration = summary.get("api_call_count", 0) - max_iter = summary.get("max_iterations", 0) - current_tool = summary.get("current_tool") - start_ts = _busy_state.turn.started_ts if _busy_state else 0 - if start_ts: - elapsed_min = int((now - start_ts) / 60) - if elapsed_min > 0: - status_parts.append(f"{elapsed_min} min elapsed") - if max_iter: - status_parts.append(f"iteration {iteration}/{max_iter}") - if current_tool: - status_parts.append(f"running: {current_tool}") + elapsed_min = 0 + if _busy_state and _busy_state.turn.started_ts: + elapsed_min = int((now - _busy_state.turn.started_ts) / 60) + if elapsed_min > 0: + status_parts.append(f"{elapsed_min} min elapsed") + if summary.get("max_iterations", 0): + status_parts.append( + f"iteration {summary.get('api_call_count', 0)}/{summary.get('max_iterations', 0)}" + ) + if summary.get("current_tool"): + status_parts.append(f"running: {summary.get('current_tool')}") except Exception: pass - status_detail = f" ({', '.join(status_parts)})" if status_parts else "" if is_steer_mode: - message = ( - f"⏩ Steered into current run{status_detail}. " - f"Your message arrives after the next tool call." - ) + head, tail = "⏩ Steered into current run", ". Your message arrives after the next tool call." elif is_redirect_mode: - message = ( - f"↪ Redirected current run{status_detail}. " - f"I'll adjust using your correction." - ) + head, tail = "↪ Redirected current run", ". I'll adjust using your correction." elif is_queue_mode and demoted_for_subagents: # Explain the demotion: the follow-up didn't kill the subagent; /stop is the escape hatch. - message = ( - f"⏳ Subagent working{status_detail} — your message is queued for " - f"when it finishes (use /stop to cancel everything)." - ) + head, tail = "⏳ Subagent working", self._BUSY_DEMOTED_TAIL elif is_queue_mode and demoted_for_compression: - message = ( - f"⏳ Compressing context{status_detail} — your message is queued for " - f"when it finishes (use /stop to cancel everything)." - ) + head, tail = "⏳ Compressing context", self._BUSY_DEMOTED_TAIL elif is_queue_mode: - message = ( - f"⏳ Queued for the next turn{status_detail}. " - f"I'll respond once the current task finishes." - ) + head, tail = "⏳ Queued for the next turn", ". I'll respond once the current task finishes." else: - message = ( - f"⚡ Interrupting current task{status_detail}. " - f"I'll respond to your message shortly." - ) + head, tail = "⚡ Interrupting current task", ". I'll respond to your message shortly." + message = f"{head}{status_detail}{tail}" - # First-touch onboarding: one-time hint about the queue/interrupt knob; the flag is persisted to - # config.yaml so it never fires again on this install. + # One-time onboarding hint about the queue/interrupt knob (flag persisted to config.yaml). try: - from agent.onboarding import ( - BUSY_INPUT_FLAG, - busy_input_hint_gateway, - is_seen, - mark_seen, - ) - _user_cfg = _load_gateway_config() - if not is_seen(_user_cfg, BUSY_INPUT_FLAG): - if is_steer_mode: - _hint_mode = "steer" - elif is_queue_mode: - _hint_mode = "queue" - elif is_redirect_mode: - _hint_mode = "redirect" - else: - _hint_mode = "interrupt" - message = ( - f"{message}\n\n" - f"{busy_input_hint_gateway(_hint_mode)}" + from agent.onboarding import (BUSY_INPUT_FLAG, busy_input_hint_gateway, is_seen, mark_seen) + if not is_seen(_load_gateway_config(), BUSY_INPUT_FLAG): + _hint_mode = ( + "steer" if is_steer_mode + else "queue" if is_queue_mode + else "redirect" if is_redirect_mode + else "interrupt" ) + message = f"{message}\n\n{busy_input_hint_gateway(_hint_mode)}" mark_seen(_hermes_home / "config.yaml", BUSY_INPUT_FLAG) except Exception as _onb_err: logger.debug("Failed to apply busy-input onboarding hint: %s", _onb_err) return message async def _send_busy_ack_reply(self, event: MessageEvent, adapter, message: str) -> None: - reply_anchor = self._reply_anchor_for_event(event) - thread_meta = self._thread_metadata_for_source(event.source, reply_anchor) try: - await adapter._send_with_retry( - chat_id=event.source.chat_id, - content=message, - reply_to=self._busy_reply_to(event, reply_anchor), - metadata=thread_meta, - ) + await self._send_busy_reply(event, adapter, message) except Exception as e: logger.debug("Failed to send busy-ack: %s", e) async def _handle_active_session_busy_message(self, event: MessageEvent, session_key: str) -> bool: - # Authorization gate: the cold path (_handle_message) checks _is_user_authorized before - # creating a session; the busy path must enforce the same check, else unauthorized users in - # shared threads (Slack/Telegram/Discord) inject messages into a session they don't own. + # Same authorization gate as the cold path, else unauthorized users in shared threads + # inject messages into a session they don't own. from gateway.run import _AGENT_PENDING_SENTINEL if not self._is_user_authorized(event.source): logger.warning( "Dropping message from unauthorized user in active session: " - "user=%s (%s), platform=%s, session=%s", - event.source.user_id, - event.source.user_name, - event.source.platform.value if event.source.platform else "unknown", - session_key, + "user=%s (%s), platform=%s, session=%s", event.source.user_id, event.source.user_name, + event.source.platform.value if event.source.platform else "unknown", session_key, ) return True # handled (silently dropped); do not fall through effective_mode = self._effective_busy_input_mode(event.source) - - # --- Draining case (gateway restarting/stopping) --- - if self._draining: + if self._draining: # gateway restarting/stopping await self._send_busy_drain_notice(event, session_key, effective_mode) return True - if await self._route_plaintext_approval_while_busy(event, session_key): return True - - # Normal busy case (agent actively running a task) adapter = self._adapter_for_source(event.source) if not adapter: return False # let default path handle it - - # Internal synthetic events (async-delegation / background-process completions) must never - # interrupt/steer: treated as user TEXT while busy, interrupt mode would abort the active turn; - # a completion surfaces as a NEW turn only when idle. Plugin events carry untrusted payload - # text, so queue them through the gateway FIFO (security metadata kept apart). - if getattr(event, "internal", False) and not event.allow_gateway_control: + # Internal synthetic events (delegation / background completions) must never interrupt or + # steer; they surface as a NEW turn when idle. Plugin events carry untrusted payload text, so + # queue them through the FIFO (security metadata kept apart). + if getattr(event, "internal", False): + if event.allow_gateway_control: + return False self._queue_or_replace_pending_event(session_key, event) return True - if getattr(event, "internal", False): - return False - - _busy_state = self._peek_session_state(session_key) - running_agent = _busy_state.turn.agent if _busy_state else None - - busy_text_mode = self._effective_busy_text_mode(event.source) if ( event.message_type == MessageType.TEXT - and busy_text_mode == "queue" + and self._effective_busy_text_mode(event.source) == "queue" and effective_mode != "steer" ): return False + _busy_state = self._peek_session_state(session_key) + running_agent = _busy_state.turn.agent if _busy_state else None _steer = await self._resolve_busy_steer_or_redirect(event, session_key, effective_mode, running_agent) - effective_mode = _steer.effective_mode - demoted_for_subagents = _steer.demoted_for_subagents - demoted_for_compression = _steer.demoted_for_compression - steered = _steer.steered - redirected = _steer.redirected - - # Queue as the next turn after the current run ends. Skip after a successful steer — the text - # is already in the run and must NOT replay. Use the FIFO helper, not raw - # merge_pending_message_event (merge_text=True newline-joins consecutive TEXT follow-ups into - # ONE turn); FIFO gives each text its own turn while keeping photo-burst / album merge for media. - if not steered and not redirected: + effective_mode, redirected = _steer.effective_mode, _steer.redirected + # Queue as the next turn — skipped after a successful steer/redirect (the text is already in + # the run and must NOT replay). FIFO gives each text its own turn (raw merge would join them). + if not _steer.steered and not redirected: self._queue_or_replace_pending_event(session_key, event) - is_queue_mode = effective_mode == "queue" is_steer_mode = effective_mode == "steer" is_redirect_mode = effective_mode == "interrupt" and redirected - - # Interrupt mode: abort in-flight tool calls; the agent loop exits at its next check point. if ( - effective_mode == "interrupt" - and not redirected - and running_agent - and running_agent is not _AGENT_PENDING_SENTINEL + effective_mode == "interrupt" and not redirected + and running_agent and running_agent is not _AGENT_PENDING_SENTINEL ): await self._interrupt_running_agent_for_busy_event(event, adapter, running_agent) - # Disabled ack: skip sending, still process input. Checked before debounce so we never stamp a - # "last ack" timestamp for an ack that was not delivered. - busy_ack_enabled = os.environ.get("HERMES_GATEWAY_BUSY_ACK_ENABLED", "true").lower() == "true" - if not busy_ack_enabled: + # Disabled ack: still process input. Checked before debounce so an undelivered ack never + # stamps the "last ack" timestamp. + if os.environ.get("HERMES_GATEWAY_BUSY_ACK_ENABLED", "true").lower() != "true": logger.debug("Busy ack suppressed for session %s", session_key) return True # input still processed, just no ack sent - # Debounce before the config-heavy display lookup: rapid follow-ups are still processed but - # shouldn't cost a config read just to learn no ack will be sent. - _BUSY_ACK_COOLDOWN = 30 + # Debounce (30s) before the config-heavy display lookup. now = time.time() - last_ack = _busy_state.turn.busy_ack_ts if _busy_state else 0 - if now - last_ack < _BUSY_ACK_COOLDOWN: + if now - (_busy_state.turn.busy_ack_ts if _busy_state else 0) < 30: return True # interrupt sent (if not queue), ack already delivered recently if is_steer_mode and not self._busy_steer_ack_enabled(event, session_key): @@ -852,44 +639,42 @@ class GatewayBusySessionMixin: self._session_state(session_key).turn.busy_ack_ts = now message = self._compose_busy_ack_message( - event, - now, - _busy_state, - running_agent, - is_steer_mode=is_steer_mode, - is_queue_mode=is_queue_mode, - is_redirect_mode=is_redirect_mode, - demoted_for_subagents=demoted_for_subagents, - demoted_for_compression=demoted_for_compression, + event, now, _busy_state, running_agent, is_steer_mode=is_steer_mode, + is_queue_mode=is_queue_mode, is_redirect_mode=is_redirect_mode, + demoted_for_subagents=_steer.demoted_for_subagents, + demoted_for_compression=_steer.demoted_for_compression, ) await self._send_busy_ack_reply(event, adapter, message) return True + # Slash name → handler method is ``_handle__command`` (``-`` → ``_``) except these. + _COMMAND_HANDLER_ALIASES = {"bg": "_handle_background_command", "sethome": "_handle_set_home_command"} + # Ordinary slash handlers shared by idle and busy dispatch. + _PLAIN_COMMANDS = ( + "status", "context", "restart", "approve", "deny", "pause", "agents", "bg", "btw", + "kanban", "subgoal", "heartbeat", "busy", "yolo", "verbose", "footer", "help", + "commands", "profile", "update", "version", + ) + # Dispatched only on the idle path (busy dispatch has its own allowlist). + _IDLE_COMMANDS = ( + "topic", "whoami", "platform", "stop", "reasoning", "memory", "skills", "fast", + "approvals", "model", "codex-runtime", "personality", "suggestions", "save", "retry", + "sethome", "compress", "usage", "topup", "insights", "reload-mcp", "reload-skills", + "bundles", "debug", "title", "resume", "sessions", "branch", "rollback", "diff", "goal", + "loop", "refine", "review", "voice", + ) + + def _command_handler_table(self, names) -> Dict[str, Any]: + return { + name: getattr( + self, self._COMMAND_HANDLER_ALIASES.get(name, f"_handle_{name.replace('-', '_')}_command"), + ) + for name in names + } + def _gateway_plain_command_handlers(self): """Return ordinary slash handlers shared by idle and busy dispatch.""" - return { - "status": self._handle_status_command, - "context": self._handle_context_command, - "restart": self._handle_restart_command, - "approve": self._handle_approve_command, - "deny": self._handle_deny_command, - "pause": self._handle_pause_command, - "agents": self._handle_agents_command, - "bg": self._handle_background_command, - "btw": self._handle_btw_command, - "kanban": self._handle_kanban_command, - "subgoal": self._handle_subgoal_command, - "heartbeat": self._handle_heartbeat_command, - "busy": self._handle_busy_command, - "yolo": self._handle_yolo_command, - "verbose": self._handle_verbose_command, - "footer": self._handle_footer_command, - "help": self._handle_help_command, - "commands": self._handle_commands_command, - "profile": self._handle_profile_command, - "update": self._handle_update_command, - "version": self._handle_version_command, - } + return self._command_handler_table(self._PLAIN_COMMANDS) async def _send_command_ack(self, source, text: str, label: str) -> None: """Best-effort acknowledgment for a slash command that falls through to agent processing.""" @@ -903,78 +688,30 @@ class GatewayBusySessionMixin: logger.debug("%s ack send failed", label, exc_info=True) def _gateway_idle_command_handlers(self): - """Slash handlers dispatched only when no agent is running for the session (idle path). + """Slash handlers dispatched only on the idle path (busy dispatch has its own allowlist).""" + return self._command_handler_table(self._IDLE_COMMANDS) - Busy dispatch keeps its own explicit allowlist (``_dispatch_busy_slash_command``).""" - return { - "topic": self._handle_topic_command, - "whoami": self._handle_whoami_command, - "platform": self._handle_platform_command, - "stop": self._handle_stop_command, - "reasoning": self._handle_reasoning_command, - "memory": self._handle_memory_command, - "skills": self._handle_skills_command, - "fast": self._handle_fast_command, - "approvals": self._handle_approvals_command, - "model": self._handle_model_command, - "codex-runtime": self._handle_codex_runtime_command, - "personality": self._handle_personality_command, - "suggestions": self._handle_suggestions_command, - "save": self._handle_save_command, - "retry": self._handle_retry_command, - "sethome": self._handle_set_home_command, - "compress": self._handle_compress_command, - "usage": self._handle_usage_command, - "topup": self._handle_topup_command, - "insights": self._handle_insights_command, - "reload-mcp": self._handle_reload_mcp_command, - "reload-skills": self._handle_reload_skills_command, - "bundles": self._handle_bundles_command, - "debug": self._handle_debug_command, - "title": self._handle_title_command, - "resume": self._handle_resume_command, - "sessions": self._handle_sessions_command, - "branch": self._handle_branch_command, - "rollback": self._handle_rollback_command, - "diff": self._handle_diff_command, - "goal": self._handle_goal_command, - "loop": self._handle_loop_command, - "refine": self._handle_refine_command, - "review": self._handle_review_command, - "voice": self._handle_voice_command, - } + # busy_handler key (hermes_cli/commands.py CommandDef) → mid-run variant ``_busy__command``. + _BUSY_SPECIAL_HANDLERS: Dict[str, str] = { + k: f"_busy_{k}_command" for k in ("start", "stop", "new", "queue", "steer", "egress", "goal", "loop") + } - async def _dispatch_busy_slash_command( - self, event: MessageEvent, cmd_def, quick_key: str, source, - ): + async def _dispatch_busy_slash_command(self, event: MessageEvent, cmd_def, quick_key: str, source): """Dispatch a recognized slash command while an agent is running. - Order: ``busy_handler`` (special mid-run variant) → ``busy_policy == "dispatch"`` (normal - handler) → catch-all busy-reject text. Rejecting beats falling through to interrupt + - discard: Discord-registered slash commands would interrupt the agent AND be discarded by - the slash-command safety net, producing a zero-char response. + Order: ``busy_handler`` (mid-run variant) → ``busy_policy == "dispatch"`` (normal handler) + → catch-all reject text. Rejecting beats interrupt + discard (a zero-char response). """ name = cmd_def.name policy = getattr(cmd_def, "busy_policy", "reject") handler_key = getattr(cmd_def, "busy_handler", None) - if handler_key: - special = { - "start": self._busy_start_command, - "stop": self._busy_stop_command, - "new": self._busy_new_command, - "queue": self._busy_queue_command, - "steer": self._busy_steer_command, - "egress": self._busy_egress_command, - "goal": self._busy_goal_command, - "loop": self._busy_loop_command, - }.get(handler_key) + special = self._BUSY_SPECIAL_HANDLERS.get(handler_key) if special is not None: - return await special(event, quick_key, source) + return await getattr(self, special)(event, quick_key, source) reject_text = self._BUSY_REJECT_TEXT.get(handler_key) if reject_text is not None: return reject_text - if policy in ("dispatch", "interrupt_then_dispatch"): plain = self._gateway_plain_command_handlers().get(name) if plain is not None: @@ -984,21 +721,15 @@ class GatewayBusySessionMixin: "falling back to busy-reject", policy, name, ) - # Catch-all: any other recognized slash command hit the running-agent guard — reject - # gracefully rather than falling through to interrupt + discard. return ( f"⏳ Agent is running — `/{name}` can't run " f"mid-turn. Wait for the current response or `/stop` first." ) async def _handle_pause_command(self, event: MessageEvent): - """`/pause [reason]` engages the global emergency stop; `/pause off` (resume/stop) lifts it. - - In-band resume path for messaging-only operators — the estop gate lets recognized slash - commands through while paused so a user without host-shell access is never locked out. - """ + """`/pause [reason]` engages the global emergency stop; `/pause off` lifts it (the estop gate + lets slash commands through while paused so messaging-only operators are never locked out).""" from agent import estop - args = (event.get_command_args() or "").strip() if args.lower() in {"off", "resume", "stop", "disengage"}: if estop.disengage(): @@ -1006,12 +737,8 @@ class GatewayBusySessionMixin: return "Hermes wasn't paused." state = estop.get_state() if state is not None and not args: - reason = state.get("reason") - suffix = f" (reason: {reason})" if reason else "" - return ( - f"⏸️ Hermes is already paused{suffix}. " - "Use `/pause off` to resume." - ) + suffix = f" (reason: {state.get('reason')})" if state.get("reason") else "" + return f"⏸️ Hermes is already paused{suffix}. Use `/pause off` to resume." estop.engage(reason=args or None) suffix = f" (reason: {args})" if args else "" return ( @@ -1020,167 +747,116 @@ class GatewayBusySessionMixin: ) async def _busy_start_command(self, event: MessageEvent, quick_key: str, source): - # Telegram sends /start for bot launches/deep-links — a platform ping, not a user command: - # no help dump, no agent interrupt, no queued text. + # Telegram's /start is a platform ping (bot launch/deep-link), not a user command. logger.info("Ignoring /start platform ping for active session %s", quick_key) return "" async def _busy_egress_command(self, event: MessageEvent, quick_key: str, source): from hermes_cli.proxy_cli import format_status_text - return format_status_text() async def _busy_stop_command(self, event: MessageEvent, quick_key: str, source): - # /stop must hard-kill the session when an agent is running. A soft interrupt - # (agent.interrupt()) doesn't help when the agent is truly hung — the executor thread is - # blocked and never checks _interrupt_requested. + # Hard-kill: a soft interrupt can't reach a truly hung executor thread. from gateway.run import _INTERRUPT_REASON_STOP await self._interrupt_and_clear_session( - quick_key, - source, - interrupt_reason=_INTERRUPT_REASON_STOP, - invalidation_reason="stop_command", + quick_key, source, interrupt_reason=_INTERRUPT_REASON_STOP, invalidation_reason="stop_command", ) logger.info("STOP for session %s — agent interrupted, session lock released", quick_key) return EphemeralReply(t("gateway.stop.stopped")) async def _busy_new_command(self, event: MessageEvent, quick_key: str, source): - # /reset and /new must bypass the running-agent guard so they actually dispatch as commands - # instead of being queued as user text (which would be fed back to the agent with the same - # broken history — #2170). Clear any pending messages so the old text doesn't replay + # /reset and /new bypass the running-agent guard (else they'd queue as user text and replay + # into the same broken history); clear pending messages so the old text doesn't replay. from gateway.run import _INTERRUPT_REASON_RESET await self._interrupt_and_clear_session( - quick_key, - source, - interrupt_reason=_INTERRUPT_REASON_RESET, - invalidation_reason="new_command", + quick_key, source, interrupt_reason=_INTERRUPT_REASON_RESET, invalidation_reason="new_command", ) - # Clean up the running agent entry so the reset handler - # doesn't think an agent is still active. return await self._handle_reset_command(event) async def _busy_queue_command(self, event: MessageEvent, quick_key: str, source): - # /queue — queue without interrupting. Each /queue is its own full agent turn, run - # FIFO after the current run (and earlier /queue items) finish; messages are NOT merged. + # Each /queue is its own full agent turn, run FIFO after the current run; never merged. queued_text = event.get_command_args().strip() - # Preserve media/reply payloads: a /queue carrying a photo, document, or reply context is - # valid even with no prompt text (e.g. "/queue" as the caption of an image). Dropping these - # fields silently lost the attachment when the queued turn ran. + # A /queue carrying media or reply context is valid with no prompt text (image caption). has_media = bool(getattr(event, "media_urls", None)) if not queued_text and not has_media: return "Usage: /queue " adapter = self._adapter_for_source(source) if adapter: - queued_event = MessageEvent( - text=queued_text, - message_type=event.message_type if has_media else MessageType.TEXT, - source=event.source, - raw_message=event.raw_message, - message_id=event.message_id, + self._enqueue_fifo(quick_key, MessageEvent( + text=queued_text, message_type=event.message_type if has_media else MessageType.TEXT, + source=event.source, raw_message=event.raw_message, message_id=event.message_id, media_urls=list(getattr(event, "media_urls", []) or []), media_types=list(getattr(event, "media_types", []) or []), media_text_inlined=list(getattr(event, "media_text_inlined", []) or []), - reply_to_message_id=event.reply_to_message_id, - reply_to_text=event.reply_to_text, + reply_to_message_id=event.reply_to_message_id, reply_to_text=event.reply_to_text, reply_to_author_id=event.reply_to_author_id, reply_to_author_name=event.reply_to_author_name, - reply_to_is_own_message=event.reply_to_is_own_message, - auto_skill=event.auto_skill, - channel_prompt=event.channel_prompt, - channel_context=event.channel_context, - internal=event.internal, - timestamp=event.timestamp, - ) - self._enqueue_fifo(quick_key, queued_event, adapter) - depth = self._queue_depth(quick_key, adapter=self._adapter_for_source(source)) - if depth <= 1: - return "Queued for the next turn." - return f"Queued for the next turn. ({depth} queued)" + reply_to_is_own_message=event.reply_to_is_own_message, auto_skill=event.auto_skill, + channel_prompt=event.channel_prompt, channel_context=event.channel_context, + internal=event.internal, timestamp=event.timestamp, + ), adapter) + depth = self._queue_depth(quick_key, adapter=adapter) + return "Queued for the next turn." + (f" ({depth} queued)" if depth > 1 else "") async def _busy_steer_command(self, event: MessageEvent, quick_key: str, source): - # /steer — inject mid-run after the next tool call. Unlike /queue (turn boundary), - # /steer lands BETWEEN tool-call iterations inside the same agent run, by appending to the - # last tool result's content. No interrupt, no new user turn, no role-alternation violation. + # /steer lands BETWEEN tool-call iterations of the same run (appended to the last tool + # result) — no interrupt, no new user turn, no role-alternation violation. from gateway.run import _AGENT_PENDING_SENTINEL steer_text = event.get_command_args().strip() if not steer_text: return "Usage: /steer " _steer_state = self._peek_session_state(quick_key) running_agent = _steer_state.turn.agent if _steer_state else None - if running_agent is _AGENT_PENDING_SENTINEL: - # Agent hasn't started yet — queue as turn-boundary fallback. + + def _queue_fallback(reply: str) -> str: + # Turn-boundary fallback: queue the steer text as its own follow-up turn. adapter = self._adapter_for_source(source) if adapter: - queued_event = MessageEvent( - text=steer_text, - message_type=MessageType.TEXT, - source=event.source, - message_id=event.message_id, - channel_prompt=event.channel_prompt, + self._enqueue_fifo(quick_key, MessageEvent( + text=steer_text, message_type=MessageType.TEXT, source=event.source, + message_id=event.message_id, channel_prompt=event.channel_prompt, channel_context=event.channel_context, - ) - self._enqueue_fifo(quick_key, queued_event, adapter) - return "Agent still starting — /steer queued for the next turn." - if running_agent and hasattr(running_agent, "steer"): - try: - accepted = running_agent.steer(steer_text) - except Exception as exc: - logger.warning("Steer failed for session %s: %s", quick_key, exc) - return f"⚠️ Steer failed: {exc}" - if accepted: - preview = steer_text[:60] + ("..." if len(steer_text) > 60 else "") - return f"⏩ Steer queued — arrives after the next tool call: '{preview}'" + ), adapter) + return reply + + if running_agent is _AGENT_PENDING_SENTINEL: + return _queue_fallback("Agent still starting — /steer queued for the next turn.") + if not running_agent or not hasattr(running_agent, "steer"): + return _queue_fallback("No active agent — /steer queued for the next turn.") + try: + accepted = running_agent.steer(steer_text) + except Exception as exc: + logger.warning("Steer failed for session %s: %s", quick_key, exc) + return f"⚠️ Steer failed: {exc}" + if not accepted: return "Steer rejected (empty payload)." - # Running agent is missing or lacks steer() — fall back to queue. - adapter = self._adapter_for_source(source) - if adapter: - queued_event = MessageEvent( - text=steer_text, - message_type=MessageType.TEXT, - source=event.source, - message_id=event.message_id, - channel_prompt=event.channel_prompt, - channel_context=event.channel_context, - ) - self._enqueue_fifo(quick_key, queued_event, adapter) - return "No active agent — /steer queued for the next turn." + preview = steer_text[:60] + ("..." if len(steer_text) > 60 else "") + return f"⏩ Steer queued — arrives after the next tool call: '{preview}'" async def _busy_goal_command(self, event: MessageEvent, quick_key: str, source): - # /goal is safe mid-run for status/pause/clear/wait (inspection and control-plane only — - # doesn't interrupt the running turn). Setting new goal text mid-run is rejected like - # /model so we don't race a second continuation prompt against the current turn. + # Control verbs are safe mid-run (state only); setting new goal text is rejected so we don't + # race a second continuation against the current turn. wait/gate take an argument. _goal_arg = (event.get_command_args() or "").strip().lower() _goal_verb = _goal_arg.split(None, 1)[0] if _goal_arg else "" - # Exact-match control verbs, plus the wait/unwait barrier verbs (take a pid) and the gate - # management verb (gates run at turn boundary, so editing the gate list mid-run is safe). - _is_control = ( + if ( not _goal_arg or _goal_arg in {"status", "pause", "resume", "clear", "stop", "done", "unwait"} or _goal_verb in {"wait", "gate"} - ) - if _is_control: + ): return await self._handle_goal_command(event) return "Agent is running — use /goal status / pause / clear / wait mid-run, or /stop before setting a new goal." async def _busy_loop_command(self, event: MessageEvent, quick_key: str, source): - # /loop mirrors /goal: control verbs are safe mid-run (state only — read at the next idle - # boundary); setting a new loop mid-run is rejected so we don't race the current turn. + # Mirrors /goal: control verbs are safe mid-run; a new loop is rejected. _loop_arg = (event.get_command_args() or "").strip().lower() if not _loop_arg or _loop_arg in {"status", "pause", "resume", "stop", "clear", "cancel", "help", "--help", "-h"}: return await self._handle_loop_command(event) return "Agent is running — use /loop status / pause / stop mid-run, or /stop before setting a new loop." - def _check_slash_access( - self, source: SessionSource, canonical_cmd: str - ) -> Optional[str]: - """Return a denial message if ``source`` cannot run ``canonical_cmd``, else None. - - Used by the cold and running-agent dispatch paths in ``_handle_message`` so admin/user gating - can't be bypassed by an in-flight agent. Backward-compat: without ``allow_admin_from`` for the - scope, ``policy_for_source`` returns ``enabled=False`` and this always returns None. - """ + def _check_slash_access(self, source: SessionSource, canonical_cmd: str) -> Optional[str]: + """Denial message if ``source`` cannot run ``canonical_cmd``, else None (both dispatch paths + use it so an in-flight agent can't bypass admin gating; no ``allow_admin_from`` → None).""" from gateway.slash_access import policy_for_source as _policy_for_source - if not canonical_cmd: return None policy = _policy_for_source(self.config, source) @@ -1188,35 +864,25 @@ class GatewayBusySessionMixin: return None logger.info( "Slash command /%s denied for %s:%s (not admin, not in user_allowed_commands)", - canonical_cmd, - source.platform.value if source.platform else "?", - source.user_id, + canonical_cmd, source.platform.value if source.platform else "?", source.user_id, ) allowed_preview = sorted(policy.user_allowed_commands) if allowed_preview: suffix = ( - "You can run: " - + ", ".join(f"/{c}" for c in allowed_preview[:12]) - + ("…" if len(allowed_preview) > 12 else "") - + ". Use /whoami for the full list." + "You can run: " + ", ".join(f"/{c}" for c in allowed_preview[:12]) + + ("…" if len(allowed_preview) > 12 else "") + ". Use /whoami for the full list." ) else: suffix = ( - "No slash commands are enabled for non-admins on this " - "platform. Ask an admin to add you to allow_admin_from " - "or to set user_allowed_commands." + "No slash commands are enabled for non-admins on this platform. Ask an admin to " + "add you to allow_admin_from or to set user_allowed_commands." ) return f"⛔ /{canonical_cmd} is admin-only here. {suffix}" def _sibling_thread_run_keys(self, source: SessionSource, own_key: str) -> list: - """Find running-agent keys for OTHER participants in the same thread. - - In per-user thread mode each participant gets an isolated key - (``...:{thread_id}:{user_id}``), so another user's run is invisible to the caller's own - ``/stop``. Returns keys of *actually running* agents (not the pending sentinel, not the - caller's own) sharing the caller's ``{chat_id}:{thread_id}`` prefix; empty when not in a - thread or no sibling runs exist. Callers must still gate on authorization. - """ + """Running-agent keys of OTHER participants in the same thread (per-user thread mode keys + are ``...:{thread_id}:{user_id}``, so another user's run is invisible to the caller's own + ``/stop``). Excludes the pending sentinel and ``own_key``; callers still gate on authz.""" from gateway.run import _AGENT_PENDING_SENTINEL thread_id = getattr(source, "thread_id", None) chat_id = getattr(source, "chat_id", None) @@ -1224,57 +890,39 @@ class GatewayBusySessionMixin: return [] platform = source.platform.value chat_type = getattr(source, "chat_type", None) or "" - # Prefix that every per-user key in this thread shares, up to and including the thread_id - # segment. Match the exact key or prefix + ":" (a further user_id segment) so an unrelated - # thread whose id merely starts with this one is not matched. - prefix = ":".join( - ["agent:main", platform, chat_type, str(chat_id), str(thread_id)] - ) - matches = [] - for key, agent in self._running_agent_items(): - if key == own_key: - continue - if agent is _AGENT_PENDING_SENTINEL or not agent: - continue - if key == prefix or key.startswith(prefix + ":"): - matches.append(key) - return matches + # Match the exact key or prefix + ":" so a thread id that merely starts with this one + # is not matched. + prefix = ":".join(["agent:main", platform, chat_type, str(chat_id), str(thread_id)]) + return [ + key + for key, agent in self._running_agent_items() + if key != own_key + and agent is not _AGENT_PENDING_SENTINEL and agent + and (key == prefix or key.startswith(prefix + ":")) + ] def _is_stale_restart_redelivery(self, event: MessageEvent) -> bool: - """Return True if this /restart is a Telegram re-delivery we already handled. + """True if this /restart is a Telegram re-delivery we already handled. - The previous gateway wrote ``.restart_last_processed.json`` with the triggering platform - + update_id when it processed the /restart. A /restart on the same platform with - update_id <= that value is a redelivery when this process booted from that restart; - otherwise the marker must still be recent (< 5 minutes). Telegram only (the only platform - with a numeric cross-session update ordering); other platforms return False. + The previous gateway wrote ``.restart_last_processed.json`` (platform + update_id). A + /restart with update_id <= that value is a redelivery when this process booted from that + restart; otherwise the marker must be < 5 minutes old. Telegram only (numeric ordering). """ from gateway.run import _hermes_home - if event is None or event.source is None: + if event is None or event.source is None or event.platform_update_id is None: return False - if event.platform_update_id is None: - return False - if event.source.platform is None: - return False - # Only Telegram populates platform_update_id currently; be explicit - # so future platforms aren't accidentally gated by this check. try: - platform_value = event.source.platform.value + if event.source.platform.value != "telegram": + return False except Exception: return False - if platform_value != "telegram": - return False try: marker_path = _hermes_home / ".restart_last_processed.json" if not marker_path.exists(): - # Belt-and-suspenders for a missing dedup marker (cleaned up, or the previous write - # failed): without it the update_id comparison can't run and a redelivered /restart - # would re-restart the gateway forever. Suppress ONLY when a restart cycle is - # independently confirmed: this process booted from a chat-originated /restart - # (_booted_from_restart) AND is within a short post-boot window; a genuine first - # /restart on a fresh boot is never swallowed (flag stays False). Consume the flag - # one-shot so a later legitimate /restart in the same session is honored. + # Missing marker: a redelivered /restart would otherwise re-restart forever. Suppress + # ONLY when this process booted from a chat /restart AND is within a short post-boot + # window; consume the flag one-shot so a later legitimate /restart is honored. if ( getattr(self, "_booted_from_restart", False) and time.time() - getattr(self, "_startup_time", 0.0) < 60 @@ -1286,149 +934,77 @@ class GatewayBusySessionMixin: except Exception: return False - if data.get("platform") != platform_value: - return False recorded_uid = data.get("update_id") - if not isinstance(recorded_uid, int): - return False - if event.platform_update_id > recorded_uid: + if ( + data.get("platform") != "telegram" + or not isinstance(recorded_uid, int) + or event.platform_update_id > recorded_uid + ): return False - # A service-managed restart can legitimately take longer than the marker's normal five- - # minute trust window while adapters, cron, and in-flight deliveries drain. Consume the boot - # signal one-shot so a later genuine command is evaluated normally. + # A service-managed restart can outlast the 5-minute trust window; consume the boot + # signal one-shot. if getattr(self, "_booted_from_restart", False): self._booted_from_restart = False return True - # Staleness guard: ignore markers older than 5 minutes so a legitimately old one (e.g. crash - # recovery where notify never fired) doesn't swallow a fresh /restart. + # Staleness guard: an old marker (crash recovery) must not swallow a fresh /restart. requested_at = data.get("requested_at") - if isinstance(requested_at, (int, float)): - if time.time() - requested_at > 300: - return False - return True + return not (isinstance(requested_at, (int, float)) and time.time() - requested_at > 300) async def _handle_suggestions_command(self, event: MessageEvent) -> str: - """Handle /suggestions in the gateway. - - Delegates to the shared handler so CLI and gateway never drift. The origin is built from - the event source so an accepted suggestion's job delivers back to this chat/thread. - """ + """/suggestions via the shared handler (origin = event source so jobs deliver back here).""" from gateway.run import _command_origin_for_source - args = (event.get_command_args() or "").strip() - origin = _command_origin_for_source(event.source) try: from hermes_cli.suggestions_cmd import handle_suggestions_command - - return handle_suggestions_command(args, origin=origin, surface="gateway") + return handle_suggestions_command( + (event.get_command_args() or "").strip(), + origin=_command_origin_for_source(event.source), surface="gateway", + ) except Exception as e: logger.debug("suggestions command failed: %s", e) return f"Suggestions command failed: {e}" async def _handle_blueprint_command(self, event: MessageEvent): - """Handle /blueprint in the gateway. - - Delegates to the shared handler so CLI, TUI, and gateway never drift. Origin is built - from the event source so a directly created blueprint job delivers back to this chat. - """ + """/blueprint via the shared handler (origin = event source so jobs deliver back here).""" from gateway.run import _command_origin_for_source - args = (event.get_command_args() or "").strip() - origin = _command_origin_for_source(event.source) try: from hermes_cli.blueprint_cmd import handle_blueprint_command - - return handle_blueprint_command(args, origin=origin, surface="gateway") + return handle_blueprint_command( + (event.get_command_args() or "").strip(), + origin=_command_origin_for_source(event.source), surface="gateway", + ) except Exception as e: logger.debug("blueprint command failed: %s", e) from hermes_cli.blueprint_cmd import BlueprintCommandResult - return BlueprintCommandResult(f"Cron blueprint command failed: {e}") async def _maybe_confirm_destructive_slash( - self, - *, - event: MessageEvent, - command: str, - title: str, - detail: str, - execute, + self, *, event: MessageEvent, command: str, title: str, detail: str, execute ) -> Union[str, "EphemeralReply", None]: """Gate a destructive session slash command (/new, /reset, /undo). - ``execute`` is an async ``execute() -> str | EphemeralReply`` performing the action. It - runs immediately if ``approvals.destructive_slash_confirm`` is off; otherwise this routes - through ``_request_slash_confirm`` (native buttons or text fallback): ``once`` runs it, - ``always`` persists ``destructive_slash_confirm: false`` then runs it, ``cancel`` returns - a "cancelled" message without running it. + ``execute()`` (async → str | EphemeralReply) runs immediately when + ``approvals.destructive_slash_confirm`` is off; otherwise via ``_request_slash_confirm``: + ``once`` runs it, ``always`` persists the opt-out then runs it, ``cancel`` skips it. """ - # Gate check. confirm_required = True try: - cfg = self._read_user_config() - approvals = cfg.get("approvals") if isinstance(cfg, dict) else None + approvals = self._read_user_config().get("approvals") if isinstance(approvals, dict): confirm_required = bool(approvals.get("destructive_slash_confirm", True)) except Exception: pass - if not confirm_required: return await execute() session_key = self._session_key_for_source(event.source) async def _on_confirm(choice: str): - if choice == "cancel": - return f"🟡 /{command} cancelled. Conversation unchanged." - persisted = False - if choice == "always": - try: - from cli import save_config_value - # save_config_value swallows its own errors and reports the - # outcome in the return value, so the try block alone says - # nothing about whether the write landed. - persisted = bool( - save_config_value("approvals.destructive_slash_confirm", False) - ) - if persisted: - logger.info( - "User opted out of destructive slash confirm (session=%s)", - session_key, - ) - else: - logger.warning( - "Could not persist destructive_slash_confirm=false " - "(session=%s); config.yaml is not writable", - session_key, - ) - except Exception as exc: - logger.warning( - "Failed to persist destructive_slash_confirm=false: %s", exc, - ) - result = await execute() - if choice == "always": - if persisted: - note = ( - "\n\nℹ️ Future /clear, /new, /reset, and /undo will run " - "without confirmation. Re-enable via " - "`approvals.destructive_slash_confirm: true` in config.yaml." - ) - else: - # The user did approve this run, so the action still goes ahead, but the - # preference did not stick and the prompt will be back next time. Say so rather - # than promising an opt-out that was never written. - note = ( - "\n\n⚠️ Could not save that preference (config.yaml is not " - "writable), so /clear, /new, /reset, and /undo will ask " - "again next time. To silence it permanently, set " - "`approvals.destructive_slash_confirm: false` in config.yaml." - ) - if isinstance(result, str): - return result + note - # EphemeralReply or other: leave untouched, since the note would - # mangle structured replies. - return result - return result + # Via the class, not ``self``: tests drive this gate on a bare SimpleNamespace runner. + return await GatewayBusySessionMixin._run_confirmed_destructive_slash( + choice, command, execute, session_key + ) _p = self._typed_command_prefix_for(event.source.platform) prompt_message = ( @@ -1441,83 +1017,93 @@ class GatewayBusySessionMixin: f"_Text fallback: reply `{_p}approve`, `{_p}always`, or `{_p}cancel`._" ) return await self._request_slash_confirm( - event=event, - command=command, - title=title, - message=prompt_message, - handler=_on_confirm, + event=event, command=command, title=title, message=prompt_message, handler=_on_confirm ) + _DESTRUCTIVE_OPTOUT_NOTE = { + True: ( + "\n\nℹ️ Future /clear, /new, /reset, and /undo will run " + "without confirmation. Re-enable via " + "`approvals.destructive_slash_confirm: true` in config.yaml." + ), + # The user did approve this run, so the action still goes ahead, but the preference did + # not stick and the prompt will be back next time. Say so rather than promising an + # opt-out that was never written. + False: ( + "\n\n⚠️ Could not save that preference (config.yaml is not " + "writable), so /clear, /new, /reset, and /undo will ask " + "again next time. To silence it permanently, set " + "`approvals.destructive_slash_confirm: false` in config.yaml." + ), + } + + @staticmethod + async def _run_confirmed_destructive_slash(choice: str, command: str, execute, session_key: str): + """Confirm-callback body: ``cancel`` → message; ``always`` persists the opt-out, then runs.""" + if choice == "cancel": + return f"🟡 /{command} cancelled. Conversation unchanged." + persisted = False + if choice == "always": + try: + from cli import save_config_value + # save_config_value swallows its own errors and reports the outcome in the return + # value, so the try block alone says nothing about whether the write landed. + persisted = bool(save_config_value("approvals.destructive_slash_confirm", False)) + if persisted: + logger.info("User opted out of destructive slash confirm (session=%s)", session_key) + else: + logger.warning( + "Could not persist destructive_slash_confirm=false " + "(session=%s); config.yaml is not writable", session_key, + ) + except Exception as exc: + logger.warning("Failed to persist destructive_slash_confirm=false: %s", exc) + result = await execute() + # Only plain-string results get the note: it would mangle an EphemeralReply. + if choice == "always" and isinstance(result, str): + return result + GatewayBusySessionMixin._DESTRUCTIVE_OPTOUT_NOTE[persisted] + return result + async def _request_slash_confirm( - self, - *, - event: MessageEvent, - command: str, - title: str, - message: str, - handler, + self, *, event: MessageEvent, command: str, title: str, message: str, handler ) -> Optional[str]: - """Ask the user to confirm an expensive slash command. - - ``handler(choice: str) -> str`` runs on the event loop when the user responds with - ``"once"``, ``"always"``, or ``"cancel"``; its return value is sent as a gateway message. - Returns the immediate acknowledgment: ``None`` if buttons rendered (self-explanatory), - otherwise the text-fallback message itself IS the ack. - """ + """Ask the user to confirm a slash command; ``handler(choice)`` runs on "once"/"always"/ + "cancel" and its return is sent as a message. Returns None if buttons rendered, else the + text-fallback message (which IS the ack).""" from tools import slash_confirm as _slash_confirm_mod - source = event.source session_key = self._session_key_for_source(source) - # Bare-runner test harnesses (object.__new__(GatewayRunner)) skip __init__ and lack the - # counter attribute; fall back to a local counter. Real runs always have the attribute. + # object.__new__ test runners lack the counter; fall back to a local one. counter = getattr(self, "_slash_confirm_counter", None) if counter is None: import itertools as _itertools - counter = _itertools.count(1) - self._slash_confirm_counter = counter + counter = self._slash_confirm_counter = _itertools.count(1) confirm_id = f"{next(counter)}" - # Register the pending confirm FIRST so a super-fast button click - # cannot race the send_slash_confirm return. + # Register FIRST so a fast button click cannot race the send_slash_confirm return. _slash_confirm_mod.register(session_key, confirm_id, command, handler) adapter = self._adapter_for_source(source) metadata = self._thread_metadata_for_source(source, self._reply_anchor_for_event(event)) - used_buttons = False if adapter is not None: try: button_result = await adapter.send_slash_confirm( - chat_id=source.chat_id, - title=title, - message=message, - session_key=session_key, - confirm_id=confirm_id, - metadata=metadata, + chat_id=source.chat_id, title=title, message=message, session_key=session_key, + confirm_id=confirm_id, metadata=metadata, ) if button_result and getattr(button_result, "success", False): - used_buttons = True + return None # buttons rendered — no redundant text ack except Exception as exc: - logger.debug( - "send_slash_confirm failed for %s on %s: %s", - command, source.platform, exc, - ) - - if used_buttons: - # Buttons rendered — no redundant text ack. - return None - # Text fallback — return the prompt message as the direct reply. + logger.debug("send_slash_confirm failed for %s on %s: %s", command, source.platform, exc) + # Text fallback — the prompt message itself is the direct reply. return message def _read_user_config(self) -> Dict[str, Any]: - """Read the user's raw config.yaml (cached) for gate lookups. - - Used by slash-confirm gates that must reflect on-disk state changes - (e.g. a prior "Always Approve" click) without a gateway restart. - """ + """Raw config.yaml for gate lookups that must see on-disk changes without a restart.""" try: from hermes_cli.config import load_config cfg = load_config() - return cfg if isinstance(cfg, dict) else {} except Exception: return {} + return cfg if isinstance(cfg, dict) else {}