Skip to content

The agent that grows with you

fix: bound gateway probes and structure ensure parser errors

Tekniumad1099d6c531
diff --git a/hermes_cli/gateway_runtime_discovery.py b/hermes_cli/gateway_runtime_discovery.py
index 0a77fc08a86..648ba48a100 100644
--- a/hermes_cli/gateway_runtime_discovery.py
+++ b/hermes_cli/gateway_runtime_discovery.py
@@ -66,8 +66,15 @@ def query_identify(home: Path, *, timeout: float) -> dict:
path = _socket_path(home)
request = b'{"protocol":1,"verb":"identify","id":1}\n'
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
- client.settimeout(max(0.001, deadline - time.monotonic()))
+ budget = deadline - time.monotonic()
+ if budget <= 0:
+ raise TimeoutError
+ client.settimeout(budget)
client.connect(str(path))
+ budget = deadline - time.monotonic()
+ if budget <= 0:
+ raise TimeoutError
+ client.settimeout(budget)
client.sendall(request)
data = bytearray()
while b"\n" not in data:
diff --git a/hermes_cli/gateway_runtime_service.py b/hermes_cli/gateway_runtime_service.py
index 20d60c210db..7134b759a82 100644
--- a/hermes_cli/gateway_runtime_service.py
+++ b/hermes_cli/gateway_runtime_service.py
@@ -120,14 +120,20 @@ def _launchd(home: Path, deadline: float) -> ExistingService | None:
if definition.get("Disabled"):
raise RuntimeStartError("service_disabled")
domains = [f"gui/{os.getuid()}", f"user/{os.getuid()}"] # windows-footgun: ok — native launchd only
+ found = []
for domain in domains:
result = _run(["launchctl", "print", f"{domain}/{label}"], deadline)
if result.returncode == 0:
- return ExistingService("launchd", ("launchctl", "kickstart", f"{domain}/{label}"),
- "state = running" in result.stdout)
+ found.append(ExistingService("launchd", ("launchctl", "kickstart", f"{domain}/{label}"),
+ "state = running" in result.stdout))
+ continue
# launchctl's native absent-service code; other errors retain uncertainty.
if result.returncode != 113:
raise RuntimeStartError("service_manager_unavailable")
+ if len(found) > 1:
+ raise RuntimeStartError("service_scope_conflict", "conflict")
+ if found:
+ return found[0]
if installed:
# Load ONLY the existing file, never bootout/rewrite or kickstart -k.
return ExistingService("launchd", ("launchctl", "bootstrap", domains[0], str(plist)))
diff --git a/hermes_cli/subcommands/gateway.py b/hermes_cli/subcommands/gateway.py
index a7fa976d083..657a99a57be 100644
--- a/hermes_cli/subcommands/gateway.py
+++ b/hermes_cli/subcommands/gateway.py
@@ -8,6 +8,26 @@ from typing import Callable
from hermes_cli.subcommands._shared import add_accept_hooks_flag
+class _GatewayCommandParser(argparse.ArgumentParser):
+ """Ensure's parser errors share its machine-readable command boundary."""
+
+ def __init__(self, *args, ensure_json=False, **kwargs):
+ self.ensure_json = ensure_json
+ super().__init__(*args, **kwargs)
+
+ def parse_known_args(self, args=None, namespace=None):
+ parsed, unknown = super().parse_known_args(args, namespace)
+ if self.ensure_json and unknown:
+ self.error("unknown arguments")
+ return parsed, unknown
+
+ def error(self, message):
+ if not self.ensure_json:
+ return super().error(message)
+ print('{"endpoint":null,"reason_code":"invalid_invocation","state":"inaccessible"}')
+ self.exit(2, "gateway ensure: invalid invocation\n")
+
+
def _flag(parser, *names, help, **kw):
parser.add_argument(*names, action="store_true", help=help, **kw)
@@ -31,7 +51,8 @@ def build_gateway_parser(
"""Attach the ``gateway`` and ``proxy`` subcommands to ``subparsers``."""
gateway_parser = subparsers.add_parser("gateway", help="Messaging gateway management",
description="Manage the messaging gateway (Telegram, Discord, WhatsApp, Weixin, and more)")
- gateway_subparsers = gateway_parser.add_subparsers(dest="gateway_command")
+ gateway_subparsers = gateway_parser.add_subparsers(
+ dest="gateway_command", parser_class=_GatewayCommandParser)
gateway_run = gateway_subparsers.add_parser(
"run", help="Run gateway in foreground (recommended for WSL, Docker, Termux)")
@@ -63,7 +84,8 @@ def build_gateway_parser(
from hermes_cli.gateway_runtime_cli import cmd_gateway_ensure
gateway_ensure = gateway_subparsers.add_parser(
- "ensure", help="Ensure a local runtime without installing or replacing a service",
+ "ensure", ensure_json=True,
+ help="Ensure a local runtime without installing or replacing a service",
epilog="Exit codes: 0 ready; 2 invalid invocation; 3 incompatible; "
"4 authorization/profile mismatch; 5 deadline; 6 draining/update-paused; "
"7 inaccessible/conflicting supervisor. Pending startup is not readiness.")
diff --git a/tests/hermes_cli/test_gateway_runtime_ensure.py b/tests/hermes_cli/test_gateway_runtime_ensure.py
index d0c056da3ad..4b01720ec70 100644
--- a/tests/hermes_cli/test_gateway_runtime_ensure.py
+++ b/tests/hermes_cli/test_gateway_runtime_ensure.py
@@ -22,7 +22,12 @@ def test_ensure_waits_for_real_control_owner_without_claiming_pending_is_ready(t
home.mkdir(mode=0o700)
payload = {"runtime_protocol": 1, "state": "starting", "instance_id": "peer",
"served_profiles": [{"profile_id": str(home), "home": str(home)}]}
- server = GatewayControlServer(home, verb_handlers={"identify": lambda: payload})
+ stalled = False
+ def identify():
+ if stalled:
+ time.sleep(0.5)
+ return payload
+ server = GatewayControlServer(home, verb_handlers={"identify": identify})
assert await server.start()
try:
before = time.monotonic()
@@ -35,6 +40,9 @@ def test_ensure_waits_for_real_control_owner_without_claiming_pending_is_ready(t
payload["served_profiles"] = []
result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=0.3)
assert result.state == "inaccessible" and result.reason_code == "profile_mismatch"
+ stalled = True
+ result = await asyncio.to_thread(runtime.ensure_gateway_runtime, home, timeout=0.1)
+ assert result.state == "starting" and result.reason_code == "deadline"
assert not (home / "logs").exists()
finally:
await server.stop()
@@ -57,9 +65,10 @@ def test_installed_service_start_is_nonmutating_and_failed_manager_never_spawns(
original = unit.read_bytes()
calls = tmp_path / "calls.jsonl"
helper = tmp_path / "inert-supervisor"
- helper.write_text('#!' + sys.executable + '\nimport json,sys\nfrom pathlib import Path\n'
+ helper.write_text('#!' + sys.executable + '\nimport json,sys,time\nfrom pathlib import Path\n'
+ f'p=Path({str(calls)!r})\n'
+ 'with p.open("a") as f: f.write(json.dumps(sys.argv[1:])+"\\n")\n'
+ + 'if (p.parent/"stall").exists(): time.sleep(5)\n'
+ 'if (p.parent/"fail").exists(): print("private-supervisor-token"); sys.exit(3)\n'
+ 'if "show" in sys.argv and "system" in sys.argv and (p.parent/"single").exists():\n print("LoadState=not-found")\n'
+ 'elif "show" in sys.argv:\n print("LoadState=loaded\\nActiveState=inactive\\nSubState=dead\\nUnitFileState=enabled")\n'
@@ -85,6 +94,12 @@ def test_installed_service_start_is_nonmutating_and_failed_manager_never_spawns(
assert "private-supervisor-token" not in repr(result)
assert sum("start" in json.loads(line) for line in calls.read_text().splitlines()) == 1
assert not (home / "logs").exists()
+ (tmp_path / "stall").touch()
+ before = time.monotonic()
+ result = runtime.ensure_gateway_runtime(home, timeout=0.2)
+ assert result.reason_code == "deadline"
+ assert time.monotonic() - before < 2
+ assert sum("start" in json.loads(line) for line in calls.read_text().splitlines()) == 1
@pytest.mark.linux_only
@@ -105,6 +120,11 @@ def test_public_ensure_json_deadline_and_invalid_invocation(tmp_path):
env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)
assert result.returncode == 2
assert json.loads(result.stdout)["reason_code"] == "invalid_invocation"
+ result = subprocess.run([sys.executable, "-m", "hermes_cli.main", "gateway", "ensure", "--json", "--unknown", "private-value"],
+ env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=15)
+ assert result.returncode == 2
+ assert json.loads(result.stdout)["reason_code"] == "invalid_invocation"
+ assert "private-value" not in result.stdout
@pytest.mark.linux_only
@@ -200,3 +220,20 @@ def test_native_windows_spawn_never_retries_without_breakaway(tmp_path, monkeypa
start.spawn_unmanaged_gateway(tmp_path, deadline=time.monotonic()+5)
assert len(calls) == 1
assert calls[0]["creationflags"] == windows_detach_flags()
+
+
+def test_native_launchd_ambiguous_domains_cannot_start(tmp_path, monkeypatch):
+ from hermes_cli.gateway_runtime_service import discover_existing_gateway_service, RuntimeStartError
+ peer = tmp_path / "inert_launchd.py"
+ peer.write_text("print('state = not running')\n", encoding="utf-8")
+ actual = subprocess.run
+ calls = []
+ def boundary(argv, **kwargs):
+ assert argv[0] == "launchctl"
+ calls.append(argv)
+ return actual([sys.executable, str(peer), *argv[1:]], **kwargs)
+ monkeypatch.setattr(subprocess, "run", boundary)
+ with pytest.raises(RuntimeStartError, match="service_scope_conflict"):
+ discover_existing_gateway_service(tmp_path.resolve(), deadline=time.monotonic()+5)
+ assert len(calls) == 2 and all(argv[1] == "print" for argv in calls)