gateway_launchd_runtime.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. """macOS: start an unmanaged gateway as a one-off launchd job so it keeps Local Network access.
  2. Local Network Privacy attributes a process to its responsible code. A gateway that Desktop, a
  3. terminal or the updater starts as a plain child is attributed to that app, and once the app quits
  4. every surviving descendant becomes responsible for itself: a bare venv Python, which macOS denies
  5. with ``EHOSTUNREACH`` on any LAN connect (a model server on another machine). A job that launchd
  6. spawns through ``/usr/bin/osascript`` is attributed to osascript, an exempt Apple platform binary,
  7. for its whole life, whoever asked for it (#71206; ``gateway_launchd.launchd_program_arguments``).
  8. Nothing is installed: the plist is loaded once and deleted, it is never in ~/Library/LaunchAgents
  9. and has no KeepAlive, so the job never starts at login and launchd never restarts the gateway.
  10. Stdlib only, because the restart watcher imports this from a bare interpreter.
  11. """
  12. from __future__ import annotations
  13. import os
  14. import plistlib
  15. import re
  16. import subprocess
  17. import time
  18. import uuid
  19. from pathlib import Path
  20. # Never ``ai.hermes.*``: that prefix is what the gateway's restart route, its control-socket
  21. # supervisor declaration and every fleet scan read as "an installed, KeepAlive service".
  22. LABEL_PREFIX = "com.nousresearch.hermes.runtime."
  23. _POLL_INTERVAL_S = 0.5
  24. def _budget(deadline: float | None, cap: float) -> float:
  25. """``cap`` seconds, never past the caller's startup deadline (0 once it has passed)."""
  26. return cap if deadline is None else max(0.0, min(cap, deadline - time.monotonic()))
  27. def _launchctl(*args: str, timeout: float) -> subprocess.CompletedProcess[str] | None:
  28. if timeout <= 0:
  29. return None
  30. try:
  31. return subprocess.run(["launchctl", *args], capture_output=True, text=True, encoding="utf-8",
  32. errors="replace", timeout=timeout, check=False, stdin=subprocess.DEVNULL)
  33. except (OSError, subprocess.TimeoutExpired):
  34. return None
  35. class GatewayJob:
  36. """The ``poll()``/``pid`` view of a launched job that ``ensure_gateway_runtime`` reads."""
  37. def __init__(self, target: str, deadline: float | None):
  38. self.target = target
  39. self._deadline = deadline
  40. self.pid: int | None = None
  41. self._status: int | None = None
  42. self._checked = 0.0
  43. def poll(self) -> int | None:
  44. if self._status is not None:
  45. return self._status
  46. if time.monotonic() - self._checked < _POLL_INTERVAL_S:
  47. return None
  48. self._checked = time.monotonic()
  49. done = _launchctl("print", self.target, timeout=_budget(self._deadline, 5))
  50. if done is None:
  51. return None
  52. if done.returncode != 0:
  53. self._status = 1 # the job is gone without a recorded exit
  54. return self._status
  55. if match := re.search(r"^\s*pid = (\d+)", done.stdout, re.MULTILINE):
  56. self._record_gateway_pid(int(match.group(1)))
  57. return None
  58. if match := re.search(r"^\s*last exit code = (-?\d+)", done.stdout, re.MULTILINE):
  59. self._status = int(match.group(1))
  60. return self._status
  61. def _record_gateway_pid(self, wrapper_pid: int) -> None:
  62. # The job's own process is osascript; the gateway is its only child (the shell execs it).
  63. # Its pid is what gateway_state.json names, so a startup-failure report can match it.
  64. if self.pid not in (None, wrapper_pid) or not (timeout := _budget(self._deadline, 5)):
  65. return
  66. try:
  67. out = subprocess.run(["pgrep", "-P", str(wrapper_pid)], capture_output=True, text=True, encoding="utf-8",
  68. timeout=timeout, check=False, stdin=subprocess.DEVNULL).stdout.split()
  69. except (OSError, subprocess.TimeoutExpired):
  70. out = []
  71. self.pid = int(out[0]) if out else wrapper_pid
  72. def _remove_finished_jobs(deadline: float | None) -> None:
  73. """Unload earlier jobs whose gateway has exited; a running one is never touched."""
  74. listed = _launchctl("list", timeout=_budget(deadline, 10))
  75. for line in (listed.stdout.splitlines() if listed and listed.returncode == 0 else []):
  76. fields = line.split()
  77. if len(fields) == 3 and fields[0] == "-" and fields[2].startswith(LABEL_PREFIX):
  78. _launchctl("remove", fields[2], timeout=_budget(deadline, 10))
  79. def start_gateway_job(command: list[str], *, env: dict[str, str], cwd: str | Path,
  80. log_path: str | Path, deadline: float | None = None) -> GatewayJob | None:
  81. """Run ``command`` as a one-off job in this user's GUI launchd domain. ``None`` when launchd
  82. cannot take it (no GUI session, e.g. over SSH): the caller starts it as a plain child instead.
  83. ``deadline`` (monotonic) bounds every launchctl call, here and in the job's ``poll()``."""
  84. from hermes_cli.gateway_launchd import launchd_program_arguments
  85. _remove_finished_jobs(deadline)
  86. label = f"{LABEL_PREFIX}{uuid.uuid4().hex[:12]}"
  87. target = f"gui/{os.getuid()}/{label}" # windows-footgun: ok — macOS-only module
  88. log_path = Path(log_path)
  89. # launchd stamps XPC_SERVICE_NAME=<label> on the job; the gateway must still read as the
  90. # unsupervised process it is, or /restart would exit for a respawn no KeepAlive provides.
  91. wrapped = ["/usr/bin/env", "XPC_SERVICE_NAME=0", *command]
  92. plist = log_path.parent / f".{label}.plist"
  93. fd = os.open(plist, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) # holds the launch env
  94. try:
  95. with os.fdopen(fd, "wb") as handle:
  96. plistlib.dump({
  97. "Label": label,
  98. "ProgramArguments": launchd_program_arguments(wrapped, log_path, log_path),
  99. "EnvironmentVariables": dict(env),
  100. "WorkingDirectory": str(cwd),
  101. "RunAtLoad": True,
  102. }, handle)
  103. done = _launchctl("bootstrap", f"gui/{os.getuid()}", str(plist), # windows-footgun: ok — macOS-only
  104. timeout=_budget(deadline, 10))
  105. finally:
  106. plist.unlink(missing_ok=True)
  107. return GatewayJob(target, deadline) if done is not None and done.returncode == 0 else None