The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: require explicit consent for gateway service setup
Teknium16d6b7daa13b
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 40d83814079..2bb7780aa15 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1883,6 +1883,7 @@ DEFAULT_CONFIG = {"export": {"otlp": {"enabled": False, "endpoint": "", "headers_env": {}}},},"gateway": { # Gateway settings (messaging platforms: Telegram, Discord, Slack, ...).+ "service_install_choice": None, # null | install | decline; never authorizes ordinary launch installation.# Named-profile allowlist for multiplex mode. None = serve all; [] = default only."multiplex_profile_allowlist": None,# Seconds to let a SIGTERM-interrupted gateway agent unwind before adapter/databasediff --git a/hermes_cli/gateway_setup_service.py b/hermes_cli/gateway_setup_service.pyindex 5d7bb876fcc..12dad69aa26 100644--- a/hermes_cli/gateway_setup_service.py+++ b/hermes_cli/gateway_setup_service.py@@ -1,82 +1,101 @@"""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,- )+import sys++SERVICE_INSTALL_QUESTION = (+ "Install the gateway service so Hermes starts automatically at login "+ "and keeps scheduled jobs and messaging available?"+)+++def record_service_choice(choice: str, config: dict | None = None) -> None:+ from hermes_cli.config import load_config, save_config++ if choice not in {"install", "decline"}:+ raise ValueError("service_install_choice must be install or decline")+ current = load_config()+ current.setdefault("gateway", {})["service_install_choice"] = choice+ save_config(current)+ # Setup keeps a working config which it saves again after this step.+ if config is not None:+ config.setdefault("gateway", {})["service_install_choice"] = choice+++def wants_service_install(*, interactive: bool, install: bool = False,+ config: dict | None = None) -> bool:+ from hermes_cli.config import load_config+ from hermes_cli.gateway import prompt_yes_no++ if install:+ return True+ if not interactive or not sys.stdin.isatty():+ return False+ choice = (config if config is not None else load_config()).get("gateway", {}).get("service_install_choice")+ if choice is None:+ if prompt_yes_no(SERVICE_INSTALL_QUESTION, False):+ return True+ record_service_choice("decline", config)+ return choice == "install"+++def ensure_gateway_service(context: str = "setup", *, interactive: bool = False,+ install: bool = False, config: dict | None = None) -> bool:+ """Start existing services; install only with explicit setup consent.++ Import and ordinary noninteractive callers cannot install, even with a saved+ install preference. False leaves foreground/unmanaged startup to the caller.+ """+ from hermes_cli import gateway as gwfrom 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 ...")+ gw.print_info("Run hermes gateway run as the container main process; use a Docker restart policy for persistence.")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")+ supports_systemd = gw.supports_systemd_services()+ if not (supports_systemd or gw.is_macos() or gw.is_windows()):+ gw.print_info("No supported service manager found. Run: hermes gateway run")return False-try:- if _is_service_running():+ if gw._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()+ if not gw._is_service_installed():+ if context == "import" or not wants_service_install(+ interactive=interactive, install=install, config=config+ ):+ gw.print_info("No service installed. Run: hermes gateway run")+ gw.print_info("Without a service, scheduled jobs and messaging stop at logout/reboot; jobs cannot run while the host is off.")+ return False+ if supports_systemd and gw.has_conflicting_systemd_units():+ gw.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)+ gw.systemd_install(force=False, non_interactive=True)+ elif gw.is_macos():+ gw.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+ gw._gw_windows().install(force=False)+ # Installers can refuse without raising (e.g. temporary-home guard).+ if not gw._is_service_installed():+ gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")+ return False+ record_service_choice("install", config)if supports_systemd:- systemd_start()- elif is_macos():- launchd_start()+ gw.systemd_start()+ elif gw.is_macos():+ gw.launchd_start()else:- _gw_windows().start()- print_success(" Gateway service running (cron jobs + messaging platforms).")+ gw._gw_windows().start()+ gw.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 gw.UserSystemdUnavailableError as exc:+ gw.print_warning("Could not reach user systemd to start the gateway service:")+ gw._print_indented(str(exc), gw.print_info)+ except gw.SystemScopeRequiresRootError as exc:+ gw.print_warning(f"Gateway service needs root for this scope: {exc}")+ gw._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")+ gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")+ except Exception as exc:+ gw.print_warning(f"Gateway service setup failed: {exc}")+ gw.print_info("You can retry manually: hermes gateway install")return Falsediff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex dd9286bd0be..03a93e5c0c6 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -631,10 +631,9 @@ def _run_full_setup(config: dict, hermes_home, *, is_existing: bool, migration_rif not _skip("gateway", "Messaging Platforms"):setup_gateway(config)return- # A skipped (migrated) gateway section still needs its service so imported platforms- # and cron jobs become active.+ # Migration does not imply consent to install a persistent service.from hermes_cli.gateway_setup_service import ensure_gateway_service- ensure_gateway_service(context="setup")+ ensure_gateway_service(context="setup", interactive=True, config=config)def _step(key: str, label: str, run) -> tuple:return label, lambda: None if _skip(key, label) else run()diff --git a/hermes_cli/setup_platforms.py b/hermes_cli/setup_platforms.pyindex 9391a79551c..19003bedfa5 100644--- a/hermes_cli/setup_platforms.py+++ b/hermes_cli/setup_platforms.py@@ -353,6 +353,6 @@ def setup_gateway(config: dict):if _is_service_running():_restart_running_gateway(any_messaging, supports_systemd)else:- # Not running: install (if needed) and start, no questions asked.- ensure_gateway_service(context="setup")+ # Existing services can start; a new service requires explicit consent.+ ensure_gateway_service(context="setup", interactive=True, config=config)print_info(_RULE)diff --git a/hermes_cli/setup_quick.py b/hermes_cli/setup_quick.pyindex b765a63ecd4..05bc129c632 100644--- a/hermes_cli/setup_quick.py+++ b/hermes_cli/setup_quick.py@@ -117,10 +117,9 @@ def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool):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`).+ # Messaging is optional; service persistence still requires explicit consent.from hermes_cli.gateway_setup_service import ensure_gateway_service- ensure_gateway_service(context="setup")+ ensure_gateway_service(context="setup", interactive=True, config=config)print()print_success("Setup complete! You're ready to go.")_info(None, " Configure all settings: hermes setup")diff --git a/tests/hermes_cli/test_ensure_gateway_service.py b/tests/hermes_cli/test_ensure_gateway_service.pyindex a49bde90e61..2fae3ac8221 100644--- a/tests/hermes_cli/test_ensure_gateway_service.py+++ b/tests/hermes_cli/test_ensure_gateway_service.py@@ -1,14 +1,4 @@-"""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-"""+"""Service setup failure reporting; consent integration lives in test_gateway_service_choice."""import hermes_cli.gateway as gateway_modfrom hermes_cli.gateway_setup_service import ensure_gateway_service@@ -27,14 +17,14 @@ class TestEnsureGatewayService:called = []monkeypatch.setattr(gateway_mod, "systemd_install", lambda **kw: called.append("install"))- assert ensure_gateway_service() is False+ assert ensure_gateway_service(install=True) is Falseassert not calledout = capsys.readouterr().outassert "restart policy" in outdef test_no_service_manager_is_noop(self, monkeypatch, capsys):_patch_host(monkeypatch, systemd=False)- assert ensure_gateway_service() is False+ assert ensure_gateway_service(install=True) is Falseout = capsys.readouterr().outassert "hermes gateway" in out@@ -45,30 +35,10 @@ 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 ensure_gateway_service() is True+ assert ensure_gateway_service(install=True) is Trueassert 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 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)@@ -78,7 +48,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 ensure_gateway_service() is True+ assert ensure_gateway_service(install=True) is Trueassert calls == ["start"]def test_conflicting_units_block_install(self, monkeypatch):@@ -93,19 +63,10 @@ class TestEnsureGatewayService:calls = []monkeypatch.setattr(gateway_mod, "systemd_install", lambda **kw: calls.append("install"))- assert ensure_gateway_service() is False+ assert ensure_gateway_service(install=True) is Falseassert 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 ensure_gateway_service() is True- assert calls == ["install", "start"]def test_never_raises_on_install_failure(self, monkeypatch, capsys):_patch_host(monkeypatch)@@ -118,7 +79,7 @@ class TestEnsureGatewayService:monkeypatch.setattr(gateway_mod, "systemd_install", boom)- assert ensure_gateway_service() is False+ assert ensure_gateway_service(install=True) is Falseout = capsys.readouterr().outassert "hermes gateway install" in out@@ -134,7 +95,7 @@ class TestEnsureGatewayService:monkeypatch.setattr(gateway_mod, "systemd_install", bail)- assert ensure_gateway_service() is False+ assert ensure_gateway_service(install=True) is Falseout = capsys.readouterr().outassert "hermes gateway install" in out@@ -148,6 +109,6 @@ class TestEnsureGatewayService:monkeypatch.setattr(gateway_mod, "systemd_start", unreachable)- assert ensure_gateway_service() is False+ assert ensure_gateway_service(install=True) is Falseout = capsys.readouterr().outassert "enable linger" in outdiff --git a/tests/hermes_cli/test_gateway_service_choice.py b/tests/hermes_cli/test_gateway_service_choice.pynew file mode 100644index 00000000000..104d2b0bb62--- /dev/null+++ b/tests/hermes_cli/test_gateway_service_choice.py@@ -0,0 +1,104 @@+"""Service consent through real config/discovery/install; only OS peers are fake."""+import io+import json+import os+from pathlib import Path+import sys+import tempfile++import pytest++from hermes_cli import config as config_api+from hermes_cli import gateway+from hermes_cli import gateway_setup_service as setup_service+++def supervisor(tmp_path, monkeypatch):+ # The installer intentionally rejects /tmp profiles. A disposable RAM-backed+ # home exercises that real guard without disabling it or touching user state.+ with tempfile.TemporaryDirectory(prefix="hermes-choice-", dir="/dev/shm") as directory:+ home = Path(directory)+ profile = home / "profile"+ profile.mkdir()+ monkeypatch.setenv("HOME", str(home))+ monkeypatch.setenv("HERMES_HOME", str(profile))+ runtime = home / "run"+ runtime.mkdir()+ (runtime / "bus").touch()+ monkeypatch.setenv("XDG_RUNTIME_DIR", str(runtime))+ monkeypatch.delenv("DBUS_SESSION_BUS_ADDRESS", raising=False)+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ calls = tmp_path / "calls.jsonl"+ state = tmp_path / "active"+ for name in ("systemctl", "loginctl", "sudo"):+ exe = bin_dir / name+ exe.write_text(+ f"#!{sys.executable}\n"+ "import json, os, pathlib, sys\n"+ f"calls = pathlib.Path({str(calls)!r})\n"+ "with calls.open('a') as stream: stream.write(json.dumps([pathlib.Path(sys.argv[0]).name, *sys.argv[1:]]) + '\\n')\n"+ f"active = pathlib.Path({str(state)!r})\n"+ "args = sys.argv[1:]\n"+ "if 'enable' in args and os.getenv('CHOICE_FAIL'): sys.exit(1)\n"+ "if 'start' in args: active.touch()\n"+ "if 'is-active' in args: print('active' if active.exists() else 'inactive')\n"+ "elif 'show-user' in args: print('yes')\n"+ "elif 'is-system-running' in args: print('running')\n",+ encoding="utf-8",+ )+ exe.chmod(0o700)+ monkeypatch.setenv("PATH", str(bin_dir) + os.pathsep + os.environ["PATH"])+ # Inject the owned executable at the OS command boundary, retaining the+ # live-system guard (which correctly blocks a command named systemctl).+ peer = bin_dir / "supervisor-peer"+ peer.write_bytes((bin_dir / "systemctl").read_bytes())+ peer.chmod(0o700)+ monkeypatch.setattr(gateway, "_systemctl_cmd", lambda system=False: [str(peer)])+ yield profile, calls+++def _operations(calls):+ return [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []++[email protected]_only[email protected]("choice", [None, "decline", "install"])+def test_import_and_ordinary_setup_never_authorize_install(supervisor, choice):+ profile, calls = supervisor+ config_api.save_config({"gateway": {"service_install_choice": choice}})+ before = (profile / "config.yaml").read_bytes()+ assert setup_service.ensure_gateway_service() is False+ assert setup_service.ensure_gateway_service(context="import") is False+ assert not gateway.get_systemd_unit_path().exists()+ assert not any(set(op) & {"enable", "enable-linger", "start", "daemon-reload"} for op in _operations(calls))+ assert (profile / "config.yaml").read_bytes() == before++[email protected]_only[email protected]("answer, fail", [(False, False), (True, False), (True, True)])+def test_explicit_setup_consent_is_durable_only_after_success(supervisor, monkeypatch, answer, fail):+ profile, calls = supervisor+ config_api.save_config({"gateway": {"service_install_choice": None}, "custom": "keep"})+ prompts = []+ monkeypatch.setattr(gateway, "prompt_yes_no", lambda *args: prompts.append(args) or answer)+ stream = io.StringIO()+ stream.isatty = lambda: True+ monkeypatch.setattr(sys, "stdin", stream)+ if fail:+ monkeypatch.setenv("CHOICE_FAIL", "1")+ config = config_api.load_config()+ result = setup_service.ensure_gateway_service(interactive=True, config=config)+ expected = None if fail else ("install" if answer else "decline")+ assert config_api.load_config()["gateway"]["service_install_choice"] == expected+ assert config["gateway"]["service_install_choice"] == expected+ assert config_api.load_config()["custom"] == "keep"+ assert result is (answer and not fail)+ assert len(prompts) == 1+ if not fail:+ setup_service.ensure_gateway_service(interactive=True)+ assert len(prompts) == 1+ if not answer:+ assert not gateway.get_systemd_unit_path().exists()+ assert not any(set(op) & {"enable", "enable-linger", "start", "daemon-reload"} for op in _operations(calls))