The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a secondary API_SERVER_KEY no longer skips the profile; start/install/status honour the live multiplexer
Teknium37dcc0a6e84b
diff --git a/gateway/config_env.py b/gateway/config_env.pyindex b5cf0c5e0e2..e3d384bbf37 100644--- a/gateway/config_env.py+++ b/gateway/config_env.py@@ -21,6 +21,7 @@ from gateway.config import (PlatformConfig,_getenv_str,_has_usable_api_server_key,+ platform_binds_port,)from utils import is_truthy_value@@ -168,6 +169,15 @@ def _env_reply_mode(config: GatewayConfig, platform: Platform, env: str) -> Noneconfig.platforms.setdefault(platform, PlatformConfig()).reply_to_mode = mode+def _loading_secondary_under_multiplexer() -> bool:+ """True while a multiplexer loads a NON-default profile's config (``_profile_runtime_scope`` sets the+ home override; the runner sets the multiplex flag). Same signal ``gateway.config`` uses for scoped reads."""+ from agent.secret_scope import is_multiplex_active+ from hermes_constants import get_hermes_home_override, profile_name_for_home+ override = get_hermes_home_override()+ return bool(override) and is_multiplex_active() and profile_name_for_home(override) != "default"++def _enable_from_env(config: GatewayConfig, platform: Platform, *, pop_marker: bool = False, warn: bool = True) -> PlatformConfig:@@ -184,7 +194,13 @@ def _enable_from_env(explicit = extra.pop("_enabled_explicit", False) if pop_marker else extra.get("_enabled_explicit", False)if platform_config.enabled:return platform_config- if not explicit:+ if not explicit and not (+ platform_binds_port(platform.value, extra) and _loading_secondary_under_multiplexer()+ ):+ # A secondary's port-binding credential (the docs require API_SERVER_KEY in its .env for+ # /p/<profile>/ auth) must not turn into listener intent: the default profile owns the one+ # shared listener and ``_load_secondary_profile_config`` skips the WHOLE profile for it (#100397).+ # The credential itself still lands in ``extra`` for the shared adapter to authenticate with.platform_config.enabled = Trueelif warn:_warn_explicit_disable_beats_env(platform)diff --git a/gateway/status.py b/gateway/status.pyindex 082566fe448..9f16f13b999 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -380,6 +380,18 @@ def _profile_name_for_home(profile_home: Path) -> Optional[str]:return profile_home.name if profile_home.parent.name == "profiles" else None+def profile_flag_value(command: str) -> Optional[str]:+ """The ``-p``/``--profile`` argument of a command line, or None. Token equality is the only safe+ profile match: a substring test lets ``-p ops`` claim (and ``gateway stop`` SIGTERM) ``-p ops-2``."""+ tokens = command.split()+ for i, tok in enumerate(tokens):+ if tok.startswith("--profile="):+ return tok.partition("=")[2]+ if tok in ("-p", "--profile") and i + 1 < len(tokens):+ return tokens[i + 1]+ return None++def _command_line_belongs_to_profile(command: str, profile_home: Path) -> bool:"""True when a gateway command line belongs to ``profile_home`` (mirrors``hermes_cli.gateway._matches_current_profile``): a stale state file can record a PID recycled@@ -389,10 +401,7 @@ def _command_line_belongs_to_profile(command: str, profile_home: Path) -> bool:profile_name = _profile_name_for_home(profile_home)home_lc = str(profile_home).lower().replace("\\", "/")if profile_name is not None and profile_name != "default":- profile_lc = profile_name.lower()- return any(needle in command_lc for needle in (- f"--profile {profile_lc}", f"-p {profile_lc}", f"hermes_home={home_lc}"- ))+ return profile_flag_value(command_lc) == profile_name.lower() or f"hermes_home={home_lc}" in command_lc# Default profile: accept unless argv names another profile or a conflicting explicit# HERMES_HOME= (its absence is not disqualifying -- HERMES_HOME usually arrives via the env).if "--profile " in command_lc or " -p " in command_lc:diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex a016272e007..837fd9b63d1 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -384,7 +384,7 @@ def _print_ticker_health(pids: list) -> None:def cron_status():"""Show cron execution status."""from cron.jobs import list_jobs- from hermes_cli.gateway import find_gateway_pids+ from hermes_cli.gateway import find_gateway_pids, named_profile_served_by_running_multiplexerprint()provider = _active_cron_provider_name()@@ -395,6 +395,12 @@ def cron_status():"not the in-process ticker.", Colors.GREEN))print(color(" (No ticker heartbeat is expected for an external provider; ""due jobs are delivered by an authenticated webhook.)", Colors.DIM))+ elif not find_gateway_pids() and named_profile_served_by_running_multiplexer():+ # Satellite profile: the default multiplexer's ticker fires this store (same answer as+ # `_builtin_gateway_liveness`, which `cron list` uses -- the two must not disagree).+ print(color("✓ Gateway is running via the default-profile multiplexer — it ticks this profile's jobs.",+ Colors.GREEN))+ print(color(" Ticker health is reported by `hermes cron status` on the default profile.", Colors.DIM))else:pids = find_gateway_pids()gateway_alive_via_lock = Falsediff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 12a3bec0daf..d8ba7e8639b 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -570,7 +570,9 @@ def _scan_gateway_pids(pids: list[int] = []# Strict matcher shared with gateway.status: requires a real ``gateway run`` argv, so# ``gateway status``/``dashboard`` siblings and ``python -m tui_gateway`` don't match.- from gateway.status import looks_like_gateway_command_line, looks_like_gateway_runtime_command_line+ from gateway.status import (+ looks_like_gateway_command_line, looks_like_gateway_runtime_command_line, profile_flag_value,+ )current_home = str(get_hermes_home().resolve())# Forward slashes on both sides of the HERMES_HOME= match (mirrors gateway.status).current_home_lc = current_home.lower().replace("\\", "/")@@ -581,9 +583,9 @@ def _scan_gateway_pids(def _matches_current_profile(command: str) -> bool:command_lc = command.lower().replace("\\", "/")if current_profile_name:+ # Token equality, not substring: `-p ops` must not claim (or SIGTERM) an `-p ops-2` gateway.return (- f"--profile {current_profile_name_lc}" in command_lc- or f"-p {current_profile_name_lc}" in command_lc+ profile_flag_value(command_lc) == current_profile_name_lcor f"hermes_home={current_home_lc}" in command_lc)@@ -4332,13 +4334,16 @@ def named_profile_served_by_running_multiplexer(profile_name: str | None = None)return Falsetry:- from gateway.status import _pid_exists, _pid_from_record, _read_pid_record- rec = _read_pid_record(default_root / "gateway.pid")- if not rec:- return False- pid = _pid_from_record(rec)- if not pid or not _pid_exists(pid):+ from hermes_cli.gateway_multiplex_served import live_default_gateway_pid, recorded_served_profiles+ if live_default_gateway_pid() is None:return False+ from hermes_cli.profiles import normalize_profile_name+ # The live gateway's own record wins: the CLI process cannot see an env-only opt-in on the+ # default profile (`hermes -p X` loads X's .env) and a config edit after start is not live yet.+ # Only a record without the key (pre-multiplex writer) falls through to config derivation.+ recorded = recorded_served_profiles(default_root)+ if recorded is not None:+ return normalize_profile_name(suffix) in {normalize_profile_name(p) for p in recorded}from gateway.config import _env_multiplex_profiles_overridecfg_path = default_root / "config.yaml"@@ -4362,7 +4367,6 @@ def named_profile_served_by_running_multiplexer(profile_name: str | None = None)else:raw_allowlist = gateway_cfg.get("multiplex_profile_allowlist")from gateway.config import _normalize_multiplex_profile_allowlist- from hermes_cli.profiles import normalize_profile_nameprofile_allowlist = _normalize_multiplex_profile_allowlist(raw_allowlist)return profile_allowlist is None or normalize_profile_name(suffix) in profile_allowlistexcept Exception:@@ -4370,17 +4374,21 @@ def named_profile_served_by_running_multiplexer(profile_name: str | None = None)return False-def _guard_named_profile_under_multiplexer(force: bool = False) -> None:- """Refuse a named-profile gateway when a multiplexing default gateway already serves it (a second one- would double-bind its platforms: two pollers on one token, port fights). ``--force`` overrides."""+def _named_profile_refused_under_multiplexer(force: bool = False) -> bool:+ """Print the served-profile refusal and return True when a named-profile gateway must not start:+ a multiplexing default gateway already serves it (a second one would double-bind its platforms: two+ pollers on one token, port fights). ``--force`` overrides. Shared by ``run`` and the service verbs+ (``start``/``install``/``restart``): a refusal only inside ``gateway run`` leaves the service manager+ to discover it — systemd parks the unit on exit 78 while the CLI prints "started"; launchd+ (KeepAlive, no exit-status gating) respawns it every ThrottleInterval forever."""if force:- return+ return Falsetry:suffix = _current_profile_name()except Exception:- return+ return Falseif not named_profile_served_by_running_multiplexer():- return+ return Falseprint_error(f"The default gateway is running as a profile multiplexer and already "@@ -4398,6 +4406,13 @@ def _guard_named_profile_under_multiplexer(force: bool = False) -> None:print()print(" Pass --force to start a separate profile gateway anyway (not")print(" recommended while the multiplexer is running).")+ return True+++def _guard_named_profile_under_multiplexer(force: bool = False) -> None:+ """Exit-78 form of ``_named_profile_refused_under_multiplexer`` for the CLI entry points."""+ if not _named_profile_refused_under_multiplexer(force=force):+ return# EX_CONFIG, not 1: the refusal is decided purely by config, so it is permanent. The systemd unit# (Restart=always, StartLimitIntervalSec=0) relies on RestartPreventExitStatus=78 as its only# backstop — exit 1 turned a correct refusal into an unbounded restart loop; s6 maps 78 to@@ -6028,6 +6043,8 @@ def _cmd_install(args):managed_error("install gateway service")returnforce = getattr(args, "force", False)+ # `--force` doubles as the reinstall flag here; a served profile's unit would only ever exit 78.+ _guard_named_profile_under_multiplexer(force=force)system = getattr(args, "system", False)run_as_user = getattr(args, "run_as_user", None)if is_termux():@@ -6066,6 +6083,7 @@ def _cmd_uninstall(args):def _cmd_start(args):system = getattr(args, "system", False)start_all = getattr(args, "all", False)+ _guard_named_profile_under_multiplexer(force=getattr(args, "force", False))if not start_all and _dispatch_via_service_manager_if_s6("start"):returnif start_all:@@ -6129,6 +6147,8 @@ def _cmd_restart(args):_refuse_from_inside_gateway("restart", "restart loops")system = getattr(args, "system", False)restart_all = getattr(args, "all", False)+ force = getattr(args, "force", False)+ _guard_named_profile_under_multiplexer(force=force)if restart_all and _dispatch_all_via_service_manager_if_s6("restart"):returnif not restart_all and _dispatch_via_service_manager_if_s6("restart"):@@ -6175,7 +6195,7 @@ def _cmd_restart(args):print("✓ Stopped gateway for this profile")_wait_for_gateway_exit(timeout=10.0, force_after=5.0)print("Starting gateway...")- run_gateway(verbose=0)+ run_gateway(verbose=0, force=force)# ``hermes gateway status`` hints for a manually-run / stopped gateway, keyed by host kind.diff --git a/hermes_cli/gateway_multiplex_served.py b/hermes_cli/gateway_multiplex_served.pynew file mode 100644index 00000000000..01a8d5e3e1b--- /dev/null+++ b/hermes_cli/gateway_multiplex_served.py@@ -0,0 +1,43 @@+"""Which profiles does the LIVE default multiplexer serve? One answer for every CLI/dashboard surface.++``gateway/run_adapters.py::_record_served_profiles`` writes ``served_profiles`` into the default+home's ``gateway_state.json`` at startup. That record is the truth about the running process; the+default ``config.yaml`` plus ``GATEWAY_MULTIPLEX_PROFILES`` as seen by the *CLI* process is only a+guess (``hermes -p coder ...`` loads coder's ``.env``, so an env-only opt-in on the default profile+is invisible to it, and an allowlist edited after start flips the guess before the restart).+"""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Optional++logger = logging.getLogger(__name__)+++def live_default_gateway_pid() -> Optional[int]:+ """PID of the default profile's gateway when its pid record names a live process, else None."""+ from hermes_constants import get_default_hermes_root+ from gateway.status import _pid_exists, _pid_from_record, _read_pid_record+ rec = _read_pid_record(get_default_hermes_root() / "gateway.pid")+ pid = _pid_from_record(rec) if rec else None+ return pid if pid and _pid_exists(pid) else None+++def recorded_served_profiles(default_root: Optional[Path] = None) -> Optional[list[str]]:+ """``served_profiles`` the live default gateway recorded, or None when the key is absent (a record+ from before the multiplexer recorded it, or a stopped/absent gateway). Callers fall back to config+ derivation only on None: an empty list is an authoritative "serves nobody else"."""+ from hermes_constants import get_default_hermes_root+ from gateway.status import read_runtime_status+ if live_default_gateway_pid() is None:+ return None+ runtime = read_runtime_status((default_root or get_default_hermes_root()) / "gateway_state.json")+ served = (runtime or {}).get("served_profiles")+ return [str(p) for p in served] if isinstance(served, list) else None+++def multiplexer_served_secondaries() -> list[str]:+ """Named profiles the live default multiplexer serves (excludes ``default``); empty when none."""+ return [p for p in (recorded_served_profiles() or []) if p and p != "default"]diff --git a/hermes_cli/status.py b/hermes_cli/status.pyindex 8d1536b1869..07386ef37f9 100644--- a/hermes_cli/status.py+++ b/hermes_cli/status.py@@ -219,12 +219,21 @@ def _render_platforms(ctx):def _render_gateway(ctx):_section("Gateway Service")try:- from hermes_cli.gateway import get_gateway_runtime_snapshot, _format_gateway_pids+ from hermes_cli.gateway import (+ get_gateway_runtime_snapshot, _format_gateway_pids, named_profile_served_by_running_multiplexer)+ from hermes_cli.gateway_multiplex_served import multiplexer_served_secondariessnapshot = get_gateway_runtime_snapshot()+ # A satellite profile has no gateway.pid of its own; the default multiplexer is its live process.+ if not snapshot.running and named_profile_served_by_running_multiplexer():+ _kv_flag("Status:", True, "running (via the default-profile multiplexer)", "stopped")+ _kv("Manage with:", "hermes gateway status # from the default profile")+ return_kv_flag("Status:", snapshot.running, "running", "stopped")_kv("Manager:", snapshot.manager)if snapshot.gateway_pids:_kv("PID(s):", _format_gateway_pids(snapshot.gateway_pids))+ if snapshot.running and (served := multiplexer_served_secondaries()):+ _kv("Serves:", ", ".join(served))if snapshot.has_process_service_mismatch:_kv("Service:", "installed but not managing the current running gateway")elif _is_termux() and not snapshot.gateway_pids:diff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.pyindex 0eeb8dd0ccd..c135f803016 100644--- a/hermes_cli/subcommands/gateway.py+++ b/hermes_cli/subcommands/gateway.py@@ -8,6 +8,13 @@ from typing import Callablefrom hermes_cli.subcommands._shared import add_accept_hooks_flag+# `start`/`restart` on a named profile refuse while the default multiplexer serves it (a second gateway+# would double-bind its platforms); `gateway run` carries its own broader --force text.+_FORCE_SERVED_PROFILE_HELP = (+ "Start a separate gateway for this profile even when the default multiplexer already serves it "+ "(not recommended: two pollers on one bot token, port conflicts)")++def _flag(parser, *names, help, **kw):parser.add_argument(*names, action="store_true", help=help, **kw)@@ -66,6 +73,7 @@ def build_gateway_parser(_add_system_flag(gateway_start)_flag(gateway_start, "--all",help="Kill ALL stale gateway processes across all profiles before starting")+ _flag(gateway_start, "--force", help=_FORCE_SERVED_PROFILE_HELP)_add_compat_platform_flag(gateway_start)gateway_stop = gateway_subparsers.add_parser("stop", help="Stop gateway service")@@ -76,6 +84,7 @@ def build_gateway_parser(_add_system_flag(gateway_restart)_flag(gateway_restart, "--all",help="Kill ALL gateway processes across all profiles before restarting")+ _flag(gateway_restart, "--force", help=_FORCE_SERVED_PROFILE_HELP)_add_compat_platform_flag(gateway_restart)gateway_status = gateway_subparsers.add_parser("status", help="Show gateway status")@@ -87,7 +96,8 @@ def build_gateway_parser(gateway_install = gateway_subparsers.add_parser("install", help="Install gateway as a systemd/launchd background service")- _flag(gateway_install, "--force", help="Force reinstall")+ _flag(gateway_install, "--force",+ help="Force reinstall, and install even when the default multiplexer already serves this profile")_flag(gateway_install, "--system",help="Install as a Linux system-level service (starts at boot)")gateway_install.add_argument("--run-as-user", dest="run_as_user",diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.pyindex 1bfe78043db..c3fc4a15af4 100644--- a/hermes_cli/web_routers/ops.py+++ b/hermes_cli/web_routers/ops.py@@ -250,6 +250,15 @@ async def set_webhook_enabled(name: str, body: WebhookEnabledToggle):@router.post("/api/gateway/start")async def start_gateway(profile: Optional[str] = None):+ from hermes_cli.gateway import named_profile_served_by_running_multiplexer+ # The spawned `hermes -p X gateway start` would refuse with exit 78 into an action log nobody reads;+ # surface the same refusal here so the UI can point at the multiplexer instead of showing "started".+ if profile and profile != "default" and await asyncio.to_thread(named_profile_served_by_running_multiplexer, profile):+ raise HTTPException(+ status_code=409,+ detail=f"The default gateway already serves profile '{profile}' as a multiplexer; "+ "restart it from the default profile instead of starting a separate gateway.",+ )with http_failure("Failed to spawn gateway start", 500, "Failed to start gateway"):proc = _spawn_hermes_action(_gateway_subcommand(profile, "start"), "gateway-start")return {"ok": True, "pid": proc.pid, "name": "gateway-start"}diff --git a/tests/gateway/test_multiplex_secondary_port_binding_env.py b/tests/gateway/test_multiplex_secondary_port_binding_env.pynew file mode 100644index 00000000000..80479702912--- /dev/null+++ b/tests/gateway/test_multiplex_secondary_port_binding_env.py@@ -0,0 +1,59 @@+"""A secondary profile's port-binding credential wires the key without claiming the listener (#100397).++The docs require ``API_SERVER_KEY`` in a secondary's ``.env`` for ``/p/<profile>/`` auth, yet the env pass+turned it into ``api_server.enabled = True`` and ``_load_secondary_profile_config`` skipped the whole profile.+"""++from __future__ import annotations++import pytest+++def multiplex_root(tmp_path, monkeypatch):+ root = tmp_path / "hermes"+ (root / "profiles" / "coder").mkdir(parents=True)+ (root / "config.yaml").write_text("model: {default: x}\n")+ (root / "profiles" / "coder" / "config.yaml").write_text("model: {default: x}\n")+ (root / "profiles" / "coder" / ".env").write_text("API_SERVER_KEY=abcdefghijklmnopqrstuvwxyz123456\n")+ monkeypatch.setenv("HERMES_HOME", str(root))+ monkeypatch.delenv("API_SERVER_KEY", raising=False)+ import hermes_constants+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)+ from agent import secret_scope+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)+ return root+++def _api_server(home):+ from gateway.config import Platform, load_gateway_config+ from gateway.run import _profile_runtime_scope+ with _profile_runtime_scope(home):+ return load_gateway_config().platforms.get(Platform.API_SERVER)+++def test_secondary_api_server_key_wires_key_but_does_not_enable_listener(multiplex_root):+ pc = _api_server(multiplex_root / "profiles" / "coder")+ assert pc is not None and pc.extra.get("key")+ assert pc.enabled is False+++def test_default_profile_api_server_key_still_enables_listener(multiplex_root):+ (multiplex_root / ".env").write_text("API_SERVER_KEY=abcdefghijklmnopqrstuvwxyz123456\n")+ pc = _api_server(multiplex_root)+ assert pc is not None and pc.enabled is True and pc.extra.get("key")+++ ("cmdline", "expected"),+ [+ ("/v/python -m hermes_cli.main -p ops-2 gateway run", False),+ ("/v/python -m hermes_cli.main --profile ops2 gateway run", False),+ ("/v/python -m hermes_cli.main -p ops gateway run", True),+ ("/v/python -m hermes_cli.main --profile=ops gateway run", True),+ ],+)+def test_profile_match_is_token_equality_not_substring(tmp_path, cmdline, expected):+ """``-p ops`` must never claim (or let ``gateway stop`` SIGTERM) an ``-p ops-2`` gateway."""+ from gateway.status import _command_line_belongs_to_profile+ assert _command_line_belongs_to_profile(cmdline, tmp_path / "profiles" / "ops") is expecteddiff --git a/tests/hermes_cli/test_gateway_multiplex_served_record.py b/tests/hermes_cli/test_gateway_multiplex_served_record.pynew file mode 100644index 00000000000..e77e22cc651--- /dev/null+++ b/tests/hermes_cli/test_gateway_multiplex_served_record.py@@ -0,0 +1,96 @@+"""The live multiplexer's recorded ``served_profiles`` decides "served"; every start verb honours it.++- Probe: ``named_profile_served_by_running_multiplexer`` reads the pid-verified default+ ``gateway_state.json`` first (env-only opt-in on the default profile is invisible to ``hermes -p X``);+ config/env derivation is only the fallback when the key is absent.+- ``gateway start`` / ``install`` / ``restart`` refuse (exit 78) like ``run`` does, so a served profile+ never gets a permanently failing systemd unit or a launchd respawn loop; ``--force`` overrides.+- ``hermes status`` / ``cron status`` on a satellite say running-via-multiplexer; the default lists served.+"""++from __future__ import annotations++import argparse+import contextlib+import io+import json+import os++import pytest+++def served_root(tmp_path, monkeypatch):+ root = tmp_path / "hermes"+ (root / "profiles" / "coder").mkdir(parents=True)+ (root / "profiles" / "other").mkdir(parents=True)+ (root / "config.yaml").write_text("model: {default: x}\n") # NO multiplex flag: env-only opt-in+ (root / "gateway.pid").write_text(json.dumps({"pid": os.getpid(), "hermes_home": str(root)}))+ (root / "gateway_state.json").write_text(json.dumps(+ {"pid": os.getpid(), "hermes_home": str(root), "served_profiles": ["default", "coder"]}))+ monkeypatch.setenv("HERMES_HOME", str(root / "profiles" / "coder"))+ monkeypatch.delenv("GATEWAY_MULTIPLEX_PROFILES", raising=False)+ import hermes_constants+ monkeypatch.setattr(hermes_constants, "_default_hermes_root_memo", None)+ return root+++def test_probe_trusts_live_record_over_cli_side_config(served_root):+ from hermes_cli.gateway import named_profile_served_by_running_multiplexer+ assert named_profile_served_by_running_multiplexer("coder") is True+ assert named_profile_served_by_running_multiplexer("other") is False+ # Config says multiplex on, but the running gateway did not pick up 'other': the record wins.+ (served_root / "config.yaml").write_text("gateway: {multiplex_profiles: true}\n")+ assert named_profile_served_by_running_multiplexer("other") is False+++def test_probe_falls_back_to_config_only_without_recorded_key(served_root):+ from hermes_cli.gateway import named_profile_served_by_running_multiplexer+ (served_root / "gateway_state.json").write_text(json.dumps({"pid": os.getpid()}))+ assert named_profile_served_by_running_multiplexer("coder") is False+ (served_root / "config.yaml").write_text("gateway: {multiplex_profiles: true}\n")+ assert named_profile_served_by_running_multiplexer("coder") is True++[email protected]("verb", ["start", "install", "restart"])+def test_service_verbs_refuse_served_profile_with_exit_78(served_root, monkeypatch, verb):+ import hermes_cli.gateway as gw+ calls: list = []+ monkeypatch.setattr(gw, "_service_backend", lambda: "systemd")+ monkeypatch.setattr(gw, "_service_call", lambda backend, v, system: calls.append(v))+ monkeypatch.setattr(gw, "_install_systemd_from_cli", lambda *a, **k: calls.append("install"))+ monkeypatch.setattr(gw, "_dispatch_via_service_manager_if_s6", lambda v: False)+ monkeypatch.setattr(gw, "_installed_service_kind_for", lambda *a, **k: "systemd")+ monkeypatch.setattr(gw, "is_managed", lambda: False)+ monkeypatch.setattr(gw, "is_termux", lambda: False)+ fn = getattr(gw, f"_cmd_{verb}")+ ns = argparse.Namespace(system=False, all=False, force=False, run_as_user=None)+ with contextlib.redirect_stdout(io.StringIO()), pytest.raises(SystemExit) as exc:+ fn(ns)+ assert exc.value.code == gw.GATEWAY_FATAL_CONFIG_EXIT_CODE and calls == []++ ns.force = True+ with contextlib.redirect_stdout(io.StringIO()):+ fn(ns)+ assert calls, f"--force must let `gateway {verb}` reach the service manager"+++def test_status_surfaces_agree_for_a_satellite_profile(served_root, monkeypatch):+ import hermes_cli.gateway as gw+ import hermes_cli.status as st+ import hermes_cli.cron as cr+ monkeypatch.setattr(gw, "find_gateway_pids", lambda *a, **k: [])+ monkeypatch.setattr(gw, "get_gateway_runtime_snapshot",+ lambda system=False: gw.GatewayRuntimeSnapshot(manager="systemd (user)"))+ monkeypatch.setattr(cr, "_active_cron_provider_name", lambda: "builtin")+ monkeypatch.setattr(cr, "_print_active_jobs_summary", lambda jobs: None)++ buf = io.StringIO()+ with contextlib.redirect_stdout(buf):+ st._render_gateway(None)+ assert "running" in buf.getvalue() and "multiplexer" in buf.getvalue()++ buf = io.StringIO()+ with contextlib.redirect_stdout(buf):+ cr.cron_status()+ assert "NOT fire" not in buf.getvalue() and "multiplexer" in buf.getvalue()diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.mdindex e2d09a49b9a..0afd4f1cb64 100644--- a/website/docs/user-guide/multi-profile-gateways.md+++ b/website/docs/user-guide/multi-profile-gateways.md@@ -115,19 +115,29 @@ moment the flag is off.#### 1. Secondary profiles must not start their own gateway-With a multiplexer running, a named-profile `hermes gateway start` / `run` is a-**hard error**, pointing you back at the multiplexer:+With a multiplexer running, a named-profile `hermes gateway run`, `start`,+`install` or `restart` is a **hard error** (exit code 78), pointing you back at+the multiplexer:```The default gateway is running as a profile multiplexer and already servesprofile 'coder'. ...```+The refusal happens in the CLI before any service manager is touched, so a served+profile never ends up with a permanently failed systemd unit or a launchd respawn+loop. The Desktop app's per-profile "Start gateway" action is refused the same way.+"Served" is read from the running gateway's own record (`served_profiles` in the+default home's `gateway_state.json`), so it stays correct when the multiplexer was+enabled only through `GATEWAY_MULTIPLEX_PROFILES` in the default profile's+environment, or when the allowlist was edited after the gateway started.+The multiplexer is the single inbound process; a second profile gateway would-double-bind that profile's platforms. Pass `--force` only if you deliberately-want a separate process for that profile (not recommended while the multiplexer-is running). The cross-profile lifecycle wrapper script earlier on this page is-therefore **not** used in multiplex mode — you only manage the default gateway.+double-bind that profile's platforms. Pass `--force` (accepted by `run`, `start`,+`install` and `restart`) only if you deliberately want a separate process for that+profile (not recommended while the multiplexer is running). The cross-profile+lifecycle wrapper script earlier on this page is therefore **not** used in+multiplex mode — you only manage the default gateway.#### 2. HTTP-inbound platforms are reached via a `/p/<profile>/` URL prefix@@ -164,7 +174,11 @@ Authentication follows the profile named in the URL. Unprefixed endpoints keepusing the default listener's existing credentials.- `/p/coder/...` API-server requests must use `API_SERVER_KEY` from- `~/.hermes/profiles/coder/.env`; the default listener key is rejected.+ `~/.hermes/profiles/coder/.env`; the default listener key is rejected. Under+ the multiplexer that key only authenticates the prefix — it does not turn on a+ second `api_server` listener in the secondary profile (which would otherwise be+ the port-binding conflict described below), so you do not need to pin+ `platforms.api_server.enabled: false` in the secondary's `config.yaml`.- A webhook route that targets `coder` must declare `profile: coder` besideits existing route-specific `secret` in the default profile's`config.yaml`. That secret is then accepted only at@@ -224,10 +238,13 @@ parent conversation.#### 5. One PID/lock and one status surfaceThere is a single process-level PID and lock (the multiplexer, under the default-home). `hermes status` reports the multiplexer and the profiles it serves;-`hermes status -p <name>` slices to one profile. Each profile still writes its-own `runtime_status.json` under its own home, so existing per-profile readers-keep working.+home). `hermes status` on the default profile reports the multiplexer and lists+the profiles it serves (`Serves: coder, research`); `hermes -p coder status`,+`hermes -p coder gateway status` and `hermes -p coder cron status` all report+"running via the default-profile multiplexer" instead of "stopped". The single+`gateway_state.json` lives under the default home: secondary adapters appear+there as `<profile>:<platform>` entries beside `served_profiles`; nothing is+written under a secondary profile's home.#### What does **not** change