Skip to content

The agent that grows with you

refactor: extract gateway bootstrap and writable initialization phases

Teknium0c2873402d67
diff --git a/gateway/run.py b/gateway/run.py
index c907ba4187e..93ab5fe3d78 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3263,12 +3263,15 @@ def _instantiate_builtin_adapter(platform: Platform, config: Any) -> Optional[Ba
return adapter_cls(config)
+from gateway.run_runtime_init import GatewayRuntimeInitMixin
+
+
class GatewayRunner(
GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, GatewaySlashCommandsMixin,
GatewayVoiceMixin, GatewayAdapterLifecycleMixin, GatewayTopicThreadsMixin, GatewayTurnMixin,
GatewayShutdownMixin, GatewayBusySessionMixin, GatewayConfigLoadersMixin, GatewayStartupMixin,
GatewaySessionWatchersMixin, GatewayNotificationsMixin, GatewayInboundMixin, GatewayGoalsMixin,
- GatewayAgentCacheMixin):
+ GatewayAgentCacheMixin, GatewayRuntimeInitMixin):
"""Main gateway controller: manages adapter lifecycles, routes messages to/from the agent."""
# Class-level defaults so partial construction in tests doesn't blow up on attribute access.
@@ -4801,376 +4804,18 @@ async def _wait_for_pid_exit(pid: int, attempts: int, delay: float) -> bool:
return False
-async def _start_gateway_replace_existing_instance(existing_pid: int, replace: bool) -> bool:
- """Handle a live gateway PID under this HERMES_HOME: replace it (``--replace``) or refuse.
- Returns False when startup must abort (refused, permission denied, target still alive)."""
- from gateway.status import get_process_start_time, remove_pid_file, terminate_pid
- if not replace:
- hermes_home = str(get_hermes_home())
- logger.error(
- "Another gateway instance is already running (PID %d, HERMES_HOME=%s). "
- "Use 'hermes gateway restart' to replace it, or 'hermes gateway stop' first.",
- existing_pid, hermes_home)
- print(
- f"\n❌ Gateway already running (PID {existing_pid}).\n"
- f" Use 'hermes gateway restart' to replace it,\n"
- f" or 'hermes gateway stop' to kill it first.\n"
- f" Or use 'hermes gateway run --replace' to auto-replace.\n")
- return False
-
- # Never signal a process not provably ours (a poisoned PID record → cross-profile restart loop).
- if _replace_target_belongs_to_other_profile(existing_pid):
- from gateway.status import _get_process_hermes_home
- logger.error(
- "Refusing --replace: PID %d cannot be proven to belong "
- "to this profile's gateway (HERMES_HOME %s). Remove the "
- "stale PID record or stop the owning profile explicitly.",
- existing_pid, _get_process_hermes_home())
- return False
- existing_start_time = get_process_start_time(existing_pid)
- logger.info("Replacing existing gateway instance (PID %d) with --replace.", existing_pid)
- # Takeover marker: target exits 0 on our SIGTERM (exit 1 → systemd Restart=on-failure flap loop).
- try:
- from gateway.status import write_takeover_marker
- write_takeover_marker(existing_pid)
- except Exception as e:
- logger.debug("Could not write takeover marker: %s", e)
- # Snapshot children BEFORE signalling: reparented orphans are invisible yet hold scoped token locks.
- try:
- from gateway.status import _snapshot_gateway_children
- _old_gateway_children = _snapshot_gateway_children(existing_pid)
- except Exception:
- _old_gateway_children = []
- try:
- terminate_pid(existing_pid, force=False)
- except ProcessLookupError:
- pass # Already gone
- except (PermissionError, OSError):
- logger.error("Permission denied killing PID %d. Cannot replace.", existing_pid)
- _clear_takeover_marker_quiet()
- return False
- # Up to 10s for SIGTERM, then SIGKILL.
- if not await _wait_for_pid_exit(existing_pid, 20, 0.5):
- logger.warning("Old gateway (PID %d) did not exit after SIGTERM, sending SIGKILL.", existing_pid)
- old_gateway_exited = False
- try:
- terminate_pid(existing_pid, force=True, expected_start_time=existing_start_time)
- except ProcessLookupError:
- old_gateway_exited = True
- except (PermissionError, OSError):
- pass
- # Confirm SIGKILL took (D-state/zombie) before clearing PID/locks, or two gateways share a token.
- if not old_gateway_exited and not await _wait_for_pid_exit(existing_pid, 20, 0.25):
- logger.error(
- "Old gateway (PID %d) still appears alive after SIGKILL; "
- "aborting replacement to avoid a duplicate gateway.", existing_pid)
- _clear_takeover_marker_quiet()
- return False
- # Reap orphaned children (POSIX; mirrors Windows taskkill /T) so they stop holding scoped token locks.
- try:
- from gateway.status import reap_gateway_children
- reap_gateway_children(_old_gateway_children, parent_pid=existing_pid)
- except Exception:
- logger.debug("Child reap for replaced gateway PID %d failed", existing_pid, exc_info=True)
- remove_pid_file()
- # remove_pid_file() is a no-op when the PID doesn't match; force-unlink covers a crashed old process.
- with suppress(Exception):
- (get_hermes_home() / "gateway.pid").unlink(missing_ok=True)
- # The old process may not have consumed the marker (SIGKILL'd before its handler read it).
- _clear_takeover_marker_quiet()
- # Stopped (Ctrl+Z) processes don't release scoped locks on exit; stale lock files block the new gateway.
- try:
- from gateway.status import release_all_scoped_locks
- _released = release_all_scoped_locks(owner_pid=existing_pid, owner_start_time=existing_start_time)
- if _released:
- logger.info("Released %d stale scoped lock(s) from old gateway.", _released)
- except Exception:
- pass
- return True
-
-
-def _start_gateway_configure_logging(verbosity: Optional[int]) -> None:
- """Sync bundled skills, set up file logging + startup security audit, and the -v/-q stderr handler."""
- def _sync_skills() -> None:
- from tools.skills_sync import sync_skills
- sync_skills(quiet=True)
-
- _best_effort(_sync_skills)
-
- # Centralized logging (agent.log INFO+, errors.log WARNING+, gateway.log gateway-only); idempotent.
- from hermes_logging import setup_logging, _safe_stderr
- setup_logging(hermes_home=_hermes_home, mode="gateway")
-
- def _security_audit() -> None:
- # Warn-on-load, never blocks: surfaces root / weak-SSH / unauthenticated-listener exposure.
- from hermes_cli.security_audit_startup import log_startup_security_warnings
-
- def _raw_cfg():
- from hermes_cli.config import read_raw_config
- return read_raw_config()
-
- log_startup_security_warnings(hermes_home=_hermes_home, config=_best_effort(_raw_cfg))
-
- _best_effort(_security_audit, "Startup security audit failed (non-fatal): %s")
-
- # Optional stderr handler from -v/-q: None (quiet) = none; 0 = WARNING; 1 = INFO; 2+ = DEBUG.
- if verbosity is not None:
- _stderr_level = {0: logging.WARNING, 1: logging.INFO}.get(verbosity, logging.DEBUG)
- _stderr_handler = logging.StreamHandler(_safe_stderr())
- _stderr_handler.setLevel(_stderr_level)
- _stderr_handler.setFormatter(_gateway_stderr_formatter())
- root = logging.getLogger()
- root.addHandler(_stderr_handler)
- if _stderr_level < root.level: # so DEBUG records can reach the handler
- root.setLevel(_stderr_level)
-
-
-def _start_gateway_make_shutdown_signal_handler(runner, _signal_initiated_shutdown: list):
- """Build the SIGINT/SIGTERM handler; ``_signal_initiated_shutdown[0]`` records an unplanned signal."""
- def shutdown_signal_handler(received_signal=None):
- # Planned --replace takeover (sibling marked this PID): exit 0 so systemd won't revive us.
- def _takeover() -> bool:
- from gateway.status import consume_takeover_marker_for_self
- return consume_takeover_marker_for_self()
-
- # Planned stop: CLI marks first, else its SIGTERM looks like an external kill. SIGINT = Ctrl+C.
- def _planned_stop() -> bool:
- from gateway.status import consume_planned_stop_marker_for_self
- return consume_planned_stop_marker_for_self()
-
- # Fast (<10ms) sync snapshot: stdlib + /proc, no subprocesses (`ps aux` here once blocked ~3s).
- def _snapshot():
- from gateway.shutdown_forensics import snapshot_shutdown_context
- return snapshot_shutdown_context(received_signal)
-
- planned_takeover = bool(_best_effort(_takeover, "Takeover marker check failed: %s"))
- planned_stop = received_signal == signal.SIGINT or (
- not planned_takeover and bool(_best_effort(_planned_stop, "Planned stop marker check failed: %s")))
- _shutdown_ctx = _best_effort(_snapshot, "snapshot_shutdown_context failed: %s")
- sig_name = _shutdown_ctx["signal"] if _shutdown_ctx else None
-
- if planned_takeover:
- logger.info("Received %s as a planned --replace takeover — exiting cleanly", sig_name or "SIGTERM")
- elif planned_stop:
- logger.info("Received %s as a planned gateway stop — exiting cleanly", sig_name or "SIGTERM/SIGINT")
- else:
- # Mirrored onto the runner so _stop_impl suppresses the gateway_state=stopped persist for
- # unexpected signals; operator stops take the `planned_stop` branch and leave it False (DO persist).
- _signal_initiated_shutdown[0] = runner._signal_initiated_shutdown = True
- logger.info("Received %s — initiating shutdown", sig_name or "SIGTERM/SIGINT")
-
- if _shutdown_ctx is not None:
- def _log_context() -> None:
- # The most useful line for "gateway keeps dying" tickets.
- from gateway.shutdown_forensics import format_context_for_log
- logger.warning("Shutdown context: %s", format_context_for_log(_shutdown_ctx))
-
- def _diagnostic() -> None:
- # Heavyweight (ps auxf, pstree, dmesg), detached so it finishes even if our cgroup is torn
- # down; bounded by an internal timeout, never blocks.
- from gateway.shutdown_forensics import spawn_async_diagnostic
- spawn_async_diagnostic(
- _hermes_home / "logs" / "gateway-shutdown-diag.log", _shutdown_ctx["signal"], timeout_seconds=5.0)
-
- _best_effort(_log_context, "format_context_for_log failed: %s")
- _best_effort(_diagnostic, "spawn_async_diagnostic failed: %s")
- asyncio.create_task(runner.stop())
- return shutdown_signal_handler
-
-
-def _start_gateway_claim_pid_file() -> bool:
- """Claim the runtime lock + PID file (O_EXCL winner is the authoritative gateway). False = lost."""
- import atexit
- from gateway.status import (
- acquire_gateway_runtime_lock, get_running_pid, release_gateway_runtime_lock,
- remove_pid_file, write_pid_file)
- _current_pid = get_running_pid()
- if _current_pid is not None and _current_pid != os.getpid():
- logger.error("Another gateway instance (PID %d) started during our startup. "
- "Exiting to avoid double-running.", _current_pid)
- return False
- if not acquire_gateway_runtime_lock():
- logger.error("Gateway runtime lock is already held by another instance. Exiting.")
- return False
- try:
- write_pid_file()
- except FileExistsError:
- release_gateway_runtime_lock()
- logger.error("PID file race lost to another gateway instance. Exiting.")
- return False
- atexit.register(remove_pid_file)
- atexit.register(release_gateway_runtime_lock)
- return True
-
-
-async def _start_gateway_start_control_socket(runner):
- """Start the gateway control socket (identify/status/pause-for-update); None when unavailable."""
- import atexit
- _control_server = None
- try:
- # Started immediately after the PID-file claim: winning that O_EXCL race is the moment this process
- # becomes the authoritative gateway for its HERMES_HOME, so from here on "does a socket answer?" is
- # a truthful liveness/identity query for updater and fleet consumers. Strictly non-fatal: a bind
- # failure only means consumers fall back to the process-scan/state-file layer, exactly as before
- # this feature. See #92091.
- from gateway.control_socket import GatewayControlServer
- # pause-for-update: the updater asks us to drain + exit (freeing venv handles) vs. a tree-kill
- # (same path as SIGUSR1). Handler runs on the socket executor thread, so marshal onto the loop.
- # pause-for-update (#92091 step 2): the updater asks this gateway to drain in-flight turns and exit
- # cleanly — releasing every venv file handle — instead of being tree-killed mid-turn. Same drain
- # path as SIGUSR1/service restarts (request_restart(via_service=True)); the updater (or the service
- # manager) relaunches after the code swap.
- _main_loop = asyncio.get_running_loop()
-
- def _pause_for_update_handler() -> dict:
- try:
- from hermes_cli.gateway import _get_restart_drain_timeout
- _drain = float(_get_restart_drain_timeout())
- except Exception:
- _drain = 30.0
- accepted_box: list[bool] = []
- _done = threading.Event()
-
- def _request() -> None:
- try:
- accepted_box.append(runner.request_restart(detached=False, via_service=True))
- finally:
- _done.set()
-
- _main_loop.call_soon_threadsafe(_request)
- _done.wait(timeout=5.0)
- accepted = bool(accepted_box and accepted_box[0])
- return {
- "pausing": accepted, "already_stopping": not accepted,
- "pid": os.getpid(), "drain_timeout": _drain}
-
- _control_server = GatewayControlServer(
- verb_handlers={"pause-for-update": _pause_for_update_handler})
- if not await _control_server.start():
- _control_server = None
- else:
- atexit.register(_control_server.cleanup_files)
- except Exception as _cs_exc:
- logger.debug("Control socket startup failed (non-fatal): %s", _cs_exc)
- _control_server = None
- return _control_server
-
-
-def _start_gateway_start_cron_and_housekeeping(runner):
- """Start the cron scheduler thread + gateway housekeeping thread; returns
- ``(cron_stop, cron_provider, cron_thread, housekeeping_thread)``."""
- # The event loop is passed so cron delivery can use live adapters (E2EE support).
- from cron.scheduler_provider import (
- InProcessCronScheduler, resolve_cron_scheduler, scheduler_for_profile_mode)
- cron_stop = threading.Event()
- multiplex_cron = bool(getattr(runner.config, "multiplex_profiles", False))
- cron_provider = scheduler_for_profile_mode(
- resolve_cron_scheduler(), multiplex_profiles=multiplex_cron)
- cron_start_kwargs: Dict[str, Any] = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}
-
- # Multiplex: tell the ticker which profile homes to tick, else secondary profiles' jobs never run.
- if isinstance(cron_provider, InProcessCronScheduler) and multiplex_cron:
- try:
- profile_homes = _multiplex_profile_homes(runner.config)
- if profile_homes:
- cron_start_kwargs["profile_homes"] = profile_homes
- # Per-profile adapters so each profile's cron output goes via its own bot, not the default's.
- cron_start_kwargs["profile_adapters"] = getattr(runner, "_profile_adapters", None)
- # runner.adapters belongs to "default"; naming it keeps the ticker from routing a secondary's
- # cron through the default bot (even before that profile's adapter connects).
- cron_start_kwargs["default_profile"] = "default"
- logger.info(
- "Cron scheduler will tick %d profile(s) under multiplex: %s", len(profile_homes),
- [p[0] if isinstance(p, tuple) else p for p in profile_homes])
- except Exception as exc:
- logger.warning("Could not resolve profile homes for multiplex cron: %s", exc)
-
- # Only the in-process ticker polls local due jobs, so only it gets the external-drain dispatch gate.
- if isinstance(cron_provider, InProcessCronScheduler):
- cron_start_kwargs["can_dispatch"] = lambda: not (
- runner._draining or runner._external_drain_active)
- cron_thread = threading.Thread(
- target=cron_provider.start, args=(cron_stop,), kwargs=cron_start_kwargs, daemon=True,
- name="cron-scheduler")
- cron_thread.start()
-
- # External providers fire over loopback HTTP to THIS process's api_server; if it never came up (usually
- # API_SERVER_KEY missing) every fire fails while manual runs work — misread as a job bug. Say it ONCE.
- if not isinstance(cron_provider, InProcessCronScheduler):
- try:
- _has_api_server = Platform.API_SERVER in (runner.adapters or {})
- except Exception:
- _has_api_server = True # never let the tell break startup
- if not _has_api_server:
- logger.warning(
- "Cron provider '%s' is active but the api_server adapter is "
- "NOT running in this gateway — scheduled fires arrive over "
- "loopback HTTP and will all fail (jobs only run when "
- "triggered manually). Most common cause: API_SERVER_KEY is "
- "missing from this gateway process's environment. Restart "
- "the gateway through its supervisor (`hermes gateway "
- "restart`) so the profile env loads.",
- getattr(cron_provider, "name", "external"))
-
- # Gateway-only housekeeping runs independently of the cron provider; shares cron_stop for shutdown.
- housekeeping_thread = threading.Thread(
- target=_start_gateway_housekeeping, args=(cron_stop,),
- kwargs={"adapters": runner.adapters, "loop": asyncio.get_running_loop(),
- "cron_provider": cron_provider, "runner": runner},
- daemon=True, name="gateway-housekeeping")
- housekeeping_thread.start()
- return cron_stop, cron_provider, cron_thread, housekeeping_thread
-
-
-async def _start_gateway_shutdown_tail(
- runner, _control_server, cron_stop: threading.Event, cron_provider,
- cron_thread: threading.Thread, housekeeping_thread: threading.Thread,
- _planned_stop_watcher_stop: threading.Event, _planned_stop_watcher_thread: threading.Thread,
- _signal_initiated_shutdown: list) -> bool:
- """Post-``wait_for_shutdown`` teardown; returns the process exit verdict (True = exit 0)."""
- # Control socket first: once shutdown begins we are no longer a truthful "serving here" answer and a
- # successor must be able to bind. Early-exit paths rely on the atexit cleanup_files hook instead.
- if _control_server is not None:
- try:
- await _control_server.stop()
- except Exception:
- logger.debug("Control socket stop failed (non-fatal)", exc_info=True)
-
- def _stop_keepalive() -> None:
- from hermes_cli.nous_auth_keepalive import stop_nous_auth_keepalive
- stop_nous_auth_keepalive()
-
- _best_effort(_stop_keepalive)
- if _exit_with_failure_verdict(runner):
- return False
-
- # Never join(): an in-flight cron delivery is a coroutine on THIS loop; a sync join would drop it.
- # Stop cron scheduler + housekeeping cleanly. These MUST be awaited cooperatively, not join()ed. A cron
- # delivery in flight when the gateway restarts is a coroutine scheduled onto THIS event loop
- # (safe_schedule_threadsafe); the ticker thread is blocked on its future.result(). A synchronous
- # cron_thread.join() would block the loop, so that delivery could never run — it timed out and the
- # message was silently dropped (#58818). Awaiting keeps the loop alive so the in-flight delivery
- # finishes before we tear down.
- cron_stop.set()
- _stop_cron_provider(cron_provider)
- if not await _await_thread_exit(cron_thread, timeout=_CRON_SHUTDOWN_DRAIN_TIMEOUT):
- logger.warning("Cron ticker did not exit within %.0fs of shutdown — an in-flight "
- "delivery may have been dropped.", _CRON_SHUTDOWN_DRAIN_TIMEOUT)
- await _await_thread_exit(housekeeping_thread, timeout=_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT)
-
- # Stop the planned-stop watcher (daemon=True so this is belt-and-suspenders).
- _planned_stop_watcher_stop.set()
- _planned_stop_watcher_thread.join(timeout=2)
-
- with suppress(Exception):
- await _shutdown_mcp_servers_nonblocking()
-
- return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])
-
-
async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False, verbosity: Optional[int] = 0) -> bool:
"""Start the gateway and run until interrupted; False if it failed to start (non-zero exit so
systemd can auto-restart). ``replace`` kills any existing instance first (avoids restart-loop deadlocks)."""
+ from gateway.run_bootstrap import (
+ _start_gateway_replace_existing_instance,
+ _start_gateway_configure_logging,
+ _start_gateway_make_shutdown_signal_handler,
+ _start_gateway_claim_pid_file,
+ _start_gateway_start_control_socket,
+ _start_gateway_start_cron_and_housekeeping,
+ _start_gateway_shutdown_tail
+ )
# Set here (not at import) so incidental gateway.run imports from CLI code don't poison it.
os.environ["HERMES_EXEC_ASK"] = "1"
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
new file mode 100644
index 00000000000..e6f1d76d165
--- /dev/null
+++ b/gateway/run_bootstrap.py
@@ -0,0 +1,380 @@
+"""Process startup phases; diagnostics remain in the gateway facade."""
+from __future__ import annotations
+
+import threading
+from typing import Optional
+
+async def _start_gateway_replace_existing_instance(existing_pid: int, replace: bool) -> bool:
+ """Handle a live gateway PID under this HERMES_HOME: replace it (``--replace``) or refuse.
+ Returns False when startup must abort (refused, permission denied, target still alive)."""
+ from gateway.run import (_clear_takeover_marker_quiet, _replace_target_belongs_to_other_profile, _wait_for_pid_exit, get_hermes_home, logger, suppress)
+ from gateway.status import get_process_start_time, remove_pid_file, terminate_pid
+ if not replace:
+ hermes_home = str(get_hermes_home())
+ logger.error(
+ "Another gateway instance is already running (PID %d, HERMES_HOME=%s). "
+ "Use 'hermes gateway restart' to replace it, or 'hermes gateway stop' first.",
+ existing_pid, hermes_home)
+ print(
+ f"\n❌ Gateway already running (PID {existing_pid}).\n"
+ f" Use 'hermes gateway restart' to replace it,\n"
+ f" or 'hermes gateway stop' to kill it first.\n"
+ f" Or use 'hermes gateway run --replace' to auto-replace.\n")
+ return False
+
+ # Never signal a process not provably ours (a poisoned PID record → cross-profile restart loop).
+ if _replace_target_belongs_to_other_profile(existing_pid):
+ from gateway.status import _get_process_hermes_home
+ logger.error(
+ "Refusing --replace: PID %d cannot be proven to belong "
+ "to this profile's gateway (HERMES_HOME %s). Remove the "
+ "stale PID record or stop the owning profile explicitly.",
+ existing_pid, _get_process_hermes_home())
+ return False
+ existing_start_time = get_process_start_time(existing_pid)
+ logger.info("Replacing existing gateway instance (PID %d) with --replace.", existing_pid)
+ # Takeover marker: target exits 0 on our SIGTERM (exit 1 → systemd Restart=on-failure flap loop).
+ try:
+ from gateway.status import write_takeover_marker
+ write_takeover_marker(existing_pid)
+ except Exception as e:
+ logger.debug("Could not write takeover marker: %s", e)
+ # Snapshot children BEFORE signalling: reparented orphans are invisible yet hold scoped token locks.
+ try:
+ from gateway.status import _snapshot_gateway_children
+ _old_gateway_children = _snapshot_gateway_children(existing_pid)
+ except Exception:
+ _old_gateway_children = []
+ try:
+ terminate_pid(existing_pid, force=False)
+ except ProcessLookupError:
+ pass # Already gone
+ except (PermissionError, OSError):
+ logger.error("Permission denied killing PID %d. Cannot replace.", existing_pid)
+ _clear_takeover_marker_quiet()
+ return False
+ # Up to 10s for SIGTERM, then SIGKILL.
+ if not await _wait_for_pid_exit(existing_pid, 20, 0.5):
+ logger.warning("Old gateway (PID %d) did not exit after SIGTERM, sending SIGKILL.", existing_pid)
+ old_gateway_exited = False
+ try:
+ terminate_pid(existing_pid, force=True, expected_start_time=existing_start_time)
+ except ProcessLookupError:
+ old_gateway_exited = True
+ except (PermissionError, OSError):
+ pass
+ # Confirm SIGKILL took (D-state/zombie) before clearing PID/locks, or two gateways share a token.
+ if not old_gateway_exited and not await _wait_for_pid_exit(existing_pid, 20, 0.25):
+ logger.error(
+ "Old gateway (PID %d) still appears alive after SIGKILL; "
+ "aborting replacement to avoid a duplicate gateway.", existing_pid)
+ _clear_takeover_marker_quiet()
+ return False
+ # Reap orphaned children (POSIX; mirrors Windows taskkill /T) so they stop holding scoped token locks.
+ try:
+ from gateway.status import reap_gateway_children
+ reap_gateway_children(_old_gateway_children, parent_pid=existing_pid)
+ except Exception:
+ logger.debug("Child reap for replaced gateway PID %d failed", existing_pid, exc_info=True)
+ remove_pid_file()
+ # remove_pid_file() is a no-op when the PID doesn't match; force-unlink covers a crashed old process.
+ with suppress(Exception):
+ (get_hermes_home() / "gateway.pid").unlink(missing_ok=True)
+ # The old process may not have consumed the marker (SIGKILL'd before its handler read it).
+ _clear_takeover_marker_quiet()
+ # Stopped (Ctrl+Z) processes don't release scoped locks on exit; stale lock files block the new gateway.
+ try:
+ from gateway.status import release_all_scoped_locks
+ _released = release_all_scoped_locks(owner_pid=existing_pid, owner_start_time=existing_start_time)
+ if _released:
+ logger.info("Released %d stale scoped lock(s) from old gateway.", _released)
+ except Exception:
+ pass
+ return True
+
+
+def _start_gateway_configure_logging(verbosity: Optional[int]) -> None:
+ """Sync bundled skills, set up file logging + startup security audit, and the -v/-q stderr handler."""
+ from gateway.run import (_best_effort, _gateway_stderr_formatter, _hermes_home, logging)
+ def _sync_skills() -> None:
+ from tools.skills_sync import sync_skills
+ sync_skills(quiet=True)
+
+ _best_effort(_sync_skills)
+
+ # Centralized logging (agent.log INFO+, errors.log WARNING+, gateway.log gateway-only); idempotent.
+ from hermes_logging import setup_logging, _safe_stderr
+ setup_logging(hermes_home=_hermes_home, mode="gateway")
+
+ def _security_audit() -> None:
+ # Warn-on-load, never blocks: surfaces root / weak-SSH / unauthenticated-listener exposure.
+ from hermes_cli.security_audit_startup import log_startup_security_warnings
+
+ def _raw_cfg():
+ from hermes_cli.config import read_raw_config
+ return read_raw_config()
+
+ log_startup_security_warnings(hermes_home=_hermes_home, config=_best_effort(_raw_cfg))
+
+ _best_effort(_security_audit, "Startup security audit failed (non-fatal): %s")
+
+ # Optional stderr handler from -v/-q: None (quiet) = none; 0 = WARNING; 1 = INFO; 2+ = DEBUG.
+ if verbosity is not None:
+ _stderr_level = {0: logging.WARNING, 1: logging.INFO}.get(verbosity, logging.DEBUG)
+ _stderr_handler = logging.StreamHandler(_safe_stderr())
+ _stderr_handler.setLevel(_stderr_level)
+ _stderr_handler.setFormatter(_gateway_stderr_formatter())
+ root = logging.getLogger()
+ root.addHandler(_stderr_handler)
+ if _stderr_level < root.level: # so DEBUG records can reach the handler
+ root.setLevel(_stderr_level)
+
+
+def _start_gateway_make_shutdown_signal_handler(runner, _signal_initiated_shutdown: list):
+ """Build the SIGINT/SIGTERM handler; ``_signal_initiated_shutdown[0]`` records an unplanned signal."""
+ from gateway.run import (_best_effort, _hermes_home, asyncio, logger, signal)
+ def shutdown_signal_handler(received_signal=None):
+ # Planned --replace takeover (sibling marked this PID): exit 0 so systemd won't revive us.
+ def _takeover() -> bool:
+ from gateway.status import consume_takeover_marker_for_self
+ return consume_takeover_marker_for_self()
+
+ # Planned stop: CLI marks first, else its SIGTERM looks like an external kill. SIGINT = Ctrl+C.
+ def _planned_stop() -> bool:
+ from gateway.status import consume_planned_stop_marker_for_self
+ return consume_planned_stop_marker_for_self()
+
+ # Fast (<10ms) sync snapshot: stdlib + /proc, no subprocesses (`ps aux` here once blocked ~3s).
+ def _snapshot():
+ from gateway.shutdown_forensics import snapshot_shutdown_context
+ return snapshot_shutdown_context(received_signal)
+
+ planned_takeover = bool(_best_effort(_takeover, "Takeover marker check failed: %s"))
+ planned_stop = received_signal == signal.SIGINT or (
+ not planned_takeover and bool(_best_effort(_planned_stop, "Planned stop marker check failed: %s")))
+ _shutdown_ctx = _best_effort(_snapshot, "snapshot_shutdown_context failed: %s")
+ sig_name = _shutdown_ctx["signal"] if _shutdown_ctx else None
+
+ if planned_takeover:
+ logger.info("Received %s as a planned --replace takeover — exiting cleanly", sig_name or "SIGTERM")
+ elif planned_stop:
+ logger.info("Received %s as a planned gateway stop — exiting cleanly", sig_name or "SIGTERM/SIGINT")
+ else:
+ # Mirrored onto the runner so _stop_impl suppresses the gateway_state=stopped persist for
+ # unexpected signals; operator stops take the `planned_stop` branch and leave it False (DO persist).
+ _signal_initiated_shutdown[0] = runner._signal_initiated_shutdown = True
+ logger.info("Received %s — initiating shutdown", sig_name or "SIGTERM/SIGINT")
+
+ if _shutdown_ctx is not None:
+ def _log_context() -> None:
+ # The most useful line for "gateway keeps dying" tickets.
+ from gateway.shutdown_forensics import format_context_for_log
+ logger.warning("Shutdown context: %s", format_context_for_log(_shutdown_ctx))
+
+ def _diagnostic() -> None:
+ # Heavyweight (ps auxf, pstree, dmesg), detached so it finishes even if our cgroup is torn
+ # down; bounded by an internal timeout, never blocks.
+ from gateway.shutdown_forensics import spawn_async_diagnostic
+ spawn_async_diagnostic(
+ _hermes_home / "logs" / "gateway-shutdown-diag.log", _shutdown_ctx["signal"], timeout_seconds=5.0)
+
+ _best_effort(_log_context, "format_context_for_log failed: %s")
+ _best_effort(_diagnostic, "spawn_async_diagnostic failed: %s")
+ asyncio.create_task(runner.stop())
+ return shutdown_signal_handler
+
+
+def _start_gateway_claim_pid_file() -> bool:
+ """Claim the runtime lock + PID file (O_EXCL winner is the authoritative gateway). False = lost."""
+ from gateway.run import (logger, os)
+ import atexit
+ from gateway.status import (
+ acquire_gateway_runtime_lock, get_running_pid, release_gateway_runtime_lock,
+ remove_pid_file, write_pid_file)
+ _current_pid = get_running_pid()
+ if _current_pid is not None and _current_pid != os.getpid():
+ logger.error("Another gateway instance (PID %d) started during our startup. "
+ "Exiting to avoid double-running.", _current_pid)
+ return False
+ if not acquire_gateway_runtime_lock():
+ logger.error("Gateway runtime lock is already held by another instance. Exiting.")
+ return False
+ try:
+ write_pid_file()
+ except FileExistsError:
+ release_gateway_runtime_lock()
+ logger.error("PID file race lost to another gateway instance. Exiting.")
+ return False
+ atexit.register(remove_pid_file)
+ atexit.register(release_gateway_runtime_lock)
+ return True
+
+
+async def _start_gateway_start_control_socket(runner):
+ """Start the gateway control socket (identify/status/pause-for-update); None when unavailable."""
+ from gateway.run import (asyncio, logger, os, threading)
+ import atexit
+ _control_server = None
+ try:
+ # Started immediately after the PID-file claim: winning that O_EXCL race is the moment this process
+ # becomes the authoritative gateway for its HERMES_HOME, so from here on "does a socket answer?" is
+ # a truthful liveness/identity query for updater and fleet consumers. Strictly non-fatal: a bind
+ # failure only means consumers fall back to the process-scan/state-file layer, exactly as before
+ # this feature. See #92091.
+ from gateway.control_socket import GatewayControlServer
+ # pause-for-update: the updater asks us to drain + exit (freeing venv handles) vs. a tree-kill
+ # (same path as SIGUSR1). Handler runs on the socket executor thread, so marshal onto the loop.
+ # pause-for-update (#92091 step 2): the updater asks this gateway to drain in-flight turns and exit
+ # cleanly — releasing every venv file handle — instead of being tree-killed mid-turn. Same drain
+ # path as SIGUSR1/service restarts (request_restart(via_service=True)); the updater (or the service
+ # manager) relaunches after the code swap.
+ _main_loop = asyncio.get_running_loop()
+
+ def _pause_for_update_handler() -> dict:
+ try:
+ from hermes_cli.gateway import _get_restart_drain_timeout
+ _drain = float(_get_restart_drain_timeout())
+ except Exception:
+ _drain = 30.0
+ accepted_box: list[bool] = []
+ _done = threading.Event()
+
+ def _request() -> None:
+ try:
+ accepted_box.append(runner.request_restart(detached=False, via_service=True))
+ finally:
+ _done.set()
+
+ _main_loop.call_soon_threadsafe(_request)
+ _done.wait(timeout=5.0)
+ accepted = bool(accepted_box and accepted_box[0])
+ return {
+ "pausing": accepted, "already_stopping": not accepted,
+ "pid": os.getpid(), "drain_timeout": _drain}
+
+ _control_server = GatewayControlServer(
+ verb_handlers={"pause-for-update": _pause_for_update_handler})
+ if not await _control_server.start():
+ _control_server = None
+ else:
+ atexit.register(_control_server.cleanup_files)
+ except Exception as _cs_exc:
+ logger.debug("Control socket startup failed (non-fatal): %s", _cs_exc)
+ _control_server = None
+ return _control_server
+
+
+def _start_gateway_start_cron_and_housekeeping(runner):
+ """Start the cron scheduler thread + gateway housekeeping thread; returns
+ ``(cron_stop, cron_provider, cron_thread, housekeeping_thread)``."""
+ from gateway.run import (Any, Dict, Platform, _multiplex_profile_homes, _start_gateway_housekeeping, asyncio, logger, threading)
+ # The event loop is passed so cron delivery can use live adapters (E2EE support).
+ from cron.scheduler_provider import (
+ InProcessCronScheduler, resolve_cron_scheduler, scheduler_for_profile_mode)
+ cron_stop = threading.Event()
+ multiplex_cron = bool(getattr(runner.config, "multiplex_profiles", False))
+ cron_provider = scheduler_for_profile_mode(
+ resolve_cron_scheduler(), multiplex_profiles=multiplex_cron)
+ cron_start_kwargs: Dict[str, Any] = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}
+
+ # Multiplex: tell the ticker which profile homes to tick, else secondary profiles' jobs never run.
+ if isinstance(cron_provider, InProcessCronScheduler) and multiplex_cron:
+ try:
+ profile_homes = _multiplex_profile_homes(runner.config)
+ if profile_homes:
+ cron_start_kwargs["profile_homes"] = profile_homes
+ # Per-profile adapters so each profile's cron output goes via its own bot, not the default's.
+ cron_start_kwargs["profile_adapters"] = getattr(runner, "_profile_adapters", None)
+ # runner.adapters belongs to "default"; naming it keeps the ticker from routing a secondary's
+ # cron through the default bot (even before that profile's adapter connects).
+ cron_start_kwargs["default_profile"] = "default"
+ logger.info(
+ "Cron scheduler will tick %d profile(s) under multiplex: %s", len(profile_homes),
+ [p[0] if isinstance(p, tuple) else p for p in profile_homes])
+ except Exception as exc:
+ logger.warning("Could not resolve profile homes for multiplex cron: %s", exc)
+
+ # Only the in-process ticker polls local due jobs, so only it gets the external-drain dispatch gate.
+ if isinstance(cron_provider, InProcessCronScheduler):
+ cron_start_kwargs["can_dispatch"] = lambda: not (
+ runner._draining or runner._external_drain_active)
+ cron_thread = threading.Thread(
+ target=cron_provider.start, args=(cron_stop,), kwargs=cron_start_kwargs, daemon=True,
+ name="cron-scheduler")
+ cron_thread.start()
+
+ # External providers fire over loopback HTTP to THIS process's api_server; if it never came up (usually
+ # API_SERVER_KEY missing) every fire fails while manual runs work — misread as a job bug. Say it ONCE.
+ if not isinstance(cron_provider, InProcessCronScheduler):
+ try:
+ _has_api_server = Platform.API_SERVER in (runner.adapters or {})
+ except Exception:
+ _has_api_server = True # never let the tell break startup
+ if not _has_api_server:
+ logger.warning(
+ "Cron provider '%s' is active but the api_server adapter is "
+ "NOT running in this gateway — scheduled fires arrive over "
+ "loopback HTTP and will all fail (jobs only run when "
+ "triggered manually). Most common cause: API_SERVER_KEY is "
+ "missing from this gateway process's environment. Restart "
+ "the gateway through its supervisor (`hermes gateway "
+ "restart`) so the profile env loads.",
+ getattr(cron_provider, "name", "external"))
+
+ # Gateway-only housekeeping runs independently of the cron provider; shares cron_stop for shutdown.
+ housekeeping_thread = threading.Thread(
+ target=_start_gateway_housekeeping, args=(cron_stop,),
+ kwargs={"adapters": runner.adapters, "loop": asyncio.get_running_loop(),
+ "cron_provider": cron_provider, "runner": runner},
+ daemon=True, name="gateway-housekeeping")
+ housekeeping_thread.start()
+ return cron_stop, cron_provider, cron_thread, housekeeping_thread
+
+
+async def _start_gateway_shutdown_tail(
+ runner, _control_server, cron_stop: threading.Event, cron_provider,
+ cron_thread: threading.Thread, housekeeping_thread: threading.Thread,
+ _planned_stop_watcher_stop: threading.Event, _planned_stop_watcher_thread: threading.Thread,
+ _signal_initiated_shutdown: list) -> bool:
+ """Post-``wait_for_shutdown`` teardown; returns the process exit verdict (True = exit 0)."""
+ from gateway.run import (_CRON_SHUTDOWN_DRAIN_TIMEOUT, _HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT, _await_thread_exit, _best_effort, _exit_with_failure_verdict, _resolve_gateway_exit_verdict, _shutdown_mcp_servers_nonblocking, _stop_cron_provider, logger, suppress)
+ # Control socket first: once shutdown begins we are no longer a truthful "serving here" answer and a
+ # successor must be able to bind. Early-exit paths rely on the atexit cleanup_files hook instead.
+ if _control_server is not None:
+ try:
+ await _control_server.stop()
+ except Exception:
+ logger.debug("Control socket stop failed (non-fatal)", exc_info=True)
+
+ def _stop_keepalive() -> None:
+ from hermes_cli.nous_auth_keepalive import stop_nous_auth_keepalive
+ stop_nous_auth_keepalive()
+
+ _best_effort(_stop_keepalive)
+ if _exit_with_failure_verdict(runner):
+ return False
+
+ # Never join(): an in-flight cron delivery is a coroutine on THIS loop; a sync join would drop it.
+ # Stop cron scheduler + housekeeping cleanly. These MUST be awaited cooperatively, not join()ed. A cron
+ # delivery in flight when the gateway restarts is a coroutine scheduled onto THIS event loop
+ # (safe_schedule_threadsafe); the ticker thread is blocked on its future.result(). A synchronous
+ # cron_thread.join() would block the loop, so that delivery could never run — it timed out and the
+ # message was silently dropped (#58818). Awaiting keeps the loop alive so the in-flight delivery
+ # finishes before we tear down.
+ cron_stop.set()
+ _stop_cron_provider(cron_provider)
+ if not await _await_thread_exit(cron_thread, timeout=_CRON_SHUTDOWN_DRAIN_TIMEOUT):
+ logger.warning("Cron ticker did not exit within %.0fs of shutdown — an in-flight "
+ "delivery may have been dropped.", _CRON_SHUTDOWN_DRAIN_TIMEOUT)
+ await _await_thread_exit(housekeeping_thread, timeout=_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT)
+
+ # Stop the planned-stop watcher (daemon=True so this is belt-and-suspenders).
+ _planned_stop_watcher_stop.set()
+ _planned_stop_watcher_thread.join(timeout=2)
+
+ with suppress(Exception):
+ await _shutdown_mcp_servers_nonblocking()
+
+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])
+
+
diff --git a/gateway/run_runtime_init.py b/gateway/run_runtime_init.py
new file mode 100644
index 00000000000..3d5c90f43ee
--- /dev/null
+++ b/gateway/run_runtime_init.py
@@ -0,0 +1,275 @@
+"""Writable runner initialization, separate from process ownership."""
+from __future__ import annotations
+
+class GatewayRuntimeInitMixin:
+ def _init_runtime_settings(self) -> None:
+ """Load ephemeral per-call config (prefill, reasoning, busy modes, timeouts, routing)."""
+ from gateway.run import (Dict)
+ self._prefill_messages = self._load_prefill_messages()
+ self._reasoning_config = self._load_reasoning_config()
+ self._service_tier = self._load_service_tier()
+ self._show_reasoning = self._load_show_reasoning()
+ self._busy_input_mode = self._load_busy_input_mode()
+ self._busy_text_mode = self._load_busy_text_mode()
+ # Secondary-profile busy modes snapshotted at multiplex startup; handlers never reread config.
+ self._busy_input_modes_by_profile: Dict[str, str] = {}
+ self._busy_text_modes_by_profile: Dict[str, str] = {}
+ self._restart_drain_timeout = self._load_restart_drain_timeout()
+ self._restart_after_turn_timeout = self._load_restart_after_turn_timeout()
+ self._cron_drain_timeout = self._load_cron_drain_timeout()
+ self._signal_interrupt_grace_timeout = self._load_signal_interrupt_grace_timeout()
+ self._provider_routing = self._load_provider_routing()
+ self._fallback_model = self._load_fallback_model()
+
+
+ def _init_session_store(self) -> None:
+ """Build the SessionStore (with process-registry reset guard), its async facade and the router."""
+ from gateway.run import (AsyncSessionStore, DeliveryRouter, SessionStore)
+ from tools.process_registry import process_registry
+ self.session_store = SessionStore(
+ self.config.sessions_dir, self.config,
+ has_active_processes_fn=lambda key: process_registry.has_active_for_session(
+ key))
+ # Loop-side boundary: sync helpers use ``session_store`` directly; async handlers await this facade.
+ self._async_session_store = AsyncSessionStore(self.session_store)
+ self.delivery_router = DeliveryRouter(self.config)
+
+
+ def _init_lifecycle_state(self) -> None:
+ """Initialise run/exit/restart flags, per-session state, and completion-delivery bookkeeping."""
+ from gateway.run import (Dict, List, MessageEvent, Optional, OrderedDict, Platform, SessionSource, SessionState, SessionTurnLeaseRegistry, asyncio, concurrent, threading, time)
+ self._running = self._exit_cleanly = self._exit_with_failure = self._draining = False
+ self._gateway_loop: Optional[asyncio.AbstractEventLoop] = None
+ self._shutdown_event = asyncio.Event()
+ self._exit_reason: Optional[str] = None
+ self._exit_code: Optional[int] = None
+ self._profile_failed_platforms: Dict[str, Dict[Platform, asyncio.Task]] = {}
+ self._systemd_watchdog = None
+ # External (NAS-driven) drain, distinct from one-way ``_draining``: set while ``.drain_request.json``
+ # exists — NEW turns refused, process stays up, removing the marker reverts to ``running``.
+ self._external_drain_active = False
+ # ``_signal_initiated_shutdown``: SIGTERM/SIGINT with no planned-stop/takeover marker (container,
+ # OOM, bare kill); _stop_impl must NOT persist gateway_state=stopped or container_boot won't restart.
+ self._restart_requested = self._signal_initiated_shutdown = self._restart_task_started = False
+ self._restart_detached = self._restart_via_service = self._detached_restart_helper_started = False
+ self._restart_command_source: Optional[SessionSource] = None
+ # Construction clock: bounds the /restart redelivery guard's window (missing dedup marker = stale).
+ self._startup_time: float = time.time()
+ # True when booted from a chat /restart (.restart_notify.json existed). One-shot signal so the
+ # marker-missing fallback suppresses a /restart only when we KNOW we just restarted.
+ self._booted_from_restart: bool = False
+ self._stop_task: Optional[asyncio.Task] = None
+ self._restart_task: Optional[asyncio.Task] = None
+ self._executor_lock = threading.Lock()
+ self._executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
+ # Set on gateway stop so the recreate-on-shutdown path can't resurrect the pool.
+ self._executor_closing = False
+ # ALL per-session state lives here (gateway/session_state.py); use _session_state / _peek_session_state.
+ self._sessions: Dict[str, SessionState] = {}
+ # Per-SESSION_ID turn lease: serializes [load history → run → flush] when two ROUTING KEYS resolve
+ # to one session_id (switch_session's many-to-one mapping), which routing-key guards cannot see.
+ self._turn_leases = SessionTurnLeaseRegistry()
+ # Stall-notified keys clear when pending clears / activity resumes / conversation boundary.
+ # Tokens for held turn leases, keyed by (routing key, run generation) so release is granted per-turn
+ # and a stale unwind can never free a newer turn's lease (#28686 ownership lesson). Held turn-lease
+ # tokens live on SessionState.turn.lease_token / .lease_generation (the old dict was keyed (routing
+ # key, generation) so a stale unwind could never free a newer turn's lease — the generation field
+ # preserves that ownership check, #28686). Runner-level queued interrupt text lives on
+ # SessionState.persistent.pending_command_text (NOTE: distinct from the adapter-level
+ # _pending_messages Dict[str, MessageEvent] in gateway/platforms/base.py, which shares the legacy
+ # name). Last successfully-resolved (non-empty) model, keyed by session. Used as a fallback when a
+ # fresh config read transiently returns an empty model (e.g. an mtime-keyed config-cache miss during
+ # a post-interrupt recovery turn). Without this, the agent is built with model="" and every API call
+ # fails HTTP 400 "No models provided" — the session goes silent until the user manually re-sends.
+ # See #35314. The ``"*"`` session entry holds a process-wide last-known-good for sessions seen for
+ # the first time. Lives on SessionState.conversation.last_resolved_model. Overflow buffer for
+ # explicit /queue commands. The adapter-level _pending_messages dict is a single slot per session
+ # (designed for "next-turn" follow-ups where repeated sends collapse into one event). /queue has
+ # different semantics: each invocation must produce its own full agent turn, in FIFO order, with no
+ # merging. When the slot is occupied, additional /queue items land here and are promoted
+ # one-at-a-time after each run's drain. Cleared on /new and /reset. /model and other mid-session
+ # operations preserve the queue. Lives on SessionState.conversation.queued_events; native image
+ # paths, busy-ack debounce timestamps and the monotonic run-generation counter (#28686, NEVER reset)
+ # live on SessionState too. See gateway.session_stall.
+ self._session_stall_notified: Dict[str, bool] = {}
+ # Startup restore gate: while restart-interrupted sessions auto-resume, real inbound messages
+ # queue instead of competing with the synthetic resume turns; drained after all resume tasks end.
+ self._startup_restore_in_progress = False
+ self._startup_restore_queue: List[MessageEvent] = []
+ self._startup_restore_tasks: List[asyncio.Task] = []
+ # Set by start_gateway() only for an explicit ``--replace`` launch; scoped to each adapter's
+ # cold-start connect and removed before any reconnect can run.
+ self._platform_lock_takeover_on_start = False
+ # Capped LRU of live SessionSources for fallback routing (shutdown notices, synthetic events) when
+ # the persisted origin is missing and _parse_session_key can't recover thread_id.
+ self._session_sources: "OrderedDict[str, SessionSource]" = OrderedDict()
+ self._session_sources_max = 512
+ # Lifecycle-scoped completion dedup: closes queue/watcher races inside one gateway without claiming
+ # exactly-once across a crash; durable replay state stays owned by tools.async_delegation.
+ self._completion_delivery_lock = threading.Lock()
+ self._completion_deliveries_inflight: set[tuple[str, str, object]] = set()
+ self._completion_deliveries_delivered: "OrderedDict[tuple[str, str, object], None]" = OrderedDict()
+ self._completion_delivery_retention = 2048
+ # Agent-triggered terminal completions from one conversation often land in the same scheduler
+ # tick; hold them briefly so the agent gets one synthetic turn instead of one per process.
+ # See #70300.
+ self._completion_notification_batches: dict[tuple[str, ...], list[tuple[str, dict, asyncio.Future]]] = {}
+ self._completion_notification_batch_tasks: dict[tuple[str, ...], asyncio.Task] = {}
+ self._completion_notification_batch_flush_tasks: set[asyncio.Task] = set()
+ self._completion_notification_batch_window = 0.1
+ self._completion_notification_batches_stopping = False
+
+
+ def _init_runtime_caches(self) -> None:
+ """Agent cache, profile identity, Teams runtime, failed-platform tracking, slash-confirm counter."""
+ from gateway.run import (Any, Dict, Optional, OrderedDict, Platform, threading)
+ # AIAgent per session preserves prompt caching (fresh agent per message ~10x cost on Anthropic).
+ # Value: (AIAgent, config_signature); LRU cap in _enforce_agent_cache_cap, TTL in expiry watcher.
+ self._agent_cache: "OrderedDict[str, tuple]" = OrderedDict()
+ self._agent_cache_lock = threading.Lock()
+ # Launch-time identity of the profile that owns ``self.adapters``; ``_authorization_adapter``
+ # compares against this rather than the per-turn ``_active_profile_name()``.
+ self._primary_profile_name = self._kanban_notifier_profile = self._active_profile_name()
+ # Teams meeting pipeline runtime (bound later when msgraph_webhook adapter exists).
+ self._teams_pipeline_runtime = None
+ self._teams_pipeline_runtime_error: Optional[str] = None
+ # Failed-to-connect platforms for background reconnection: Platform -> {config, attempts, next_retry}
+ self._failed_platforms: Dict[Platform, Dict[str, Any]] = {}
+ # Strong refs to detached fatal-error handler tasks so the loop can't GC them mid-run.
+ self._fatal_handler_tasks: set = set()
+ # Slash-confirm state lives in tools.slash_confirm (module-level) so adapters resolve callbacks
+ # without a runner backref; local counter keeps confirm_ids compact (64-byte callback_data caps).
+ import itertools
+ self._slash_confirm_counter = itertools.count(1)
+
+
+ def _init_startup_checks(self) -> None:
+ """Ensure tirith is installed and warn when manual approvals have no automated assessor."""
+ from gateway.run import (_best_effort, cfg_get, logger)
+ def _ensure_tirith() -> None:
+ from tools.tirith_security import ensure_installed
+ ensure_installed(log_failures=False) # downloads if needed; fail-open at scan time
+
+ _best_effort(_ensure_tirith)
+
+ # Manual approvals with no automated assessor (tirith off AND no auxiliary.approval) fail closed
+ # on unattended gateways — surface it so operators knowingly enable one.
+ try:
+ from hermes_cli.config import load_config as _load_full_config
+ # Startup heads-up (#30882): a gateway in manual approval mode with no automated risk assessor
+ # (tirith disabled AND no auxiliary.approval model) can only gate dangerous commands /
+ # execute_code scripts via live in-chat approval.
+ _appr_cfg = _load_full_config()
+ _appr_mode = str(
+ cfg_get(_appr_cfg, "approvals", "mode", default="manual") or "manual"
+ ).strip().lower()
+ _tirith_on = bool(cfg_get(_appr_cfg, "security", "tirith_enabled", default=True))
+ _aux_approval = cfg_get(_appr_cfg, "auxiliary", "approval", default=None)
+ if _appr_mode == "manual" and not _tirith_on and not _aux_approval:
+ logger.warning(
+ "Gateway approvals.mode=manual with no automated risk "
+ "assessor (security.tirith_enabled is false and "
+ "auxiliary.approval is unset): dangerous commands and "
+ "execute_code scripts will BLOCK until a human approves "
+ "them in chat. Enable security.tirith_enabled or configure "
+ "auxiliary.approval for unattended operation.")
+ except Exception:
+ logger.debug("approvals.mode startup check skipped", exc_info=True)
+
+
+ def _init_session_db(self) -> None:
+ """Open the session DB for the active scope and run opportunistic state.db / checkpoint maintenance."""
+ from gateway.run import (Any, Dict, Path, _SESSION_DB_UNPINNED, logger, threading)
+ # Session DB is a property caching one AsyncSessionDB per path (a handle bound here would pin the
+ # root home under multiplex); priming here keeps startup diagnostics at init.
+ # Initialize session database for session_search tool support. Same frozen-handle class of bug as
+ # SessionStore._db (#88532): a handle bound here is pinned to the process's root home, but /resume,
+ # /title, /history and session search all run inside _profile_runtime_scope on a multiplexed gateway
+ # and must see that profile's own state.db.
+ self._session_db_pinned: Any = _SESSION_DB_UNPINNED
+ self._session_db_handles: Dict[Path, Any] = {}
+ self._session_db_handles_lock = threading.Lock()
+ from gateway.session_db_recovery import RecoverableHandleCache
+ self._session_db_handle_cache = RecoverableHandleCache(
+ handles=self._session_db_handles, lock=self._session_db_handles_lock)
+ try:
+ self._open_session_db_for_active_scope(raise_on_error=True)
+ except Exception as e:
+ # WARNING (not DEBUG) so it lands in errors.log; else an NFS HERMES_HOME silently loses /resume etc.
+ logger.warning("SQLite session store not available: %s", e)
+ self._session_db_init_error = str(e) # surfaced on the home channel(s) once connected
+
+ # Opportunistic state.db maintenance (prune + optional VACUUM), at most once per min_interval_hours.
+ # A few blocking seconds per day is fine for a long-lived gateway; failures log, never raise.
+ # Surface the failure to the user via their home channel(s) once the gateway connects. Without this,
+ # state.db corruption or NFS/SMB lock failures silently degrade the entire gateway — messages may
+ # flow but nothing is persisted, and the user has no indication until they try /resume and find
+ # nothing (#88235).
+ if self._session_db is not None:
+ try:
+ from hermes_cli.config import load_config as _load_full_config
+ _sess_cfg = (_load_full_config().get("sessions") or {})
+ if _sess_cfg.get("auto_archive", False):
+ self._session_db._db.maybe_auto_archive(
+ idle_days=float(_sess_cfg.get("auto_archive_days", 3)),
+ min_interval_hours=int(_sess_cfg.get("min_interval_hours", 24)))
+ if _sess_cfg.get("auto_prune", False):
+ # Construction-time, before the loop serves traffic; sync DB is fine.
+ self._session_db._db.maybe_auto_prune_and_vacuum(
+ retention_days=int(_sess_cfg.get("retention_days", 90)),
+ min_interval_hours=int(_sess_cfg.get("min_interval_hours", 24)),
+ min_vacuum_interval_days=int(
+ _sess_cfg.get("min_vacuum_interval_days", 30)),
+ vacuum=bool(_sess_cfg.get("vacuum_after_prune", True)),
+ sessions_dir=self.config.sessions_dir)
+ except Exception as exc:
+ logger.debug("state.db auto-maintenance skipped: %s", exc)
+
+ # Stale checkpoint repo cleanup; opt-in via checkpoints.auto_prune, idempotent via .last_prune.
+ try:
+ from hermes_cli.config import load_config as _load_full_config
+ _ckpt_cfg = (_load_full_config().get("checkpoints") or {})
+ if _ckpt_cfg.get("auto_prune", False):
+ from tools.checkpoint_manager import maybe_auto_prune_checkpoints
+ # delete_orphans never honoured unattended: a missing workdir is ambiguous (deleted vs.
+ # unmounted share); orphan cleanup is only via explicit `hermes checkpoints prune`.
+ maybe_auto_prune_checkpoints(
+ retention_days=int(_ckpt_cfg.get("retention_days", 7)),
+ min_interval_hours=int(_ckpt_cfg.get("min_interval_hours", 24)),
+ delete_orphans=False,
+ max_total_size_mb=int(_ckpt_cfg.get("max_total_size_mb", 500)))
+ except Exception as exc:
+ logger.debug("checkpoint auto-maintenance skipped: %s", exc)
+
+
+ def _init_registries_and_clocks(self) -> None:
+ """Pairing stores, hook registry, voice modes, background-task set, liveness and idle clocks."""
+ from gateway.run import (Dict, List, Optional, asyncio, time)
+ # ``pairing_store``: global/default store (CLI, callers without profile context); ``pairing_stores``:
+ # per-profile map ``authz_mixin._is_user_authorized`` routes through (one whitelist per profile).
+ from gateway.pairing import PairingStore
+ from gateway.hooks import HookRegistry
+ self.pairing_store = PairingStore()
+ self.pairing_stores: Dict[str, "PairingStore"] = {}
+ self.hooks = HookRegistry()
+ # Per-chat voice reply mode: "off" | "voice_only" | "all"
+ self._voice_mode: Dict[str, str] = self._load_voice_modes()
+ # Per-(guild,user) transcript dedup: the voice/STT pipeline can emit one utterance twice.
+ self._recent_voice_transcripts: Dict[tuple[int, int], List[tuple[float, str]]] = {}
+ # Background tasks kept referenced so they are not garbage-collected mid-execution.
+ self._background_tasks: set = set()
+ # Event-loop liveness heartbeat: rewritten every 30s while the loop dispatches; supervisors use
+ # the file mtime / updated_at to tell "process alive" from "loop frozen".
+ # See #66892.
+ self._gateway_started_at: float = time.time()
+ self._loop_heartbeat_task: Optional[asyncio.Task] = None
+ self._loop_floor_timer_handle = self._loop_liveness_watchdog = None
+ # scale-to-zero: gateway-scoped "last inbound seen" clock, stamped in _handle_message (the single
+ # inbound chokepoint) and seeded to "now" so a fresh gateway isn't idle from epoch.
+ self._last_inbound_at: float = time.time()
+ # Re-arm cooldown after a wake so we don't go dormant again before the drained backlog updates
+ # the clock; and a one-shot latch so the "platform owns the suspend" notice logs once.
+ self._scale_to_zero_cooldown_until: float = 0.0
+ self._scale_to_zero_no_suspend_logged: bool = False
+
+
diff --git a/tests/gateway/test_startup_restart_race.py b/tests/gateway/test_startup_restart_race.py
index b024bcc7559..d0dc53754a0 100644
--- a/tests/gateway/test_startup_restart_race.py
+++ b/tests/gateway/test_startup_restart_race.py
@@ -311,7 +311,7 @@ async def test_start_gateway_classifies_startup_signal_exit(
_patch_aborted_startup(monkeypatch, AbortedStartupRunner)
monkeypatch.setattr(
- "gateway.run._start_gateway_make_shutdown_signal_handler", capture_signal_state
+ "gateway.run_bootstrap._start_gateway_make_shutdown_signal_handler", capture_signal_state
)
monkeypatch.setattr("gateway.run._start_cron_ticker", fail_if_cron_starts)
monkeypatch.setattr("tools.mcp_tool_lifecycle.shutdown_mcp_servers", lambda: None)