The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: a gateway that dies while starting shows its own error in the client
Tekniumac6545eeaa09
diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pyindex ab5cc1bfbb2..89d16130ce4 100644--- a/hermes_cli/gateway_client.py+++ b/hermes_cli/gateway_client.py@@ -199,7 +199,11 @@ async def connect_gateway():home = get_hermes_home().resolve()result = await asyncio.to_thread(ensure_gateway_runtime, home)if result.state != "ready" or result.endpoint is None:- detail = f" ({result.detail})" if getattr(result, "detail", None) else ""+ detail = getattr(result, "detail", None)+ if result.reason_code == "runtime_exited" and detail:+ # A multi-line startup report (redacted traceback tail + where the full log is).+ raise GatewayUnavailableError(f"Gateway could not start: {detail}", result.state)+ detail = f" ({detail})" if detail else ""raise GatewayUnavailableError(f"Gateway {result.state}: {result.reason_code or 'not_ready'}{detail}",result.state)endpoint = result.endpointdiff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.pyindex 7ea0b9e6c96..7a473f5ce19 100644--- a/hermes_cli/gateway_runtime.py+++ b/hermes_cli/gateway_runtime.py@@ -44,7 +44,8 @@ class GatewayDiscovery:endpoint: GatewayEndpoint | None = Nonereason_code: str | None = None# Human-readable cause behind a bounded ``reason_code`` when the owner published one (the- # multiplexer's park reason); never raw peer data.+ # multiplexer's park reason), or the redacted output tail of a start this call made that died+ # (``runtime_exited``); never raw peer data.detail: str | None = None@@ -231,6 +232,7 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULThome = Path(_canonical_home(profile_home))requested = Falsechild = None+ child_home, child_offset = home, 0delay = 0.025try:while True:@@ -248,8 +250,10 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULTif status is not None and observed.state == "absent":# The one start this invocation requested died without leaving an owner: waiting# out the deadline cannot change that, and this call never launches a second one.- return GatewayDiscovery("inaccessible", reason_code="runtime_exited", detail=(- f"gateway exited with status {status}; see logs/gateway-stdio.log of the started profile"))+ # Its own (redacted) output is the answer the user needs, not a pointer to a file.+ from hermes_cli.gateway_runtime_start import startup_failure_report+ return GatewayDiscovery("inaccessible", reason_code="runtime_exited",+ detail=startup_failure_report(child_home, child_offset, status))if observed.state == "starting":requested = True# A default multiplexer that is still starting will serve this named profile; never@@ -275,7 +279,8 @@ def ensure_gateway_runtime(profile_home: str | Path, *, timeout: float = DEFAULTif service is not None:start_existing_gateway_service(service, deadline=deadline)else:- from hermes_cli.gateway_runtime_start import spawn_unmanaged_gateway+ from hermes_cli.gateway_runtime_start import spawn_unmanaged_gateway, stdio_log_size+ child_home, child_offset = target, stdio_log_size(target)child = spawn_unmanaged_gateway(target, deadline=deadline)requested = Truetime.sleep(min(delay, remaining(deadline)))diff --git a/hermes_cli/gateway_runtime_start.py b/hermes_cli/gateway_runtime_start.pyindex 0d9c222e735..00a243a250f 100644--- a/hermes_cli/gateway_runtime_start.py+++ b/hermes_cli/gateway_runtime_start.py@@ -52,3 +52,40 @@ def spawn_unmanaged_gateway(profile_home: Path, *, deadline: float) -> subprocesexcept OSError as exc:reason = "windows_breakaway_unavailable" if sys.platform == "win32" else "spawn_failed"raise RuntimeStartError(reason) from exc+++def stdio_log_path(profile_home: Path) -> Path:+ return profile_home / "logs" / "gateway-stdio.log"+++def stdio_log_size(profile_home: Path) -> int:+ """Where this launch's output will start in the append-only stdio log."""+ try:+ return stdio_log_path(profile_home).stat().st_size+ except OSError:+ return 0+++_BANNER_PREFIXES = ("┌", "│", "├", "└")+_TAIL_LINES = 15+_TAIL_BYTES = 64 * 1024+++def startup_failure_report(profile_home: Path, offset: int, status: int) -> str:+ """What a client prints when the gateway it started died before serving: the exit status, the+ redacted tail of THIS launch's stdio (the traceback lives there, written before logging is up and+ before the detached-stdio redactor is installed) and the command that shows the whole log."""+ path = stdio_log_path(profile_home)+ try:+ with path.open("rb") as log:+ log.seek(max(offset, path.stat().st_size - _TAIL_BYTES))+ text = log.read().decode("utf-8", errors="replace")+ except OSError:+ text = ""+ lines = [line.rstrip() for line in text.splitlines()+ if line.strip() and not line.lstrip().startswith(_BANNER_PREFIXES)][-_TAIL_LINES:]+ from agent.redact import redact_sensitive_text+ tail = redact_sensitive_text("\n".join(lines), force=True, redact_url_credentials=True)+ see = f'type "{path}"' if sys.platform == "win32" else f"tail -n 200 '{path}'"+ body = "\n".join(" " + line for line in tail.splitlines()) if tail else " (it wrote no output)"+ return f"the gateway exited with status {status} before it could serve:\n{body}\nFull log: {see}"diff --git a/tests/hermes_cli/test_gateway_runtime_ensure.py b/tests/hermes_cli/test_gateway_runtime_ensure.pyindex c189076bff2..4a890f3709e 100644--- a/tests/hermes_cli/test_gateway_runtime_ensure.py+++ b/tests/hermes_cli/test_gateway_runtime_ensure.py@@ -435,16 +435,22 @@ def test_reserved_root_never_suppresses_a_standalone_profile_start(tmp_path, mon@pytest.mark.platforms("linux", "macos")def test_dead_unmanaged_start_is_a_prompt_terminal_verdict(tmp_path, monkeypatch):- """The one start this call requested exited without leaving an owner: report it, never- `starting` until the deadline, and never launch a second daemon."""+ """The one start this call requested exited without leaving an owner: report it with the+ redacted tail of that launch's own output (never an earlier run's), never `starting` until the+ deadline, and never launch a second daemon."""from hermes_cli import gateway_runtime as runtime, gateway_runtime_service as service, gateway_runtime_start as starthome = tmp_path / "profile"- home.mkdir(mode=0o700)+ (home / "logs").mkdir(parents=True, mode=0o700)+ (home / "logs" / "gateway-stdio.log").write_text("OLD_RUN_TRACEBACK\n", encoding="utf-8")+ secret = "sk-proj-" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4"children = []def dead_start(target, **kwargs):- children.append(subprocess.Popen([sys.executable, "-c", "raise SystemExit(3)"]))+ log = (target / "logs" / "gateway-stdio.log").open("ab")+ code = ("import sys; print('Traceback (most recent call last):'); "+ f"print('RuntimeError: boot failed with key {secret}'); sys.exit(3)")+ children.append(subprocess.Popen([sys.executable, "-c", code], stdout=log, stderr=log))return children[-1]monkeypatch.setattr(service, "discover_existing_gateway_service", lambda *a, **k: None)monkeypatch.setattr(start, "spawn_unmanaged_gateway", dead_start)@@ -453,3 +459,6 @@ def test_dead_unmanaged_start_is_a_prompt_terminal_verdict(tmp_path, monkeypatchassert time.monotonic() - before < 10assert (result.state, result.reason_code) == ("inaccessible", "runtime_exited")assert "status 3" in result.detail and len(children) == 1+ assert "RuntimeError: boot failed with key" in result.detail, result.detail+ assert secret not in result.detail and "OLD_RUN_TRACEBACK" not in result.detail+ assert "gateway-stdio.log" in result.detaildiff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.pyindex 5c9fc7d5c0d..f929b69c405 100644--- a/ui-tui/scripts/gateway_bootstrap.py+++ b/ui-tui/scripts/gateway_bootstrap.py@@ -45,7 +45,8 @@ def bootstrap(start: bool, recover: bool = False) -> dict:if not start and recover and receipt.state == "absent" and owner_crashed(home):receipt = ensure_gateway_runtime(home, timeout=30)if receipt.state != "ready" or receipt.endpoint is None:- raise RuntimeError(f"gateway {receipt.state}: {receipt.reason_code or 'not ready'}")+ detail = f"\n{receipt.detail}" if receipt.reason_code == "runtime_exited" and receipt.detail else ""+ raise RuntimeError(f"gateway {receipt.state}: {receipt.reason_code or 'not ready'}{detail}")endpoint = receipt.endpoint# A profile served by the default multiplexer has no socket of its own; the host mints its ticket.control = control_home_for(home, endpoint)