The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: add transport-only classic gateway client and option validation
Teknium6ed03be97446
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.pynew file mode 100644index 00000000000..633151ea64b--- /dev/null+++ b/hermes_cli/gateway_chat.py@@ -0,0 +1,100 @@+"""Normal classic/one-shot launch through the canonical gateway, never AIAgent."""+from __future__ import annotations++import argparse+import asyncio+import os+from pathlib import Path+import sys+import uuid++from hermes_cli.gateway_client import GatewayClientError, connect_gateway++# These options change execution or require frontend facilities not yet exposed by+# the authority. Reject them, rather than mutate process-wide gateway settings.+_UNSUPPORTED = (+ "image", "skills", "worktree", "w", "checkpoints", "pass_session_id",+ "ignore_user_config", "ignore_rules", "safe_mode", "yolo", "accept_hooks",+ "continue_last", "create_if_missing", "no_restore_cwd", "usage_file",+ "run_budget", "api_key", "base_url", "verbose", "compact",+ "list_tools", "list_toolsets",+)+_POLICY = ("model", "provider", "reasoning", "toolsets", "max_turns")+++def validate_options(args):+ unsupported = [name for name in _UNSUPPORTED if getattr(args, name, None)]+ if getattr(args, "resume", None) == "latest":+ unsupported.append("resume latest")+ if unsupported:+ flags = ", ".join("--" + name.replace("_", "-") for name in unsupported)+ raise GatewayClientError(f"Unsupported gateway CLI options: {flags}. No local fallback or policy changes were made.")+ if getattr(args, "resume", None) and (getattr(args, "in_dir", None) or+ any(getattr(args, name, None) is not None for name in _POLICY)):+ raise GatewayClientError("Resume retains gateway session policy; creation overrides are unsupported on resume.")+++async def run_gateway_chat(args):+ from hermes_cli.gateway_chat_view import GatewayChatView+ async with connect_gateway() as client:+ description = await client.rpc("runtime.describe")+ if getattr(args, "resume", None):+ snapshot = await client.rpc("session.resume", session_id=args.resume)+ else:+ contract = description.get("session_create", {})+ source = getattr(args, "source", None) or "cli"+ if source not in contract.get("sources", []):+ raise GatewayClientError(f"Gateway does not support source {source!r}")+ parameters = contract.get("parameters", [])+ policy = {key: getattr(args, key) for key in _POLICY if getattr(args, key, None) is not None}+ cwd = str(Path(getattr(args, "in_dir", None) or os.getcwd()).expanduser().resolve())+ if "cwd" in parameters:+ policy["cwd"] = cwd+ elif getattr(args, "in_dir", None):+ raise GatewayClientError("Gateway does not support --in / caller cwd; update the gateway")+ else:+ print("Warning: this gateway cannot preserve caller cwd; it uses its configured execution directory.", file=sys.stderr)+ missing = sorted(set(policy) - set(parameters))+ if missing:+ raise GatewayClientError("Gateway does not support creation options: " + ", ".join(missing))+ snapshot = await client.rpc("session.create", request_id=uuid.uuid4().hex, source=source, **policy)+ print("Session: " + snapshot["stored_session_id"], file=sys.stderr, flush=True)+ query = getattr(args, "query", None) or getattr(args, "q", None)+ oneshot_prompt = getattr(args, "oneshot", None)+ if isinstance(oneshot_prompt, str):+ query = oneshot_prompt+ quiet = bool(getattr(args, "quiet", False) or oneshot_prompt)+ oneshot = bool(oneshot_prompt or getattr(args, "oneshot_exit", False) or quiet or+ (query and not (sys.stdin.isatty() and sys.stdout.isatty())))+ view = GatewayChatView(client, snapshot, quiet=quiet)+ if getattr(args, "resume", None) and not quiet:+ for row in snapshot.get("messages", []):+ if row.get("role") in {"user", "assistant"} and isinstance(row.get("content"), str):+ print(f"{row['role']}: {row['content']}")+ return await view.run(query, oneshot=oneshot)+++def launch_from_args(args) -> int:+ from websockets.exceptions import WebSocketException+ try:+ validate_options(args)+ query_file = getattr(args, "query_file", None)+ if query_file:+ args.query = sys.stdin.read() if query_file == "-" else Path(query_file).read_text(encoding="utf-8")+ if not args.query.strip():+ raise GatewayClientError("--query-file is empty")+ if not (getattr(args, "query", None) or getattr(args, "oneshot", None) or sys.stdin.isatty()):+ raise GatewayClientError("Noninteractive chat requires --query or --oneshot")+ return asyncio.run(run_gateway_chat(args))+ except (GatewayClientError, OSError, TimeoutError, WebSocketException) as exc:+ # WebSocket errors can embed credential URLs/remote bodies.+ message = str(exc) if isinstance(exc, GatewayClientError) else "Gateway connection/read failed; no local fallback"+ print("Error: " + message, file=sys.stderr)+ return 2 if isinstance(exc, GatewayClientError) and ("Unsupported" in message or "unsupported" in message) else 1+ except KeyboardInterrupt:+ print("Detached; accepted work continues at the gateway.", file=sys.stderr)+ return 130+++def launch_from_kwargs(options) -> int:+ return launch_from_args(argparse.Namespace(**options))diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pynew file mode 100644index 00000000000..1c89e7243e8--- /dev/null+++ b/hermes_cli/gateway_chat_view.py@@ -0,0 +1,135 @@+"""Classic terminal presentation of authority events and fenced controls."""+import asyncio+from contextlib import suppress+import sys+import uuid++from hermes_cli.gateway_client import GatewayClientError+++class GatewayChatView:+ def __init__(self, client, snapshot, *, quiet=False):+ self.client = client+ self.session_id = snapshot["stored_session_id"]+ self.generation = snapshot.get("execution_generation", 0)+ self.prompts = {p["prompt_id"]: p for p in snapshot.get("prompts", [])}+ self.quiet = quiet+ self.streams = {}+ self.completions = {}+ self.changed = asyncio.Event()+ self.failure = None++ def show_prompt(self, prompt):+ print(f"\n{prompt.get('description') or prompt.get('question') or 'Approval required'}", file=sys.stderr)+ if prompt.get("command"):+ print(prompt["command"], file=sys.stderr)+ command = "/approve" if prompt["kind"] == "approval" else "/answer"+ print(f"{command} {prompt['prompt_id']} <{'|'.join(prompt.get('choices', [])) or 'answer'}>", file=sys.stderr)++ async def render(self):+ while True:+ event = await self.client.events.get()+ if isinstance(event, Exception):+ self.failure = event+ self.changed.set()+ return+ params = event.get("params", {})+ if params.get("session_id") != self.session_id:+ continue+ kind, payload = params.get("type"), params.get("payload", {})+ self.generation = params.get("execution_generation", self.generation)+ admission = params.get("admission_id") or payload.get("admission_id")+ if kind == "message.delta":+ text = payload.get("text") or payload.get("delta") or payload.get("content") or ""+ if isinstance(text, str):+ self.streams[admission] = self.streams.get(admission, "") + text+ if not self.quiet:+ print(text, end="", flush=True)+ elif kind == "message.complete":+ text = payload.get("text") or payload.get("content") or ""+ streamed = self.streams.pop(admission, "")+ if self.quiet or not streamed:+ print(text, flush=True)+ elif text.startswith(streamed):+ print(text[len(streamed):], flush=True)+ else:+ print("\n" + text, flush=True)+ self.completions[admission] = payload.get("outcome")+ elif kind in {"approval.request", "clarify.request"}:+ self.prompts[payload["prompt_id"]] = payload+ self.show_prompt(payload)+ elif kind in {"approval.settled", "clarify.settled"}:+ self.prompts.pop(payload["prompt_id"], None)+ self.changed.set()++ async def submit(self, text):+ return await self.client.rpc("prompt.submit", session_id=self.session_id,+ input_id=uuid.uuid4().hex, text=text)++ async def command(self, text):+ command, _, rest = text.partition(" ")+ if command in {"/quit", "/exit", "/detach"}:+ return False+ if command == "/stop":+ await self.client.rpc("session.interrupt", session_id=self.session_id,+ execution_generation=self.generation)+ return True+ if command in {"/approve", "/answer"}:+ prompt_id, _, answer = rest.partition(" ")+ prompt = self.prompts.get(prompt_id)+ expected = "approval" if command == "/approve" else "clarify"+ if not prompt or prompt["kind"] != expected:+ raise GatewayClientError("No matching pending control; resume to refresh")+ await self.client.rpc(expected + ".respond", session_id=self.session_id,+ execution_generation=prompt["execution_generation"], prompt_id=prompt_id,+ **({"choice": answer} if expected == "approval" else {"answer": answer}))+ return True+ if command == "/help":+ print("/stop, /approve <id> <choice>, /answer <id> <text>, /quit (detach). Other slash commands are not yet supported.")+ return True+ raise GatewayClientError("Unsupported gateway CLI command; use /help. No local command was run.")++ async def run(self, query=None, *, oneshot=False):+ for prompt in self.prompts.values():+ self.show_prompt(prompt)+ renderer = asyncio.create_task(self.render())+ try:+ receipt = await self.submit(query) if query else None+ if oneshot:+ if receipt is None:+ raise GatewayClientError("One-shot requires a query")+ admission = receipt["admission_id"]+ while admission not in self.completions:+ self.changed.clear()+ if self.failure:+ raise self.failure+ if self.prompts:+ print("Input required; detached without cancelling. Resume this session interactively.", file=sys.stderr)+ return 3+ await self.changed.wait()+ return 0 if self.completions[admission] == "completed" else 1+ from prompt_toolkit import PromptSession+ from prompt_toolkit.patch_stdout import patch_stdout+ prompt = PromptSession()+ with patch_stdout():+ while not self.failure:+ try:+ text = (await prompt.prompt_async("You> ")).strip()+ if not text:+ continue+ if text.startswith("/"):+ if not await self.command(text):+ return 0+ else:+ await self.submit(text)+ except KeyboardInterrupt:+ print("Use /stop to interrupt execution, /quit to detach.")+ except EOFError:+ return 0+ except GatewayClientError as exc:+ print(f"Error: {exc}", file=sys.stderr)+ raise self.failure+ finally:+ renderer.cancel()+ with suppress(asyncio.CancelledError):+ await rendererdiff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pynew file mode 100644index 00000000000..ccb9ac0332f--- /dev/null+++ b/hermes_cli/gateway_client.py@@ -0,0 +1,138 @@+"""Transport-only RPC client. Closing a viewer never stops its authority."""+from __future__ import annotations++import asyncio+from contextlib import asynccontextmanager, suppress+import json+import os+from pathlib import Path+import socket+import time+++class GatewayClientError(ValueError):+ pass+++class GatewayClient:+ def __init__(self, websocket):+ self.websocket = websocket+ self.events = asyncio.Queue(maxsize=4096)+ self.pending = {}+ self.sequence = 0+ self.reader = None++ async def __aenter__(self):+ self.reader = asyncio.create_task(self._read())+ return self++ async def __aexit__(self, *exc):+ self.reader.cancel()+ with suppress(asyncio.CancelledError):+ await self.reader++ async def _read(self):+ try:+ async for raw in self.websocket:+ frame = json.loads(raw)+ future = self.pending.get(frame.get("id"))+ if future is not None and not future.done():+ if "error" in frame:+ # Only bounded authority reason codes, never raw remote diagnostics.+ reason = frame["error"].get("message", "request_failed")+ if not isinstance(reason, str) or not reason.replace("_", "").isalnum() or len(reason) > 80:+ reason = "request_failed"+ future.set_exception(GatewayClientError(reason))+ else:+ future.set_result(frame.get("result", {}))+ elif "method" in frame:+ self.events.put_nowait(frame)+ except (OSError, ValueError, asyncio.QueueFull):+ pass+ finally:+ error = GatewayClientError("Gateway disconnected; accepted work was not cancelled. Resume the printed session ID.")+ for future in self.pending.values():+ if not future.done():+ future.set_exception(error)+ # A stalled consumer is failed rather than silently losing terminal events.+ if self.events.full():+ self.events.get_nowait()+ self.events.put_nowait(error)++ async def rpc(self, method, **params):+ self.sequence += 1+ rid = self.sequence+ future = asyncio.get_running_loop().create_future()+ self.pending[rid] = future+ try:+ await self.websocket.send(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}))+ return await asyncio.wait_for(future, 30)+ finally:+ self.pending.pop(rid, None)+++def _session_ticket(home: Path, endpoint) -> str:+ from hermes_cli.gateway_runtime_discovery import _socket_path, _identify_response+ request = json.dumps({"protocol": 1, "id": 1, "verb": "session-ticket", "params": {+ "profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id, "purpose": "interactive",+ }}).encode() + b"\n"+ if os.name == "nt":+ from gateway.runtime_bootstrap_windows import query_runtime_control+ data = query_runtime_control(home, request, 5)+ else:+ deadline = time.monotonic() + 5+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:+ peer.settimeout(5)+ peer.connect(str(_socket_path(home)))+ peer.sendall(request)+ data = bytearray()+ while b"\n" not in data:+ budget = deadline - time.monotonic()+ if budget <= 0:+ raise GatewayClientError("Gateway bootstrap timed out")+ peer.settimeout(budget)+ chunk = peer.recv(4096)+ if not chunk or len(data) + len(chunk) > 65536:+ raise GatewayClientError("Invalid gateway bootstrap response")+ data.extend(chunk)+ grant = _identify_response(bytes(data))+ if any(grant.get(k) != v for k, v in {+ "profile_id": endpoint.profile_id, "instance_id": endpoint.instance_id, "runtime_protocol": 1,+ }.items()) or not isinstance(grant.get("ticket"), str) or not grant["ticket"]:+ raise GatewayClientError("Gateway bootstrap identity changed; retry launch")+ return grant["ticket"]+++@asynccontextmanager+async def connect_gateway():+ from websockets.asyncio.client import connect+ from hermes_constants import get_hermes_home+ from hermes_cli.gateway_runtime import ensure_gateway_runtime+ from urllib.parse import urlsplit++ remote = os.environ.get("HERMES_TUI_GATEWAY_URL", "").strip()+ protocols = None+ if remote:+ parsed = urlsplit(remote)+ if parsed.scheme not in {"ws", "wss"} or not parsed.hostname:+ raise GatewayClientError("Invalid explicit gateway WebSocket URL; no local fallback")+ url = remote+ else:+ home = get_hermes_home().resolve()+ result = await asyncio.to_thread(ensure_gateway_runtime, home)+ if result.state != "ready" or result.endpoint is None:+ raise GatewayClientError(f"Gateway {result.state}: {result.reason_code or 'not_ready'}")+ endpoint = result.endpoint+ ticket = await asyncio.to_thread(_session_ticket, home, endpoint)+ url = endpoint.api_origin.replace("https:", "wss:").replace("http:", "ws:") + "/api/ws"+ protocols = ["hermes-gateway-v1", "hermes-gateway-ticket." + ticket]+ try:+ async with connect(url, subprotocols=protocols, open_timeout=10, max_size=8 * 1024 * 1024) as ws:+ if protocols and ws.subprotocol != "hermes-gateway-v1":+ raise GatewayClientError("Gateway protocol mismatch; update/restart required")+ async with GatewayClient(ws) as client:+ yield client+ except GatewayClientError:+ raise+ except (OSError, TimeoutError) as exc:+ raise GatewayClientError("Gateway connection failed; no local fallback") from excdiff --git a/tests/hermes_cli/test_gateway_chat.py b/tests/hermes_cli/test_gateway_chat.pynew file mode 100644index 00000000000..9c502df73ea--- /dev/null+++ b/tests/hermes_cli/test_gateway_chat.py@@ -0,0 +1,39 @@+"""Client launch must not silently downgrade policy or own execution."""+import argparse++import pytest+++def test_unsupported_launch_options_fail_before_connection(monkeypatch, capsys):+ from hermes_cli import gateway_chat+ calls = []+ monkeypatch.setattr(gateway_chat, "connect_gateway", lambda: calls.append(True))+ for option in ("yolo", "ignore_rules", "safe_mode", "worktree", "continue_last", "usage_file"):+ args = argparse.Namespace(**{option: True})+ assert gateway_chat.launch_from_args(args) == 2+ assert option.replace("_", "-") in capsys.readouterr().err+ assert calls == []+++async def test_rpc_preserves_notifications_and_errors():+ import asyncio+ import json+ from websockets.asyncio.server import serve+ from websockets.asyncio.client import connect+ from hermes_cli.gateway_client import GatewayClient, GatewayClientError++ async def peer(ws):+ async for raw in ws:+ request = json.loads(raw)+ await ws.send(json.dumps({"method": "message.complete", "params": {"text": "reply"}}))+ await ws.send(json.dumps({"id": request["id"], "error": {"message": "stale_generation"}}))++ async with serve(peer, "127.0.0.1", 0) as server:+ port = server.sockets[0].getsockname()[1]+ async with connect(f"ws://127.0.0.1:{port}") as ws:+ async with GatewayClient(ws) as client:+ with pytest.raises(GatewayClientError, match="stale_generation"):+ await client.rpc("session.interrupt", session_id="stored", execution_generation=4)+ event = await asyncio.wait_for(client.events.get(), 2)+ assert event["params"]["text"] == "reply"