Skip to content

The agent that grows with you

feat: distinguish unavailable gateway owners from absent runtimes

Tekniume903841cb861
diff --git a/gateway/runtime_contract.py b/gateway/runtime_contract.py
new file mode 100644
index 00000000000..2da16ada799
--- /dev/null
+++ b/gateway/runtime_contract.py
@@ -0,0 +1,36 @@
+"""Gateway launch decisions independent of operating-system probes."""
+
+from dataclasses import dataclass
+from typing import Literal
+
+RuntimeState = Literal[
+ "absent", "starting", "ready", "draining", "incompatible", "inaccessible", "conflict"
+]
+
+
+@dataclass(frozen=True)
+class RuntimeObservation:
+ state: RuntimeState
+ installed_service: bool = False
+ service_may_start: bool = False
+ update_paused: bool = False
+
+
+def next_start_action(observation: RuntimeObservation) -> str:
+ if observation.update_paused:
+ return "wait-update"
+ actions = {
+ "ready": "attach",
+ "starting": "wait-owner",
+ "draining": "wait-owner",
+ "incompatible": "reject-version",
+ "inaccessible": "reject-access",
+ "conflict": "reject-conflict",
+ }
+ if observation.state in actions:
+ return actions[observation.state]
+ if observation.state != "absent":
+ raise ValueError("unknown runtime state")
+ if observation.service_may_start:
+ return "wait-service"
+ return "start-service" if observation.installed_service else "spawn-unmanaged"
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.py
new file mode 100644
index 00000000000..24383e42fef
--- /dev/null
+++ b/hermes_cli/gateway_runtime.py
@@ -0,0 +1,99 @@
+"""Validated, credential-free gateway endpoint discovery for local clients."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import ipaddress
+import math
+import os
+from pathlib import Path
+from typing import Literal
+from urllib.parse import urlsplit
+
+from gateway.runtime_contract import RuntimeState
+
+
+@dataclass(frozen=True)
+class GatewayEndpoint:
+ profile_id: str
+ instance_id: str
+ authority_epoch: int
+ runtime_protocol: int
+ api_origin: str
+ supervisor: Literal["none", "systemd", "launchd", "windows", "external"]
+ capabilities: frozenset[str]
+
+
+@dataclass(frozen=True)
+class GatewayDiscovery:
+ state: RuntimeState
+ endpoint: GatewayEndpoint | None = None
+ reason_code: str | None = None
+
+
+def _canonical_home(home: str | Path) -> str:
+ return os.path.normcase(str(Path(home).expanduser().resolve()))
+
+
+def _endpoint(payload: dict, home: Path) -> GatewayDiscovery:
+ if type(payload.get("runtime_protocol")) is not int or payload["runtime_protocol"] != 1:
+ return GatewayDiscovery("incompatible", reason_code="runtime_protocol")
+ profiles = payload.get("served_profiles")
+ if not isinstance(profiles, list):
+ return GatewayDiscovery("inaccessible", reason_code="profile_mismatch")
+ matches = [p for p in profiles if isinstance(p, dict)
+ and isinstance(p.get("home"), str) and _canonical_home(p["home"]) == str(home)]
+ if len(matches) != 1 or not isinstance(matches[0].get("profile_id"), str) or not matches[0]["profile_id"]:
+ return GatewayDiscovery("inaccessible", reason_code="profile_mismatch")
+ state = payload.get("state")
+ if state in {"starting", "draining", "conflict"}:
+ return GatewayDiscovery(state)
+ if state != "ready":
+ return GatewayDiscovery("inaccessible", reason_code="invalid_runtime_state")
+ capabilities = payload.get("capabilities")
+ if (not isinstance(capabilities, list) or not all(isinstance(c, str) for c in capabilities)
+ or "session-authority-v1" not in capabilities):
+ return GatewayDiscovery("incompatible", reason_code="session_authority_unavailable")
+ epoch, instance = payload.get("authority_epoch"), payload.get("instance_id")
+ if type(epoch) is not int or epoch <= 0 or not isinstance(instance, str) or not instance:
+ return GatewayDiscovery("inaccessible", reason_code="invalid_runtime_identity")
+ origin = payload.get("api_origin")
+ if not isinstance(origin, str):
+ return GatewayDiscovery("inaccessible", reason_code="invalid_api_origin")
+ try:
+ parsed = urlsplit(origin)
+ if (parsed.scheme not in {"http", "https"} or not parsed.hostname
+ or parsed.username is not None or parsed.password is not None
+ or parsed.path or parsed.query or parsed.fragment or not parsed.port
+ or not ipaddress.ip_address(parsed.hostname).is_loopback):
+ return GatewayDiscovery("inaccessible", reason_code="invalid_api_origin")
+ except ValueError:
+ return GatewayDiscovery("inaccessible", reason_code="invalid_api_origin")
+ supervisor = payload.get("supervisor")
+ if supervisor not in {"none", "systemd", "launchd", "windows", "external"}:
+ return GatewayDiscovery("inaccessible", reason_code="invalid_supervisor")
+ return GatewayDiscovery("ready", GatewayEndpoint(
+ profile_id=matches[0]["profile_id"], instance_id=instance,
+ authority_epoch=epoch, runtime_protocol=1, api_origin=origin,
+ supervisor=supervisor, capabilities=frozenset(capabilities),
+ ))
+
+
+def discover_gateway_endpoint(profile_home: str | Path, *, timeout: float = 2.0) -> GatewayDiscovery:
+ """Read live control identity, preserving uncertainty instead of spawning."""
+ from hermes_cli.gateway_runtime_discovery import DiscoveryError, missing_owner_state, query_identify
+
+ if not math.isfinite(timeout) or timeout <= 0:
+ raise ValueError("timeout must be finite and positive")
+ home = Path(_canonical_home(profile_home))
+ try:
+ return _endpoint(query_identify(home, timeout=timeout), home)
+ except (FileNotFoundError, ConnectionRefusedError):
+ return GatewayDiscovery(missing_owner_state(home))
+ except TimeoutError:
+ return GatewayDiscovery("inaccessible", reason_code="control_timeout")
+ except DiscoveryError as exc:
+ return GatewayDiscovery("inaccessible", reason_code=exc.reason)
+ except (OSError, ValueError, TypeError):
+ # Raw peer data, paths and URLs may contain secrets; report bounded codes.
+ return GatewayDiscovery("inaccessible", reason_code="invalid_control_peer")
diff --git a/hermes_cli/gateway_runtime_discovery.py b/hermes_cli/gateway_runtime_discovery.py
new file mode 100644
index 00000000000..d7d5de8b5de
--- /dev/null
+++ b/hermes_cli/gateway_runtime_discovery.py
@@ -0,0 +1,90 @@
+"""Bounded local-control discovery without diagnostic fallback or mutation."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import socket
+import stat
+from typing import Literal
+import time
+
+
+class DiscoveryError(ValueError):
+ def __init__(self, reason: str):
+ super().__init__(reason)
+ self.reason = reason
+
+
+def _private_node(path: Path, *, kind: str) -> os.stat_result:
+ node = path.lstat()
+ predicates = {"socket": stat.S_ISSOCK, "file": stat.S_ISREG, "directory": stat.S_ISDIR}
+ if not predicates[kind](node.st_mode) or node.st_uid != os.getuid(): # windows-footgun: ok — POSIX socket path only
+ raise DiscoveryError("unsafe_control_path")
+ forbidden = 0o022 if kind == "directory" else 0o077
+ if stat.S_IMODE(node.st_mode) & forbidden:
+ raise DiscoveryError("unsafe_control_permissions")
+ return node
+
+
+def _socket_path(home: Path) -> Path:
+ _private_node(home, kind="directory")
+ direct = home / "gateway.sock"
+ if os.path.lexists(direct):
+ _private_node(direct, kind="socket")
+ return direct
+ pointer = home / "gateway.sock.path"
+ with os.fdopen(os.open(pointer, os.O_RDONLY | os.O_NOFOLLOW), "rb") as stream: # windows-footgun: ok — binary POSIX descriptor
+ metadata = os.fstat(stream.fileno())
+ if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid() # windows-footgun: ok — POSIX pointer only
+ or stat.S_IMODE(metadata.st_mode) & 0o077):
+ raise DiscoveryError("unsafe_control_pointer")
+ data = stream.read(4097)
+ if len(data) > 4096:
+ raise DiscoveryError("invalid_control_pointer")
+ target = Path(data.decode("utf-8").strip())
+ if not target.is_absolute():
+ raise DiscoveryError("invalid_control_pointer")
+ from gateway.control_socket import _home_hash
+ if target.name != f"hermes-gw-{_home_hash(home)}.sock":
+ raise DiscoveryError("invalid_control_pointer")
+ _private_node(target, kind="socket")
+ return target
+
+
+def query_identify(home: Path, *, timeout: float) -> dict:
+ """Unlike diagnostic queries, retain timeout/access/protocol failures."""
+ if os.name == "nt":
+ raise DiscoveryError("native_bootstrap_required")
+ deadline = time.monotonic() + timeout
+ 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()))
+ client.connect(str(path))
+ client.sendall(request)
+ data = bytearray()
+ while b"\n" not in data:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise TimeoutError
+ client.settimeout(remaining)
+ chunk = client.recv(min(65536, 524289 - len(data)))
+ if not chunk:
+ raise DiscoveryError("incomplete_control_response")
+ data.extend(chunk)
+ if len(data) > 524288:
+ raise DiscoveryError("oversized_control_response")
+ response = json.loads(bytes(data).split(b"\n", 1)[0])
+ if (not isinstance(response, dict) or response.get("ok") is not True
+ or response.get("protocol") != 1 or response.get("id") != 1
+ or not isinstance(response.get("result"), dict)):
+ raise DiscoveryError("invalid_control_response")
+ return response["result"]
+
+
+def missing_owner_state(home: Path) -> Literal["starting", "absent"]:
+ """A live old owner without an API is not permission to start another."""
+ from gateway.status import get_running_pid
+ return "starting" if get_running_pid(home / "gateway.pid", cleanup_stale=False) else "absent"
diff --git a/tests/hermes_cli/test_gateway_runtime.py b/tests/hermes_cli/test_gateway_runtime.py
new file mode 100644
index 00000000000..c3aecc97ba0
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_runtime.py
@@ -0,0 +1,96 @@
+"""Runtime discovery must distinguish absence from an unsafe/live owner."""
+
+import asyncio
+from contextlib import asynccontextmanager
+from pathlib import Path
+
+import pytest
+
+
+@asynccontextmanager
+async def control_peer(home: Path, payload: dict):
+ from gateway.control_socket import GatewayControlServer
+
+ home.mkdir(mode=0o700)
+ server = GatewayControlServer(home, verb_handlers={"identify": lambda: payload})
+ assert await server.start()
+ pointer = home / "gateway.sock.path"
+ if pointer.exists():
+ pointer.chmod(0o600)
+ try:
+ yield server
+ finally:
+ await server.stop()
+
+
+def test_live_discovery_does_not_treat_an_unusable_owner_as_absent(tmp_path):
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint
+
+ async def probe():
+ home = tmp_path / "profile"
+ identity = str(home.resolve())
+ payload = {
+ "protocol": 1,
+ "runtime_protocol": 1,
+ "instance_id": "fixture-instance",
+ "authority_epoch": 1,
+ "hermes_home": identity,
+ "state": "ready",
+ "api_origin": "http://127.0.0.1:41817",
+ "supervisor": "none",
+ "served_profiles": [{"profile_id": identity, "home": identity}],
+ "capabilities": ["session-authority-v1"],
+ }
+ absent = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=1)
+ assert absent.state == "absent"
+ async with control_peer(home, payload):
+ ready = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=1)
+ assert ready.state == "ready"
+ assert ready.endpoint.profile_id == identity
+ assert ready.endpoint.instance_id == "fixture-instance"
+ assert ready.endpoint.api_origin == "http://127.0.0.1:41817"
+ for key, value, expected in [
+ ("runtime_protocol", 99, "incompatible"),
+ ("runtime_protocol", True, "incompatible"),
+ ("served_profiles", [], "inaccessible"),
+ ("state", "draining", "draining"),
+ ("api_origin", "http://secret:[email protected]:41817", "inaccessible"),
+ ("api_origin", "http://example.com:41817", "inaccessible"),
+ ("authority_epoch", True, "inaccessible"),
+ ("capabilities", [], "incompatible"),
+ ]:
+ old = payload[key]
+ payload[key] = value
+ observed = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=1)
+ assert observed.state == expected, (key, observed)
+ assert "credential" not in repr(observed)
+ payload[key] = old
+ # A forged pointer is not permission to connect somewhere else or spawn.
+ (home / "gateway.sock.path").write_text(str(tmp_path / "foreign.sock"))
+ (home / "gateway.sock.path").chmod(0o666)
+ refused = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=1)
+ assert refused.state == "inaccessible"
+
+ asyncio.run(probe())
+
+
+def test_start_decisions_do_not_turn_uncertainty_into_another_owner():
+ from gateway.runtime_contract import RuntimeObservation, next_start_action
+
+ cases = [
+ (RuntimeObservation("ready"), "attach"),
+ (RuntimeObservation("starting"), "wait-owner"),
+ (RuntimeObservation("draining"), "wait-owner"),
+ (RuntimeObservation("incompatible"), "reject-version"),
+ (RuntimeObservation("inaccessible"), "reject-access"),
+ (RuntimeObservation("conflict"), "reject-conflict"),
+ (RuntimeObservation("absent"), "spawn-unmanaged"),
+ (RuntimeObservation("absent", installed_service=True), "start-service"),
+ (RuntimeObservation("absent", service_may_start=True), "wait-service"),
+ (RuntimeObservation("ready", update_paused=True), "wait-update"),
+ ]
+ for observation, expected in cases:
+ assert next_start_action(observation) == expected
+ with pytest.raises(ValueError, match="unknown runtime state"):
+ next_start_action(RuntimeObservation("invalid"))