The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): compact run_* inline comments by hand (keep every WHY/invariant)
Teknium792960cba1ca
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex b491fc05231..3ed61e4cbe9 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -199,9 +199,8 @@ class GatewayAdapterLifecycleMixin:if not platform_config:return Falseif adapter.platform in self._failed_platforms:- # 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.+ # Already queued is exactly when the watcher may have died (supervision gave up); without+ # this backstop nothing retries and the stranded check treats "queued" as safe.self._ensure_reconnect_watcher_running()return Falseself._failed_platforms[adapter.platform] = self._reconnect_queue_entry(@@ -215,8 +214,7 @@ class GatewayAdapterLifecycleMixin:"""Run the fatal handler; a platform left stranded (not reconnected, not queued, notintentionally disabled) exits the gateway with failure so the service manager restarts it."""try:- # Outer hard deadline: a hang anywhere in the impl must not wedge this task — the- # stranded check in ``finally`` only runs when we return.+ # Outer hard deadline: 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)@@ -263,8 +261,7 @@ class GatewayAdapterLifecycleMixin:self._queue_retryable_fatal_platform(adapter)async def _handle_adapter_fatal_error_impl(self, adapter: BasePlatformAdapter) -> None:- # Snapshot the slot owner first: a stale notification must not overwrite a healthy- # platform's runtime status or re-queue it.+ # Snapshot the slot owner first: a stale notification must not touch a healthy platform.existing = self.adapters.get(adapter.platform)if existing is not None and existing is not adapter:logger.debug(@@ -287,12 +284,10 @@ class GatewayAdapterLifecycleMixin:error_message=adapter.fatal_error_message,)if existing is adapter:- # Claim for teardown BEFORE awaiting disconnect(), else a concurrent second fatal- # notification for the same adapter would disconnect() it twice.+ # Claim for teardown BEFORE awaiting disconnect(), else a second fatal disconnects it twice.self.adapters.pop(adapter.platform, None)self.delivery_router.adapters = self.adapters- # Queue BEFORE any disconnect await: a half-dead transport can wedge native close() (or- # swallow CancelledError), and "disconnect then queue" left platforms permanently deaf.+ # Queue BEFORE any disconnect await: a wedged close() once left platforms permanently deaf.self._queue_retryable_fatal_platform(adapter)if existing is adapter:# Bounded by the shutdown-path timeout so this always returns to the stranded check.@@ -306,8 +301,7 @@ class GatewayAdapterLifecycleMixin:logger.error("No connected messaging platforms remain. Shutting down gateway cleanly.")await self.stop()elif not self.adapters and self._failed_platforms:- # 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.+ # All down but queued: stay alive (cron runs, watcher recovers) rather than restart-loop.logger.warning("No connected messaging platforms remain, but %d platform(s) ""queued for reconnection — gateway staying alive, watcher will "@@ -351,11 +345,9 @@ class GatewayAdapterLifecycleMixin:respawn leaves a stale handle and a SECOND watcher; ``on_give_up(name)`` fires at budget end."""# Spawn timestamp lets ``_done`` tell a rapid crash-loop from a healthy-run-then-crash._started = time.monotonic()- # 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()).+ # No create_task kwargs (test doubles mock a narrow signature); Context().run isolates instead.task = Context().run(lambda: asyncio.create_task(coro_factory()))- # 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.+ # PERMANENT watcher: the scale-to-zero idle check ignores it (else busy forever).task._hermes_supervised_watcher = True # type: ignore[attr-defined]self._retain_background_task(task)if on_spawn is not None:@@ -376,8 +368,7 @@ class GatewayAdapterLifecycleMixin:logger.error("Supervised task %s died: %r", name, exc, exc_info=exc)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.+ # A healthy run before the crash is a FRESH failure, not a crash-loop: reset the counter.healthy = time.monotonic() - _started >= self._SUPERVISED_HEALTHY_SECSeffective_attempt = 0 if healthy else _attemptif effective_attempt >= self._MAX_SUPERVISED_RESTARTS:@@ -420,8 +411,7 @@ class GatewayAdapterLifecycleMixin:_process_takes_profile = len(_inspect.signature(self._process_handoff).parameters) >= 2except Exception:_process_takes_profile = False- # 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.+ # In-flight dispatches by session id: a handoff is a FULL agent turn, so never process inline.inflight: Dict[str, "asyncio.Task"] = {}async def _dispatch(row, session_id, session_db, profile_name) -> None:@@ -430,8 +420,7 @@ class GatewayAdapterLifecycleMixin: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.+ # Leave the row 'running' so the next start's reclaim marks it failed with a clear reason.raiseexcept Exception as exc:logger.warning("Handoff for session %s failed: %s", session_id, exc, exc_info=True)@@ -455,15 +444,13 @@ class GatewayAdapterLifecycleMixin:if not await session_db.claim_handoff(session_id):# Another tick or another gateway already claimed it.continue- # 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.+ # INVARIANT (do not weaken): created inside _profile_runtime_scope but RUNS after it+ # exits; it sees the profile scope only because ensure_future copies the Context.inflight[session_id] = asyncio.ensure_future(_dispatch(row, session_id, session_db, profile_name))- # A row still 'running' at startup belongs to a gateway that died mid-dispatch; it blocks- # request_handoff until reclaimed.+ # A row still 'running' at startup died mid-dispatch and blocks request_handoff until reclaimed.def _scope(profile_home): # local: tests bind this watcher onto bare SimpleNamespace runnersreturn GatewayAdapterLifecycleMixin._scope_or_null(_async_profile_runtime_scope, profile_home)@@ -648,8 +635,7 @@ class GatewayAdapterLifecycleMixin:self._drop_from_reconnect_queue(platform, "adapter creation returned None")returnself._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.+ # is_reconnect keeps the server-side update queue so offline-period messages are delivered.success = await self._connect_adapter_with_timeout(adapter, platform, is_reconnect=True)if success:await self._install_reconnected_adapter(platform, adapter)@@ -659,13 +645,11 @@ class GatewayAdapterLifecycleMixin:"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).+ # Never installed on self.adapters: dispose here or its __init__ resources leak ~2 fds each.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.+ # Retryable failures retry at the cap forever (never auto-pause). Same fd-leak dispose.backoff = self._bump_reconnect_backoff(platform, info, attempt, adapter.fatal_error_code,adapter.fatal_error_message or "failed to reconnect",@@ -700,8 +684,7 @@ class GatewayAdapterLifecycleMixin: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.+ # Responses rejected while down are owned by this live process (startup recovery cannot claim them).with _log_suppressed(logging.DEBUG, "failed-obligation redelivery after %s reconnect failed",platform.value, exc_info=True,@@ -711,8 +694,7 @@ class GatewayAdapterLifecycleMixin:with suppress(Exception):from gateway.channel_directory import build_channel_directoryawait build_channel_directory(self.adapters)- # 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.+ # A platform offline at startup skipped its restart-interrupted sessions; resume them now.try:self._schedule_resume_pending_sessions(platform=platform)except Exception:@@ -816,15 +798,13 @@ class GatewayAdapterLifecycleMixin:)from gateway.config import load_gateway_configfrom hermes_cli.env_loader import hydrate_profile_secret_sources- # 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.+ # Hydrate external secret sources off-loop ONCE: sync hydration would stall every heartbeat.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_pluginsdiscover_plugins()- # 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.+ # This profile's `hooks:` block: start() registered before any profile scope existed.self._register_config_hooks("shell-hook/webhook registration failed for profile '%s'", profile_name, level=logging.WARNING,)@@ -897,16 +877,14 @@ class GatewayAdapterLifecycleMixin:for platform, platform_config in profile_cfg.platforms.items():if not platform_config.enabled:continue- # 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.+ # No credential in THIS profile's scope: an adapter would fan inbound across every such 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,)continue- # 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.+ # Relay/WhatsApp are shared process-level ingress under multiplex; a secondary would retry-loop.if multiplex and platform in (Platform.RELAY, Platform.WHATSAPP):continueadapter = None@@ -978,12 +956,10 @@ class GatewayAdapterLifecycleMixin: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.+ # Runtime status is process-scoped: key on profile:platform so health shows 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.+ # Declare ownership BEFORE any inbound event: adapter-level session keys are derived at ingress,+ # before the handler stamps source.profile (else every secondary keys into `agent:main:`)._set_owner = getattr(adapter, "set_owner_profile", None)if callable(_set_owner):_set_owner(profile_name)@@ -1001,11 +977,9 @@ class GatewayAdapterLifecycleMixin:else self._busy_text_mode),)- # Voice transcripts from this bot's channels dispatch through THIS adapter (primary- # wiring lives at connect time).+ # Voice transcripts from this bot's channels dispatch through THIS adapter.self._bind_voice_input_callback(adapter)- # Secondary adapters always carry the profile they serve so prune paths namespace topic- # bindings correctly under multiplex.+ # Secondary adapters carry their profile so prune paths namespace topic bindings correctly.adapter._hermes_profile_name = profile_nameasync def _secondary_reconnect_attempt(self, profile_name: str, platform: Platform):@@ -1069,9 +1043,8 @@ class GatewayAdapterLifecycleMixin:platform, profile=profile_name)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.+ # Not installed (newer reconnect won the slot, shutdown began, or connect failed):+ # release partial resources; stop only for a non-retryable fatal.await self._safe_adapter_disconnect(adapter, platform)if success or (getattr(adapter, "has_fatal_error", False)@@ -1114,8 +1087,7 @@ class GatewayAdapterLifecycleMixin:if not getattr(adapter, "fatal_error_retryable", True):returnif is_global_startup_conflict(getattr(adapter, "fatal_error_code", None)):- # 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.+ # A live foreign token holder is an ownership conflict, not a blip: park it fatal.logger.error("[MULTIPLEX] Profile '%s': %s credential is held by another ""gateway (%s) — parked, not retried. %s", profile_name, platform.value,@@ -1128,8 +1100,7 @@ class GatewayAdapterLifecycleMixin: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.+ # A raise here would die as an unretrieved-task exception logged only at GC; surface it.logger.exception("secondary-startup-reconnect handoff failed (profile=%s platform=%s)",profile_name, platform.value,@@ -1339,8 +1310,7 @@ class GatewayAdapterLifecycleMixin:def _adapter_credential_fingerprint(adapter: Any) -> Optional[str]:"""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.+ # Many adapters (Discord) keep the token on `config`; without that fallback the check is skipped.candidates = [(adapter, attr) for attr in ("token", "bot_token", "_token", "api_token", "_bot_token",@@ -1404,8 +1374,7 @@ class GatewayAdapterLifecycleMixin: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 transport provenance ``build_source`` retains, so adapter-level policy reads- # resolve the receiving adapter even once the routed profile is stamped below.+ # Same transport provenance as ``build_source``, so policy reads resolve the receiving adapter.registry = ((getattr(self, "_profile_adapters", None) or {}).get(profile_name)if profile_name else getattr(self, "adapters", None)diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex e57ec6d393c..494fc934a71 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -39,8 +39,7 @@ _DURABLE_CLAIM_OPS = {class GatewayNotificationsMixin:"""Process/completion/update notifications, media delivery and async-delegation delivery for GatewayRunner."""- # Routing-complete coalescing keys: process completions (short-window fan-in) and async- # delegations (originating session + parent session + route).+ # Coalescing keys: process completions (short-window fan-in) and async delegations (+ parent session)._COMPLETION_BATCH_KEY_FIELDS = ("session_key", "platform", "chat_type", "chat_id", "thread_id", "user_id")_ASYNC_GROUP_KEY_FIELDS = ("session_key", "parent_session_id", *_COMPLETION_BATCH_KEY_FIELDS[1:])@@ -141,8 +140,7 @@ class GatewayNotificationsMixin:return Noneroute_owns_lineage = session_entry.session_id in {pinned_session_id, target_session_id}if not route_owns_lineage:- # A delegation may survive several compression rotations: accept an intermediate stale- # route only when its own verified compression tip is the same live target.+ # Across several rotations, accept a stale route only when its own tip is the same live target.try:route_row = await session_db.get_session(session_entry.session_id)route_tip = (@@ -204,9 +202,8 @@ class GatewayNotificationsMixin:)return Noneif _end_reason != "compression":- # Idle/timeout/lifecycle end (scale-to-zero norm): the chat route is still valid and- # ``session_entry`` is its current session, so deliver here rather than drop — otherwise- # the row is acked at adapter acceptance then silently lost.+ # Idle/timeout end (scale-to-zero norm): the chat route is still valid, so deliver to its+ # current session rather than drop (the row would be acked then silently lost).logger.info("Async-delegation completion pinned to %s-ended session %s; ""retargeting to the chat's current session %s.",@@ -250,13 +247,12 @@ class GatewayNotificationsMixin:directive is a deliberate attach); stale auto-appended tags are deduped upstream."""from urllib.parse import quote as _quotewith _log_suppressed(logging.WARNING, "Post-stream media extraction failed: %s"):- # Capture [[as_document]] before extract_media strips it: image files then go through- # send_document (preserving bytes), not send_multiple_images (Telegram recompresses).+ # Capture [[as_document]] before extract_media strips it: images then go via send_document.force_document_attachments = "[[as_document]]" in responsefrom gateway.platforms.base import BasePlatformAdapter, should_send_media_as_audiomedia_files, cleaned = adapter.extract_media(response)media_files = BasePlatformAdapter.filter_media_delivery_paths(media_files)- # Strip image URLs for parity with the non-streaming chain; no extract_local_files here.+ # Strip image URLs (parity with the non-streaming chain); no extract_local_files here.adapter.extract_images(cleaned)_thread_meta = (dict(thread_metadata)@@ -302,9 +298,8 @@ class GatewayNotificationsMixin:if not text_already_delivered:text_content = _strip_response_attachments_for_direct_send(response, adapter)if text_content:- # Reconcile-by-edit first: a stream-sealed message whose recorded payload didn't confirm- # the final (post-stream mutation) already carries most of the answer; a plain send here- # would duplicate it.+ # Reconcile-by-edit first: a stream-sealed message already carries most of the answer;+ # a plain send here would duplicate it._reconciled = False_sc_msg_id = getattr(stream_consumer, "message_id", None)if (@@ -388,8 +383,7 @@ class GatewayNotificationsMixin:async def _watch_update_completion_only(self, paths: "_UpdatePaths", deadline: float, poll_interval: float) -> None:"""Fallback when no adapter/chat can be resolved: wait for the exit code, then notify."""logger.warning("Update watcher: cannot resolve adapter/chat_id, falling back to completion-only")- # Keep polling until _send_update_notification actually delivers (True) — it re-resolves the- # adapter each call and returns False (markers kept) while the platform is still reconnecting.+ # Poll until _send_update_notification delivers (it returns False while the platform reconnects).loop = asyncio.get_running_loop()while paths.any_pending() and loop.time() < deadline:if paths.exit_code.exists() and await self._send_update_notification():@@ -443,8 +437,7 @@ class GatewayNotificationsMixin:f"⚕ **Update needs your input:**\n\n{prompt_text}{default_hint}\n\n"f"Reply `{_p}approve` (yes) or `{_p}deny` (no), or type your answer directly.")- # Keep the prompt marker on disk until the user answers so a watcher after a mid-prompt- # gateway restart can recover by re-forwarding it.+ # Keep the prompt marker on disk until answered so a restarted watcher can re-forward it.self._session_state(target.session_key).persistent.update_prompt_pending = Truelogger.info("Forwarded update prompt to %s: %s", target.session_key, prompt_text[:80])@@ -504,8 +497,7 @@ class GatewayNotificationsMixin:_read_new_output()if buffer.strip() and (loop.time() - last_stream_time) >= stream_interval:await _flush_buffer()- # Forward a prompt only when none is still awaiting a response; otherwise the watcher- # would re-read the same .update_prompt.json every poll and spam duplicate prompts.+ # Forward a prompt only when none is pending, else every poll re-forwards the same prompt._pending_state = self._peek_session_state(session_key) if session_key else Noneif paths.prompt.exists() and session_key and not getattr(getattr(_pending_state, "persistent", None), "update_prompt_pending", False@@ -566,9 +558,8 @@ class GatewayNotificationsMixin:platform = Platform(platform_str)adapter = self.adapters.get(platform)if chat_id and not adapter:- # The update finished, but the target platform has not reconnected yet (common right- # after the restart that `hermes update` triggers). A definitive skip would delete the- # markers and silently lose the notification; preserve them for a later retry.+ # Target platform not reconnected yet (common right after the update's restart): keep the+ # markers for a later retry instead of silently losing the notification.return _defer("Update notification deferred: %s adapter not connected yet", platform_str)if chat_id:metadata = self._pending_marker_metadata(platform, chat_id, pending, adapter)@@ -869,8 +860,7 @@ class GatewayNotificationsMixin:from gateway.wake import adapter_supports_pushsource = await asyncio.to_thread(self._build_process_event_source, evt)if not source:- # API-server sessions bind the RAW X-Hermes-Session-Id key (_bind_api_server_session), not a- # structured ``agent:main:...`` key, so _build_process_event_source returned None above.+ # API-server sessions bind the RAW X-Hermes-Session-Id key, not a structured ``agent:...`` key.raw_sid = str(evt.get("origin_session_id") or "").strip()_sk = str(evt.get("session_key") or "").strip()if not raw_sid and _sk and _parse_session_key(_sk) is None:@@ -894,9 +884,8 @@ class GatewayNotificationsMixin:if not adapter:return Noneif not adapter_supports_push(adapter):- # Non-push adapter (api_server) resolved WITH routing metadata: its chat_id is the raw session- # id (_bind_api_server_session binds chat_id = session_id), so handle_message would run the- # wake under a build_session_key() key that never matches the raw session — self-post.+ # Non-push adapter (api_server): its chat_id IS the raw session id, so handle_message would+ # key the wake under a build_session_key() that never matches — self-post instead.raw_sid = str(evt.get("origin_session_id") or "").strip() or str(source.chat_id or "")return await self._self_post_api_server(adapter, synth_text, raw_sid, evt)try:@@ -912,9 +901,8 @@ class GatewayNotificationsMixin:"Watch pattern notification — injecting for %s chat=%s thread=%s",platform_name, source.chat_id, source.thread_id,)- # Relay-plane egress priming: a synthetic turn injected right after a restart reaches a relay- # adapter whose per-chat routing caches are cold (they warm only on inbound), so its replies- # egress without tenant discriminators and the connector's fail-closed guard declines them.+ # Relay egress priming: post-restart routing caches are cold (they warm only on inbound), so+ # replies would egress without tenant discriminators and be declined by the connector._prime = getattr(adapter, "prime_routing_cache", None)if callable(_prime):_prime(synth_event)@@ -985,15 +973,13 @@ class GatewayNotificationsMixin:return "deliver"end_reason = str(parent.get("end_reason") or "")if end_reason != "compression":- # Only a USER-closed thread of work (/new, user_exit, session_switch) is unreachable;- # idle/timeout ends are normal on scale-to-zero relays — the chat stays routable and the- # resolver retargets. Boundary set shared with the resolver: no drift.+ # Only a USER-closed session (/new, user_exit, session_switch) is unreachable; idle/timeout+ # ends stay routable and the resolver retargets. Boundary set shared with the resolver.return "terminal" if end_reason in _USER_BOUNDARY_END_REASONS else "deliver"try:tip_session_id = await session_db.get_compression_tip(parent_session_id)if not tip_session_id or tip_session_id == parent_session_id:- # Rotation caught mid-flight: parent is compression-ended but its continuation isn't- # visible yet. Retry, don't drop.+ # Rotation mid-flight: continuation not visible yet. Retry, don't drop.return "retry"tip = await session_db.get_session(tip_session_id)except Exception:@@ -1038,8 +1024,7 @@ class GatewayNotificationsMixin:elif evt_type != "completion":return claim# Background completions carry only session_key, so after /new the OLD session's notification- # would land in the chat's NEW session. Stamped events get the same pre-flight as async- # delegations; unstamped ones deliver.+ # would land in the NEW one. Stamped events get the async-delegation pre-flight; unstamped deliver.parent_session_id = str(evt.get("parent_session_id") or "").strip()if not parent_session_id:return claim@@ -1062,8 +1047,7 @@ class GatewayNotificationsMixin:)claim.proceed = Falseelif verdict == "retry":- # Transient uncertainty (session DB down / compression rotation mid-flight): tell the- # watcher to re-poll and retry rather than drop or misroute the result.+ # Transient uncertainty: tell the watcher to re-poll rather than drop or misroute.if claim.claim_id:self._settle_durable_claim("release", claim.delegation_id, claim.claim_id)claim.proceed, claim.early_result = False, False@@ -1090,8 +1074,7 @@ class GatewayNotificationsMixin:if identity is not None:with self._completion_delivery_lock:self._mark_completions_delivered_locked((identity,))- # The durable async-delegation row is the authoritative replay state — ack it after- # adapter acceptance; no parallel ledger here.+ # The durable row is the authoritative replay state — ack it after adapter acceptance.if claim.claim_id:try:from tools.async_delegation import complete_completion_delivery@@ -1124,8 +1107,7 @@ class GatewayNotificationsMixin:session_id = str(evt.get("session_id") or "unknown")exit_code = evt.get("exit_code")reason = str(evt.get("completion_reason") or "exited")- # Completion output normally passes the terminal redactor at the producer seam, but that is- # configurable and this is user-facing, so keep the unconditional gateway floor. Redact+ # Unconditional gateway redaction floor (the producer-seam redactor is configurable). Redact# BEFORE slicing: truncating first can leave a credential fragment the patterns miss.output = _redact_gateway_user_facing_secrets(str(evt.get("output") or "")).strip()if len(output) > 800:@@ -1156,15 +1138,14 @@ class GatewayNotificationsMixin:try:await asyncio.sleep(self._completion_notification_batch_window)entries = self._completion_notification_batches.pop(key, [])- # Detach before adapter delivery: a completion arriving while this batch is in flight- # must be able to schedule the next flush.+ # Detach before delivery so a completion arriving mid-flight can schedule the next flush.if self._completion_notification_batch_tasks.get(key) is current_task:self._completion_notification_batch_tasks.pop(key, None)if not entries:returnsynth_text = entries[0][0] if len(entries) == 1 else self._format_coalesced_process_completions(entries)- # A duplicate primary can legitimately return None from the lifecycle dedupe seam; try the- # next batch identity so a fresh sibling is never discarded with that duplicate.+ # A duplicate primary returns None from the dedupe seam; try the next identity so a fresh+ # sibling is never discarded with it.delivered = Nonefor _text, candidate_evt, _future in entries:delivered = await self._deliver_completion_notification(synth_text, candidate_evt)@@ -1173,8 +1154,7 @@ class GatewayNotificationsMixin:if delivered is True and len(entries) > 1:self._record_coalesced_completion_siblings([evt for _text, evt, _future in entries])except asyncio.CancelledError:- # Shutdown may cancel us mid fan-in or while adapter delivery is blocked: recover entries not- # yet detached and resolve every waiter as retryable before adapters are torn down.+ # Shutdown cancellation: recover undetached entries and resolve every waiter as retryable.delivered = Falseif not entries:entries = self._completion_notification_batches.pop(key, [])@@ -1183,8 +1163,7 @@ class GatewayNotificationsMixin:logger.exception("Coalesced process completion delivery failed")delivered = Falsefinally:- # Never strand watcher futures when formatting, delivery, or cancellation interrupts a batch:- # False follows the existing watcher retry path; None remains the ordinary dedupe result.+ # Never strand watcher futures: False = watcher retry path; None = ordinary dedupe result.self._settle_batch_waiters(entries, delivered)# Do not remove a newer flush task that reused the same route key.if self._completion_notification_batch_tasks.get(key) is current_task:@@ -1218,8 +1197,7 @@ class GatewayNotificationsMixin:async def _enqueue_process_completion_notification(self, synth_text: str, evt: dict) -> Optional[bool]:"""Fan in concurrent process completions that share one conversation."""- # Some unit tests construct GatewayRunner with object.__new__. Keep the- # batching seam lazy so those focused lifecycle tests remain valid.+ # Lazy defaults: lifecycle tests build GatewayRunner via object.__new__.for attr, default in (("_completion_notification_batches", dict), ("_completion_notification_batch_tasks", dict),("_completion_notification_batch_flush_tasks", set),@@ -1295,8 +1273,7 @@ class GatewayNotificationsMixin:for evt, synth_text in deliverable[1:]:claim_id = claim_event_delivery(evt, f"gateway-batch:{id(self)}")if claim_id is None:- # Another consumer owns this row's delivery; keep its result out of our- # consolidated text so it is never double-injected.+ # Another consumer owns this row: keep it out of our text so it is never double-injected.continuesiblings.append((evt, claim_id))blocks.append(synth_text)@@ -1319,12 +1296,10 @@ class GatewayNotificationsMixin:)self._record_coalesced_completion_siblings([evt for evt, _claim_id in siblings])else:- # Not delivered — release every sibling claim so a retry or another consumer can claim- # it, honestly leaving the durable rows pending.+ # Not delivered: release every sibling claim so a retry or another consumer can take it.self._settle_sibling_claims(siblings, release_event_delivery, "Could not release coalesced durable claim")if delivered is None:- # The primary was dropped/owned elsewhere but the siblings still need delivery —- # requeue just them for the next tick.+ # Primary dropped/owned elsewhere: requeue just the siblings for the next tick.for evt, _claim_id in siblings:_pr.completion_queue.put(evt)return delivered@@ -1339,8 +1314,7 @@ class GatewayNotificationsMixin:from tools.process_registry import process_registry as _prwhile self._running:with _log_suppressed(logging.DEBUG, "Async delegation watcher error: %s"):- # Peek for async-delegation events only; watch/completion events belong to other drains,- # so requeue anything that isn't ours.+ # Take async-delegation events only; requeue watch/completion events for their own drains.requeue = []async_events = []while not _pr.completion_queue.empty():@@ -1351,9 +1325,8 @@ class GatewayNotificationsMixin:(async_events if evt.get("type") == "async_delegation" else requeue).append(evt)for evt in requeue:_pr.completion_queue.put(evt)- # A same-tick drain often carries several completions for the SAME session (a fan-out- # finishing together); delivering each individually floods it with N synthetic turns.- # Group by full gateway route + parent session: one consolidated turn per group.+ # A fan-out finishing together yields N completions for one session; group by full route ++ # parent session so each group becomes ONE consolidated turn.groups: dict[tuple[str, ...], list[dict]] = {}for evt in async_events:self._enrich_async_delegation_routing(evt)@@ -1378,9 +1351,8 @@ class GatewayNotificationsMixin:if new_output:from agent.redact import redact_terminal_outputnew_output = redact_terminal_output(new_output, getattr(session, "command", "") or "")- # redact_terminal_output() is unforced, so it returns raw text when security.redact_secrets- # is off. This goes straight to the platform adapter, so it needs the same unconditional- # floor as agent-notify.+ # redact_terminal_output() is unforced (raw when security.redact_secrets is off); this goes+ # straight to the adapter, so apply the same unconditional floor as agent-notify.new_output = _redact_gateway_user_facing_secrets(new_output)return new_output@@ -1403,8 +1375,7 @@ class GatewayNotificationsMixin:_command = getattr(session, "command", "") or ""_raw = strip_ansi(session.output_buffer) if session.output_buffer else ""_raw = redact_terminal_output(_raw, _command)- # Truncate on line boundaries (never start mid-line): keep the last ~2000 chars snapped to- # the preceding newline, prepending a marker when output was cut.+ # Keep the last ~2000 chars snapped to a line boundary, with a marker when cut._LIMIT = 2000if len(_raw) > _LIMIT:_tail = _raw[-_LIMIT:]@@ -1424,8 +1395,7 @@ class GatewayNotificationsMixin:"completion_reason": getattr(session, "completion_reason", "exited"),"termination_source": getattr(session, "termination_source", ""),"output": _redact_gateway_user_facing_secrets(_out),- # Spawning conversation's session-db id (stamped in terminal_tool); lets delivery- # pre-flight drop this completion if the user closed that session (/new) first.+ # Spawning session-db id: lets pre-flight drop this completion if the user /new'd first."parent_session_id": (watcher.get("parent_session_id") or getattr(session, "parent_session_id", "") or ""),@@ -1477,9 +1447,8 @@ class GatewayNotificationsMixin:has_new_output = current_output_len > last_output_lenlast_output_len = current_output_lenif session.exited:- # Agent-triggered completion: inject a synthetic message unless the agent already consumed- # the result via wait/log. poll() is read-only and deliberately does NOT mark consumed —- # a status check must not suppress this delivery turn.+ # Agent-notify: inject a synthetic message unless the agent already consumed the result via+ # wait/log (poll() is read-only and deliberately does NOT mark consumed).if agent_notify and not process_registry.is_completion_consumed(session_id):completion_evt = self._build_process_completion_event(watcher, session, session_id)synth_text = format_process_notification(completion_evt)@@ -1491,9 +1460,8 @@ class GatewayNotificationsMixin:# of suppressing the result.continuebreak- # Normal text-only notification. Skip when the agent already consumed this completion via- # wait/log (output returned inline) — the raw "finished" message would be a duplicate.- # The agent_notify skip FALLS THROUGH here, hence this check. poll() is read-only.+ # Text-only notification; skip when already consumed via wait/log (the agent_notify branch+ # FALLS THROUGH here, hence the re-check).if process_registry.is_completion_consumed(session_id):logger.debug("Process watcher: completion for %s already consumed "diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex e79c246b083..75121e9025d 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -332,9 +332,8 @@ class GatewayShutdownMixin:def _scale_to_zero_is_idle(self) -> bool:from gateway.scale_to_zero import is_idle- # FULL work aggregate (cron + API runs live outside _running_agents) with fail-AWAKE reads:- # the drain counters swallow errors to 0, which for a suspend predicate would look idle, so- # an unreadable source counts as work here.+ # FULL work aggregate with fail-AWAKE reads: the drain counters swallow errors to 0, which a+ # suspend predicate would read as idle, so an unreadable source counts as work here.def _read_or_awake(label: str, fn: Callable[[], Any], busy_sentinel: Any) -> Any:try:@@ -345,9 +344,8 @@ class GatewayShutdownMixin:cron_count = _read_or_awake("cron work count", self._running_cron_job_count, 1)api_count = _read_or_awake("api work count", lambda: self._api_server_hook("active_agent_work_count"), 1)- # An attached dashboard/desktop/TUI client (heartbeat file mtime from the dashboard process) is- # inbound activity too — folded into the inbound clock, not a conjunct, so disconnect gets the- # same idle_timeout grace as a message and a lingering marker cannot pin the box.+ # An attached dashboard/desktop/TUI client (heartbeat mtime) is inbound activity — folded into+ # the inbound clock, not a conjunct, so a lingering marker cannot pin the box.last_inbound = self._last_inbound_atfrom gateway.scale_to_zero import dashboard_client_last_seenseen = _read_or_awake("dashboard heartbeat", dashboard_client_last_seen, time.time())@@ -426,9 +424,8 @@ class GatewayShutdownMixin:# After a wake the drained inbound updates _last_inbound_at; give it a window so we# don't immediately re-go-dormant on the same idle reading before traffic lands.self._scale_to_zero_cooldown_until = time.time() + max(interval, 60.0)- # Self-suspend ONLY after a clean quiesce: the relay flip (buffered delivery + wake- # poke armed) must be set before the freeze, or inbound black-holes while we sleep.- # Re-check idle one last time — inbound may have landed during the quiesce await.+ # Self-suspend ONLY after a clean quiesce (else inbound black-holes while we sleep), and+ # re-check idle — inbound may have landed during the quiesce await.if not dormant_ok:continueif not self._scale_to_zero_is_idle():@@ -457,9 +454,8 @@ class GatewayShutdownMixin:except Exception: # noqa: BLE001 - suspend is best-effort, never crashlogger.debug("scale-to-zero: self-suspend failed", exc_info=True)- # External drain control: the dashboard's begin/cancel-drain endpoint writes/removes the- # ``.drain_request.json`` marker (gateway/drain_control.py); the watcher flips the gateway- # between accepting and refusing NEW turns WITHOUT exiting (reversible on marker removal).+ # External drain control: the dashboard writes/removes ``.drain_request.json`` (gateway/drain_control.py);+ # the watcher flips between accepting and refusing NEW turns WITHOUT exiting (reversible).def _enter_external_drain(self) -> None:"""Begin external drain: refuse NEW turns (in-flight ones are NOT interrupted). Idempotent."""if self._external_drain_active:@@ -469,8 +465,7 @@ class GatewayShutdownMixin:"External drain ENGAGED (.drain_request.json present) — refusing ""new turns; %d in-flight turn(s) will finish. Process stays up.", self._active_work_count(),)- # Flip persisted lifecycle state so /api/status.gateway_busy / gateway_drainable track the- # drain; active_agents is preserved (read-merge keeps the live count), only state changes.+ # Persist "draining" so /api/status tracks it; active_agents is read-merged, only state changes.self._update_runtime_status("draining")def _exit_external_drain(self) -> None:@@ -534,7 +529,7 @@ class GatewayShutdownMixin:returninfo["paused"] = Trueinfo["pause_reason"] = reason or "auto-paused after repeated failures"- # Push next_retry far enough out that a stale code path missing "paused" still never fires.+ # next_retry=inf: a stale code path missing "paused" still never fires.info["next_retry"] = float("inf")self._update_platform_runtime_status(platform.value, platform_state="paused", error_code=None, error_message=info["pause_reason"],@@ -582,14 +577,12 @@ class GatewayShutdownMixin:self._update_runtime_status("draining")last_counts, last_status_at = counts, now- # Cron/API-server/deferred work lives outside ``self._running_agents`` — fold it into this- # wait, or a cron job's tool work is killed without warning once it's the only thing running.+ # Cron/API/deferred work lives outside ``_running_agents``; fold it in or it is killed unwarned._cron0, _api0, _deferred0 = last_counts[1:]_maybe_update_status(force=True)if not self._running_agents and not (_cron0 or _api0 or _deferred0):return snapshot, False- # Cron has its own deadline: ``restart_drain_timeout`` defaults to 0 (an interrupted chat turn- # is announced and resumable) but a cron run killed mid-flight is a permanent failure.+ # Cron has its own deadline: a chat turn is announced+resumable; a killed cron run is a permanent failure.started = loop.time()deadline = started + timeoutcron_deadline = started + (timeout if cron_timeout is None else cron_timeout)@@ -599,8 +592,7 @@ class GatewayShutdownMixin:agents, cron, api, deferred = self._drain_work_counts()return bool(((agents or api or deferred) and now < deadline) or (cron and now < cron_deadline))- # Both budgets at 0 leave this loop unentered ("interrupt immediately") as an expired deadline,- # not a special case, so timed_out below is always computed from real state.+ # Both budgets at 0 = an expired deadline (loop unentered), so timed_out still comes from real state.while _still_draining():_maybe_update_status()await asyncio.sleep(0.1)@@ -677,9 +669,8 @@ class GatewayShutdownMixin:job = get_job(job_id)if not job:continue- # deliver=local jobs, and deliver=origin jobs with no resolvable origin, resolve to zero- # targets and must stay silent rather than fall back to a home channel. Interrupted- # notices are failure-category engine status, so they honor failure_deliver.+ # deliver=local / unresolvable-origin jobs resolve to zero targets and stay silent (no home-+ # channel fallback). Interrupted notices are failure-category status: honor failure_deliver.targets = _resolve_delivery_targets(job, for_failure=True)except Exception as e:logger.debug("Cron interrupt targets unresolved for %s: %s", job_id, e)@@ -809,10 +800,8 @@ class GatewayShutdownMixin:if self._restart_requested and restart_source is not None:logger.debug("Skipping home-channel shutdown notifications for in-chat restart")return- # Suppress ONLY the home-channel broadcast when the drain asked to be quiet (routine fleet- # auto-update); per-session pings above stay (empty on a drained shutdown, useful on a- # force-interrupt). Current-epoch marker only, so an orphaned marker can't silence a fresh gateway.- # Never let the suppression check block the broadcast — fail toward the louder behaviour.+ # A quiet drain (routine fleet auto-update) suppresses ONLY the home-channel broadcast; per-session+ # pings above stay. Current-epoch marker only; a failing check fails toward the louder behaviour.with _log_suppressed(logging.DEBUG, "drain_notification_suppressed check failed: %s"):from gateway.drain_control import drain_notification_suppressedif drain_notification_suppressed():@@ -966,9 +955,8 @@ class GatewayShutdownMixin:returnwith suppress(Exception):if hasattr(agent, "shutdown_memory_provider"):- # Drain queued memory writes BEFORE teardown: shutdown_all() gives the memory worker- # only ~5s, so a /reset or rotation could drop handed-off writes (stale memory next- # session). Bounded, mirrors CLI exit; a failure never blocks teardown.+ # Drain queued memory writes BEFORE teardown (shutdown_all() gives the worker only ~5s, so a+ # /reset or rotation could drop them). Bounded; a failure never blocks teardown._mm = getattr(agent, "_memory_manager", None)if _mm is not None and hasattr(_mm, "flush_pending"):with suppress(Exception):@@ -1236,22 +1224,19 @@ class GatewayShutdownMixin:self._restart_detached = detachedself._restart_via_service = via_serviceself._restart_task_started = True- # Refuse new turns while in-flight work finishes. Keep ``_running`` True so adapters stay- # connected and the active turn can still deliver its final response.+ # Refuse new turns; keep ``_running`` True so the active turn can still deliver its final response.self._draining = Trueasync def _run_restart() -> None:await self._await_active_work_before_restart()- # Launch the detached helper only AFTER the after-turn wait: its drain_timeout+5 deadline- # covers stop() teardown; earlier it would fire the restart mid-turn.+ # Detached helper only AFTER the after-turn wait, or its drain_timeout+5 deadline fires mid-turn.if detached:with _log_suppressed(logging.ERROR, "Failed to launch detached gateway restart helper: %s"):await self._launch_detached_restart_command()await asyncio.sleep(0.05)await self.stop(restart=True, detached_restart=detached, service_restart=via_service)- # NOT in _background_tasks: _stop_impl cancels every entry there, which would propagate- # CancelledError into _stop_impl and skip _shutdown_event.set() / _exit_code = 75.+ # NOT in _background_tasks: _stop_impl cancels those, which would skip _shutdown_event.set() / exit 75.self._restart_task = asyncio.create_task(_run_restart())return True@@ -1309,9 +1294,8 @@ class GatewayShutdownMixin:_count_step("Shutdown (%s): killed %d tool subprocess(es)", process_registry.kill_all)def _mark_cron_interrupted() -> list:- # kill_all() is a global sweep, so any cron job dispatched right now lost its tool- # subprocess; its agent thread may still emit a plausible response from truncated- # output. Mark the run interrupted so it can never be reported as success.+ # kill_all() is global: a cron job mid-dispatch lost its tool subprocess and its agent thread may+ # still emit a plausible response from truncated output — mark it interrupted, never success.from cron.scheduler import mark_running_jobs_interrupted_interrupted = mark_running_jobs_interrupted(f"Gateway shutdown ({phase}) killed the job's tool subprocess before the run finished."@@ -1376,16 +1360,14 @@ class GatewayShutdownMixin:async def _stop_drain_active_work(self, timeout: float, ctx: "GatewayShutdownMixin._StopContext") -> None:"""Pre-mark resume_pending, drain agents/cron/API work into ``ctx``."""from gateway.run import GatewayRunner- # Pre-mark resume_pending BEFORE the drain: if the service manager kills us mid-drain, the- # durable marker already lets the next boot recover the sessions.+ # Pre-mark resume_pending BEFORE the drain so a mid-drain SIGKILL still leaves a durable marker._pre_drain_keys = await GatewayRunner._mark_running_sessions_resume_pending(self, "pre-drain mark_resume_pending")_cron_at_start = self._active_cron_job_count()_api_at_start = self._active_api_run_count()_deferred_at_start = ctx.deferred_count()- # Cron floor clamped to the watchdog leash so it never costs the post-drain cleanup window.- # getattr-guard: shutdown-path tests drive the phases from bare doubles lacking the class default.+ # Cron floor clamped to the watchdog leash; getattr-guard for bare shutdown-path doubles._cron_drain_cfg = getattr(self, "_cron_drain_timeout", DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT)_cron_timeout = resolve_cron_drain_budget(timeout, _cron_drain_cfg, watchdog_delay=resolve_shutdown_watchdog_delay(timeout),@@ -1441,23 +1423,19 @@ class GatewayShutdownMixin:def _work_live() -> bool:return bool(self._running_agents or self._active_api_run_count() or ctx.deferred_count())- # Wait on API-server work too: the interrupt is cooperative; closing the settle window as soon- # as _running_agents is empty would kill an API turn's tool subprocesses before it unwinds.+ # Wait on API-server work too, or an API turn's tool subprocesses are killed before it unwinds.while _work_live() and loop.time() < interrupt_deadline:self._update_runtime_status("draining")await asyncio.sleep(0.1)- # Work can materialize AFTER the one-shot interrupt (a /v1/runs task registers only when- # _create_agent returns; a pending sentinel is promoted by track_agent() later). Re-signal so- # it gets a cooperative interrupt instead of a bare tool-subprocess kill.+ # Work can materialize AFTER the one-shot interrupt (/v1/runs registers on _create_agent return;+ # pending sentinels promote later). Re-signal for a cooperative interrupt, not a bare kill.if _work_live():self._interrupt_running_agents(reason)logger.debug("Re-signaled interrupt for work still live at settle-window exit")- # Kill lingering tool subprocesses NOW, before adapter disconnect / DB close: under systemd- # (TimeoutStopSec ≈ drain_timeout + headroom) deferring risks the cgroup SIGKILL reaping them.+ # Kill tool subprocesses NOW: deferring past adapter/DB teardown risks the systemd cgroup SIGKILL._interrupted_cron_jobs = GatewayRunner._stop_kill_tool_subprocesses("post-interrupt")logger.info("Shutdown phase: post-interrupt tool kill done at +%.2fs", ctx.elapsed())- # Last window with the transport up: the cron worker's own "interrupted" notice arrives- # after adapter teardown and is lost.+ # Last window with the transport up (the cron worker's own notice arrives after teardown).with _log_suppressed(logging.DEBUG, "Cron interrupt notification failed: %s"):await self._notify_interrupted_cron_jobs(_interrupted_cron_jobs)logger.info("Shutdown phase: cron interrupt notices done at +%.2fs", ctx.elapsed())@@ -1468,8 +1446,7 @@ class GatewayShutdownMixin:with _log_suppressed(logging.ERROR, "Failed to launch detached gateway restart: %s"):await self._launch_detached_restart_command()await self._finalize_shutdown_agents(ctx.active_agents)- # Idle cached agents too: _finalize_shutdown_agents only covers agents mid-turn at drain- # time, but _agent_cache may hold agents whose MemoryProviders never got on_session_end().+ # Idle cached agents too: their MemoryProviders may never have seen on_session_end()._cache_lock = getattr(self, "_agent_cache_lock", None)_cache = getattr(self, "_agent_cache", None)if _cache_lock is not None and _cache is not None:@@ -1477,13 +1454,11 @@ class GatewayShutdownMixin:_idle_agents = list(_cache.values())_cache.clear()for _entry in _idle_agents:- # Bounded + off-loop so a wedged memory provider can't hang shutdown forever- # (this path is why SIGTERM once failed to kill the process).+ # Bounded + off-loop: a wedged memory provider here once made SIGTERM hang forever.await self._cleanup_agent_resources_off_loop(_entry[0] if isinstance(_entry, tuple) else _entry, context="shutdown idle-cache")- # Cancel + await completion flush tasks (fan-in sleep / adapter delivery) while adapters are- # still alive so every watcher gets a retryable result before platform teardown.+ # Settle completion flush tasks while adapters are alive so every watcher gets a retryable result.cancel_completion_batches = getattr(self, "_cancel_process_completion_batch_tasks", None)if cancel_completion_batches is not None:await cancel_completion_batches()@@ -1502,8 +1477,7 @@ class GatewayShutdownMixin:"""Cancel background tasks, flush pending messages, clear per-session state, final tool kill."""from gateway.run import GatewayRunnerfor _task in list(self._background_tasks):- # _restart_task is awaiting _stop_task right now; cancelling it would propagate- # CancelledError into _stop_impl and skip _shutdown_event.set(). It self-terminates anyway.+ # _restart_task awaits _stop_task: cancelling it would tunnel into _stop_impl and skip _shutdown_event.set().if _task is self._stop_task or _task is self._restart_task:continue_task.cancel()@@ -1511,21 +1485,18 @@ class GatewayShutdownMixin:self.adapters.clear()for _session_key in list(self._running_agents):self._release_running_agent_state(_session_key)- # Flush pending messages to disk before clearing: under FTS5 corruption the in-memory- # pending text is the only surviving copy; clearing unflushed loses it permanently.+ # Flush pending messages before clearing: under FTS5 corruption they are the only surviving copy.with suppress(Exception):from gateway.shutdown_flush import flush_pending_to_fileflush_pending_to_file(dict(self._pending_messages), reason="shutdown")- # The FIFO tail lives in SessionState.conversation.queued_events, not the slot dict- # above — flush it too or every follow-up parked in overflow at restart time is lost.+ # The overflow FIFO tail lives in SessionState.conversation.queued_events — flush it too.with suppress(Exception):from gateway.shutdown_flush import flush_overflow_to_fileflush_overflow_to_file({_k: list(_v) for _k, _v in dict(getattr(self, "_queued_events", None) or {}).items() if _v},reason="shutdown",)- # On the real runner these are live SessionState views whose clear() resets one field per- # session (never a wholesale dict swap that could lose a concurrent writer's entry).+ # Live SessionState views: clear() resets one field per session (never a wholesale dict swap).self._running_agents.clear()self._running_agents_ts.clear()self._pending_messages.clear()@@ -1534,12 +1505,10 @@ class GatewayShutdownMixin:if hasattr(self, _attr):getattr(self, _attr).clear()self._shutdown_event.set()- # Global catch-all subprocess kill (safe to repeat): covers the graceful path and- # anything respawned since the drain-timeout path's post-interrupt kill.+ # Global catch-all subprocess kill (safe to repeat) for the graceful path and late respawns.GatewayRunner._stop_kill_tool_subprocesses("final-cleanup")logger.info("Shutdown phase: final-cleanup tool kill done at +%.2fs", ctx.elapsed())- # Reap the process-global auxiliary-client cache: per-turn cleanup misses clients bound to- # worker-thread loops that died with their executor (cron ticks) → httpx transports leak to EMFILE.+ # Reap the auxiliary-client cache: clients bound to dead worker-thread loops leak httpx transports.def _reap_aux_clients() -> None:from agent.auxiliary_client import shutdown_cached_clientsshutdown_cached_clients()@@ -1557,9 +1526,8 @@ class GatewayShutdownMixin:)_exec_live = GatewayRunner._shutdown_executor(self, drain_timeout=_exec_quiesce_budget)if _exec_live:- # A live worker may be mid-write: closing now is the exact #101093 corruption sequence,- # so skip the close and let SQLite recover from its WAL on next open (a transient- # "database is locked" on an immediate --replace at worst, not a corrupt file).+ # A live worker may be mid-write (the #101093 corruption sequence): skip the close and let+ # SQLite recover from its WAL on next open (at worst a transient "database is locked").logger.warning("Shutdown phase: %d executor worker(s) still running after a %.2fs quiesce — skipping the ""SessionDB close/checkpoint to avoid racing a live write (#101093); handles are left "@@ -1568,8 +1536,7 @@ class GatewayShutdownMixin:returnlogger.info("Shutdown phase: executor quiesced at +%.2fs", ctx.elapsed())_step = GatewayShutdownMixin._quiet_step- # Close SQLite session DBs so the WAL lock is released; otherwise --replace leaves the old- # connection holding it until exit and the new gateway gets 'database is locked'.+ # Close SQLite session DBs so --replace's new gateway does not hit 'database is locked'.# ``_session_db`` is an AsyncSessionDB facade — unwrap; ``session_store`` holds ``_db``._self_db = getattr(self, "_session_db", None)_self_db = getattr(_self_db, "_db", _self_db)@@ -1577,18 +1544,15 @@ class GatewayShutdownMixin:for _db in (_self_db, getattr(store, "_db", None)):if _db is not None and hasattr(_db, "close"):_step("SessionDB close error", _db.close)- # A multiplexed session_store caches one SessionDB per profile; ``_db`` above only covered- # the root scope. Sweep the rest so secondary WAL locks are released before --replace.+ # Multiplexed session_store caches one SessionDB per profile; sweep the secondary WAL locks too._sweep = getattr(store, "close_all_db_handles", None)if _sweep is not None:_step("SessionDB handle sweep error", _sweep)- # Same sweep for the runner's own per-profile session_search handles (slash commands- # resolve them under profile scopes).+ # Same sweep for the runner's own per-profile session_search handles._step("Runner SessionDB handle sweep error", lambda: GatewayRunner.close_all_session_db_handles(self))def _close_shared() -> None:- # Shared SessionDB instances still held by the process-wide registry (tools, cron,- # mirror, etc. opened via get_shared_session_db but not released above).+ # Shared SessionDB instances still held by the process-wide registry (tools, cron, mirror).from hermes_state import close_shared_session_dbsclosed = close_shared_session_dbs()if closed:@@ -1606,9 +1570,8 @@ class GatewayShutdownMixin:from gateway.status import remove_pid_file, release_gateway_runtime_lockremove_pid_file()release_gateway_runtime_lock()- # Clean-shutdown marker: suspend_recently_active() need only run after unexpected exits.- # If the drain timed out and agents were force-interrupted, sessions may be half-finished- # — skip the marker so the next startup suspends them.+ # Clean-shutdown marker skips suspend_recently_active() next boot; a timed-out drain left+ # half-finished sessions, so no marker — the next startup suspends them.if not ctx.timed_out:with suppress(Exception):(_hermes_home / ".clean_shutdown").touch()@@ -1617,8 +1580,7 @@ class GatewayShutdownMixin:"Skipping .clean_shutdown marker — drain timed out with ""interrupted agents; next startup will suspend recently active sessions.")- # Stuck-loop detection: the counter increments for sessions active at each restart; at- # the threshold (3 consecutive) the next startup auto-suspends the session.+ # Stuck-loop counter: sessions active across 3 consecutive restarts are auto-suspended next boot.if ctx.active_agents:self._increment_restart_failure_counts(set(ctx.active_agents.keys()))if self._restart_requested and self._restart_command_source is None:@@ -1633,8 +1595,7 @@ class GatewayShutdownMixin:indent=None,)if self._restart_requested and self._restart_via_service:- # Service manager owns restarts: exit 75 + ``RestartForceExitStatus=75`` has systemd- # replace this process without a second helper racing the unit's stop/start job.+ # Exit 75 + ``RestartForceExitStatus=75``: systemd replaces us without a racing helper.self._exit_code = GATEWAY_SERVICE_RESTART_EXIT_CODEself._exit_reason = self._exit_reason or "Gateway restart requested"self._draining = False@@ -1673,8 +1634,7 @@ class GatewayShutdownMixin:# os._exit past drain+grace so the service manager revives us. Skipped under pytest._watchdog_done = threading.Event()self._shutdown_watchdog_done = _watchdog_done- # Shutdown-path tests and third-party runner doubles may only implement the older- # drain-count surface (no deferred-worker counter).+ # Shutdown-path doubles may lack the deferred-worker counter.ctx = GatewayShutdownMixin._StopContext(deferred_count=getattr(self, "_active_deferred_agent_worker_count", lambda: 0))diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 76e42961d9b..3ff27838ee1 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -50,8 +50,7 @@ class GatewayStartupMixin:if task is not None:await asyncio.shield(task)finally:- # The runner slot was pre-claimed before this task spawned; release it if handle_message- # raises before _handle_message takes ownership, else the real run's cleanup owns it.+ # Release the pre-claimed slot if handle_message raised before _handle_message took ownership._pre_state = self._peek_session_state(session_key)if (_pre_state.turn.agent if _pre_state else None) is _AGENT_PENDING_SENTINEL:self._release_running_agent_state(session_key)@@ -83,8 +82,7 @@ class GatewayStartupMixin:getattr(getattr(source, "platform", None), "value", None),)continue- # Mark this replay so _handle_message does not queue it again while- # the restore gate remains closed for any fresh inbound arrivals.+ # Mark the replay so _handle_message does not re-queue it while the restore gate is closed.with suppress(Exception):setattr(event, "_hermes_startup_restore_replay", True)await adapter.handle_message(event)@@ -163,8 +161,7 @@ class GatewayStartupMixin:from gateway.run import _startup_restore_drain_timeout_secstasks = list(getattr(self, "_startup_restore_tasks", []) or [])if tasks:- # Tasks that outlive the gate get a late-failure callback: their normal done-callback- # only discards them from _background_tasks, so a LATER failure would be swallowed.+ # Tasks outliving the gate get a late-failure callback (their done-callback only discards them).done = await self._wait_bounded_or_release(set(tasks), _startup_restore_drain_timeout_secs(),"Startup-restore gate released after %.0fs with %d boot auto-resume turn(s) "@@ -176,8 +173,7 @@ class GatewayStartupMixin:for task in done:report(task)self._startup_restore_tasks = []- # Warm the turn machinery BEFORE the queue drains: replayed (and- # fresh) inbound turns must not build skeleton prompts (#99373).+ # Warm the turn machinery BEFORE the queue drains: inbound turns must not build skeleton prompts.await self._await_startup_warmup()drained = await self._drain_startup_restore_queue()self._startup_restore_in_progress = False@@ -258,14 +254,12 @@ class GatewayStartupMixin:from gateway.delivery_ledger import ledger_enabled, sweep_recoverableif not await asyncio.to_thread(ledger_enabled):return []- # Only claim rows whose exact transport owner is connected this boot. A multiplexed- # gateway can host several bot identities for one platform; platform-only filtering- # would spend a disconnected bot's retry budget merely because another bot is online.+ # Claim only rows whose exact transport owner is connected: platform-only filtering would spend+ # a disconnected bot's retry budget because another bot on that platform is online._profile_adapters = getattr(self, "_profile_adapters", None) or {}_pval = lambda p: getattr(p, "value", str(p)) # noqa: E731_deliverable_targets = {(_pval(p), "default") for p in self.adapters}- # Legacy rows predate adapter_profile. They are unambiguous only in a non-multiplexed- # gateway; fail closed when multiple bot identities share the process.+ # Legacy rows (no adapter_profile) are unambiguous only without multiplexing; else fail closed.if not _profile_adapters:_deliverable_targets.update((_pval(p), None) for p in self.adapters)for _profile, _adapters in _profile_adapters.items():@@ -280,8 +274,7 @@ class GatewayStartupMixin:return []if not claimed:return []- # Clear resume_pending for EVERY claimed row before any send: claiming already spent one- # redelivery attempt and the answer is in the ledger, so the resume path must never re-run.+ # Clear resume_pending for EVERY claimed row before any send: the answer is in the ledger.await self._clear_resume_pending_for_claimed_obligations(claimed)return claimed@@ -345,9 +338,8 @@ class GatewayStartupMixin:else:# Startup rows preserve the historical default-adapter route.adapter = self.adapters.get(platform)- # Runtime claims have not reached a transport yet. If the reconnect vanished before- # dispatch, release the claim without spending an attempt so the next reconnect can retry- # it. Startup claims keep their state; attempts cap + stale cutoff bound later retries.+ # A runtime claim whose reconnect vanished before dispatch is released without spending an+ # attempt; startup claims keep their state (attempts cap + stale cutoff bound retries).if adapter is None and row.get("runtime_recovery"):await self._release_runtime_claim_quiet(row["obligation_id"], "failed to release undispatched runtime obligation %s"@@ -377,8 +369,7 @@ class GatewayStartupMixin:return 0if not claimed:return 0- # Clear before any send so the reconnect path cannot both redeliver an- # already-produced answer and schedule the same agent turn for resume.+ # Clear before any send so the reconnect path cannot both redeliver AND resume the same turn.sendable = await self._clear_resume_pending_for_claimed_obligations(claimed, require_success=True)sendable_ids = {row["obligation_id"] for row in sendable}for row in claimed:@@ -461,15 +452,13 @@ class GatewayStartupMixin:continueif not self._resume_owner_authorized(entry.session_key, source):continue- # Claim the session slot *before* spawning the task so an inbound message arriving- # between task creation and the task's first await (where _process_message_background- # sets the real sentinel) sees the slot occupied and queues, not a duplicate AIAgent.+ # Claim the slot *before* spawning so an inbound message arriving before the task's first+ # await queues instead of building a duplicate AIAgent._resume_state = self._session_state(entry.session_key)_resume_state.turn.agent = _AGENT_PENDING_SENTINEL_resume_state.turn.started_ts = time.time()self._persist_active_agents()- # Empty-text internal event: the _is_resume_pending branch in _handle_message_with_agent- # prepends the reason-aware system note before the turn runs.+ # Empty-text internal event: the _is_resume_pending branch prepends the reason-aware note.event = MessageEvent(text="", message_type=MessageType.TEXT, source=source, internal=True)task = self._retain_background_task(asyncio.create_task(self._run_startup_resume_event(adapter, event, entry.session_key))@@ -529,8 +518,7 @@ class GatewayStartupMixin:watchdog = getattr(self, "_loop_liveness_watchdog", None)if watchdog is None or not watchdog.is_alive():try:- # getattr defaults cover the config=None / bare-object test path; config-loaded- # values are already validated+clamped by GatewayConfig.from_dict; no re-clamping.+ # getattr defaults cover config=None test paths; loaded values are already clamped.self._loop_liveness_watchdog = start_loop_liveness_watchdog(loop,probe_interval=float(getattr(@@ -623,9 +611,7 @@ class GatewayStartupMixin:start_time=getattr(self, "_gateway_started_at", 0.0),))- # PERMANENT for the process lifetime, same as a _spawn_supervised watcher — tag it so- # _scale_to_zero_has_live_background_work() doesn't treat an armed, otherwise-idle- # gateway as busy forever.+ # PERMANENT watcher tag so the scale-to-zero idle check doesn't count it as busy forever.task._hermes_supervised_watcher = True # type: ignore[attr-defined]_bg = getattr(self, "_background_tasks", None)if _bg is not None:@@ -670,17 +656,15 @@ class GatewayStartupMixin:disarm_startup_watchdog()logger.info("Session storage: %s", self.config.sessions_dir)self._start_log_systemd_timing_alignment()- # Log the resolved max_iterations budget so operators can verify the config.yaml → env- # bridge at a glance (instead of silently running at a stale .env value for weeks).+ # Log the resolved max_iterations so operators can verify the config.yaml → env bridge.with suppress(Exception):logger.info("Agent budget: max_iterations=%d (agent.max_turns from config.yaml, ""or HERMES_MAX_ITERATIONS from .env, or default 500)",int(os.getenv("HERMES_MAX_ITERATIONS", "500")),)- # Redaction is ON by default; warn prominently when an operator has explicitly opted out so- # the downgrade isn't forgotten. The redactor snapshots its state at import time, so this- # log line is the source of truth for the process lifetime.+ # Warn prominently when redaction is opted out; the redactor snapshots its state at import time,+ # so this line is the source of truth for the process lifetime.with suppress(Exception):_redact_raw = os.getenv("HERMES_REDACT_SECRETS", "true")if _redact_raw.lower() in {"1", "true", "yes", "on"}:@@ -706,8 +690,7 @@ class GatewayStartupMixin:self._gateway_health_export_runtime = start_gateway_health_export(load_config())if getattr(self._gateway_health_export_runtime, "enabled", False):logger.info("Gateway health OTLP export: enabled")- # Log any active supply-chain security advisories. Deliberately does NOT block startup or- # surface inline to users — only the operator can act (uninstall, rotate credentials).+ # Supply-chain advisories: log only (never block startup or surface to users; only the operator can act).with _log_suppressed(logging.DEBUG, "security advisory check failed at gateway startup", exc_info=True):from hermes_cli.security_advisories import detect_compromised, gateway_log_message_adv_msg = gateway_log_message(detect_compromised())@@ -736,9 +719,8 @@ class GatewayStartupMixin:_alignment["expected_min"],)- # Builtin platforms whose ``<P>_ALLOWED_USERS`` / ``<P>_ALLOW_ALL_USERS`` env vars count as- # "an allowlist is configured" / "open access opted in"; plugin platforms are appended at- # check time.+ # Builtin platforms whose ``<P>_ALLOWED_USERS`` / ``<P>_ALLOW_ALL_USERS`` env vars count as an+ # allowlist / open-access opt-in; plugin platforms are appended at check time._ALLOWLIST_ENV_PLATFORMS = ("TELEGRAM", "DISCORD", "WHATSAPP", "WHATSAPP_CLOUD", "SLACK", "SIGNAL", "EMAIL", "SMS","MATTERMOST", "MATRIX", "DINGTALK", "FEISHU", "WECOM", "WECOM_CALLBACK", "WEIXIN",@@ -755,8 +737,7 @@ class GatewayStartupMixin:from gateway.run import (_OWN_POLICY_OPEN_ENV, _own_policy_open_startup_violation, _write_runtime_status_quiet)- # Plugin-registered platforms declare their own allowed_users_env / allow_all_env, so the- # warning stays accurate as plugins (IRC) arrive.+ # Plugin platforms declare their own allowed_users_env / allow_all_env.allowed_vars = list(self._BUILTIN_ALLOWED_USERS_VARS)allow_all_vars = ["GATEWAY_ALLOW_ALL_USERS", *self._BUILTIN_ALLOW_ALL_VARS]with suppress(Exception):@@ -792,9 +773,8 @@ class GatewayStartupMixin:@staticmethoddef _start_register_plugins_relay_hooks() -> None:"""Plugin discovery, relay registration and shell-hook/webhook registration. Never raises."""- # Discover Python plugins before shell hooks so plugin block decisions take precedence in- # tie cases. Explicit here because the gateway lazily imports run_agent per request, so- # the discover_plugins() side-effect in model_tools.py is NOT guaranteed to have run yet.+ # Discover plugins before shell hooks (plugin block decisions win ties). Explicit: the gateway+ # lazily imports run_agent, so model_tools' discover_plugins() side-effect may not have run.with _log_suppressed(logging.WARNING, "plugin discovery failed at gateway startup", exc_info=True):from hermes_cli.plugins import discover_pluginsdiscover_plugins()@@ -803,14 +783,11 @@ class GatewayStartupMixin:from gateway.relay import (register_relay_adapter, relay_url, self_provision_relay, send_relay_policy)- # Boot-time relay self-provision: resolve the agent's NAS token -> POST /relay/provision- # -> set GATEWAY_RELAY_* in os.environ BEFORE registration reads them. Never raises.+ # Relay self-provision sets GATEWAY_RELAY_* in os.environ BEFORE registration reads them.self_provision_relay()if register_relay_adapter():logger.info("relay adapter registered (connector at %s)", relay_url())- # Declare this gateway's relevance policy (mention-gating / free-response / allow-- # bots) to the connector so the SAME behavior governs relay delivery. Runs after- # the secret is resolved; never raises, never blocks boot.+ # Declare the relevance policy to the connector so the SAME behavior governs relay delivery.send_relay_policy()except Exception:logger.warning("relay adapter registration failed at gateway startup", exc_info=True)@@ -867,8 +844,7 @@ class GatewayStartupMixin:"Marked %d in-flight session(s) as resumable from previous run ""(%d exact, %d legacy)", exact + fallback, exact, fallback,)- # Stuck-loop detection: a session active across 3+ consecutive restarts is probably looping- # (its history keeps hanging the agent); auto-suspend so the next message starts clean.+ # Stuck-loop detection: a session active across 3+ consecutive restarts is auto-suspended.with _log_suppressed(logging.DEBUG, "Stuck-loop detection failed: %s"):stuck = self._suspend_stuck_loop_sessions()if stuck:@@ -909,9 +885,8 @@ class GatewayStartupMixin:"(platform is enabled in config.yaml but no plugin registered it)", platform.value,)continue- # Under multiplexing the default profile needs the same whole-handler runtime scope as- # a secondary profile: authorization and prompt rendering both run before the narrower- # agent-turn scope is installed.+ # Under multiplexing the default profile needs the same whole-handler runtime scope as a+ # secondary (authorization and prompt rendering run before the agent-turn scope).self._wire_adapter_handlers(adapter)_pending_connects.append((platform, platform_config, adapter))return False, enabled_platform_count, _multiplex_skipped_platforms, _pending_connects@@ -935,9 +910,8 @@ class GatewayStartupMixin:if not _pending_connects:return []- # Abort-aware concurrent wait (parity with the serial loop's between-platforms check): a- # restart/shutdown requested mid-connect must cancel still-pending connects, clean up the- # ones already completed, and abort startup.+ # Abort-aware concurrent wait: a restart/shutdown mid-connect cancels pending connects, tears down+ # completed ones, and aborts startup._task_map = {asyncio.ensure_future(_connect_one_startup(p, c, a)): (p, c, a) for (p, c, a) in _pending_connects}@@ -948,13 +922,11 @@ class GatewayStartupMixin:breakelse:return [_t.exception() or _t.result() for _t in _task_map]- # Cancel and fully settle the in-flight connects FIRST, so a completed adapter's- # disconnect cannot unblock a sibling's connect() before the sibling is cancelled.+ # Settle in-flight connects FIRST so a completed adapter's disconnect cannot unblock a sibling.for _t in _pending_tasks:_t.cancel()await asyncio.gather(*_pending_tasks, return_exceptions=True)- # Then tear down adapters whose connect already succeeded — they were never registered, so- # stop() won't reach them.+ # Then tear down adapters whose connect succeeded — never registered, so stop() won't reach them._connected_ok = [_t for _t in _task_mapif _t not in _pending_tasks and not _t.cancelled() and _t.exception() is None and _t.result()[3] == "ok"@@ -1007,8 +979,7 @@ class GatewayStartupMixin:continue# outcome == "failed"logger.warning("\u2717 %s failed to connect", platform.value)- # Defensive cleanup: a failed connect() may have allocated resources- # (aiohttp.ClientSession, poll tasks, bridge subprocesses) before giving up.+ # A failed connect() may have allocated ClientSessions / poll tasks / subprocesses.await self._safe_adapter_disconnect(adapter, platform)if not adapter.has_fatal_error:# No fatal error info means likely a transient issue -- queue for retry@@ -1044,25 +1015,21 @@ class GatewayStartupMixin:) -> Tuple[bool, int]:"""Bring up multiplexed secondary-profile adapters. Returns (aborted, connected_count)."""from gateway.run import MultiplexConfigError- # Adapters for every OTHER profile this gateway serves connect under that profile's home +- # credential scope and stamp inbound events with the profile so the agent turn resolves.+ # Secondary-profile adapters connect under their own home + credential scope.try:connected_count += await self._start_secondary_profile_adapters()except MultiplexConfigError as e:- # Invalid multiplexer config — abort startup cleanly so the operator fixes config.yaml- # rather than running a half-wired gateway.+ # Invalid multiplexer config — abort cleanly rather than run a half-wired gateway.logger.error("Gateway multiplexer config error: %s", str(e))self._startup_fail_fatal_config(str(e))return True, connected_countexcept Exception as e:logger.error("Secondary-profile adapter startup failed: %s", e, exc_info=True)finally:- # Startup authority is one phase, not a persistent runner mode: from here on every- # adapter retry is non-evicting.+ # Startup authority is one phase: from here on every adapter retry is non-evicting.self._platform_lock_takeover_on_start = False- # A platform skipped on the primary for a missing credential should have been picked up by- # a secondary profile owning the token. If none did, it is enabled in config.yaml yet- # silently unserved — surface it loudly instead of leaving a quiet dead channel.+ # A platform skipped on the primary should have been picked up by a secondary owning the token;+ # if none did it is enabled yet silently unserved — say so loudly.for _skipped in _multiplex_skipped_platforms:if not any(_skipped in _profile_map for _profile_map in self._profile_adapters.values()):logger.warning(@@ -1098,16 +1065,14 @@ class GatewayStartupMixin:logger.info("Gateway will continue running for cron job execution.")return Falseif startup_retryable_errors:- # All enabled platforms hit retryable failures. Keep the gateway alive so cron jobs- # still run and the reconnect watcher can recover them once the cause is fixed;- # exiting would turn one misconfigured platform into an infinite systemd restart loop.+ # All retryable: stay alive (cron runs, watcher recovers) rather than systemd restart-loop.logger.warning("Gateway started with no connected platforms — %d platform(s) queued for retry: %s",len(self._failed_platforms), "; ".join(startup_retryable_errors),)_write_runtime_status_quiet(gateway_state="degraded", exit_reason=None)- # (Or: no adapter for any enabled platform — missing library or credentials.) Fleet nodes- # share one config.yaml but hold credentials for only a subset, so degrade gracefully.+ # No adapter for any enabled platform: fleet nodes share one config.yaml but hold a subset of+ # credentials, so degrade gracefully.logger.warning("No adapter could be created for any of the %d configured platform(s). ""Check that required dependencies are installed and credentials are set. "@@ -1139,8 +1104,7 @@ class GatewayStartupMixin:directory = await build_channel_directory(self.adapters)ch_count = sum(len(chs) for chs in directory.get("platforms", {}).values())logger.info("Channel directory built: %d target(s)", ch_count)- # Restarting after a /update? If the update is still running, keep watching so we notify- # once it actually finishes.+ # Restarting after a /update still in progress: keep watching so we notify when it finishes.notified = await self._send_update_notification()if not notified and any((_hermes_home / name).exists()@@ -1168,8 +1132,7 @@ class GatewayStartupMixin:# auto-resume stays visible on the next user message.self._schedule_resume_pending_sessions()await self._finish_startup_restore()- # Surface state.db init failures to the user's messaging platforms so they know persistence- # is broken before losing data.+ # Surface state.db init failures to messaging platforms before the user loses data.await self._send_session_db_warning_notifications()# Resume recovered process watchers. Detach the batch atomically (fresh list, not clear(): a# concurrent append during the yield must not be lost); yield every 100 to keep the loop live.@@ -1186,10 +1149,8 @@ class GatewayStartupMixin:if i % 100 == 99:await asyncio.sleep(0)- # Long-lived supervised watchers spawned at the end of start(), in order; the supervised name is- # the method name without its leading underscore. Each watcher's docstring explains its job- # (session expiry, /model catalog TTL refresh, stall warnings, kanban notifier/dispatcher,- # CLI handoff, async-delegation completions, /loop wakeups).+ # Long-lived supervised watchers spawned at the end of start(), in order; supervised name = method+ # name minus the leading underscore._PRE_RECONNECT_WATCHERS = ("_session_expiry_watcher", "_model_catalog_refresh_watcher", "_session_stall_watcher","_kanban_notifier_watcher", "_kanban_dispatcher_watcher",@@ -1205,17 +1166,12 @@ class GatewayStartupMixin:"Starting reconnection watcher for %d failed platform(s): %s",len(self._failed_platforms), ", ".join(p.value for p in self._failed_platforms),)- # Spawned via _spawn_supervised so an exception escaping the watcher's OUTER loop is caught,- # logged, and restarted with backoff instead of silently killing it (else a platform already- # queued in _failed_platforms stays stranded: the ensure hook only runs on a NEW fatal-error- # arrival). ``on_spawn`` keeps ``_reconnect_watcher_task`` on the CURRENT live task across- # backoff respawns so a superseded handle never looks like a dead watcher.+ # Supervised: an escaping exception is restarted with backoff instead of stranding queued+ # platforms (the ensure hook only runs on a NEW fatal). ``on_spawn`` keeps the handle current.self._spawn_reconnect_watcher()for method in self._POST_RECONNECT_WATCHERS:self._spawn_supervised(getattr(self, method), method[1:])- # Scale-to-zero idle watcher ONLY when opted in (HERMES_SCALE_TO_ZERO stamp), messaging is- # relay-only/absent, and a wakeUrl is registered. When armed it drives the relay dormant on- # sustained idle, then suspends via flaps — Fly autostop is inbound-only, job-blind.+ # Scale-to-zero watcher ONLY when opted in, messaging is relay-only/absent, and a wakeUrl exists.try:if self._scale_to_zero_should_arm():logger.info(@@ -1224,14 +1180,12 @@ class GatewayStartupMixin:)self._spawn_supervised(self._scale_to_zero_watcher, "scale_to_zero_watcher")else:- # Surface WHY an OPTED-IN instance didn't arm (non-opted not arming is normal —- # stay silent); otherwise a failed arm is invisible and needs a box-dive.+ # Say WHY an OPTED-IN instance didn't arm (non-opted stays silent).self._log_scale_to_zero_not_armed_reason()except Exception: # noqa: BLE001 - arming must never block startuplogger.debug("scale-to-zero: arm check failed at startup", exc_info=True)- # Drain-control watcher: reconciles the gateway's new-turn accept-state with the external- # ``.drain_request.json`` marker the dashboard begin/cancel-drain endpoint writes. A marker- # from a prior instantiation (durable-volume restart) is ignored via its epoch.+ # Drain-control watcher: reconciles new-turn acceptance with the dashboard's ``.drain_request.json``+ # marker (prior-instantiation markers are ignored via epoch).self._spawn_supervised(self._drain_control_watcher, "drain_control_watcher")async def start(self) -> bool:@@ -1244,15 +1198,13 @@ class GatewayStartupMixin:if self._start_check_access_policy():return Trueawait self._start_recover_previous_run()- # Serialize startup restore against inbound dispatch: adapters can receive messages as soon- # as they connect, but restart-interrupted sessions are not auto-resumed until all startup- # wiring below completes, so inbound queues until every synthetic resume turn has finished.+ # Serialize startup restore against inbound: adapters receive as soon as they connect, so inbound+ # queues until every synthetic resume turn has finished.self._startup_restore_in_progress = Trueself._startup_restore_queue = []self._startup_restore_tasks = []- # Fresh-boot readiness: with no resume_pending sessions the gate opens almost immediately- # while the turn machinery is still cold, so a message in that window got a skeleton system- # prompt. Warm NOW to overlap the connects below; _finish_startup_restore awaits it (bounded).+ # Fresh boot: the gate opens while the turn machinery is still cold (skeleton prompts). Warm NOW+ # to overlap the connects; _finish_startup_restore awaits it (bounded).self._start_startup_warmup()startup_nonretryable_errors: list[str] = []startup_retryable_errors: list[str] = []@@ -1348,8 +1300,7 @@ class GatewayStartupMixin:f"no home channel configured for {platform_name}; run /sethome on the desired chat first")home_chat_id = str(home.chat_id)- # Fresh thread on the destination so the handoff has its own scrollback. Adapter returns- # None if threading is unsupported (Matrix/WhatsApp/Signal/SMS) or creation failed.+ # Fresh thread for the handoff's own scrollback; None when unsupported or creation failed.cli_title = row.get("title") or cli_session_id[:8]try:new_thread_id = await transport.adapter.create_handoff_thread(@@ -1365,8 +1316,7 @@ class GatewayStartupMixin:platform == Platform.TELEGRAM and looks_like_telegram_private_chat_id(home_chat_id))is_thread = bool(new_thread_id) and not is_telegram_private_chat- # Discord (unlike Slack/Telegram) builds in-thread messages with ``chat_id == thread id``,- # so key on the thread's OWN id; keying on the parent would make the next reply spawn anew.+ # Discord builds in-thread messages with ``chat_id == thread id``: key on the thread's OWN id.dest_source = SessionSource(platform=platform,chat_id=str(effective_thread_id) if (@@ -1414,17 +1364,14 @@ class GatewayStartupMixin:cli_session_id = row["id"]dest = await self._handoff_resolve_destination(row, profile_name)session_key = self._handoff_session_key(dest, profile_name)- # Ensure a session_store entry exists for this key (get_or_create_session creates one for a- # never-used home channel); switch_session then re-points it.+ # Ensure a session_store entry exists for this key; switch_session then re-points it.await self.async_session_store.get_or_create_session(dest.source)- # Re-bind the destination key to the CLI session_id: switch_session ends the prior session- # in SQLite and reopens the CLI session under the new key; its transcript is now active.+ # switch_session ends the prior session and reopens the CLI session under the new key.switched = await self.async_session_store.switch_session(session_key, cli_session_id)if switched is None:raise RuntimeError(f"could not switch session key {session_key} → {cli_session_id}")- # Evict any cached AIAgent for this key so the next dispatch rebuilds it against the CLI- # session_id (mirrors /resume / /branch), and clear stale running-agent state so the- # synthetic turn isn't queued behind it.+ # Evict the cached AIAgent (rebuild against the CLI session_id, like /resume) and clear stale+ # running-agent state so the synthetic turn isn't queued behind it.self._evict_cached_agent(session_key)self._release_running_agent_state(session_key)cli_title = row.get("title") or cli_session_id[:8]@@ -1443,16 +1390,13 @@ class GatewayStartupMixin:"(home=%s, thread=%s, session_key=%s)",cli_session_id, dest.platform_name, dest.home.chat_id, dest.effective_thread_id, session_key,)- # Dispatch through the runner directly: adapter.handle_message would spawn a background task- # and lose error visibility; inline _handle_message keeps success/failure observable.+ # Inline _handle_message keeps success/failure observable (handle_message would detach it).response_text = await self._handle_message(synthetic_event)if not response_text:- # Streaming may have already delivered the response inline; the agent ran without- # raising either way — count as success.+ # Streaming may have delivered inline; the agent ran without raising — success.return- # Send the reply to the new thread if we created one, else the configured home channel- # (which may carry a thread_id). Use the resolved transport (not adapter.send) so a- # relay-fronted logical platform is stamped on the outbound frame (send_for_platform).+ # Reply into the new thread (else the home channel) via the resolved transport, so a relay-fronted+ # logical platform is stamped on the outbound frame.send_metadata = {"thread_id": dest.effective_thread_id} if dest.effective_thread_id else Nonetry:result = await dest.transport.send(