Skip to content

The agent that grows with you

refactor(gateway): publish-adapter/notice-allowed/scope-or-null/update-exit-code helpers; fold silent process-watcher loop

Teknium9d6606a80148
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index e748ff99133..3d62e6e6db0 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -496,10 +496,8 @@ class GatewayAdapterLifecycleMixin:
# A row still 'running' at startup belongs to a gateway that died mid-dispatch; it blocks
# request_handoff until reclaimed.
- def _scope(profile_home):
- if profile_home is None:
- return contextlib.nullcontext()
- return _async_profile_runtime_scope(profile_home)
+ def _scope(profile_home): # local: tests bind this watcher onto bare SimpleNamespace runners
+ return GatewayAdapterLifecycleMixin._scope_or_null(_async_profile_runtime_scope, profile_home)
for _pname, _phome in _handoff_watch_scopes(self):
with _log_suppressed(logging.DEBUG, "Stale-handoff reclaim failed", exc_info=True):
@@ -727,11 +725,15 @@ class GatewayAdapterLifecycleMixin:
logger.warning("Reconnect %s: %s, removing from retry queue", platform.value, reason)
del self._failed_platforms[platform]
- async def _install_reconnected_adapter(self, platform, adapter) -> None:
- """Publish a freshly reconnected primary adapter and replay what it missed while down."""
+ def _publish_primary_adapter(self, platform, adapter) -> None:
+ """Register a connected primary adapter and wire voice mode/input (transcription without /voice join)."""
self.adapters[platform] = adapter
self._sync_voice_mode_state_to_adapter(adapter)
self._bind_voice_input_callback(adapter)
+
+ async def _install_reconnected_adapter(self, platform, adapter) -> None:
+ """Publish a freshly reconnected primary adapter and replay what it missed while down."""
+ self._publish_primary_adapter(platform, adapter)
self.delivery_router.adapters = self.adapters
del self._failed_platforms[platform]
self._update_platform_runtime_status(
@@ -925,11 +927,9 @@ class GatewayAdapterLifecycleMixin:
if owner is None:
return False
pv = platform.value
+ head = f"Profile '{owner}' and '{profile_name}' both configure {pv} "
if kind == "credential":
- message = (
- f"Profile '{owner}' and '{profile_name}' both configure {pv} with the same credential. "
- f"Give each profile its own {pv} credential."
- )
+ message = head + f"with the same credential. Give each profile its own {pv} credential."
logger.error(
"Profile '%s' and '%s' both configure %s with the same credential — refusing to start the "
"duplicate (one credential cannot be consumed twice). Give each profile its own %s credential.",
@@ -937,10 +937,7 @@ class GatewayAdapterLifecycleMixin:
)
else:
bind, port = claim[-2:]
- message = (
- f"Profile '{owner}' and '{profile_name}' both configure {pv} sidecars on the same listener. "
- f"Configure a distinct listener for profile '{profile_name}'."
- )
+ message = head + f"sidecars on the same listener. Configure a distinct listener for profile '{profile_name}'."
logger.error(
"Profile '%s' and '%s' both configure %s sidecars on %s:%s — refusing to start the duplicate "
"listener. Set platforms.%s.extra.sidecar_port to a distinct port for profile '%s'.",
@@ -1276,6 +1273,11 @@ class GatewayAdapterLifecycleMixin:
except Exception:
return None
+ @staticmethod
+ def _scope_or_null(scope_factory, profile_home):
+ """``scope_factory(profile_home)`` or a nullcontext when the profile home is unknown."""
+ return scope_factory(profile_home) if profile_home is not None else contextlib.nullcontext()
+
@staticmethod
def _stamp_event_profile(event, profile_name: str) -> None:
"""Best-effort: stamp ``source.profile`` on an inbound event that has none yet."""
@@ -1293,10 +1295,7 @@ class GatewayAdapterLifecycleMixin:
async def _handler(event):
self._stamp_event_profile(event, profile_name)
- async with (
- _async_profile_runtime_scope(profile_home) if profile_home is not None
- else contextlib.nullcontext()
- ):
+ async with self._scope_or_null(_async_profile_runtime_scope, profile_home):
return await self._handle_message(event)
return _handler
@@ -1369,10 +1368,7 @@ class GatewayAdapterLifecycleMixin:
async def _handler(event, source):
if getattr(source, "profile", None) is None:
source.profile = profile_name
- with (
- _profile_runtime_scope(profile_home) if profile_home is not None
- else contextlib.nullcontext()
- ):
+ with self._scope_or_null(_profile_runtime_scope, profile_home):
return await self._handle_gateway_platform_event(event, source)
return _handler
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 8c0791c6d7f..ad314224046 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -430,6 +430,10 @@ class GatewayNotificationsMixin:
paths.exit_code.write_text("124", encoding="utf-8")
await self._send_update_notification()
+ @staticmethod
+ def _update_exit_code(paths: "_UpdatePaths") -> int:
+ return int(paths.exit_code.read_text(encoding="utf-8").strip() or "1")
+
@staticmethod
def _read_update_output_since(path: Path, offset: int) -> tuple[str, int]:
"""Read update output defensively; logs may contain invalid UTF-8."""
@@ -524,7 +528,7 @@ class GatewayNotificationsMixin:
_read_new_output()
await _flush_buffer()
with _log_suppressed(logging.WARNING, "Update final notification failed: %s"):
- exit_code = int(paths.exit_code.read_text(encoding="utf-8").strip() or "1")
+ exit_code = self._update_exit_code(paths)
await target.send(
"✅ Hermes update finished." if exit_code == 0
else "❌ Hermes update failed (exit code {}).".format(exit_code)
@@ -601,7 +605,7 @@ class GatewayNotificationsMixin:
if not paths.exit_code.exists():
return _defer("Update notification deferred: update still running")
- exit_code = int(paths.exit_code.read_text(encoding="utf-8").strip() or "1")
+ 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)
@@ -1564,24 +1568,18 @@ class GatewayNotificationsMixin:
logger.debug("Process watcher started: %s (every %ss, notify=%s, agent_notify=%s)",
session_id, interval, notify_mode, agent_notify)
- if notify_mode == "off" and not agent_notify:
- # Still wait for the process to exit so we can log it, but don't push any messages.
- while True:
- await asyncio.sleep(interval)
- session = process_registry.get(session_id)
- if session is None or session.exited:
- break
- logger.debug("Process watcher ended (silent): %s", session_id)
- return
-
+ silent = notify_mode == "off" and not agent_notify
last_output_len = 0
while True:
await asyncio.sleep(interval)
-
session = process_registry.get(session_id)
if session is None:
break
-
+ if silent:
+ # Still wait for the process to exit so we can log it, but don't push any messages.
+ if session.exited:
+ break
+ continue
current_output_len = len(session.output_buffer)
has_new_output = current_output_len > last_output_len
last_output_len = current_output_len
@@ -1627,4 +1625,4 @@ class GatewayNotificationsMixin:
f"[Background process {session_id} is still running~ New output:\n{new_output}]",
)
- logger.debug("Process watcher ended: %s", session_id)
+ logger.debug("Process watcher ended%s: %s", " (silent)" if silent else "", session_id)
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index e0803edc085..6a7263d174b 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -657,6 +657,15 @@ class GatewayShutdownMixin:
platform_cfg = self.config.platforms.get(platform)
return platform_cfg is None or bool(platform_cfg.gateway_restart_notification)
+ def _notice_allowed(self, platform: Platform, what: str) -> bool:
+ """``_restart_notification_allowed`` with the INFO suppression line for shutdown notices."""
+ if self._restart_notification_allowed(platform):
+ return True
+ logger.info(
+ "Shutdown notification suppressed for %s: %s has gateway_restart_notification=false", what, platform.value,
+ )
+ return False
+
async def _notify_interrupted_cron_jobs(self, job_ids) -> int:
"""Tell the owner of each just-interrupted cron job that its run died; returns notices sent.
@@ -791,11 +800,7 @@ class GatewayShutdownMixin:
adapter = self.adapters.get(platform)
if not adapter:
continue
- if not self._restart_notification_allowed(platform):
- logger.info(
- "Shutdown notification suppressed for active session: %s has gateway_restart_notification=false",
- platform_str,
- )
+ if not self._notice_allowed(platform, "active session"):
continue
reply_to_message_id = getattr(source, "message_id", None)
if reply_to_message_id is None and restart_key == dedup_key:
@@ -807,9 +812,7 @@ class GatewayShutdownMixin:
except Exception as e:
logger.debug("Failed to send shutdown notification to %s:%s: %s", platform_str, chat_id, e)
continue
- if await self._send_shutdown_notice(
- adapter, chat_id, msg, "active chat", platform_str, metadata=metadata
- ):
+ if await self._send_shutdown_notice(adapter, chat_id, msg, "active chat", platform_str, metadata=metadata):
notified.add(dedup_key)
if self._restart_requested and restart_source is not None:
logger.debug("Skipping home-channel shutdown notifications for in-chat restart")
@@ -833,11 +836,7 @@ class GatewayShutdownMixin:
home = self.config.get_home_channel(platform)
if not home or not home.chat_id:
continue
- if not self._restart_notification_allowed(platform):
- logger.info(
- "Shutdown notification suppressed for home channel: %s has gateway_restart_notification=false",
- platform.value,
- )
+ if not self._notice_allowed(platform, "home channel"):
continue
dedup_key = _notice_target_key(platform.value, home.chat_id, home.thread_id)
if dedup_key in notified:
@@ -944,10 +943,8 @@ class GatewayShutdownMixin:
await asyncio.wait_for(self._run_in_executor_with_context(_call), timeout=self._FINALIZE_TIMEOUT_S)
except asyncio.TimeoutError:
logger.warning(
- "Session finalize hooks (%s, reason=%s) exceeded %ss; "
- "proceeding without blocking the event loop (the worker "
- "thread is left to finish on its own).",
- session_id, reason, self._FINALIZE_TIMEOUT_S,
+ "Session finalize hooks (%s, reason=%s) exceeded %ss; proceeding without blocking the event loop "
+ "(the worker thread is left to finish on its own).", session_id, reason, self._FINALIZE_TIMEOUT_S,
)
except Exception as finalize_exc:
logger.debug("Session finalize hooks (%s, reason=%s) failed: %s", session_id, reason, finalize_exc)
@@ -967,9 +964,8 @@ class GatewayShutdownMixin:
)
except asyncio.TimeoutError:
logger.warning(
- "Agent resource cleanup%s exceeded %ss; proceeding without "
- "blocking the event loop (the worker thread is left to finish "
- "on its own). (#53175)", ctx_label, self._CLEANUP_TIMEOUT_S,
+ "Agent resource cleanup%s exceeded %ss; proceeding without blocking the event loop (the worker "
+ "thread is left to finish on its own). (#53175)", ctx_label, self._CLEANUP_TIMEOUT_S,
)
except Exception as cleanup_exc:
logger.warning("Agent resource cleanup%s failed: %s (#53175)", ctx_label, cleanup_exc)
@@ -1346,6 +1342,9 @@ class GatewayShutdownMixin:
if _async_n:
logger.info("Shutdown (%s): interrupted %d background delegation(s)", phase, _async_n)
+ _step("process_registry.kill_all", _kill_processes)
+ _marked_cron_jobs = _step("mark_running_jobs_interrupted", _mark_cron_interrupted) or []
+ _step("async interrupt_all", _interrupt_delegations)
def _cleanup_environments() -> None:
from tools.terminal_tool import cleanup_all_environments
cleanup_all_environments()
@@ -1354,9 +1353,6 @@ class GatewayShutdownMixin:
from tools.browser_tool import cleanup_all_browsers
cleanup_all_browsers()
- _step("process_registry.kill_all", _kill_processes)
- _marked_cron_jobs = _step("mark_running_jobs_interrupted", _mark_cron_interrupted) or []
- _step("async interrupt_all", _interrupt_delegations)
_step("cleanup_all_environments", _cleanup_environments)
_step("cleanup_all_browsers", _cleanup_browsers)
return _marked_cron_jobs
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 1dad13227f2..62b758fb496 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -1076,10 +1076,7 @@ class GatewayStartupMixin:
)
continue
if outcome == "ok":
- self.adapters[platform] = adapter
- self._sync_voice_mode_state_to_adapter(adapter)
- # Wire voice input at connect time so transcription works without /voice join.
- self._bind_voice_input_callback(adapter)
+ self._publish_primary_adapter(platform, adapter)
connected_count += 1
self._update_platform_runtime_status(
platform.value, platform_state="connected", error_code=None, error_message=None,