Skip to content

The agent that grows with you

fix(gateway): a Desktop-started macOS gateway keeps LAN access after Desktop quits

Tekniumb5a73d46a08c
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index b75e3d0f3a9..e845b118506 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -1098,6 +1098,7 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: b
_WINDOWS_GATEWAY_BREAKAWAY_ENV, pid_exists_stdlib, windows_detach_flags,
windows_detach_flags_without_breakaway,
)
+ from hermes_cli.gateway_launchd_runtime import start_gateway_job
pid = int(sys.argv[1])
cmd = sys.argv[2:]
@@ -1110,9 +1111,8 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: b
break
time.sleep(0.2)
- # Route the respawned gateway's stray stdout/stderr to the same sidecar log _spawn_detached
- # uses: with DEVNULL a gateway killed moments after respawn (parent Job Object teardown when
- # breakaway is denied) left ZERO trace. Best-effort: DEVNULL when the log dir is unavailable.
+ # Respawned stdout/stderr go to _spawn_detached's sidecar log: with DEVNULL a gateway killed moments
+ # after respawn (Job Object teardown when breakaway is denied) left ZERO trace. Best-effort.
_stdio_target = subprocess.DEVNULL
_stdio_fh = None
try:
@@ -1125,13 +1125,10 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: b
except Exception:
pass
- # Platform-appropriate detach for the respawned gateway: POSIX start_new_session (setsid);
- # Windows needs explicit creationflags. CREATE_BREAKAWAY_FROM_JOB is critical: the watcher may
- # itself sit inside a job object (Electron/Tauri parent) and without breakaway the respawned
- # gateway dies when that job tears down. See _subprocess_compat.windows_detach_flags().
+ # Detach the respawn: POSIX setsid; Windows needs CREATE_BREAKAWAY_FROM_JOB, since the watcher may sit in a job
+ # object (Electron/Tauri parent) whose teardown would otherwise kill it (_subprocess_compat.windows_detach_flags).
_popen_kwargs = {{"stdout": _stdio_target, "stderr": _stdio_target}}
- # Anchor at the stable working dir and overlay the env (VIRTUAL_ENV / PYTHONPATH /
- # HERMES_HOME) the windowless base interpreter needs to import hermes_cli. Empty on POSIX.
+ # Stable cwd + env overlay (VIRTUAL_ENV/PYTHONPATH/HERMES_HOME) the windowless interpreter needs; empty on POSIX.
if _respawn_cwd:
_popen_kwargs["cwd"] = _respawn_cwd
_base_env = {{**os.environ, **_respawn_env_overlay}}
@@ -1150,6 +1147,9 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: b
_popen_kwargs["creationflags"] = windows_detach_flags_without_breakaway()
_popen_kwargs["env"] = {{**_base_env, _WINDOWS_GATEWAY_BREAKAWAY_ENV: "0"}}
subprocess.Popen(cmd, **_popen_kwargs)
+ elif sys.platform == "darwin" and _stdio_fh and start_gateway_job(
+ cmd, env=_base_env, cwd=os.getcwd(), log_path=_log_dir / "gateway-stdio.log"):
+ pass # a launchd job: its LAN access outlives whoever ran this one
else:
if _respawn_env_overlay:
_popen_kwargs["env"] = _base_env
diff --git a/hermes_cli/gateway_launchd_runtime.py b/hermes_cli/gateway_launchd_runtime.py
new file mode 100644
index 00000000000..cc091424801
--- /dev/null
+++ b/hermes_cli/gateway_launchd_runtime.py
@@ -0,0 +1,114 @@
+"""macOS: start an unmanaged gateway as a one-off launchd job so it keeps Local Network access.
+
+Local Network Privacy attributes a process to its responsible code. A gateway that Desktop, a
+terminal or the updater starts as a plain child is attributed to that app, and once the app quits
+every surviving descendant becomes responsible for itself: a bare venv Python, which macOS denies
+with ``EHOSTUNREACH`` on any LAN connect (a model server on another machine). A job that launchd
+spawns through ``/usr/bin/osascript`` is attributed to osascript, an exempt Apple platform binary,
+for its whole life, whoever asked for it (#71206; ``gateway_launchd.launchd_program_arguments``).
+
+Nothing is installed: the plist is loaded once and deleted, it is never in ~/Library/LaunchAgents
+and has no KeepAlive, so the job never starts at login and launchd never restarts the gateway.
+Stdlib only, because the restart watcher imports this from a bare interpreter.
+"""
+from __future__ import annotations
+
+import os
+import plistlib
+import re
+import subprocess
+import time
+import uuid
+from pathlib import Path
+
+# Never ``ai.hermes.*``: that prefix is what the gateway's restart route, its control-socket
+# supervisor declaration and every fleet scan read as "an installed, KeepAlive service".
+LABEL_PREFIX = "com.nousresearch.hermes.runtime."
+_POLL_INTERVAL_S = 0.5
+
+
+def _launchctl(*args: str, timeout: float = 10) -> subprocess.CompletedProcess[str] | None:
+ try:
+ return subprocess.run(["launchctl", *args], capture_output=True, text=True, encoding="utf-8",
+ errors="replace", timeout=timeout, check=False, stdin=subprocess.DEVNULL)
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+
+
+class GatewayJob:
+ """The ``poll()``/``pid`` view of a launched job that ``ensure_gateway_runtime`` reads."""
+
+ def __init__(self, target: str):
+ self.target = target
+ self.pid: int | None = None
+ self._status: int | None = None
+ self._checked = 0.0
+
+ def poll(self) -> int | None:
+ if self._status is not None:
+ return self._status
+ if time.monotonic() - self._checked < _POLL_INTERVAL_S:
+ return None
+ self._checked = time.monotonic()
+ done = _launchctl("print", self.target, timeout=5)
+ if done is None:
+ return None
+ if done.returncode != 0:
+ self._status = 1 # the job is gone without a recorded exit
+ return self._status
+ if match := re.search(r"^\s*pid = (\d+)", done.stdout, re.MULTILINE):
+ self._record_gateway_pid(int(match.group(1)))
+ return None
+ if match := re.search(r"^\s*last exit code = (-?\d+)", done.stdout, re.MULTILINE):
+ self._status = int(match.group(1))
+ return self._status
+
+ def _record_gateway_pid(self, wrapper_pid: int) -> None:
+ # The job's own process is osascript; the gateway is its only child (the shell execs it).
+ # Its pid is what gateway_state.json names, so a startup-failure report can match it.
+ if self.pid not in (None, wrapper_pid):
+ return
+ try:
+ out = subprocess.run(["pgrep", "-P", str(wrapper_pid)], capture_output=True, text=True, encoding="utf-8",
+ timeout=5, check=False, stdin=subprocess.DEVNULL).stdout.split()
+ except (OSError, subprocess.TimeoutExpired):
+ out = []
+ self.pid = int(out[0]) if out else wrapper_pid
+
+
+def _remove_finished_jobs() -> None:
+ """Unload earlier jobs whose gateway has exited; a running one is never touched."""
+ listed = _launchctl("list")
+ for line in (listed.stdout.splitlines() if listed and listed.returncode == 0 else []):
+ fields = line.split()
+ if len(fields) == 3 and fields[0] == "-" and fields[2].startswith(LABEL_PREFIX):
+ _launchctl("remove", fields[2])
+
+
+def start_gateway_job(command: list[str], *, env: dict[str, str], cwd: str | Path,
+ log_path: str | Path) -> GatewayJob | None:
+ """Run ``command`` as a one-off job in this user's GUI launchd domain. ``None`` when launchd
+ cannot take it (no GUI session, e.g. over SSH): the caller starts it as a plain child instead."""
+ from hermes_cli.gateway_launchd import launchd_program_arguments
+ _remove_finished_jobs()
+ label = f"{LABEL_PREFIX}{uuid.uuid4().hex[:12]}"
+ target = f"gui/{os.getuid()}/{label}" # windows-footgun: ok — macOS-only module
+ log_path = Path(log_path)
+ # launchd stamps XPC_SERVICE_NAME=<label> on the job; the gateway must still read as the
+ # unsupervised process it is, or /restart would exit for a respawn no KeepAlive provides.
+ wrapped = ["/usr/bin/env", "XPC_SERVICE_NAME=0", *command]
+ plist = log_path.parent / f".{label}.plist"
+ fd = os.open(plist, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) # holds the launch env
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ plistlib.dump({
+ "Label": label,
+ "ProgramArguments": launchd_program_arguments(wrapped, log_path, log_path),
+ "EnvironmentVariables": dict(env),
+ "WorkingDirectory": str(cwd),
+ "RunAtLoad": True,
+ }, handle)
+ done = _launchctl("bootstrap", f"gui/{os.getuid()}", str(plist)) # windows-footgun: ok — macOS-only
+ finally:
+ plist.unlink(missing_ok=True)
+ return GatewayJob(target) if done is not None and done.returncode == 0 else None
diff --git a/hermes_cli/gateway_runtime_start.py b/hermes_cli/gateway_runtime_start.py
index ac185f2479f..3d675e29178 100644
--- a/hermes_cli/gateway_runtime_start.py
+++ b/hermes_cli/gateway_runtime_start.py
@@ -7,6 +7,7 @@ import subprocess
import sys
from hermes_cli._subprocess_compat import windows_detach_popen_kwargs, _WINDOWS_GATEWAY_BREAKAWAY_ENV
+from hermes_cli.gateway_launchd_runtime import GatewayJob, start_gateway_job
from hermes_cli.gateway_runtime_service import RuntimeStartError, remaining
@@ -33,7 +34,7 @@ DAEMON_STRIPPED_ENV = (
def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float, idle_exit: bool = False,
- force: bool = False) -> subprocess.Popen:
+ force: bool = False) -> subprocess.Popen | GatewayJob:
"""Request a daemon, not readiness. Refuse Windows no-breakaway fallback.
No --replace, persistence, login changes, elevation, shell, or inherited stdio.
@@ -72,6 +73,9 @@ def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float, idle_exit: b
remaining(deadline)
logs = home / "logs"
logs.mkdir(parents=True, exist_ok=True)
+ if sys.platform == "darwin": # LAN access must outlive the app that asked for the gateway
+ if job := start_gateway_job(command, env=env, cwd=root, log_path=logs / "gateway-stdio.log"):
+ return job
try:
with (logs / "gateway-stdio.log").open("ab", buffering=0) as output:
remaining(deadline)
diff --git a/tests/hermes_cli/test_gateway_launchd_runtime.py b/tests/hermes_cli/test_gateway_launchd_runtime.py
new file mode 100644
index 00000000000..f635c75aabc
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_launchd_runtime.py
@@ -0,0 +1,55 @@
+"""An unmanaged macOS gateway runs as a one-off launchd job through osascript, not as its caller's child.
+
+Local Network Privacy attributes a process to its responsible app; a gateway left running after the
+app that started it quits becomes responsible for itself and macOS refuses its LAN connects (a model
+server on another machine answers ``No route to host``). A launchd-spawned osascript stays the
+responsible code for the job's whole life (#71206).
+"""
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+from hermes_cli.gateway_launchd_runtime import start_gateway_job
+from tests.waiting import wait_until
+
+
+def _command_of(pid: int) -> str:
+ return subprocess.run(["ps", "-o", "command=", "-p", str(pid)], capture_output=True, text=True, encoding="utf-8",
+ check=False, stdin=subprocess.DEVNULL).stdout.strip()
+
+
+def test_gateway_job_is_a_launchd_osascript_child_that_reads_as_unsupervised(tmp_path):
+ report = tmp_path / "report.json"
+ release = tmp_path / "release"
+ child = (
+ "import json, os, pathlib, time; "
+ f"pathlib.Path({str(report)!r}).write_text(json.dumps({{'ppid': os.getppid(), "
+ "'xpc': os.environ.get('XPC_SERVICE_NAME'), 'marker': os.environ.get('PROBE_MARKER')}})); "
+ f"[time.sleep(0.1) for _ in range(300) if not pathlib.Path({str(release)!r}).exists()]"
+ )
+ job = start_gateway_job([sys.executable, "-c", child], env={**os.environ, "PROBE_MARKER": "env-carried"},
+ cwd=tmp_path, log_path=tmp_path / "gateway-stdio.log")
+ assert job is not None, "launchd refused the job in this user's GUI domain"
+ try:
+ assert wait_until(report.exists, timeout=30)
+ seen = json.loads(report.read_text(encoding="utf-8-sig"))
+ wrapper = seen["ppid"]
+ # The caller is not an ancestor: launchd (pid 1) spawned osascript, osascript the command.
+ assert _command_of(wrapper).startswith("/usr/bin/osascript"), _command_of(wrapper)
+ assert subprocess.run(["ps", "-o", "ppid=", "-p", str(wrapper)], capture_output=True, text=True, encoding="utf-8",
+ check=False, stdin=subprocess.DEVNULL).stdout.strip() == "1"
+ assert seen["marker"] == "env-carried"
+ # Read as unsupervised, or /restart would exit for a respawn no KeepAlive provides.
+ assert seen["xpc"] == "0"
+ assert not list(tmp_path.glob(".*.plist")), "the plist holding the launch env must not stay on disk"
+ assert job.poll() is None
+ finally:
+ release.write_text("", encoding="utf-8")
+ assert wait_until(lambda: job.poll() is not None, timeout=30)
+ assert job.poll() == 0
diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.md
index d194653a40c..3bef1150036 100644
--- a/website/docs/user-guide/messaging/index.md
+++ b/website/docs/user-guide/messaging/index.md
@@ -682,6 +682,8 @@ The plist sets `RunAtLoad`, so loading it starts the gateway. `hermes gateway in
:::info Local Network access (LAN devices fail with "No route to host")
macOS Local Network Privacy attributes a socket to the executable launchd spawned for the job. A bare venv Python has no application identity, so a launchd-run gateway could not reach LAN hosts (Home Assistant, local model servers) — every connect failed with `errno 65 No route to host` while the same URL worked from Terminal, and no prompt was ever shown to grant it. The generated plist therefore runs the gateway through `/usr/bin/osascript`; a JXA `system()` call starts the gateway without an interactive event-polling loop, and macOS treats its children as osascript's own — an Apple platform binary, exempt from the check. `ps` shows `osascript → stderr_timestamp → gateway run`; stop/restart/KeepAlive behave exactly as before. A plist installed by an older Hermes is refreshed by `hermes gateway install` (or on the next `hermes gateway start`).
+
+Without an installed service, the gateway Hermes starts for you (Hermes Desktop, a chat or TUI client, or the restart after `hermes update`) runs the same way, as a one-off launchd job labelled `com.nousresearch.hermes.runtime.<id>`. A plain child process would lose LAN access as soon as the app that started it quits: macOS then holds the gateway itself responsible, and denies it. The one-off job is never installed in `~/Library/LaunchAgents`, never starts at login and is never restarted by launchd. Because osascript is the responsible app, macOS file-access prompts for that gateway (Documents, Downloads, …) name **osascript**, not Hermes.
:::
:::tip Picking up new credentials after `hermes auth add` / `hermes auth reset`