Skip to content

The agent that grows with you

fix(gateway): resolve the launchd drain cap's job label through the wrapper

liuhao1024fa34336c92ff
diff --git a/gateway/restart.py b/gateway/restart.py
index 720053590cf..160dae4ba22 100644
--- a/gateway/restart.py
+++ b/gateway/restart.py
@@ -36,6 +36,11 @@ def map_fatal_config_exit_for_launchd(returncode: int) -> int:
# environment (e.g. ``sudo env -i``).
EXTERNAL_GATEWAY_SUPERVISOR_ENV = "HERMES_GATEWAY_EXTERNAL_SUPERVISOR"
+# Re-exported by the stderr-timestamp launchd wrapper (hermes_cli/stderr_timestamp.py).
+# launchd stamps ``XPC_SERVICE_NAME`` only on the wrapper itself; the gateway grandchild
+# sees ``XPC_SERVICE_NAME=0`` and would otherwise be invisible to the drain cap.
+LAUNCHD_LABEL_ENV = "HERMES_LAUNCHD_LABEL"
+
DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT = float(DEFAULT_CONFIG["agent"]["restart_drain_timeout"])
DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT = float(DEFAULT_CONFIG["gateway"]["signal_interrupt_grace_timeout"])
DEFAULT_GATEWAY_POST_INTERRUPT_GRACE_TIMEOUT = 5.0
@@ -93,13 +98,22 @@ def launchd_service_label(environ: Mapping[str, str] | None = None) -> str | Non
populate ``XPC_SERVICE_NAME``, and ``launchctl print`` reports
``exit timeout = 1`` for them — treating those as a budget would cap the
drain to 0 for a gateway Ctrl+C'd in such a terminal.
+
+ When this process is a launchd grandchild (the generated plist runs the
+ stderr-timestamp wrapper as the job process), ``XPC_SERVICE_NAME`` reads
+ ``"0"`` and the wrapper's re-exported ``HERMES_LAUNCHD_LABEL`` is used.
"""
if sys.platform != "darwin":
return None
env = os.environ if environ is None else environ
label = str(env.get("XPC_SERVICE_NAME", "") or "").strip()
if not label.startswith("ai.hermes"):
- return None
+ # Under the generated launchd plist the gateway is a grandchild (the stderr-timestamp
+ # wrapper is the job process), so XPC_SERVICE_NAME reads "0" here; the wrapper
+ # re-exports the real job label for exactly this fallback.
+ label = str(env.get(LAUNCHD_LABEL_ENV, "") or "").strip()
+ if not label.startswith("ai.hermes"):
+ return None
return label
diff --git a/hermes_cli/stderr_timestamp.py b/hermes_cli/stderr_timestamp.py
index a4f24b6d153..04bcd72f4eb 100644
--- a/hermes_cli/stderr_timestamp.py
+++ b/hermes_cli/stderr_timestamp.py
@@ -15,6 +15,9 @@ from typing import BinaryIO, Sequence, TextIO
EXTERNAL_SUPERVISOR_FLAG = "--external-supervisor"
+# gateway/restart.py reads this to size the stop drain to the job's live ExitTimeOut.
+LAUNCHD_LABEL_ENV = "HERMES_LAUNCHD_LABEL"
+
_TIMESTAMP_PREFIX = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}(?:\s|$)")
@@ -85,6 +88,22 @@ def _is_hermes_gateway_run_argv(command: Sequence[str]) -> bool:
return bool(looks_like_gateway_command_line(" ".join(str(part) for part in command)))
+def _child_launchd_label_env(environ: Mapping[str, str] | None = None) -> dict[str, str]:
+ """Env vars that carry this wrapper's launchd identity to the grandchild.
+
+ launchd stamps ``XPC_SERVICE_NAME=<job label>`` only on this wrapper (its direct child; an
+ interactive shell has none, the grandchild sees ``XPC_SERVICE_NAME=0``). Re-exporting the
+ label lets the gateway resolve its job without it (e.g. the stop-drain cap reading the
+ live ``ExitTimeOut`` in gateway/restart.py). Only ``ai.hermes.*`` labels are exported;
+ app-coalition labels are meaningless as a job identity.
+ """
+ env = os.environ if environ is None else environ
+ label = str(env.get("XPC_SERVICE_NAME", "") or "").strip()
+ if not label.startswith("ai.hermes"):
+ return {}
+ return {LAUNCHD_LABEL_ENV: label}
+
+
def _prepare_child_command(command: Sequence[str], environ: Mapping[str, str] | None = None) -> list[str]:
"""Return the argv to exec, upgrading stale launchd-wrapped gateway commands.
@@ -134,7 +153,11 @@ def main(argv: Sequence[str] | None = None) -> int:
log_path: Path = args.error_log
try:
- proc = subprocess.Popen(_prepare_child_command(args.command), stderr=subprocess.PIPE)
+ proc = subprocess.Popen(
+ _prepare_child_command(args.command),
+ stderr=subprocess.PIPE,
+ env={**os.environ, **_child_launchd_label_env()},
+ )
except OSError as exc:
with _open_log(log_path) as log_file:
_write_timestamped_line(log_file, f"failed to start stderr-timestamped command: {exc}")
diff --git a/tests/gateway/test_launchd_exit_timeout_drain_cap.py b/tests/gateway/test_launchd_exit_timeout_drain_cap.py
index e92c2c27c21..6e56f33e2c9 100644
--- a/tests/gateway/test_launchd_exit_timeout_drain_cap.py
+++ b/tests/gateway/test_launchd_exit_timeout_drain_cap.py
@@ -18,9 +18,11 @@ from types import SimpleNamespace
import pytest
from gateway.restart import (
+ LAUNCHD_LABEL_ENV,
LAUNCHD_STOP_CLEANUP_RESERVE_S,
effective_stop_drain_timeout,
effective_stop_watchdog_delay,
+ launchd_service_label,
read_launchd_exit_timeout_s,
resolve_launchd_capped_drain,
)
@@ -58,6 +60,27 @@ def test_launchd_label_leaked_onto_linux_is_ignored():
assert _read_budget("ai.hermes.gateway") is None
+def test_grandchild_resolves_label_from_wrapper_reexport(monkeypatch):
+ """Under the generated plist the gateway is a grandchild: launchd stamps XPC_SERVICE_NAME
+ only on the stderr-timestamp wrapper, the grandchild reads "0", and the wrapper re-exports
+ the job label as HERMES_LAUNCHD_LABEL so the drain cap still resolves its budget."""
+ monkeypatch.setattr(restart_mod.sys, "platform", "darwin")
+ grandchild_env = {"XPC_SERVICE_NAME": "0", LAUNCHD_LABEL_ENV: "ai.hermes.gateway"}
+
+ assert launchd_service_label(grandchild_env) == "ai.hermes.gateway"
+ # The re-export keeps the ai.hermes predicate: an app-coalition label is still not our job.
+ assert launchd_service_label({"XPC_SERVICE_NAME": "0", LAUNCHD_LABEL_ENV: "application.com.example.ide.123"}) is None
+ # No fallback at all (foreground start, or a wrapper older than the re-export) stays None.
+ assert launchd_service_label({"XPC_SERVICE_NAME": "0"}) is None
+ # A direct launchd child (no wrapper) keeps the XPC path.
+ assert launchd_service_label({"XPC_SERVICE_NAME": "ai.hermes.gateway"}) == "ai.hermes.gateway"
+
+ # End to end: the grandchild sizes its stop drain to the live ExitTimeOut.
+ fake_run = lambda *a, **k: SimpleNamespace(returncode=0, stdout="exit timeout = 60\n") # noqa: E731
+ budget = read_launchd_exit_timeout_s(environ=grandchild_env, uid=501, run=fake_run)
+ assert resolve_launchd_capped_drain(180.0, budget) == 60.0 - LAUNCHD_STOP_CLEANUP_RESERVE_S
+
+
def _runner(*, drain: float, launchd: float | None, by_signal: bool):
return SimpleNamespace(
_restart_drain_timeout=drain, _launchd_exit_timeout_s=launchd, _stop_requested_by_signal=by_signal,
diff --git a/tests/hermes_cli/test_stderr_timestamp.py b/tests/hermes_cli/test_stderr_timestamp.py
index c408aae608b..9fb4f4e3af5 100644
--- a/tests/hermes_cli/test_stderr_timestamp.py
+++ b/tests/hermes_cli/test_stderr_timestamp.py
@@ -90,6 +90,64 @@ def test_prepare_skips_interactive_xpc_zero_even_for_gateway_argv():
)
+def test_child_launchd_label_env_exports_only_hermes_job_labels():
+ assert stderr_timestamp._child_launchd_label_env(_LAUNCHD_ENV) == {
+ stderr_timestamp.LAUNCHD_LABEL_ENV: "ai.hermes.gateway-butler"
+ }
+ # Interactive shells and the grandchild itself read "0": nothing to export.
+ assert stderr_timestamp._child_launchd_label_env({"PATH": "/usr/bin", "XPC_SERVICE_NAME": "0"}) == {}
+ assert stderr_timestamp._child_launchd_label_env({"PATH": "/usr/bin"}) == {}
+ # App-coalition labels (IDE integrated terminals) are not a Hermes job identity.
+ assert (
+ stderr_timestamp._child_launchd_label_env(
+ {"PATH": "/usr/bin", "XPC_SERVICE_NAME": "application.com.example.ide.123"}
+ )
+ == {}
+ )
+
+
+def test_main_exports_launchd_label_to_child(tmp_path, monkeypatch):
+ """The gateway grandchild must resolve its job (drain cap) from HERMES_LAUNCHD_LABEL."""
+ monkeypatch.setenv("XPC_SERVICE_NAME", "ai.hermes.gateway-butler")
+ monkeypatch.delenv(stderr_timestamp.LAUNCHD_LABEL_ENV, raising=False)
+ log_path = tmp_path / "gateway.error.log"
+ marker_path = tmp_path / "label.txt"
+ code = (
+ "import os\n"
+ f"from pathlib import Path\n"
+ f"Path({str(marker_path)!r}).write_text("
+ f"os.environ.get({stderr_timestamp.LAUNCHD_LABEL_ENV!r}, 'unset'), encoding='utf-8')\n"
+ )
+
+ rc = stderr_timestamp.main(
+ ["--error-log", str(log_path), "--", sys.executable, "-c", code]
+ )
+
+ assert rc == 0
+ assert marker_path.read_text(encoding="utf-8") == "ai.hermes.gateway-butler"
+
+
+def test_main_does_not_fabricate_label_for_xpc_zero(tmp_path, monkeypatch):
+ """Foreground/unsupervised starts must not inherit a fabricated job label."""
+ monkeypatch.setenv("XPC_SERVICE_NAME", "0")
+ monkeypatch.delenv(stderr_timestamp.LAUNCHD_LABEL_ENV, raising=False)
+ log_path = tmp_path / "gateway.error.log"
+ marker_path = tmp_path / "label.txt"
+ code = (
+ "import os\n"
+ f"from pathlib import Path\n"
+ f"Path({str(marker_path)!r}).write_text("
+ f"os.environ.get({stderr_timestamp.LAUNCHD_LABEL_ENV!r}, 'unset'), encoding='utf-8')\n"
+ )
+
+ rc = stderr_timestamp.main(
+ ["--error-log", str(log_path), "--", sys.executable, "-c", code]
+ )
+
+ assert rc == 0
+ assert marker_path.read_text(encoding="utf-8") == "unset"
+
+
# The child is ``python -c <record argv>`` carrying a "gateway run" tail as inert data, which is
# exactly what the guard's real-gateway spawn check matches; it exits at once.
@pytest.mark.spawns_gateway_lookalike