The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): `hermes chat --format stream-json` rides the gateway transport with a closed JSONL protocol
teknium149ee9d6c74f8
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.pyindex 960640923d8..d71d17b90a4 100644--- a/hermes_cli/gateway_chat.py+++ b/hermes_cli/gateway_chat.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport argparseimport asyncio+import contextlibimport osfrom pathlib import Pathimport sys@@ -79,7 +80,7 @@ def validate_options(args):f"\n Example: {_SAFE_MODE_EXAMPLE}")-async def run_gateway_chat(args):+async def run_gateway_chat(args, emitter=None):from hermes_cli.gateway_chat_view import GatewayChatViewasync with connect_gateway() as client:description = await client.rpc("runtime.describe")@@ -124,14 +125,16 @@ async def run_gateway_chat(args):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)+ if emitter is not None:+ emitter.bind_session(snapshot["stored_session_id"])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)+ quiet = bool(getattr(args, "quiet", False) or oneshot_prompt or emitter is not None)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)+ view = GatewayChatView(client, snapshot, quiet=quiet, emitter=emitter)if (getattr(args, "resume", None) or title) and not quiet:for row in snapshot.get("messages", []):if row.get("role") in {"user", "assistant"} and isinstance(row.get("content"), str):@@ -141,11 +144,35 @@ async def run_gateway_chat(args):def launch_from_args(args) -> int:from websockets.exceptions import WebSocketException+ emitter = None+ if getattr(args, "output_format", "text") == "stream-json":+ # Built before validation/connection so any failed start still closes the protocol+ # (init + result) instead of exiting with an empty stdout.+ from hermes_cli.stream_json import StreamJsonEmitter+ emitter = StreamJsonEmitter(model=getattr(args, "model", None) or "")++ def failed(message, code):+ print("Error: " + message, file=sys.stderr)+ if emitter is not None:+ return emitter.emit_result({"failed": True, "error": message}, exit_code=code)+ return code+try:validate_options(args)from hermes_cli.gateway_chat_startup import ensure_launch_provider- if not ensure_launch_provider(args):- return 0+ if emitter is None:+ if not ensure_launch_provider(args):+ return 0+ else:+ # Setup guidance is human text and the guard exits on a non-TTY: both must become+ # stderr diagnostics + a failed ``result`` when stdout is machine-readable.+ try:+ with contextlib.redirect_stdout(sys.stderr):+ configured = ensure_launch_provider(args)+ except SystemExit:+ configured = False+ if not configured:+ return failed("credentials or agent init failed", 1)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")@@ -153,14 +180,15 @@ def launch_from_args(args) -> int:raise GatewayClientError("--query-file is empty")if not (getattr(args, "query", None) or getattr(args, "q", 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))+ return asyncio.run(run_gateway_chat(args, emitter=emitter))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+ return failed(message, 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)+ if emitter is not None:+ return emitter.emit_result({"interrupted": True}, exit_code=130)return 130diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex f71fe651471..789996698ac 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -8,13 +8,16 @@ from hermes_cli.gateway_client import GatewayClientErrorclass GatewayChatView:- def __init__(self, client, snapshot, *, quiet=False):+ def __init__(self, client, snapshot, *, quiet=False, emitter=None):self.client = clientself.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.pending = snapshot.get("pending", [])- self.quiet = quiet+ # ``--format stream-json``: stdout belongs to the JSONL protocol, so every human line is+ # replaced by an emitter event and the terminal record carries the exit code.+ self.emitter = emitter+ self.quiet = quiet or emitter is not Noneself.finite = Falseself.streams = {}self.completions = {}@@ -58,6 +61,7 @@ class GatewayChatView:admission = params.get("admission_id") or payload.get("admission_id")handler = {"message.delta": self._delta, "message.complete": self._complete,+ "tool.start": self._tool_start, "tool.complete": self._tool_complete,"approval.request": self._request, "clarify.request": self._request,"approval.settled": self._settled, "clarify.settled": self._settled,}.get(kind)@@ -65,9 +69,24 @@ class GatewayChatView:handler(admission, payload)self.changed.set()+ def _tool_start(self, admission, payload):+ if self.emitter is not None:+ self.emitter.on_tool_progress("tool.started", payload.get("tool_name"), None, payload.get("args"),+ tool_call_id=payload.get("tool_call_id") or None)++ def _tool_complete(self, admission, payload):+ if self.emitter is not None:+ self.emitter.on_tool_progress("tool.completed", payload.get("tool_name"), None, payload.get("args"),+ tool_call_id=payload.get("tool_call_id") or None,+ result=payload.get("result"), is_error=payload.get("is_error", False))+def _delta(self, admission, payload):text = payload.get("text") or payload.get("delta") or payload.get("content") or ""- if isinstance(text, str) and not self.quiet:+ if not isinstance(text, str):+ return+ if self.emitter is not None:+ self.emitter.on_text_delta(text)+ elif not self.quiet:self.streams[admission] = self.streams.get(admission, "") + textprint(text, end="", flush=True)@@ -168,8 +187,14 @@ class GatewayChatView:return 3await self.changed.wait()terminal = self.completions[admission]+ outcome = terminal.get("outcome")+ if self.emitter is not None:+ return self.emitter.emit_result(+ {"final_response": terminal.get("text") or terminal.get("content") or "",+ "failed": outcome not in ("completed", "cancelled"), "interrupted": outcome == "cancelled"},+ session_id=self.session_id, exit_code=130 if outcome == "cancelled" else 0)print(terminal.get("text") or terminal.get("content") or "", flush=True)- return 0 if terminal.get("outcome") == "completed" else 1+ return 0 if outcome == "completed" else 1from prompt_toolkit import PromptSessionfrom prompt_toolkit.patch_stdout import patch_stdoutprompt = PromptSession()diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex b13e3c5f909..e78eb3d3d5b 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -1738,15 +1738,16 @@ _CHAT_PASSTHROUGH = (def cmd_chat(args):"""Run interactive chat CLI."""- if _bypass_chat_launch(args) or not _resolve_use_tui(args):+ from hermes_cli.stream_json import stream_json_requested+ # Structured stdout is a non-interactive protocol: it overrides HERMES_TUI/display.interface too,+ # so it is decided before the TUI gate and always rides the gateway transport.+ if stream_json_requested(args) or _bypass_chat_launch(args) or not _resolve_use_tui(args):from hermes_cli.gateway_chat_startup import launch_gateway_chatsys.exit(launch_gateway_chat(args))_apply_safe_mode(args)_apply_user_config_bypass(args)_guard_noninteractive_user_config(args)- from hermes_cli.stream_json import stream_json_requested- # Structured stdout is a non-interactive protocol: it overrides HERMES_TUI/display.interface too.- use_tui = False if stream_json_requested(args) else _resolve_use_tui(args)+ use_tui = _resolve_use_tui(args)_resolve_chat_session_args(args, use_tui)diff --git a/hermes_cli/stream_json.py b/hermes_cli/stream_json.pyindex d134f3eff25..b58101a1ae8 100644--- a/hermes_cli/stream_json.py+++ b/hermes_cli/stream_json.py@@ -50,6 +50,11 @@ class StreamJsonEmitter:agent.tool_progress_callback = self.on_tool_progressreturn self+ def bind_session(self, session_id: str) -> None:+ """Record the id the gateway assigned after ``init`` was written, so an interrupted or failed+ run still reports which session holds the accepted work."""+ self._session_id = session_id or self._session_id+def on_text_delta(self, text: str | None) -> None:# Only None/"" (the turn-end sentinel) is dropped: whitespace deltas are part of the text, and# a consumer concatenating ``text`` events must reproduce the answer byte for byte.diff --git a/tests/hermes_cli/test_gateway_chat_failures.py b/tests/hermes_cli/test_gateway_chat_failures.pyindex df74da868a5..dda0a4183f7 100644--- a/tests/hermes_cli/test_gateway_chat_failures.py+++ b/tests/hermes_cli/test_gateway_chat_failures.py@@ -11,7 +11,7 @@ def test_direct_query_alias_survives_noninteractive_launch(monkeypatch):from hermes_cli import gateway_chat_startupseen = []- async def run(args):+ async def run(args, emitter=None):seen.append(args.q)return 0diff --git a/tests/hermes_cli/test_stream_json.py b/tests/hermes_cli/test_stream_json.pyindex e7c8df5d111..435fe0c6c97 100644--- a/tests/hermes_cli/test_stream_json.py+++ b/tests/hermes_cli/test_stream_json.py@@ -1,7 +1,6 @@"""``hermes chat -q … --format stream-json`` emits a parseable JSONL event stream and nothing else on stdout."""import json-import signalimport pytest@@ -43,57 +42,44 @@ def test_emitter_event_stream_is_valid_jsonl(capsys):assert all("timestamp" in e for e in events)-def _run_stream_json_chat(monkeypatch, capsys, run_conversation, credentials_ok=True):- """parser → cmd_chat → cli.main → quiet single-query path with a deterministic fake agent."""- import cli- import hermes_cli.main as cli_entry- from hermes_cli._parser import build_top_level_parser-- class FakeAgent:- model = "test-model"- session_id = "session-123"-- def run_conversation(self, **_kwargs):- return run_conversation(self)-- class FakeCLI:- def __init__(self, **_kwargs):- self.session_id = "session-123"- self.conversation_history = []- self.agent = None- self._active_agent_route_signature = None- self.tool_progress_mode = None+def _run_stream_json_chat(monkeypatch, capsys, run_turn, credentials_ok=True):+ """parser → cmd_chat → gateway transport with a deterministic fake authority peer.- def _claim_active_session(self, *_a, **_k):- return True+ ``run_turn(peer)`` plays the authority: it queues the execution events a turn would publish and+ returns the terminal ``message.complete`` payload (or raises ``KeyboardInterrupt`` for Ctrl-C).+ """+ import asyncio+ from contextlib import asynccontextmanager- def _ensure_runtime_credentials(self):- return credentials_ok-- def _resolve_turn_agent_config(self, _query):- return {"signature": "r", "model": None, "runtime": None, "request_overrides": None}-- def _init_agent(self, **_kwargs):- self.agent = FakeAgent()- return True-- def chat(self, _query, images=None):- print("human output") # must never reach stdout under stream-json+ import hermes_cli.main as cli_entry+ from hermes_cli import gateway_chat, gateway_chat_startup+ from hermes_cli._parser import build_top_level_parser- monkeypatch.setattr(cli, "HermesCLI", FakeCLI)- monkeypatch.setattr(cli, "_finalize_single_query", lambda _cli: None)- monkeypatch.setattr(cli, "_emit_interrupted_session_end", lambda *_a, **_k: None)- monkeypatch.setattr(cli, "_start_worktree_setup", lambda *_a, **_k: None)- monkeypatch.setattr(cli.atexit, "register", lambda *_a, **_k: None)- monkeypatch.setattr(signal, "signal", lambda *_a, **_k: None)+ class Peer:+ def __init__(self):+ self.events = asyncio.Queue()++ def emit(self, kind, payload, admission="adm-1"):+ self.events.put_nowait({"method": "event", "params": {+ "type": kind, "session_id": "session-123", "admission_id": admission, "payload": payload}})++ async def rpc(self, method, **params):+ if method == "runtime.describe":+ return {"session_create": {"sources": ["cli"], "parameters": ["cwd", "model", "request_id", "source"]}}+ if method == "session.create":+ return {"stored_session_id": "session-123", "info": {"model": "test-model"}}+ assert method == "prompt.submit"+ self.emit("message.complete", {**run_turn(self), "admission_id": "adm-1"})+ return {"admission_id": "adm-1"}++ @asynccontextmanager+ async def connected():+ yield Peer()++ monkeypatch.setattr(gateway_chat, "connect_gateway", connected)+ monkeypatch.setattr(gateway_chat_startup, "ensure_launch_provider", lambda _args: credentials_ok)monkeypatch.setattr(cli_entry, "_resolve_use_tui", lambda _args: pytest.fail("TUI resolution consulted"))- monkeypatch.setattr(cli_entry, "_has_any_provider_configured", lambda: True)- monkeypatch.setattr(cli_entry, "_start_chat_background_prefetch", lambda: None)- monkeypatch.setattr(cli_entry, "_pin_kanban_board_env", lambda: None)monkeypatch.setattr(cli_entry, "_confirm_startup_expensive_model_override", lambda _a: None)- monkeypatch.setattr(cli_entry, "_warn_retired_xai_models", lambda: None)- monkeypatch.setattr("hermes_cli.free_tier_bootstrap.run_bootstrap", lambda **_k: None)- monkeypatch.setattr("hermes_cli.quiet_single_query.continue_quiet_notify_completions", lambda *_a, **_k: None)parser, _, _ = build_top_level_parser()args = parser.parse_args(["chat", "-q", "hello", "--format", "stream-json"])@@ -102,21 +88,22 @@ def _run_stream_json_chat(monkeypatch, capsys, run_conversation, credentials_ok=return exc_info.value.code, _events(capsys)-def _ok_turn(agent):- agent.stream_delta_callback("hello")- agent.tool_progress_callback("tool.started", "read_file", "p", {"path": "f"})- agent.tool_progress_callback("tool.completed", "read_file", None, None, duration=0.01, result="contents")- return {"final_response": "hello", "failed": False}+def _ok_turn(peer):+ peer.emit("message.delta", {"text": "hello"})+ peer.emit("tool.start", {"tool_call_id": "c1", "tool_name": "read_file", "args": {"path": "f"}})+ peer.emit("tool.complete", {"tool_call_id": "c1", "tool_name": "read_file", "args": {"path": "f"},+ "is_error": False, "result": "contents"})+ return {"text": "hello", "outcome": "completed"}-def _interrupted_turn(_agent):+def _interrupted_turn(_peer):raise KeyboardInterrupt@pytest.mark.parametrize("turn, credentials_ok, exit_code, types", [(_ok_turn, True, 0, ["system", "text", "tool_use", "tool_result", "result"]),(_interrupted_turn, True, 130, ["system", "result"]),- (_ok_turn, False, 1, ["system", "result"]), # credentials fail before the agent exists+ (_ok_turn, False, 1, ["system", "result"]), # credentials fail before any session exists])def test_chat_stream_json_implies_quiet_and_closes_with_result(monkeypatch, capsys, turn, credentials_ok, exit_code,types):@@ -124,7 +111,9 @@ def test_chat_stream_json_implies_quiet_and_closes_with_result(monkeypatch, capscode, events = _run_stream_json_chat(monkeypatch, capsys, turn, credentials_ok=credentials_ok)assert code == exit_codeassert [e["type"] for e in events] == types- assert events[-1]["exit_code"] == exit_code and events[-1]["session_id"] == "session-123"+ assert events[-1]["exit_code"] == exit_code+ # A launch refused before the gateway created a session has none to report.+ assert events[-1]["session_id"] == ("session-123" if credentials_ok else "")@pytest.mark.parametrize("argv, message", [