The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): drop statement-separator blank lines inside run_* function bodies (whitespace-only)
Teknium3d1fbd3696b4
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.pyindex 9ace375554c..5d5ca6573c6 100644--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@ -273,7 +273,6 @@ class GatewayAdapterLifecycleMixin: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",@@ -288,21 +287,17 @@ class GatewayAdapterLifecycleMixin:error_code=adapter.fatal_error_code,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.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.self._queue_retryable_fatal_platform(adapter)-if existing is adapter:# 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:self._exit_reason = adapter.fatal_error_message or "All messaging adapters disconnected"if adapter.fatal_error_retryable:@@ -357,7 +352,6 @@ 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()).task = Context().run(lambda: asyncio.create_task(coro_factory()))@@ -421,14 +415,12 @@ class GatewayAdapterLifecycleMixin:``completed``/``failed``."""from gateway.run import _async_profile_runtime_scope, _handoff_watch_scopes, _reclaim_staleawait asyncio.sleep(5) # let platforms connect before dispatching through them-# 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) >= 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.inflight: Dict[str, "asyncio.Task"] = {}@@ -480,7 +472,6 @@ class GatewayAdapterLifecycleMixin:with _log_suppressed(logging.DEBUG, "Stale-handoff reclaim failed", exc_info=True):async with _scope(_phome):await _reclaim_stale(self)-try:while self._running:try:@@ -647,7 +638,6 @@ class GatewayAdapterLifecycleMixin: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@@ -656,14 +646,12 @@ class GatewayAdapterLifecycleMixin:self._drop_from_reconnect_queue(platform, "no bot credential on queued config")returnlogger.info("Reconnecting %s (attempt %d)...", platform.value, attempt)-adapter = Nonetry: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.@@ -717,7 +705,6 @@ 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.try:@@ -726,14 +713,12 @@ class GatewayAdapterLifecycleMixin:logger.debug("failed-obligation redelivery after %s reconnect failed", platform.value, exc_info=True,)-# Rebuild channel directory with the new adaptertry:from gateway.channel_directory import build_channel_directoryawait build_channel_directory(self.adapters)except Exception:pass-# 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:@@ -775,12 +760,10 @@ class GatewayAdapterLifecycleMixin:)if not getattr(self.config, "multiplex_profiles", False):return 0-try:from hermes_cli.profiles import get_active_profile_nameexcept Exception:return 0-active = get_active_profile_name() or "default"connected = 0claimed = self._primary_resource_claims(active)@@ -798,7 +781,6 @@ class GatewayAdapterLifecycleMixin:raiseexcept Exception as e:logger.error("Failed to start adapters for profile '%s': %s", profile_name, e, exc_info=True)-self._record_served_profiles(active, profile_homes)return connected@@ -842,22 +824,18 @@ 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.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.self._register_config_hooks("shell-hook/webhook registration failed for profile '%s'", profile_name, level=logging.WARNING,)-profile_cfg = load_gateway_config()violation = _own_policy_open_startup_violation(profile_cfg)self._snapshot_profile_busy_modes(profile_name, profile_runtime_cfg)@@ -867,7 +845,6 @@ class GatewayAdapterLifecycleMixin:"Enable GATEWAY_ALLOW_ALL_USERS or the platform allow-all flag ""for that profile, or change dm_policy/group_policy away from 'open'.")-port_binding_platforms = sorted(platform.valuefor platform, platform_config in profile_cfg.platforms.items()@@ -1121,7 +1098,6 @@ class GatewayAdapterLifecycleMixin:"Secondary %s reconnect attempt failed (profile: %s)", platform.value,profile_name, exc_info=True,)-if not self._running:returnattempts += 1@@ -1411,7 +1387,6 @@ class GatewayAdapterLifecycleMixin:config.extra.setdefault("thread_sessions_per_user", getattr(self.config, "thread_sessions_per_user", False))-with _log_suppressed(logging.DEBUG, "Platform registry lookup for '%s' failed: %s", platform.value):from gateway.platform_registry import platform_registryif platform_registry.is_registered(platform.value):diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex df42a624c36..d9ca12fe21b 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -94,7 +94,6 @@ class GatewayNotificationsMixin:adapter = self._adapter_for_source(source)if not adapter:return-config = getattr(self, "config", None)chat_id = getattr(source, "chat_id", None)if config and getattr(source, "platform", None) == Platform.SLACK and _is_slack_ignored_channel(config, chat_id):@@ -115,7 +114,6 @@ class GatewayNotificationsMixin:"[%s] send_private_notice failed, falling back to public",getattr(source, "platform", "?"), exc_info=True,)-await adapter.send(source.chat_id, content, metadata=metadata)async def _resolve_compression_lineage_target(@@ -127,14 +125,12 @@ class GatewayNotificationsMixin:except Exception:logger.debug("Async-delegation compression-tip lookup failed for %s", pinned_session_id, exc_info=True)target_session_id = None-if not target_session_id or target_session_id == pinned_session_id:logger.warning("Async-delegation completion pinned to compressed session %s ""without a continuation; dropping injection.", pinned_session_id,)return None-try:tip_row = await session_db.get_session(target_session_id)except Exception:@@ -145,7 +141,6 @@ class GatewayNotificationsMixin:target_session_id, "unknown" if tip_row is None else "ended",)return None-route_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@@ -162,7 +157,6 @@ class GatewayNotificationsMixin:except Exception:route_tip = Noneroute_owns_lineage = route_tip == target_session_id-if not route_owns_lineage:logger.warning("Async-delegation completion for compression lineage %s -> %s "@@ -189,20 +183,17 @@ class GatewayNotificationsMixin:"dropping injection (#55578 fail-closed).")return None-pinned_row = Nonetry:pinned_row = await session_db.get_session(pinned_session_id)except Exception:logger.debug("Async-delegation parent lookup failed for %s", pinned_session_id, exc_info=True)-if pinned_row is None:logger.warning("Async-delegation completion has unknown spawning session %s; ""dropping injection (#55578 fail-closed).", pinned_session_id,)return None-target_session_id = pinned_session_idfollows_compression = Falseif pinned_row.get("ended_at"):@@ -224,17 +215,14 @@ class GatewayNotificationsMixin:_end_reason or "idle", pinned_session_id, session_entry.session_id,)return session_entry-follows_compression = Truetarget_session_id = await self._resolve_compression_lineage_target(session_db, session_entry, pinned_session_id,)if target_session_id is None:return None-if target_session_id == session_entry.session_id:return session_entry-prior_session_id = session_entry.session_idif follows_compression:switched = await self.async_session_store.advance_compression_session(@@ -248,7 +236,6 @@ class GatewayNotificationsMixin:"owning session %s; dropping injection.", session_entry.session_key, target_session_id,)return None-logger.info("Pinned async-delegation completion to owning session %s (was %s) for routing key %s (#57498)",target_session_id, prior_session_id, session_entry.session_key,@@ -268,20 +255,17 @@ class GatewayNotificationsMixin:# Capture [[as_document]] before extract_media strips it: image files then go through# send_document (preserving bytes), not send_multiple_images (Telegram recompresses).force_document_attachments = "[[as_document]]" in response-from 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.adapter.extract_images(cleaned)-_thread_meta = (dict(thread_metadata)if thread_metadata is not Noneelse self._thread_metadata_for_source(event.source, self._reply_anchor_for_event(event)))chat_id = event.source.chat_id-# Images go out as one batch (e.g. Signal's multi-attachment RPC) unless [[as_document]].def _is_photo(media_path: str, is_voice: bool) -> bool:ext = Path(media_path).suffix.lower()@@ -289,14 +273,12 @@ class GatewayNotificationsMixin:image_paths = [p for p, v in media_files if _is_photo(p, v)]non_image_media = [(p, v) for p, v in media_files if not _is_photo(p, v)]-if image_paths:try:images = [(f"file://{_quote(p)}", "") for p in image_paths]await adapter.send_multiple_images(chat_id=chat_id, images=images, metadata=_thread_meta)except Exception as e:logger.warning("[%s] Post-stream image batch delivery failed: %s", adapter.name, e)-for media_path, is_voice in non_image_media:try:ext = Path(media_path).suffix.lower()@@ -346,12 +328,10 @@ class GatewayNotificationsMixin:logger.debug("Queued-lane reconcile edit failed (%s); falling back to send.", _qe)if not _reconciled:await adapter.send(source.chat_id, text_content, metadata=metadata)-# Failed turns deliver their (normalized failure) text but must not upload attachments as if# they succeeded — mirrors the ``not agent_result.get("failed")`` completed-turn guard.if not deliver_media:return-synthetic_event = MessageEvent(text="", source=source, message_id=event_message_id)await self._deliver_media_from_response(response, synthetic_event, adapter, thread_metadata=metadata)@@ -360,7 +340,6 @@ class GatewayNotificationsMixin:existing_task = getattr(self, "_update_notification_task", None)if existing_task and not existing_task.done():return-try:self._update_notification_task = asyncio.create_task(self._watch_update_progress())except RuntimeError:@@ -488,13 +467,11 @@ class GatewayNotificationsMixin:paths = self._update_paths()loop = asyncio.get_running_loop()deadline = loop.time() + timeout-target = self._resolve_update_target(paths)if target is None:await self._watch_update_completion_only(paths, deadline, poll_interval)returnsession_key = target.session_key-bytes_sent = 0last_stream_time = loop.time()buffer = ""@@ -528,11 +505,9 @@ class GatewayNotificationsMixin:logger.info("Update finished (exit=%s), notified %s", exit_code, session_key)self._clear_update_markers(paths, session_key)return-_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._pending_state = self._peek_session_state(session_key) if session_key else None@@ -548,9 +523,7 @@ class GatewayNotificationsMixin:await self._forward_update_prompt(target, prompt_text, prompt_data.get("default", ""))except (json.JSONDecodeError, OSError) as e:logger.debug("Failed to read update prompt: %s", e)-await asyncio.sleep(poll_interval)-if not paths.exit_code.exists():logger.warning("Update watcher timed out after %.0fs", timeout)paths.exit_code.write_text("124", encoding="utf-8")@@ -568,7 +541,6 @@ class GatewayNotificationsMixin:paths = self._update_paths()if not paths.any_pending():return False-cleanup = Trueactive_pending_path = paths.claimed@@ -589,17 +561,13 @@ class GatewayNotificationsMixin:return Trueelif not paths.claimed.exists():return True-pending = json.loads(paths.claimed.read_text(encoding="utf-8"))platform_str = pending.get("platform")chat_id = pending.get("chat_id")-if not paths.exit_code.exists():return _defer("Update notification deferred: update still running")-exit_code = self._update_exit_code(paths)output = paths.output.read_bytes().decode("utf-8", errors="replace") if paths.output.exists() else ""-platform = Platform(platform_str)adapter = self.adapters.get(platform)if chat_id and not adapter:@@ -628,7 +596,6 @@ class GatewayNotificationsMixin:if cleanup:for p in (active_pending_path, paths.claimed, paths.output, paths.exit_code):p.unlink(missing_ok=True)-return Trueasync def _send_restart_notification(self) -> Optional[tuple[str, str, Optional[str]]]:@@ -637,29 +604,24 @@ class GatewayNotificationsMixin:notify_path = _hermes_home / ".restart_notify.json"if not notify_path.exists():return None-try:data = json.loads(notify_path.read_text(encoding="utf-8"))platform_str = data.get("platform")chat_id = data.get("chat_id")thread_id = data.get("thread_id")-if not platform_str or not chat_id:return None-platform = Platform(platform_str)transport = resolve_delivery_transport(platform, self.config, self.adapters)if transport is None:logger.debug("Restart notification skipped: no live transport for %s", platform_str)return None-platform_cfg = self.config.platforms.get(platform)if platform_cfg is not None and not platform_cfg.gateway_restart_notification:logger.info("Restart notification suppressed: %s has gateway_restart_notification=false", platform_str)return None-metadata = self._pending_marker_metadata(platform, chat_id, data, transport.adapter)if data.get("delivered_via_upstream_relay") is True:metadata = dict(metadata or {})@@ -677,7 +639,6 @@ class GatewayNotificationsMixin:"Restart notification to %s:%s was not delivered: %s", platform_str, chat_id, _send_error(result),)return None-logger.info("Sent restart notification to %s:%s", platform_str, chat_id)return str(platform_str), str(chat_id), str(thread_id) if thread_id else Noneexcept Exception as e:@@ -733,7 +694,6 @@ class GatewayNotificationsMixin:delivered: set[tuple[str, str, Optional[str]]] = set()skipped = skip_targets or set()message = "♻️ Gateway online — Hermes is back and ready."-for platform, platform_cfg, home, transport in self._home_channel_transports():if not platform_cfg.gateway_restart_notification:logger.info(@@ -741,17 +701,14 @@ class GatewayNotificationsMixin:platform.value,)continue-target = _notice_target_key(platform.value, home.chat_id, home.thread_id)if target in skipped or target in delivered:continue-if await self._send_home_channel_message(platform, home, transport, message, "Home-channel startup notification failed for %s:%s: %s",):delivered.add(target)logger.info("Sent home-channel startup notification to %s:%s", platform.value, home.chat_id)-return deliveredasync def _send_session_db_warning_notifications(self) -> None:@@ -764,7 +721,6 @@ class GatewayNotificationsMixin:error = getattr(self, "_session_db_init_error", None)if not error:return-from hermes_state import classify_persistence_error, format_session_db_unavailableif classify_persistence_error(error) == "corrupt":message = (@@ -779,9 +735,7 @@ class GatewayNotificationsMixin:f"⚠️ Session database unavailable — messages may not be persisted. "f"{format_session_db_unavailable()}\nRun `hermes doctor` for diagnostics.")-logger.warning("Broadcasting state.db failure warning to home channels: %s", error)-for platform, _platform_cfg, home, transport in self._home_channel_transports():await self._send_home_channel_message(platform, home, transport, message, "state.db warning notification failed for %s:%s: %s",@@ -795,7 +749,6 @@ class GatewayNotificationsMixin:from gateway.run import _parse_session_keysession_key = str(evt.get("session_key") or "").strip()derived = {}-if session_key:try:self.session_store._ensure_loaded()@@ -804,13 +757,10 @@ class GatewayNotificationsMixin:return entry.originexcept Exception as exc:logger.debug("Synthetic process-event session-store lookup failed for %s: %s", session_key, exc)-cached_source = self._get_cached_session_source(session_key)if cached_source is not None:return cached_source-derived = _parse_session_key(session_key) or {}-platform_name = str(evt.get("platform") or derived.get("platform") or "").strip().lower()chat_type = str(evt.get("chat_type") or derived.get("chat_type") or "").strip().lower()chat_id = str(evt.get("chat_id") or derived.get("chat_id") or "").strip()@@ -821,7 +771,6 @@ class GatewayNotificationsMixin:session_key, platform_name, chat_type, chat_id, evt.get("type", "?"),)return None-try:platform = Platform(platform_name)# Reject dynamic pseudo-members: plugin platforms must be registered.@@ -863,7 +812,6 @@ class GatewayNotificationsMixin:watch_events = _drain_gateway_watch_events(completion_queue)if self._load_background_notifications_mode() == "off":return-for evt in watch_events:synth_text = _format_gateway_process_notification(evt)if not synth_text:@@ -1094,7 +1042,6 @@ class GatewayNotificationsMixin:return claimelif 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.@@ -1139,18 +1086,15 @@ class GatewayNotificationsMixin:return claim.early_resultif identity is not None and self._completion_identity_seen(identity, claim=True):return None-accepted = Falsetry:injection_result = await self._inject_watch_notification(synth_text, evt)if injection_result is not True:return injection_resultaccepted = True-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.if claim.claim_id:@@ -1224,7 +1168,6 @@ class GatewayNotificationsMixin: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.delivered = None@@ -1270,7 +1213,6 @@ class GatewayNotificationsMixin:task.cancel()if tasks:await asyncio.gather(*tasks, return_exceptions=True)-# Defensive cleanup for an orphaned queue with no live flush task.batches = getattr(self, "_completion_notification_batches", {})for entries in batches.values():@@ -1291,10 +1233,8 @@ class GatewayNotificationsMixin:):if not hasattr(self, attr):setattr(self, attr, default())-if self._completion_notification_batches_stopping:return False-key = self._event_route_key(evt, self._COMPLETION_BATCH_KEY_FIELDS)future = asyncio.get_running_loop().create_future()self._completion_notification_batches.setdefault(key, []).append((synth_text, evt, future))@@ -1348,13 +1288,11 @@ class GatewayNotificationsMixin:if identity is not None and self._completion_identity_seen(identity):continuedeliverable.append((evt, synth_text))-if not deliverable:return Noneif len(deliverable) == 1:evt, synth_text = deliverable[0]return await self._deliver_completion_notification(synth_text, evt)-from tools.async_delegation import claim_event_delivery, complete_event_delivery, release_event_deliveryprimary_evt, primary_text = deliverable[0]blocks = [primary_text]@@ -1367,10 +1305,8 @@ class GatewayNotificationsMixin:continuesiblings.append((evt, claim_id))blocks.append(synth_text)-if not siblings:return await self._deliver_completion_notification(primary_text, primary_evt)-header = (f"[IMPORTANT: {len(blocks)} background subagent delegations ""completed for this session. Treat these results as one "@@ -1528,10 +1464,8 @@ class GatewayNotificationsMixin:thread_id = watcher.get("thread_id", "")agent_notify = watcher.get("notify_on_complete", False)notify_mode = self._load_background_notifications_mode()-logger.debug("Process watcher started: %s (every %ss, notify=%s, agent_notify=%s)",session_id, interval, notify_mode, agent_notify)-silent = notify_mode == "off" and not agent_notifylast_output_len = 0while True:@@ -1547,7 +1481,6 @@ class GatewayNotificationsMixin:current_output_len = len(session.output_buffer)has_new_output = current_output_len > last_output_lenlast_output_len = current_output_len-if 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 —@@ -1563,7 +1496,6 @@ 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.@@ -1579,7 +1511,6 @@ class GatewayNotificationsMixin:message_text = self._format_process_final_message(session_id, session, notify_mode)await self._send_watcher_message(platform_name, chat_id, thread_id, message_text)break-elif has_new_output and notify_mode == "all" and not agent_notify:# New output — deliver a status update (only in "all" mode; agent_notify watchers# only care about completion).@@ -1588,5 +1519,4 @@ class GatewayNotificationsMixin:platform_name, chat_id, thread_id,f"[Background process {session_id} is still running~ New output:\n{new_output}]",)-logger.debug("Process watcher ended%s: %s", " (silent)" if silent else "", session_id)diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 00d5c21f6b2..bdca671c884 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -282,7 +282,6 @@ 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.await self._clear_resume_pending_for_claimed_obligations(claimed)@@ -308,7 +307,6 @@ class GatewayStartupMixin:except Exception:logger.debug("delivery ledger import failed", exc_info=True)return 0-redelivered = 0for row in claimed:adapter = await self._obligation_adapter(row)@@ -382,7 +380,6 @@ 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.sendable = await self._clear_resume_pending_for_claimed_obligations(claimed, require_success=True)@@ -411,7 +408,6 @@ class GatewayStartupMixin:except Exception as exc:logger.warning("Failed to enumerate resume-pending sessions: %s", exc)return None-# Restart-loop breaker: only boots WITH restart-interrupted sessions count; when tripped, skip# auto-resume for THIS boot only (inbound still served; sessions stay resume_pending).if candidates:@@ -449,18 +445,15 @@ class GatewayStartupMixin:candidates = self._resume_pending_candidates(platform)if candidates is None:return 0-now = datetime.now()scheduled = 0for entry in candidates:marker = entry.last_resume_marked_at or entry.updated_atif marker is not None and (now - marker).total_seconds() > window:continue-# Already being resumed (e.g. scheduled at startup, still in-flight) — no second turn.if self._is_session_running(entry.session_key):continue-source = entry.originadapter = self._adapter_for_source(source)if adapter is None:@@ -471,7 +464,6 @@ 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.@@ -479,7 +471,6 @@ class GatewayStartupMixin:_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.event = MessageEvent(text="", message_type=MessageType.TEXT, source=source, internal=True)@@ -538,7 +529,6 @@ class GatewayStartupMixin:if getattr(self, "_loop_floor_timer_handle", None) is None:with _log_suppressed(logging.DEBUG, "Failed to arm gateway loop floor timer", exc_info=True):self._loop_floor_timer_handle = _arm_loop_floor_timer(loop)-watchdog = getattr(self, "_loop_liveness_watchdog", None)if watchdog is None or not watchdog.is_alive():try:@@ -599,7 +589,6 @@ class GatewayStartupMixin:"""Start the local Group Chat worker without importing the dashboard."""import tui_gateway.server # noqa: F401from tui_gateway import methods_groups-service = methods_groups.get_hosted_room_service()if service is None:service = methods_groups.start_hosted_room_service()@@ -722,7 +711,6 @@ 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).with _log_suppressed(logging.DEBUG, "security advisory check failed at gateway startup", exc_info=True):@@ -792,7 +780,6 @@ class GatewayStartupMixin:"or explicitly opt in with GATEWAY_ALLOW_ALL_USERS=true plus ""dm_policy/group_policy: open on the platform.")-reason = _own_policy_open_startup_violation(self.config)if reason:platform_value = reason.split(":", 1)[0]@@ -818,7 +805,6 @@ class GatewayStartupMixin:with _log_suppressed(logging.WARNING, "plugin discovery failed at gateway startup", exc_info=True):from hermes_cli.plugins import discover_pluginsdiscover_plugins()-# Generic relay adapter only if GATEWAY_RELAY_URL / gateway.relay_url is set; no URL -> no-op.try:from gateway.relay import (@@ -835,7 +821,6 @@ class GatewayStartupMixin:send_relay_policy()except Exception:logger.warning("relay adapter registration failed at gateway startup", exc_info=True)-GatewayStartupMixin._register_config_hooks("shell-hook registration failed at gateway startup")@staticmethod@@ -861,14 +846,12 @@ class GatewayStartupMixin:from gateway.run import _hermes_homeself._start_register_plugins_relay_hooks()self.hooks.discover_and_load()-# Recover background processes from checkpoint (crash recovery)with _log_suppressed(logging.WARNING, "Process checkpoint recovery: %s"):from tools.process_registry import process_registryrecovered = process_registry.recover_from_checkpoint()if recovered:logger.info("Recovered %s background process(es) from previous run", recovered)-# Recover sessions active at last exit (exact turn markers + 120s recency fallback for# marker-less older turns). SKIP after a clean exit — the previous process already drained._clean_marker = _hermes_home / ".clean_shutdown"@@ -891,7 +874,6 @@ 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.with _log_suppressed(logging.DEBUG, "Stuck-loop detection failed: %s"):@@ -923,7 +905,6 @@ class GatewayStartupMixin:_multiplex_skipped_platforms.append(platform)continueenabled_platform_count += 1-adapter = self._create_adapter(platform, platform_config)if not adapter:# Distinguish between missing builtin deps and missing plugin@@ -1086,7 +1067,6 @@ class GatewayStartupMixin:# Startup authority is one phase, not a persistent runner mode: 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.@@ -1156,21 +1136,18 @@ class GatewayStartupMixin:)self._spawn_supervised(self._hosted_room_worker_watcher, "hosted_room_worker")self._start_loop_heartbeat_task()-hook_count = len(self.hooks.loaded_hooks)if hook_count:logger.info("%s hook(s) loaded", hook_count)await self.hooks.emit("gateway:startup", {"platforms": [p.value for p in self.adapters]})if connected_count > 0:logger.info("Gateway running with %s platform(s)", connected_count)-# Initial channel directory for send_message name resolutionwith _log_suppressed(logging.WARNING, "Channel directory build failed: %s"):from gateway.channel_directory import build_channel_directorydirectory = 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.notified = await self._send_update_notification()@@ -1184,11 +1161,9 @@ class GatewayStartupMixin:"""Post-connect wiring: services, boot notifications, startup restore, recovered watchers."""from gateway.run import _planned_restart_notification_pending, _restart_notification_pendingawait self._start_post_connect_services(connected_count)-# Let fresh adapters settle before lifecycle sends (helps Discord thread deliveries).if connected_count > 0:await asyncio.sleep(1.0)-# Before _send_restart_notification() unlinks the marker: did we boot from a chat /restart?# One-shot signal for _is_stale_restart_redelivery.if _restart_notification_pending():@@ -1198,16 +1173,13 @@ class GatewayStartupMixin:await self._await_startup_boot_sends(planned_restart_notification_pending=_planned_restart_notification_pending(),)-# Auto-resume restart-interrupted sessions (ledger-answered ones were cleared above); a failed# 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.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.with _log_suppressed(logging.ERROR, "Recovered watcher setup error: %s"):@@ -1237,7 +1209,6 @@ class GatewayStartupMixin:"""Spawn the long-lived supervised background watchers."""for method in self._PRE_RECONNECT_WATCHERS:self._spawn_supervised(getattr(self, method), method[1:])-if self._failed_platforms:logger.info("Starting reconnection watcher for %d failed platform(s): %s",@@ -1249,10 +1220,8 @@ class GatewayStartupMixin:# 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.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.@@ -1269,7 +1238,6 @@ class GatewayStartupMixin: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.@@ -1285,7 +1253,6 @@ 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.@@ -1296,7 +1263,6 @@ class GatewayStartupMixin:# 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).self._start_startup_warmup()-startup_nonretryable_errors: list[str] = []startup_retryable_errors: list[str] = [](@@ -1304,7 +1270,6 @@ class GatewayStartupMixin:) = await self._start_prefilter_platforms()if _aborted:return True-if await self._abort_startup_if_shutdown_requested():return True_raw = await self._start_connect_pending(_pending_connects)@@ -1313,7 +1278,6 @@ class GatewayStartupMixin:connected_count = await self._start_aggregate_connect_results(_raw, startup_retryable_errors, startup_nonretryable_errors)-if await self._abort_startup_if_shutdown_requested():return True_aborted, connected_count = await self._start_secondary_profiles(@@ -1325,12 +1289,10 @@ class GatewayStartupMixin:connected_count, enabled_platform_count, startup_retryable_errors, startup_nonretryable_errors):return True-if await self._abort_startup_if_shutdown_requested():return Trueself.delivery_router.adapters = self.adaptersself._wire_teams_pipeline_runtime()-self._running = Trueself._install_plugin_message_injector()self._update_runtime_status("running")@@ -1383,9 +1345,7 @@ class GatewayStartupMixin:platform = Platform(platform_name)except (ValueError, KeyError):raise RuntimeError(f"unknown platform '{platform_name}'")-handoff_config, handoff_adapters = self._handoff_resolve_scope(profile_name)-# Alias-aware transport: a relay-fronted gateway registers ONE Platform.RELAY adapter fronting# N logical platforms, so a literal adapters.get() would miss a deliverable one.transport = resolve_delivery_transport(platform, handoff_config, handoff_adapters)@@ -1397,7 +1357,6 @@ 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.cli_title = row.get("title") or cli_session_id[:8]@@ -1409,7 +1368,6 @@ class GatewayStartupMixin:logger.debug("Handoff: create_handoff_thread raised on %s: %s", platform_name, exc, exc_info=True)new_thread_id = Noneeffective_thread_id = new_thread_id or (str(home.thread_id) if home.thread_id else None)-# Telegram private-chat DM topics use the DM-topic source shape (user_id == chat_id) so the# synthetic turn binds the same key later inbound turns arrive on (`dm`, not `thread`).is_telegram_private_chat = (@@ -1465,7 +1423,6 @@ 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.await self.async_session_store.get_or_create_session(dest.source)@@ -1479,7 +1436,6 @@ class GatewayStartupMixin:# 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]synthetic_event = MessageEvent(text=(@@ -1503,7 +1459,6 @@ class GatewayStartupMixin:# Streaming may have already delivered the response inline; the agent ran without# raising either way — count as 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).