Skip to content

The agent that grows with you

feat(gateway): HermesGateway service verbs + updater Restart-Service + docs

ethernete6c7d4a55505
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 2e64ec06e68..fe123155e6a 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -3212,6 +3212,13 @@ DEFAULT_CONFIG = {
# the historical serve-all behavior; [] serves only the default.
"multiplex_profile_allowlist": None,
+ # The MSIX HermesGateway Windows Service posture (windows MSIX
+ # installs only; see `hermes gateway service on|off|status`).
+ # False = the service exists but stays demand-start/stopped
+ # (config-only posture — settled 2026-09-03); True = automatic
+ # at logon, bots keep running without the desktop app.
+ "service": False,
+
# After an unexpected SIGTERM interrupts a running gateway agent,
# wait this many seconds for it to unwind before adapter and database
# teardown proceeds. Keep this short so service-manager shutdowns do
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index ed62747bd8a..28fe339b47d 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1235,6 +1235,12 @@ def _prepare_profile_gateway_update_restart(profile: str, pid: int) -> str | Non
manager and race its replacement process. Ordinary foreground gateways
retain the existing detached-watcher behavior.
+ A sealed MSIX install whose HermesGateway Windows Service is running
+ has a service manager for this: the SCM restarts the service
+ (graceful-stop → respawn — drain-first by construction, the frontend's
+ STOP writes the planned-stop marker). Restart-Service is the whole
+ dance; arming a detached watcher beside it would double-spawn.
+
When the profile-derived relaunch cannot be armed -- typically because
``_gateway_run_args_for_profile`` cannot rebuild a run argv for this
profile -- fall back to replaying the process's own captured command
@@ -1243,8 +1249,12 @@ def _prepare_profile_gateway_update_restart(profile: str, pid: int) -> str | Non
unmapped gateways. Without this the caller has no way to relaunch the
process and (before #88654) silently left it running pre-update modules
against post-update code on disk. ``argv`` is already captured above,
- so the fallback costs nothing extra.
+ so the fallback costs nothing.
"""
+ # The SCM owns restarts on a service-managed sealed install (#D6b
+ # windows half): Restart-Service, no watcher, no scan.
+ if _try_scm_service_restart():
+ return "scm-service"
argv = _capture_gateway_argv(pid)
if argv and "--external-supervisor" in argv:
return "external-supervisor"
@@ -1255,6 +1265,39 @@ def _prepare_profile_gateway_update_restart(profile: str, pid: int) -> str | Non
return None
+def _try_scm_service_restart() -> bool:
+ """Restart the HermesGateway Windows Service when it's the running
+ gateway's manager: sealed MSIX install + service present + running.
+
+ Returns True when the SCM restart was issued (the caller must NOT arm
+ a detached watcher); False on any other machine shape (source
+ installs, service absent or stopped — the normal paths apply).
+ """
+ if sys.platform != "win32":
+ return False
+ try:
+ import win32serviceutil
+ except ImportError:
+ return False
+ try:
+ from gateway.windows_service import SERVICE_NAME
+ from pm.ensure import sealed
+
+ if not sealed():
+ return False
+ status = win32serviceutil.QueryServiceStatus(SERVICE_NAME)
+ running = bool(status and status[1] == 4) # SERVICE_RUNNING
+ if not running:
+ return False
+ win32serviceutil.RestartService(SERVICE_NAME)
+ print(f" ⏻ Restarting {SERVICE_NAME} service (graceful drain → respawn)")
+ return True
+ except Exception:
+ # Not service-managed (most installs): the ordinary restart paths
+ # own it. Never fail the update over a service lookup.
+ return False
+
+
def launch_detached_gateway_restart_by_cmdline(
old_pid: int, run_argv: list[str]
) -> bool:
@@ -4483,6 +4526,106 @@ def _ensure_linger_enabled() -> None:
_print_linger_enable_warning(username, detail or linger_detail)
+def _windows_scm_service_command(action: str | None) -> None:
+ """`hermes gateway service on|off|status` — the MSIX HermesGateway
+ Windows Service (SCM-registered at MSIX install, demand-start;
+ plan: gateway-msix-windows-service, Task 5; config-only posture).
+
+ "on" = automatic-at-logon + start now (persisted via gateway.service).
+ "off" = demand-start + stop now.
+ "status" = SCM state + the config key.
+ """
+ if sys.platform != "win32":
+ print_error("`hermes gateway service` manages the MSIX HermesGateway "
+ "Windows Service — not available on this platform.")
+ return
+ try:
+ import win32service
+ import win32serviceutil
+ except ImportError:
+ print_error("pywin32 is required for service management.")
+ return
+
+ from gateway.windows_service import SERVICE_NAME
+
+ def _config_get() -> bool:
+ try:
+ from hermes_cli.config import get_config_value
+
+ return bool(get_config_value("gateway.service", False))
+ except Exception:
+ return False
+
+ def _scm_status() -> tuple[bool, str]:
+ """(installed, state-name) — service absent = (False, 'not installed')."""
+ try:
+ status = win32serviceutil.QueryServiceStatus(SERVICE_NAME)
+ states = {
+ 1: "stopped",
+ 2: "start pending",
+ 3: "stop pending",
+ 4: "running",
+ 5: "continue pending",
+ 6: "pause pending",
+ 7: "paused",
+ }
+ return True, states.get(status[1], f"unknown ({status[1]})")
+ except Exception:
+ return False, "not installed"
+
+ if action in (None, "status"):
+ installed, state = _scm_status()
+ enabled = _config_get()
+ print(f"HermesGateway service: {state}" if installed else
+ "HermesGateway service: not installed (MSIX bundles only)")
+ print(f" config gateway.service: {'on' if enabled else 'off'}")
+ if installed and state == "running" and not enabled:
+ print_warning("service is running but the config key is off — "
+ "run `hermes gateway service on` to persist")
+ return
+
+ if action == "on":
+ installed, _ = _scm_status()
+ if not installed:
+ print_error("HermesGateway service is not installed — it ships "
+ "with the MSIX bundle (desktop app install).")
+ return
+ try:
+ # Automatic at logon + start now, gracefully.
+ win32serviceutil.ChangeServiceConfig(
+ SERVICE_NAME, starttype=win32service.SERVICE_AUTO_START
+ )
+ win32serviceutil.StartService(SERVICE_NAME)
+ from cli import save_config_value
+
+ save_config_value("gateway.service", True)
+ print(f"✓ {SERVICE_NAME}: automatic at logon + starting now")
+ print(" Bots keep running without the desktop app.")
+ except Exception as exc:
+ print_error(f"Could not enable service: {exc}")
+ return
+
+ if action == "off":
+ installed, _ = _scm_status()
+ if not installed:
+ print_error("HermesGateway service is not installed.")
+ return
+ try:
+ win32serviceutil.ChangeServiceConfig(
+ SERVICE_NAME, starttype=win32service.SERVICE_DEMAND_START
+ )
+ win32serviceutil.StopService(SERVICE_NAME) # graceful: frontend marker path
+ from cli import save_config_value
+
+ save_config_value("gateway.service", False)
+ print(f"✓ {SERVICE_NAME}: demand-start + stopping (graceful drain)")
+ except Exception as exc:
+ print_error(f"Could not disable service: {exc}")
+ return
+
+ print_error(f"Unknown service action: {action!r} (on|off|status)")
+
+
def _select_systemd_scope(system: bool = False) -> bool:
if system:
return True
@@ -9050,6 +9193,9 @@ def _gateway_command_inner(args):
print("Starting gateway...")
run_gateway(verbose=0)
+ elif subcmd == "service":
+ _windows_scm_service_command(getattr(args, "gateway_service_action", None))
+
elif subcmd == "status":
deep = getattr(args, "deep", False)
full = getattr(args, "full", False)
diff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.py
index 7092e8f09f6..75b7675d14d 100644
--- a/hermes_cli/subcommands/gateway.py
+++ b/hermes_cli/subcommands/gateway.py
@@ -170,6 +170,21 @@ def build_gateway_parser(
)
_add_compat_platform_flag(gateway_status)
+ # gateway service (MSIX HermesGateway Windows Service — the SCM one)
+ gateway_service = gateway_subparsers.add_parser(
+ "service",
+ help="Manage the HermesGateway Windows Service (MSIX installs)",
+ description=(
+ "The bundled MSIX installs a HermesGateway Windows Service "
+ "(demand-start, stopped). 'on' = automatic at logon + start "
+ "now; 'off' = demand + stop; 'status' = SCM state + config."
+ ),
+ )
+ gateway_service_sub = gateway_service.add_subparsers(dest="gateway_service_action")
+ gateway_service_sub.add_parser("on", help="Enable: automatic at logon + start now")
+ gateway_service_sub.add_parser("off", help="Disable: demand-start + stop now")
+ gateway_service_sub.add_parser("status", help="Show SCM state + config key")
+
# gateway install
gateway_install = gateway_subparsers.add_parser(
"install", help="Install gateway as a systemd/launchd background service"
diff --git a/tests/hermes_cli/test_gateway_scm_service.py b/tests/hermes_cli/test_gateway_scm_service.py
new file mode 100644
index 00000000000..4149331cf4f
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_scm_service.py
@@ -0,0 +1,142 @@
+"""Tests: `hermes gateway service` verbs + the updater's SCM restart branch.
+
+Hermetic — pywin32/SCM calls stubbed; the CONTRACTS are what's tested:
+dispatch, config persistence, the sealed+running gate for the updater's
+Restart-Service path, and the fall-through to ordinary restarts on every
+other machine shape.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import patch
+
+import pytest
+
+import hermes_cli.gateway as gw
+
+
+def _fake_scm(monkeypatch, *, installed=True, running=True, calls=None):
+ """Stub the pywin32 SCM surface; record calls into `calls`."""
+ import sys
+ import types
+
+ if calls is None:
+ calls = []
+ mod = types.ModuleType("win32service")
+ mod.SERVICE_AUTO_START = 2
+ mod.SERVICE_DEMAND_START = 3
+ util_mod = types.ModuleType("win32serviceutil")
+ util_mod.QueryServiceStatus = lambda name: (None, 4 if running else 1) if installed else (_ for _ in ()).throw(OSError("not installed"))
+ util_mod.ChangeServiceConfig = lambda name, starttype: calls.append(("config", starttype))
+ util_mod.StartService = lambda name: calls.append(("start",))
+ util_mod.StopService = lambda name: calls.append(("stop",))
+ util_mod.RestartService = lambda name: calls.append(("restart",))
+ monkeypatch.setitem(sys.modules, "win32service", mod)
+ monkeypatch.setitem(sys.modules, "win32serviceutil", util_mod)
+ return calls
+
+
+def test_service_status_not_installed(monkeypatch, capfd):
+ monkeypatch.setattr(gw.sys, "platform", "win32")
+ import sys as _sys
+
+ _sys.modules.pop("win32service", None)
+ _sys.modules.pop("win32serviceutil", None)
+
+ import types
+
+ mod = types.ModuleType("win32service")
+ mod.SERVICE_AUTO_START = 2
+ mod.SERVICE_DEMAND_START = 3
+ util_mod = types.ModuleType("win32serviceutil")
+
+ def boom(name):
+ raise OSError("not installed")
+
+ util_mod.QueryServiceStatus = boom
+ monkeypatch.setitem(_sys.modules, "win32service", mod)
+ monkeypatch.setitem(_sys.modules, "win32serviceutil", util_mod)
+
+ gw._windows_scm_service_command(None)
+ out = capfd.readouterr().out
+ assert "not installed" in out
+
+
+def test_service_on_configures_starts_persists(monkeypatch, capfd):
+ monkeypatch.setattr(gw.sys, "platform", "win32")
+ calls = _fake_scm(monkeypatch, installed=True, running=True)
+ saved = {}
+ monkeypatch.setattr("cli.save_config_value", lambda k, v: saved.update({k: v}))
+
+ gw._windows_scm_service_command("on")
+ assert ("config", 2) in calls # SERVICE_AUTO_START
+ assert ("start",) in calls
+ assert saved == {"gateway.service": True}
+ assert "automatic at logon" in capfd.readouterr().out
+
+
+def test_service_off_demand_stops_persists(monkeypatch, capfd):
+ monkeypatch.setattr(gw.sys, "platform", "win32")
+ calls = _fake_scm(monkeypatch, installed=True, running=True)
+ saved = {}
+ monkeypatch.setattr("cli.save_config_value", lambda k, v: saved.update({k: v}))
+
+ gw._windows_scm_service_command("off")
+ assert ("config", 3) in calls # SERVICE_DEMAND_START
+ assert ("stop",) in calls
+ assert saved == {"gateway.service": False}
+
+
+def test_service_unknown_action_is_an_error(monkeypatch, capfd):
+ monkeypatch.setattr(gw.sys, "platform", "win32")
+ calls = _fake_scm(monkeypatch, installed=True, running=True)
+ monkeypatch.setattr("cli.save_config_value", lambda k, v: None)
+ gw._windows_scm_service_command("dance")
+ assert "Unknown service action" in capfd.readouterr().out
+
+
+# ── the updater's SCM restart branch ─────────────────────────────────
+
+
+def test_updater_scm_restart_gated_on_running_service(monkeypatch):
+ """Sealed + HermesGateway RUNNING → Restart-Service, True (skip the
+ detached watcher); any other shape → False (ordinary paths)."""
+ monkeypatch.setattr(gw.sys, "platform", "win32")
+ calls = _fake_scm(monkeypatch, installed=True, running=True)
+
+ import importlib
+ import sys
+
+ sys.modules.pop("pm.ensure", None)
+ pm_ensure = importlib.import_module("pm.ensure")
+
+ monkeypatch.setattr(pm_ensure, "sealed", lambda: True)
+
+ assert gw._try_scm_service_restart() is True
+ assert ("restart",) in calls
+
+
+def test_updater_scm_restart_false_when_not_sealed(monkeypatch):
+ monkeypatch.setattr(gw.sys, "platform", "win32")
+ calls = _fake_scm(monkeypatch, installed=True, running=True)
+ import importlib
+
+ pm_ensure = importlib.import_module("pm.ensure")
+ monkeypatch.setattr(pm_ensure, "sealed", lambda: False)
+ assert gw._try_scm_service_restart() is False
+ assert calls == [] # no SCM touch
+
+
+def test_updater_scm_restart_false_when_service_stopped(monkeypatch):
+ monkeypatch.setattr(gw.sys, "platform", "win32")
+ calls = _fake_scm(monkeypatch, installed=True, running=False)
+ import importlib
+
+ pm_ensure = importlib.import_module("pm.ensure")
+ monkeypatch.setattr(pm_ensure, "sealed", lambda: True)
+ assert gw._try_scm_service_restart() is False
+
+
+def test_updater_scm_restart_false_on_posix(monkeypatch):
+ monkeypatch.setattr(gw.sys, "platform", "linux")
+ assert gw._try_scm_service_restart() is False
diff --git a/website/docs/user-guide/features/gateway-service.md b/website/docs/user-guide/features/gateway-service.md
new file mode 100644
index 00000000000..fc4eba1fcd4
--- /dev/null
+++ b/website/docs/user-guide/features/gateway-service.md
@@ -0,0 +1,68 @@
+# Gateway Service
+
+The messaging gateway (Telegram, Discord, WhatsApp, and every other
+platform adapter) normally runs as a child of wherever you started it —
+a terminal, `hermes serve`, or the desktop app's backend. On Windows,
+the **bundled MSIX install** ships one more way: a real Windows Service.
+
+## What it is
+
+Installing the desktop app registers a service named **HermesGateway**
+in the Windows Service Control Manager. It arrives **stopped** and
+**demand-start** — it never starts on its own. When you turn it on, the
+Service Control Manager owns the gateway's lifecycle:
+
+- **automatic at logon** — bots start when you sign in, no app needed
+- **restart on crash** — the SCM respawns the gateway if it dies
+- **bots survive app close** — the service is not the desktop app's
+ child; closing the app never touches it
+
+The service runs as *you* (the installing user), using your Hermes home
+— the same sessions, memory, and config as every other surface. The
+default profile's gateway is what it serves; multiplexed profiles ride
+the same process, exactly as a foreground gateway.
+
+## Turning it on
+
+```bash
+hermes gateway service on
+```
+
+That flips the service to automatic-at-logon and starts it now,
+gracefully. Turning it off is the same shape:
+
+```bash
+hermes gateway service off # demand-start + graceful stop
+hermes gateway service status # SCM state + the config key
+```
+
+The posture persists in the `gateway.service` config key, so `hermes
+gateway service status` is the one command that answers "is this on?"
+
+## Updates and the graceful stop
+
+Stopping the service — by you, by an update, or by Windows shutdown —
+is always graceful: in-flight agent sessions drain, the session database
+flushes, and platform locks release (the same drain path `hermes
+gateway stop` uses). `hermes update` on a service-managed install
+restarts the service through the SCM (`Restart-Service`) — the drain
+happens first, the respawn after, so a mixed-version gateway is never
+left serving.
+
+## Uninstall
+
+Uninstalling the desktop app removes the service automatically (MSIX
+registers it; MSIX removes it). Bots stop — same as today, where
+uninstalling the payload removes the gateway's runtime.
+
+## Platform notes
+
+- **Windows MSIX installs only.** Source installs (and every other
+ platform) keep the foreground `hermes gateway run`, systemd, or
+ launchd paths — see [the CLI gateway
+ docs](/user-guide/cli#gateway).
+- The service requires Windows 10 1903+ (the MSIX's minimum OS — the
+ same floor the desktop app ships with).
+- `services.msc` shows it as "Hermes Gateway"; manage it there if you
+ like, though the `hermes gateway service` verbs keep the config key
+ in sync, which the SCM console does not.
diff --git a/website/sidebars.ts b/website/sidebars.ts
index eba4ad2e92f..38f8c2f76e5 100644
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@ -68,6 +68,7 @@ const sidebars: SidebarsConfig = {
items: [
'user-guide/features/overview',
'user-guide/features/tool-gateway',
+ 'user-guide/features/gateway-service',
{
type: 'category',
label: 'Core',