Skip to content

The agent that grows with you

fix(gateway): scope the Local Network hint and keep the osascript wrapper out of gateway process scans

kshitijk4pooreda2432cce6c
diff --git a/gateway/status.py b/gateway/status.py
index 0302da6d419..5e986dc08f6 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -518,6 +518,10 @@ def _gateway_command_subcommand(command: str | None) -> str | None:
if not tokens:
return None
basenames = [t.rsplit("/", 1)[-1] for t in tokens]
+ # The launchd job's osascript wrapper (gateway_launchd.launchd_program_arguments) carries the gateway argv
+ # inside one AppleScript string; the gateway itself is its child and is matched on its own command line.
+ if basenames[0] == "osascript":
+ return None
# Gateway-dedicated entrypoints carry no subcommand to inspect.
if any(t == "gateway/run.py" or t.endswith("/gateway/run.py") for t in tokens):
return "run"
diff --git a/hermes_cli/gateway_launchd.py b/hermes_cli/gateway_launchd.py
index b11eaf56353..cd60588545d 100644
--- a/hermes_cli/gateway_launchd.py
+++ b/hermes_cli/gateway_launchd.py
@@ -223,7 +223,9 @@ def launchd_program_arguments(command: list[str], stdout_log: Path, stderr_log:
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
+ so the command appends both to the same files the plist's ``StandardOutPath``/``StandardErrorPath``
+ name (those keys stay: they are where osascript's own output lands — an empty result line per exit
+ and an un-timestamped ``execution error`` line on non-zero exit); ``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).
@@ -340,10 +342,10 @@ def generate_launchd_plist() -> str:
# 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)
+ stdout_log, stderr_log = log_dir / "gateway.log", log_dir / "gateway.error.log"
+ command = _timestamped_stderr_gateway_command(stderr_log, external_supervisor=True)
prog_args_xml = "\n ".join(
- f"<string>{escape(part)}</string>"
- for part in launchd_program_arguments(command, log_dir / "gateway.log", log_dir / "gateway.error.log")
+ f"<string>{escape(part)}</string>" for part in launchd_program_arguments(command, stdout_log, stderr_log)
)
# Persist the configured RLIMIT_NOFILE floor: launchd defaults to soft 256, and every plist
@@ -424,10 +426,10 @@ def generate_launchd_plist() -> str:
<integer>60</integer>
{nofile_block}
<key>StandardOutPath</key>
- <string>{log_dir}/gateway.log</string>
+ <string>{stdout_log}</string>
<key>StandardErrorPath</key>
- <string>{log_dir}/gateway.error.log</string>
+ <string>{stderr_log}</string>
</dict>
</plist>
"""
diff --git a/plugins/platforms/homeassistant/adapter.py b/plugins/platforms/homeassistant/adapter.py
index 917f288b7b5..002e4adf872 100644
--- a/plugins/platforms/homeassistant/adapter.py
+++ b/plugins/platforms/homeassistant/adapter.py
@@ -4,8 +4,11 @@ Requires aiohttp, HASS_TOKEN (Long-Lived Access Token) and HASS_URL (default htt
"""
import asyncio
+import errno
import json
import logging
+import os
+import sys
import time
import uuid
from datetime import datetime
@@ -65,11 +68,15 @@ _TRIGGERED = ("cleared", "triggered") # binary_sensor wording, indexed by ``sta
def _connect_error_detail(exc: BaseException) -> str:
- """Annotate macOS Local Network Privacy denials so launchd HA failures are actionable (#71206)."""
+ """Annotate macOS Local Network Privacy denials so launchd HA failures are actionable (#71206).
+
+ Only a launchd-supervised gateway on macOS (``HERMES_SUPERVISED_CHILD`` is set by the generated plist)
+ can be denied this way; the same errno elsewhere is a genuinely unreachable host.
+ """
text = str(exc)
- os_error = getattr(exc, "os_error", None) or getattr(exc, "__cause__", None) or exc
- errno_val = getattr(os_error, "errno", None)
- if errno_val == 65 or "No route to host" in text or "EHOSTUNREACH" in text:
+ os_error = getattr(exc, "os_error", None) or exc.__cause__ or exc
+ if (sys.platform == "darwin" and os.environ.get("HERMES_SUPERVISED_CHILD")
+ and getattr(os_error, "errno", None) == errno.EHOSTUNREACH):
return (
f"{text} — macOS Local Network Privacy is blocking this launchd gateway from the LAN. "
"Run `hermes gateway install` to regenerate the launchd job, then `hermes gateway restart`. "
diff --git a/tests/gateway/test_homeassistant.py b/tests/gateway/test_homeassistant.py
index a52bdae2876..f1c1ce27d26 100644
--- a/tests/gateway/test_homeassistant.py
+++ b/tests/gateway/test_homeassistant.py
@@ -4,6 +4,7 @@ Tests real logic: state change formatting, event filtering pipeline,
cooldown behavior, config integration, and adapter initialization.
"""
+import errno
import time
from unittest.mock import AsyncMock, MagicMock, patch
@@ -320,12 +321,19 @@ class TestWsUrlConstruction:
class TestLocalNetworkConnectHint:
- def test_ehostunreach_names_the_launchd_remedy(self):
+ @pytest.mark.macos_only
+ def test_ehostunreach_under_launchd_names_the_remedy(self, monkeypatch):
+ """Only the launchd-supervised gateway can be denied by Local Network Privacy; the same errno from a
+ Terminal-run gateway is a genuinely unreachable host and must not be blamed on macOS (#71206)."""
from plugins.platforms.homeassistant.adapter import _connect_error_detail
- err = OSError(65, "No route to host")
+ err = OSError(errno.EHOSTUNREACH, "No route to host")
+ monkeypatch.delenv("HERMES_SUPERVISED_CHILD", raising=False)
+ assert _connect_error_detail(err) == str(err)
+
+ monkeypatch.setenv("HERMES_SUPERVISED_CHILD", "1")
detail = _connect_error_detail(err)
- assert "No route to host" in detail
+ assert detail.startswith(str(err))
assert "Local Network" in detail
assert "hermes gateway install" in detail
assert "71206" in detail
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 3e6f1ab4cff..e27048a761a 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -25,9 +25,11 @@ 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."""
+def _osascript_exec_argv(program_args: list[str]) -> list[str]:
+ """The argv a launchd ``ProgramArguments`` of ``/usr/bin/osascript -e <script>`` hands to ``exec`` —
+ undoing the AppleScript string escaping, then POSIX shell quoting, the way osascript and /bin/sh will."""
+ assert program_args[:2] == ["/usr/bin/osascript", "-e"] and len(program_args) == 3, program_args
+ script = program_args[2]
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)])
@@ -1859,8 +1861,7 @@ class TestProfileArg:
# 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]) == [
+ assert _osascript_exec_argv(program_args) == [
"/usr/bin/python3",
"-m",
"hermes_cli.stderr_timestamp",
@@ -1891,10 +1892,12 @@ class TestProfileArg:
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])
+ argv = _osascript_exec_argv(program_args)
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")]
+ # The wrapper's own ps line must never be taken for the gateway (stop/status would signal osascript).
+ assert status.looks_like_gateway_command_line(" ".join(program_args)) is False
def test_launchd_plist_path_uses_real_user_home_not_profile_home(self, tmp_path, monkeypatch):
profile_dir = tmp_path / ".hermes" / "profiles" / "orcha"
@@ -2610,7 +2613,7 @@ class TestServiceTakeoverGovernance:
# 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 (inside the osascript wrapper).
- argv = _osascript_exec_argv(plistlib.loads(plist.encode("utf-8"))["ProgramArguments"][2])
+ argv = _osascript_exec_argv(plistlib.loads(plist.encode("utf-8"))["ProgramArguments"])
assert argv[argv.index("gateway") + 1] == "run"
assert "<key>KeepAlive</key>" in plist
assert "<true/>" in plist