The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): launchd gateway reaches the local network on macOS (#71206, #57812)
kshitijk4poor5d63d3e5c502
diff --git a/hermes_cli/gateway_launchd.py b/hermes_cli/gateway_launchd.pyindex 209fc3b5667..b11eaf56353 100644--- a/hermes_cli/gateway_launchd.py+++ b/hermes_cli/gateway_launchd.py@@ -14,6 +14,7 @@ import shleximport subprocessimport sysimport time+from xml.sax.saxutils import escapedef _gw():@@ -211,6 +212,27 @@ def _gateway_run_command() -> list[str]:return [_gw().get_python_path(), "-m", "hermes_cli.main", *_gw()._profile_arg().split(), "gateway", "run", "--replace"]+def launchd_program_arguments(command: list[str], stdout_log: Path, stderr_log: Path) -> list[str]:+ """launchd ``ProgramArguments`` that run ``command`` with a Local Network identity macOS accepts (#71206).++ macOS Local Network Privacy attributes a socket to the process launchd spawned for the job. A bare+ venv Python has no application ID and is not platform-entitled, so every LAN connect from the+ launchd gateway dies with ``EHOSTUNREACH`` while the same code works from Terminal (whose grant it+ inherits). An ad-hoc-signed helper .app does not help: nehelper never prompts for it and denies+ (#57812 dead-end table, re-verified live on macOS 26.3). ``/usr/bin/osascript``'s ``do shell script``+ spawns its child as osascript-responsible — an Apple platform binary — so the child is exempt;+ ``/bin/sh -c exec …`` and ``/usr/bin/time`` wrappers are NOT (the launchd job identity is the+ non-entitled first executable). ``do shell script`` buffers the child's stdout/stderr until it exits,+ so the command redirects both to the log files the plist would otherwise route; ``exec`` keeps the+ gateway a direct child in the job's process group, so ``launchctl bootout`` / ``kickstart -k`` still+ deliver SIGTERM to it and KeepAlive's ``SuccessfulExit`` semantics are preserved (osascript exits 0+ exactly when the shell did).+ """+ shell = f"exec {shlex.join(command)} >> {shlex.quote(str(stdout_log))} 2>> {shlex.quote(str(stderr_log))}"+ applescript = shell.replace("\\", "\\\\").replace('"', '\\"')+ return ["/usr/bin/osascript", "-e", f'do shell script "{applescript}"']++def _timestamped_stderr_gateway_command(error_log: Path, *, external_supervisor: bool = False) -> list[str]:"""Wrap gateway run so raw stderr lines are timestamped before file write. ``external_supervisor``(launchd ProgramArguments only) adds ``--external-supervisor`` so ``hermes update`` hands back to@@ -316,10 +338,12 @@ def generate_launchd_plist() -> str:_gw()._append_node_dir_for_service(priority_dirs)sane_path = ":".join(dict.fromkeys(priority_dirs + [p for p in os.environ.get("PATH", "").split(":") if p]))- # ProgramArguments (incl. --profile); the stderr wrapper keeps launchd restart semantics while timestamping stderr.+ # ProgramArguments (incl. --profile); the stderr wrapper keeps launchd restart semantics while timestamping+ # stderr; the osascript wrapper gives the job a Local Network identity (see launchd_program_arguments).+ command = _timestamped_stderr_gateway_command(log_dir / "gateway.error.log", external_supervisor=True)prog_args_xml = "\n ".join(- f"<string>{part}</string>"- for part in _timestamped_stderr_gateway_command(log_dir / "gateway.error.log", external_supervisor=True)+ f"<string>{escape(part)}</string>"+ for part in launchd_program_arguments(command, log_dir / "gateway.log", log_dir / "gateway.error.log"))# Persist the configured RLIMIT_NOFILE floor: launchd defaults to soft 256, and every plistdiff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.pyindex 72798684e26..3e6f1ab4cff 100644--- a/tests/hermes_cli/test_gateway_service.py+++ b/tests/hermes_cli/test_gateway_service.py@@ -2,6 +2,8 @@import osimport plistlib+import re+import shleximport subprocessfrom pathlib import Pathfrom types import SimpleNamespace@@ -23,6 +25,17 @@ from gateway.restart import ()+def _osascript_exec_argv(script: str) -> list[str]:+ """The argv ``/usr/bin/osascript -e <script>`` hands to ``exec`` — undoing the AppleScript string+ escaping, then POSIX shell quoting, the way osascript and /bin/sh will."""+ prefix, suffix = 'do shell script "', '"'+ assert script.startswith(prefix) and script.endswith(suffix), script+ shell = re.sub(r"\\(.)", r"\1", script[len(prefix):-len(suffix)])+ exec_, *argv = shlex.split(shell)+ assert exec_ == "exec", shell+ return argv++class TestUserSystemdPrivateSocketPreflight:def test_preflight_accepts_private_socket_without_dbus_bus(self, monkeypatch):monkeypatch.setattr(gateway_cli, "_ensure_user_systemd_env", lambda: None)@@ -1844,7 +1857,10 @@ class TestProfileArg:plist = gateway_cli.generate_launchd_plist()program_args = plistlib.loads(plist.encode("utf-8"))["ProgramArguments"]- assert program_args == [+ # The job is launched through osascript so macOS Local Network Privacy attributes the+ # gateway's sockets to a platform binary (#71206); the real command is the exec'd child.+ assert program_args[:2] == ["/usr/bin/osascript", "-e"]+ assert _osascript_exec_argv(program_args[2]) == ["/usr/bin/python3","-m","hermes_cli.stderr_timestamp",@@ -1859,8 +1875,27 @@ class TestProfileArg:"gateway","run","--external-supervisor",+ ">>",+ str(profile_dir / "logs" / "gateway.log"),+ "2>>",+ str(profile_dir / "logs" / "gateway.error.log"),]+ def test_launchd_osascript_wrapper_round_trips_shell_hostile_paths(self, tmp_path, monkeypatch):+ """A home with spaces, quotes and a backslash survives shlex + AppleScript + plist quoting."""+ profile_dir = tmp_path / 'my "odd" dir \\ here' / ".hermes"+ profile_dir.mkdir(parents=True)+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(profile_dir))+ monkeypatch.setattr(gateway_cli, "get_hermes_home", lambda: profile_dir)+ monkeypatch.setattr(gateway_cli, "get_python_path", lambda: str(profile_dir / "bin dir" / "python"))++ program_args = plistlib.loads(gateway_cli.generate_launchd_plist().encode("utf-8"))["ProgramArguments"]+ argv = _osascript_exec_argv(program_args[2])++ assert argv[0] == str(profile_dir / "bin dir" / "python")+ assert argv[-3:] == [str(profile_dir / "logs" / "gateway.log"), "2>>", str(profile_dir / "logs" / "gateway.error.log")]+def test_launchd_plist_path_uses_real_user_home_not_profile_home(self, tmp_path, monkeypatch):profile_dir = tmp_path / ".hermes" / "profiles" / "orcha"profile_dir.mkdir(parents=True)@@ -2574,9 +2609,9 @@ class TestServiceTakeoverGovernance:plist = gateway_cli.generate_launchd_plist()# The whole bug class: no --replace anywhere in the supervised argv.assert "--replace" not in plist- # It still runs the plain gateway command under KeepAlive.- assert "<string>gateway</string>" in plist- assert "<string>run</string>" in plist+ # It still runs the plain gateway command under KeepAlive (inside the osascript wrapper).+ argv = _osascript_exec_argv(plistlib.loads(plist.encode("utf-8"))["ProgramArguments"][2])+ assert argv[argv.index("gateway") + 1] == "run"assert "<key>KeepAlive</key>" in plistassert "<true/>" in plistdiff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.mdindex 5cb9bf41be8..4df31e92783 100644--- a/website/docs/user-guide/messaging/index.md+++ b/website/docs/user-guide/messaging/index.md@@ -667,6 +667,10 @@ The generated plist lives at `~/Library/LaunchAgents/ai.hermes.gateway.plist`. Ilaunchd plists are static — if you install new tools (e.g. a new Node.js version via nvm, or ffmpeg via Homebrew) after setting up the gateway, run `hermes gateway install` again to capture the updated PATH. The gateway will detect the stale plist and reload automatically.:::+:::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` (`do shell script "exec …"`), whose children macOS treats 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`).+:::+:::tip Picking up new credentials after `hermes auth add` / `hermes auth reset`Agents run as threads inside the one gateway process; the only child processes are tool subprocesses (terminal commands, browsers), which never hold provider credentials. A running gateway also re-reads the `openai-codex` login it seeded from `auth.json` the next time its pool selects that entry after it had gone `exhausted` or `dead` (entries added with `hermes auth add openai-codex` are independent accounts and are not resynced). When you want every session on the fresh login at once, restart the gateway — but prefer the drain-aware path over a bare kill: