The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: auto-install gateway service during setup and import
Teknium715d26cdf492
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 98d0f41df1c..e5c201d49e6 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -1066,6 +1066,22 @@ def run_import(args) -> None:for pname in gw_profiles:print(f" hermes -p {pname} gateway install")+ # Bring the restored install to life: the backup may contain bot+ # tokens and registered cron jobs, but they're inert without a+ # gateway process. Install/start the service automatically (a+ # platform-less gateway is a supported mode, so this is safe even+ # for backups with no messaging config). Best-effort and prompt-free;+ # failures print a manual fallback and never fail the import.+ try:+ from hermes_cli.gateway import ensure_gateway_service, _is_service_running++ if not _is_service_running():+ print()+ ensure_gateway_service(context="import")+ except Exception:+ print("\nStart the gateway to activate cron jobs and messaging:")+ print(" hermes gateway install")+print("Done. Your Hermes configuration has been restored.")diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 744e3ceb2cb..f97f8ada99e 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -2446,6 +2446,94 @@ def install_linux_gateway_from_setup(force: bool = False, enable_on_startup: booreturn scope, True+def ensure_gateway_service(context: str = "setup") -> bool:+ """Install and start the gateway service without prompting.++ The zero-decision service path used by ``hermes setup`` (end of wizard)+ and ``hermes import``: if this host supports a service manager and no+ gateway service exists yet, install a user-scope service and start it.+ A gateway with zero configured platforms is a supported degraded mode+ (it runs the cron scheduler and picks up platforms as tokens appear),+ so this never needs to gate on messaging being configured.++ Never prompts, never raises — always safe to call from any flow,+ including non-TTY ones. Returns True when a service is installed and+ running (or already was) by the time we return.++ Scope choice: always the least-surprising, no-privilege option —+ user-scope systemd unit on Linux, LaunchAgent on macOS, Scheduled Task+ on Windows. Users who want a boot-time system service still run+ ``hermes gateway install --system`` explicitly (that path prompts and+ requires root; we never self-elevate from an installer).+ """+ 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 user and system 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:+ from hermes_cli import gateway_windows++ # Registers the Scheduled Task AND starts it.+ gateway_windows.install(force=False)+ print_success(" Gateway service installed and started.")+ return True++ if supports_systemd:+ systemd_start()+ elif is_macos():+ launchd_start()+ else:+ from hermes_cli import gateway_windows++ gateway_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:")+ for line in str(e).splitlines():+ print_info(f" {line}")+ 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 (e.g. temp-HOME+ # guard). A background-service failure must 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() -> tuple[bool | None, str]:"""Return systemd linger status for the current user.diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex d18c813f5e2..3c65981cbb0 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -2175,10 +2175,9 @@ def setup_gateway(config: dict):if not selected:print_info("No platforms selected. Run 'hermes setup gateway' later to configure.")- return-- for idx in selected:- _configure_platform(platforms[idx])+ else:+ for idx in selected:+ _configure_platform(platforms[idx])# ── Gateway Service Setup ──# Count any platform (built-in or plugin) the user configured during this@@ -2230,160 +2229,67 @@ def setup_gateway(config: dict):f" hermes config set {plat.upper()}_HOME_CHANNEL <channel_id>")- # Offer to install the gateway as a system service- import platform as _platform-- _is_linux = _platform.system() == "Linux"- _is_macos = _platform.system() == "Darwin"- _is_windows = _platform.system() == "Windows"-- from hermes_cli.gateway import (- _is_service_installed,- _is_service_running,- supports_systemd_services,- has_conflicting_systemd_units,- has_legacy_hermes_units,- install_linux_gateway_from_setup,- print_systemd_scope_conflict_warning,- print_legacy_unit_warning,- systemd_start,- systemd_restart,- launchd_install,- launchd_start,- launchd_restart,- UserSystemdUnavailableError,- SystemScopeRequiresRootError,- _system_scope_wizard_would_need_root,- _print_system_scope_remediation,- )-- service_installed = _is_service_installed()- service_running = _is_service_running()- supports_systemd = supports_systemd_services()- supports_service_manager = supports_systemd or _is_macos or _is_windows-- print()- if supports_systemd and has_conflicting_systemd_units():- print_systemd_scope_conflict_warning()- print()+ # ── Gateway Service Setup ──+ # Runs UNCONDITIONALLY — even with zero platforms configured. A gateway+ # without platforms is a supported mode (cron scheduler keeps running,+ # and adapters come up automatically once tokens are added later, e.g.+ # via `hermes import` or `hermes setup gateway`). Gating this on+ # messaging config was the bug that left install-then-import machines+ # with registered cron jobs and restored bot tokens but no process to+ # serve them.+ from hermes_cli.gateway import (+ _is_service_running,+ supports_systemd_services,+ ensure_gateway_service,+ systemd_restart,+ launchd_restart,+ UserSystemdUnavailableError,+ SystemScopeRequiresRootError,+ _system_scope_wizard_would_need_root,+ _print_system_scope_remediation,+ )+ import platform as _platform- if supports_systemd and has_legacy_hermes_units():- print_legacy_unit_warning()- print()+ _is_macos = _platform.system() == "Darwin"+ _is_windows = _platform.system() == "Windows"+ supports_systemd = supports_systemd_services()- if service_running:- if supports_systemd and _system_scope_wizard_would_need_root():+ print()+ if _is_service_running():+ # Already running: only offer a restart when this setup pass may+ # have changed platform config — a restart interrupts any active+ # session, so it stays behind a prompt.+ if supports_systemd and _system_scope_wizard_would_need_root():+ _print_system_scope_remediation("restart")+ elif any_messaging and prompt_yes_no(+ " Restart the gateway to pick up changes?", True+ ):+ try:+ if supports_systemd:+ systemd_restart()+ elif _is_macos:+ launchd_restart()+ elif _is_windows:+ from hermes_cli import gateway_windows+ gateway_windows.restart()+ except UserSystemdUnavailableError as e:+ print_error(" Restart failed — user systemd not reachable:")+ for line in str(e).splitlines():+ print(f" {line}")+ except SystemScopeRequiresRootError as e:+ # Defense in depth: the pre-check above should have+ # caught this, but a race (unit file appearing mid-run)+ # could still land here. Previously this exited the+ # whole wizard via sys.exit(1).+ print_error(f" Restart failed: {e}")_print_system_scope_remediation("restart")- elif prompt_yes_no(" Restart the gateway to pick up changes?", True):- try:- if supports_systemd:- systemd_restart()- elif _is_macos:- launchd_restart()- elif _is_windows:- from hermes_cli import gateway_windows- gateway_windows.restart()- except UserSystemdUnavailableError as e:- print_error(" Restart failed — user systemd not reachable:")- for line in str(e).splitlines():- print(f" {line}")- except SystemScopeRequiresRootError as e:- # Defense in depth: the pre-check above should have- # caught this, but a race (unit file appearing mid-run)- # could still land here. Previously this exited the- # whole wizard via sys.exit(1).- print_error(f" Restart failed: {e}")- _print_system_scope_remediation("restart")- except Exception as e:- print_error(f" Restart failed: {e}")- elif service_installed:- if supports_systemd and _system_scope_wizard_would_need_root():- _print_system_scope_remediation("start")- elif prompt_yes_no(" Start the gateway service?", True):- try:- if supports_systemd:- systemd_start()- elif _is_macos:- launchd_start()- elif _is_windows:- from hermes_cli import gateway_windows- gateway_windows.start()- except UserSystemdUnavailableError as e:- print_error(" Start failed — user systemd not reachable:")- for line in str(e).splitlines():- print(f" {line}")- except SystemScopeRequiresRootError as e:- print_error(f" Start failed: {e}")- _print_system_scope_remediation("start")- except Exception as e:- print_error(f" Start failed: {e}")- elif supports_service_manager:- if supports_systemd:- svc_name = "systemd"- elif _is_macos:- svc_name = "launchd"- else:- svc_name = "Scheduled Task"- if prompt_yes_no(- f" Install the gateway as a {svc_name} service? (runs in background, starts on boot)",- True,- ):- try:- installed_scope = None- did_install = False- started_inline = False- if supports_systemd:- installed_scope, did_install = install_linux_gateway_from_setup(force=False)- elif _is_macos:- launchd_install(force=False)- did_install = True- else:- # gateway_windows.install() registers the Scheduled- # Task AND starts it immediately (via schtasks /Run- # or a direct spawn fallback), so no separate start- # prompt is needed here.- from hermes_cli import gateway_windows- gateway_windows.install(force=False)- did_install = True- started_inline = True- print()- if did_install and not started_inline and prompt_yes_no(" Start the service now?", True):- try:- if supports_systemd:- systemd_start(system=installed_scope == "system")- elif _is_macos:- launchd_start()- except UserSystemdUnavailableError as e:- print_error(" Start failed — user systemd not reachable:")- for line in str(e).splitlines():- print(f" {line}")- except SystemScopeRequiresRootError as e:- print_error(f" Start failed: {e}")- _print_system_scope_remediation("start")- except Exception as e:- print_error(f" Start failed: {e}")- except Exception as e:- print_error(f" Install failed: {e}")- print_info(" You can try manually: hermes gateway install")- else:- print_info(" You can install later: hermes gateway install")- if supports_systemd and os.geteuid() == 0: # windows-footgun: ok — guarded by supports_systemd (Linux only)- print_info(" Or as a boot-time service: hermes gateway install --system")- print_info(" Or run in foreground: hermes gateway")- else:- from hermes_constants import is_container- if is_container():- 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 ...")- print_info(" docker restart <container> # Manual restart")- else:- print_info("Start the gateway to bring your bots online:")- print_info(" hermes gateway # Run in foreground")+ except Exception as e:+ print_error(f" Restart failed: {e}")+ else:+ # Not running: install (if needed) and start, no questions asked.+ ensure_gateway_service(context="setup")- print_info("━" * 50)+ print_info("━" * 50)# =============================================================================@@ -3156,6 +3062,11 @@ def run_setup_wizard(args):# Section 4: Messaging Platformsif not (migration_ran and _skip_configured_section(config, "gateway", "Messaging Platforms")):setup_gateway(config)+ else:+ # Section skipped (migrated config) — still make sure the gateway+ # service exists so cron jobs and migrated platforms actually run.+ from hermes_cli.gateway import ensure_gateway_service+ ensure_gateway_service(context="setup")# Section 5: Toolsif not (migration_ran and _skip_configured_section(config, "tools", "Tools")):@@ -3231,6 +3142,12 @@ def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool):if gateway_choice == 0:setup_gateway(config)save_config(config)+ 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 another machine).+ from hermes_cli.gateway 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.pyindex 0fb69caa3ec..31784abf641 100644--- a/tests/hermes_cli/test_backup.py+++ b/tests/hermes_cli/test_backup.py@@ -15,6 +15,17 @@ import pytest# Helpers# ---------------------------------------------------------------------------[email protected](autouse=True)+def _no_real_gateway_service(monkeypatch):+ """run_import() auto-installs the gateway service post-restore; tests must+ never touch the host's systemd/launchd. Individual tests re-patch these to+ assert the wiring."""+ import hermes_cli.gateway as gateway_mod++ monkeypatch.setattr(gateway_mod, "ensure_gateway_service", lambda **kw: False)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)++def _advance_backup_clock(seconds: float = 1.1) -> None:"""Skew hermes_cli.backup's datetime forward instead of sleeping.@@ -264,6 +275,81 @@ class TestImport:else:zf.writestr(name, content)+ def test_import_auto_installs_gateway_service(self, tmp_path, monkeypatch):+ """After a restore, run_import brings the gateway service up without+ prompting — restored cron jobs and bot tokens must not sit dormant+ (the install-then-import dead-gateway bug)."""+ import hermes_cli.gateway as gateway_mod++ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ calls = []+ monkeypatch.setattr(+ gateway_mod, "ensure_gateway_service",+ lambda **kw: calls.append(kw) or True,+ )+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)++ zip_path = tmp_path / "backup.zip"+ self._make_backup_zip(zip_path, {"config.yaml": "model: test\n"})++ from hermes_cli.backup import run_import+ run_import(Namespace(zipfile=str(zip_path), force=True))++ assert calls and calls[0].get("context") == "import"++ def test_import_skips_service_when_already_running(self, tmp_path, monkeypatch):+ """A live gateway is left alone — no reinstall churn during import."""+ import hermes_cli.gateway as gateway_mod++ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ calls = []+ monkeypatch.setattr(+ gateway_mod, "ensure_gateway_service",+ lambda **kw: calls.append(kw) or True,+ )+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: True)++ zip_path = tmp_path / "backup.zip"+ self._make_backup_zip(zip_path, {"config.yaml": "model: test\n"})++ from hermes_cli.backup import run_import+ run_import(Namespace(zipfile=str(zip_path), force=True))++ assert not calls++ def test_import_survives_service_layer_import_failure(self, tmp_path, monkeypatch, capsys):+ """If the service helpers can't even be reached, import still completes+ and prints the manual fallback."""+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)++ import hermes_cli.gateway as gateway_mod++ def boom():+ raise RuntimeError("service layer unavailable")++ monkeypatch.setattr(gateway_mod, "_is_service_running", boom)++ zip_path = tmp_path / "backup.zip"+ self._make_backup_zip(zip_path, {"config.yaml": "model: test\n"})++ from hermes_cli.backup import run_import+ run_import(Namespace(zipfile=str(zip_path), force=True))++ out = capsys.readouterr().out+ assert "Done. Your Hermes configuration has been restored." in out+ assert "hermes gateway install" in out+diff --git a/tests/hermes_cli/test_ensure_gateway_service.py b/tests/hermes_cli/test_ensure_gateway_service.pynew file mode 100644index 00000000000..547c24c36e9--- /dev/null+++ b/tests/hermes_cli/test_ensure_gateway_service.py@@ -0,0 +1,152 @@+"""Tests for hermes_cli.gateway.ensure_gateway_service — the zero-prompt+service install/start path used by `hermes setup` and `hermes import`.++The helper's contract:+ * never prompts, never raises (returns False on any failure)+ * no-ops in containers and on hosts without a service manager+ * short-circuits True when a service is already running+ * installs (user scope) then starts when nothing is installed+ * starts without reinstalling when a unit exists but isn't running+ * refuses to install on top of conflicting user+system systemd units+"""++import hermes_cli.gateway as gateway_mod+++def _patch_host(monkeypatch, *, container=False, systemd=True, macos=False, windows=False):+ monkeypatch.setattr("hermes_constants.is_container", lambda: container)+ monkeypatch.setattr(gateway_mod, "supports_systemd_services", lambda: systemd)+ monkeypatch.setattr(gateway_mod, "is_macos", lambda: macos)+ monkeypatch.setattr(gateway_mod, "is_windows", lambda: windows)+++class TestEnsureGatewayService:+ def test_container_is_noop(self, monkeypatch, capsys):+ _patch_host(monkeypatch, container=True)+ called = []+ monkeypatch.setattr(gateway_mod, "systemd_install", lambda **kw: called.append("install"))++ assert gateway_mod.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+ out = capsys.readouterr().out+ assert "hermes gateway" in out++ def test_already_running_short_circuits(self, monkeypatch):+ _patch_host(monkeypatch)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: True)+ called = []+ 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 not called++ def test_fresh_host_installs_and_starts_user_scope(self, monkeypatch):+ _patch_host(monkeypatch)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)+ monkeypatch.setattr(gateway_mod, "_is_service_installed", lambda: False)+ monkeypatch.setattr(gateway_mod, "has_conflicting_systemd_units", lambda: False)+ calls = []+ monkeypatch.setattr(+ gateway_mod, "systemd_install",+ lambda force=False, non_interactive=False, **kw: calls.append(+ ("install", force, non_interactive, kw)+ ),+ )+ monkeypatch.setattr(gateway_mod, "systemd_start", lambda **kw: calls.append(("start", kw)))++ assert gateway_mod.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"]+ # non_interactive so legacy-unit cleanup can't prompt+ assert calls[0][2] is True+ assert calls[1][0] == "start"++ def test_installed_but_stopped_starts_without_reinstall(self, monkeypatch):+ _patch_host(monkeypatch)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)+ monkeypatch.setattr(gateway_mod, "_is_service_installed", lambda: True)+ calls = []+ 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 calls == ["start"]++ def test_conflicting_units_block_install(self, monkeypatch):+ _patch_host(monkeypatch)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)+ monkeypatch.setattr(gateway_mod, "_is_service_installed", lambda: False)+ monkeypatch.setattr(gateway_mod, "has_conflicting_systemd_units", lambda: True)+ warned = []+ monkeypatch.setattr(+ gateway_mod, "print_systemd_scope_conflict_warning", lambda: warned.append(True)+ )+ calls = []+ monkeypatch.setattr(gateway_mod, "systemd_install", lambda **kw: calls.append("install"))++ assert gateway_mod.ensure_gateway_service() is False+ assert warned and not calls++ def test_macos_uses_launchd(self, monkeypatch):+ _patch_host(monkeypatch, systemd=False, macos=True)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)+ monkeypatch.setattr(gateway_mod, "_is_service_installed", lambda: False)+ calls = []+ 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 calls == ["install", "start"]++ def test_never_raises_on_install_failure(self, monkeypatch, capsys):+ _patch_host(monkeypatch)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)+ monkeypatch.setattr(gateway_mod, "_is_service_installed", lambda: False)+ monkeypatch.setattr(gateway_mod, "has_conflicting_systemd_units", lambda: False)++ def boom(**kw):+ raise RuntimeError("dbus fell over")++ monkeypatch.setattr(gateway_mod, "systemd_install", boom)++ assert gateway_mod.ensure_gateway_service() is False+ out = capsys.readouterr().out+ assert "hermes gateway install" in out++ def test_never_raises_on_sys_exit(self, monkeypatch, capsys):+ """Install paths that sys.exit() must not abort setup/import."""+ _patch_host(monkeypatch)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)+ monkeypatch.setattr(gateway_mod, "_is_service_installed", lambda: False)+ monkeypatch.setattr(gateway_mod, "has_conflicting_systemd_units", lambda: False)++ def bail(**kw):+ raise SystemExit(1)++ monkeypatch.setattr(gateway_mod, "systemd_install", bail)++ assert gateway_mod.ensure_gateway_service() is False+ out = capsys.readouterr().out+ assert "hermes gateway install" in out++ def test_user_systemd_unreachable_reports_remediation(self, monkeypatch, capsys):+ _patch_host(monkeypatch)+ monkeypatch.setattr(gateway_mod, "_is_service_running", lambda: False)+ monkeypatch.setattr(gateway_mod, "_is_service_installed", lambda: True)++ def unreachable(**kw):+ raise gateway_mod.UserSystemdUnavailableError("no D-Bus session\nenable linger")++ monkeypatch.setattr(gateway_mod, "systemd_start", unreachable)++ assert gateway_mod.ensure_gateway_service() is False+ out = capsys.readouterr().out+ assert "enable linger" in out