Skip to content

The agent that grows with you

refactor: extract gateway setup service orchestration

Teknium02d0307c24d2
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index 9c4d4fe4dad..f1c61a6a9ee 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -1031,7 +1031,8 @@ def _revive_gateway_after_import(hermes_root: Path) -> None:
"To start a gateway for this home, run: hermes gateway install")
return
try:
- from hermes_cli.gateway import ensure_gateway_service, _is_service_running
+ from hermes_cli.gateway import _is_service_running
+ from hermes_cli.gateway_setup_service import ensure_gateway_service
if not _is_service_running():
print()
ensure_gateway_service(context="import")
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 57f0b87b725..5fc7314b440 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -2435,66 +2435,6 @@ def install_linux_gateway_from_setup(force: bool = False, enable_on_startup: boo
return scope, True
-def ensure_gateway_service(context: str = "setup") -> bool:
- """Install and start a user-scope gateway service without prompting (``hermes setup``/``import``).
- A zero-platform gateway is a supported degraded mode (cron runs), so this never gates on messaging
- config. Never raises; True when a service is installed and running."""
- from hermes_constants import is_container
- if is_container():
- # Containers use restart policies, not service managers.
- print_info("Start the gateway to bring your bots online:")
- print_info(" hermes gateway run # Run as container main process")
- print_info("")
- print_info("For automatic restarts, use a Docker restart policy:")
- print_info(" docker run --restart unless-stopped ...")
- return False
-
- supports_systemd = supports_systemd_services()
- if not (supports_systemd or is_macos() or is_windows()):
- print_info(" No supported service manager found on this host.")
- print_info(" Run the gateway in the foreground with: hermes gateway")
- return False
-
- try:
- if _is_service_running():
- return True
- if not _is_service_installed():
- if supports_systemd and has_conflicting_systemd_units():
- # Both units would fight over bot tokens; don't pile a fresh install onto a conflicted state.
- print_systemd_scope_conflict_warning()
- return False
- print_info(" Installing the gateway background service ...")
- if supports_systemd:
- systemd_install(force=False, non_interactive=True)
- elif is_macos():
- launchd_install(force=False)
- else:
- _gw_windows().install(force=False) # Registers the Scheduled Task AND starts it.
- print_success(" Gateway service installed and started.")
- return True
- if supports_systemd:
- systemd_start()
- elif is_macos():
- launchd_start()
- else:
- _gw_windows().start()
- print_success(" Gateway service running (cron jobs + messaging platforms).")
- return True
- except UserSystemdUnavailableError as e:
- print_warning(" Could not reach user systemd to start the gateway service:")
- _print_indented(str(e), print_info)
- except SystemScopeRequiresRootError as e:
- print_warning(f" Gateway service needs root for this scope: {e}")
- _print_system_scope_remediation("start")
- except SystemExit:
- # Some install/start paths sys.exit() on hard failures (temp-HOME guard); never abort setup/import.
- print_warning(" Gateway service install did not complete.")
- print_info(" You can retry manually: hermes gateway install")
- except Exception as e:
- print_warning(f" Gateway service install failed: {e}")
- print_info(" You can retry manually: hermes gateway install")
- return False
-
def get_systemd_linger_status(username: str | None = None) -> tuple[bool | None, str]:
"""Linger status for *username* or the current user when omitted.
diff --git a/hermes_cli/gateway_setup_service.py b/hermes_cli/gateway_setup_service.py
new file mode 100644
index 00000000000..5d7bb876fcc
--- /dev/null
+++ b/hermes_cli/gateway_setup_service.py
@@ -0,0 +1,82 @@
+"""Gateway service setup orchestration; runtime startup is separate."""
+
+def ensure_gateway_service(context: str = "setup") -> bool:
+ """Install and start a user-scope gateway service without prompting (``hermes setup``/``import``).
+ A zero-platform gateway is a supported degraded mode (cron runs), so this never gates on messaging
+ config. Never raises; True when a service is installed and running."""
+ from hermes_cli.gateway import (
+ print_info,
+ supports_systemd_services,
+ is_macos,
+ is_windows,
+ _is_service_running,
+ _is_service_installed,
+ has_conflicting_systemd_units,
+ print_systemd_scope_conflict_warning,
+ systemd_install,
+ launchd_install,
+ _gw_windows,
+ print_success,
+ systemd_start,
+ launchd_start,
+ UserSystemdUnavailableError,
+ print_warning,
+ _print_indented,
+ SystemScopeRequiresRootError,
+ _print_system_scope_remediation,
+ )
+ from hermes_constants import is_container
+ if is_container():
+ # Containers use restart policies, not service managers.
+ print_info("Start the gateway to bring your bots online:")
+ print_info(" hermes gateway run # Run as container main process")
+ print_info("")
+ print_info("For automatic restarts, use a Docker restart policy:")
+ print_info(" docker run --restart unless-stopped ...")
+ return False
+
+ supports_systemd = supports_systemd_services()
+ if not (supports_systemd or is_macos() or is_windows()):
+ print_info(" No supported service manager found on this host.")
+ print_info(" Run the gateway in the foreground with: hermes gateway")
+ return False
+
+ try:
+ if _is_service_running():
+ return True
+ if not _is_service_installed():
+ if supports_systemd and has_conflicting_systemd_units():
+ # Both units would fight over bot tokens; don't pile a fresh install onto a conflicted state.
+ print_systemd_scope_conflict_warning()
+ return False
+ print_info(" Installing the gateway background service ...")
+ if supports_systemd:
+ systemd_install(force=False, non_interactive=True)
+ elif is_macos():
+ launchd_install(force=False)
+ else:
+ _gw_windows().install(force=False) # Registers the Scheduled Task AND starts it.
+ print_success(" Gateway service installed and started.")
+ return True
+ if supports_systemd:
+ systemd_start()
+ elif is_macos():
+ launchd_start()
+ else:
+ _gw_windows().start()
+ print_success(" Gateway service running (cron jobs + messaging platforms).")
+ return True
+ except UserSystemdUnavailableError as e:
+ print_warning(" Could not reach user systemd to start the gateway service:")
+ _print_indented(str(e), print_info)
+ except SystemScopeRequiresRootError as e:
+ print_warning(f" Gateway service needs root for this scope: {e}")
+ _print_system_scope_remediation("start")
+ except SystemExit:
+ # Some install/start paths sys.exit() on hard failures (temp-HOME guard); never abort setup/import.
+ print_warning(" Gateway service install did not complete.")
+ print_info(" You can retry manually: hermes gateway install")
+ except Exception as e:
+ print_warning(f" Gateway service install failed: {e}")
+ print_info(" You can retry manually: hermes gateway install")
+ return False
diff --git a/hermes_cli/setup.py b/hermes_cli/setup.py
index 566fe7a7f45..dd9286bd0be 100644
--- a/hermes_cli/setup.py
+++ b/hermes_cli/setup.py
@@ -633,7 +633,7 @@ def _run_full_setup(config: dict, hermes_home, *, is_existing: bool, migration_r
return
# A skipped (migrated) gateway section still needs its service so imported platforms
# and cron jobs become active.
- from hermes_cli.gateway import ensure_gateway_service
+ from hermes_cli.gateway_setup_service import ensure_gateway_service
ensure_gateway_service(context="setup")
def _step(key: str, label: str, run) -> tuple:
diff --git a/hermes_cli/setup_platforms.py b/hermes_cli/setup_platforms.py
index 596e33ef411..9391a79551c 100644
--- a/hermes_cli/setup_platforms.py
+++ b/hermes_cli/setup_platforms.py
@@ -346,7 +346,8 @@ def setup_gateway(config: dict):
# mode (cron keeps running; adapters come up once tokens are added via `hermes import` /
# `hermes setup gateway`). Gating it on messaging config left install-then-import machines
# with cron jobs and bot tokens but no process to serve them.
- from hermes_cli.gateway import _is_service_running, supports_systemd_services, ensure_gateway_service
+ from hermes_cli.gateway import _is_service_running, supports_systemd_services
+ from hermes_cli.gateway_setup_service import ensure_gateway_service
supports_systemd = supports_systemd_services()
print()
if _is_service_running():
diff --git a/hermes_cli/setup_quick.py b/hermes_cli/setup_quick.py
index 5f31223aa18..b765a63ecd4 100644
--- a/hermes_cli/setup_quick.py
+++ b/hermes_cli/setup_quick.py
@@ -119,7 +119,7 @@ def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool):
else:
# Messaging skipped — still install/start the gateway service so cron jobs run and
# platforms come alive as soon as tokens are added later (e.g. via `hermes import`).
- from hermes_cli.gateway import ensure_gateway_service
+ from hermes_cli.gateway_setup_service import ensure_gateway_service
ensure_gateway_service(context="setup")
print()
print_success("Setup complete! You're ready to go.")
diff --git a/tests/hermes_cli/test_backup.py b/tests/hermes_cli/test_backup.py
index 58b49c842a2..3fde74ec1d1 100644
--- a/tests/hermes_cli/test_backup.py
+++ b/tests/hermes_cli/test_backup.py
@@ -10,6 +10,7 @@ from pathlib import Path
from unittest.mock import patch
import pytest
+import hermes_cli.gateway_setup_service as service_setup
# ---------------------------------------------------------------------------
@@ -23,7 +24,7 @@ def _no_real_gateway_service(monkeypatch):
assert the wiring."""
import hermes_cli.gateway as gateway_mod
- monkeypatch.setattr(gateway_mod, "ensure_gateway_service", lambda **kw: False)
+ monkeypatch.setattr(service_setup, "ensure_gateway_service", lambda **kw: False)
monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)
@@ -419,7 +420,7 @@ class TestImport:
calls = []
monkeypatch.setattr(
- gateway_mod, "ensure_gateway_service",
+ service_setup, "ensure_gateway_service",
lambda **kw: calls.append(kw) or True,
)
monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)
@@ -443,7 +444,7 @@ class TestImport:
calls = []
monkeypatch.setattr(
- gateway_mod, "ensure_gateway_service",
+ service_setup, "ensure_gateway_service",
lambda **kw: calls.append(kw) or True,
)
monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: True)
@@ -2204,7 +2205,7 @@ class TestImportHonorsHermesHomeOverride:
calls = []
monkeypatch.setattr(
- "hermes_cli.gateway.ensure_gateway_service",
+ "hermes_cli.gateway_setup_service.ensure_gateway_service",
lambda *a, **kw: calls.append(kw),
)
monkeypatch.setattr(
@@ -2238,7 +2239,7 @@ class TestImportHonorsHermesHomeOverride:
calls = []
monkeypatch.setattr(
- "hermes_cli.gateway.ensure_gateway_service",
+ "hermes_cli.gateway_setup_service.ensure_gateway_service",
lambda *a, **kw: calls.append(kw),
)
monkeypatch.setattr(
diff --git a/tests/hermes_cli/test_ensure_gateway_service.py b/tests/hermes_cli/test_ensure_gateway_service.py
index 547c24c36e9..a49bde90e61 100644
--- a/tests/hermes_cli/test_ensure_gateway_service.py
+++ b/tests/hermes_cli/test_ensure_gateway_service.py
@@ -11,6 +11,7 @@ The helper's contract:
"""
import hermes_cli.gateway as gateway_mod
+from hermes_cli.gateway_setup_service import ensure_gateway_service
def _patch_host(monkeypatch, *, container=False, systemd=True, macos=False, windows=False):
@@ -26,14 +27,14 @@ class TestEnsureGatewayService:
called = []
monkeypatch.setattr(gateway_mod, "systemd_install", lambda **kw: called.append("install"))
- assert gateway_mod.ensure_gateway_service() is False
+ assert ensure_gateway_service() is False
assert not called
out = capsys.readouterr().out
assert "restart policy" in out
def test_no_service_manager_is_noop(self, monkeypatch, capsys):
_patch_host(monkeypatch, systemd=False)
- assert gateway_mod.ensure_gateway_service() is False
+ assert ensure_gateway_service() is False
out = capsys.readouterr().out
assert "hermes gateway" in out
@@ -44,7 +45,7 @@ class TestEnsureGatewayService:
monkeypatch.setattr(gateway_mod, "systemd_install", lambda **kw: called.append("install"))
monkeypatch.setattr(gateway_mod, "systemd_start", lambda **kw: called.append("start"))
- assert gateway_mod.ensure_gateway_service() is True
+ assert ensure_gateway_service() is True
assert not called
def test_fresh_host_installs_and_starts_user_scope(self, monkeypatch):
@@ -61,7 +62,7 @@ class TestEnsureGatewayService:
)
monkeypatch.setattr(gateway_mod, "systemd_start", lambda **kw: calls.append(("start", kw)))
- assert gateway_mod.ensure_gateway_service() is True
+ assert ensure_gateway_service() is True
assert calls[0][0] == "install"
# user scope: no system=True ever passed from this path
assert "system" not in calls[0][3] or not calls[0][3]["system"]
@@ -77,7 +78,7 @@ class TestEnsureGatewayService:
monkeypatch.setattr(gateway_mod, "systemd_install", lambda **kw: calls.append("install"))
monkeypatch.setattr(gateway_mod, "systemd_start", lambda **kw: calls.append("start"))
- assert gateway_mod.ensure_gateway_service() is True
+ assert ensure_gateway_service() is True
assert calls == ["start"]
def test_conflicting_units_block_install(self, monkeypatch):
@@ -92,7 +93,7 @@ class TestEnsureGatewayService:
calls = []
monkeypatch.setattr(gateway_mod, "systemd_install", lambda **kw: calls.append("install"))
- assert gateway_mod.ensure_gateway_service() is False
+ assert ensure_gateway_service() is False
assert warned and not calls
def test_macos_uses_launchd(self, monkeypatch):
@@ -103,7 +104,7 @@ class TestEnsureGatewayService:
monkeypatch.setattr(gateway_mod, "launchd_install", lambda force=False: calls.append("install"))
monkeypatch.setattr(gateway_mod, "launchd_start", lambda: calls.append("start"))
- assert gateway_mod.ensure_gateway_service() is True
+ assert ensure_gateway_service() is True
assert calls == ["install", "start"]
def test_never_raises_on_install_failure(self, monkeypatch, capsys):
@@ -117,7 +118,7 @@ class TestEnsureGatewayService:
monkeypatch.setattr(gateway_mod, "systemd_install", boom)
- assert gateway_mod.ensure_gateway_service() is False
+ assert ensure_gateway_service() is False
out = capsys.readouterr().out
assert "hermes gateway install" in out
@@ -133,7 +134,7 @@ class TestEnsureGatewayService:
monkeypatch.setattr(gateway_mod, "systemd_install", bail)
- assert gateway_mod.ensure_gateway_service() is False
+ assert ensure_gateway_service() is False
out = capsys.readouterr().out
assert "hermes gateway install" in out
@@ -147,6 +148,6 @@ class TestEnsureGatewayService:
monkeypatch.setattr(gateway_mod, "systemd_start", unreachable)
- assert gateway_mod.ensure_gateway_service() is False
+ assert ensure_gateway_service() is False
out = capsys.readouterr().out
assert "enable linger" in out