The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): finite gateway chat exits non-zero when the turn did not finish
Teknium646bfc4c094e
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 33242552969..9a0014122ed 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -243,22 +243,25 @@ class GatewayChatView:return self.emitter.emit_result({"failed": True, "error": message}, session_id=self.session_id, exit_code=3)return 3- async def _write_usage_file(self, admission, outcome):- """``-z --usage-file``: the same JSON ledger the in-process one-shot wrote, read from the- result the owner committed with this admission's settlement (best-effort, never raises)."""+ async def _settled_result(self, admission):+ """The structured result the owner committed with this admission's settlement — the same+ dict the in-process one-shot got from ``run_conversation`` (best-effort, never raises)."""from websockets.exceptions import WebSocketException- from hermes_cli.oneshot import _write_usage_file- result = {}try:receipt = await self.client.rpc("prompt.receipt", session_id=self.session_id,admission_id=admission, include_result=True)- result = dict(receipt.get("result") or {})+ return dict(receipt.get("result") or {})# Transport loss / refusal, or a receipt whose ``result`` is not a mapping.except (GatewayClientError, OSError, TimeoutError, WebSocketException,AttributeError, TypeError, ValueError) as exc:- # The ledger is still written from the outcome alone; a missing receipt is not fatal.- logger.debug("usage-file receipt for %s unavailable: %s", admission, exc)- result.setdefault("session_id", self.session_id)+ # The exit code and ledger still follow the settled outcome; a missing receipt is not fatal.+ logger.debug("settled result for %s unavailable: %s", admission, exc)+ return {}++ def _write_usage_file(self, result, outcome):+ """``-z --usage-file``: the same JSON ledger the in-process one-shot wrote."""+ from hermes_cli.oneshot import _write_usage_file+ result = {**result, "session_id": result.get("session_id") or self.session_id}failure = None if outcome in ("completed", "cancelled") else (result.get("error") or outcome or "failed")_write_usage_file(self.usage_file, result, failure=failure)@@ -296,19 +299,28 @@ class GatewayChatView:await self.changed.wait()terminal = self.completions[admission]outcome = terminal.get("outcome")+ text = terminal.get("text") or terminal.get("content") or ""+ # The outcome only says failed/cancelled; a turn stopped by --max-turns settles+ # 'completed' with ``completed: False`` in its committed result. Judge both with the+ # in-process exit contracts: `-z` 0/2/130 (1 = no text), `chat -q`/`-Q` 0/1/130.+ from hermes_cli.oneshot import _oneshot_exit_code+ from hermes_cli.turn_exit import turn_exit_code+ result = await self._settled_result(admission)+ result.update(failed=bool(result.get("failed")) or outcome not in ("completed", "cancelled"),+ interrupted=bool(result.get("interrupted")) or outcome == "cancelled")+ exit_code = (_oneshot_exit_code(text, result) if self.unattended+ else turn_exit_code(result, kanban_worker=False))if self.usage_file:- await self._write_usage_file(admission, outcome)+ self._write_usage_file(result, 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 self.emitter.emit_result({**result, "final_response": text},+ session_id=self.session_id, exit_code=exit_code)+ print(text, flush=True)# Same stderr exit contract as the legacy -Q path: automation wrappers read the# durable id from this line, and it names the physical row (a compaction may have# advanced it past the row printed at start).print(f"\nsession_id: {self.session_id}", file=sys.stderr, flush=True)- return 0 if outcome == "completed" else 1+ return exit_codefrom prompt_toolkit import PromptSessionfrom prompt_toolkit.patch_stdout import patch_stdoutfrom hermes_cli.skin_engine import get_active_prompt_symbol, get_active_skindiff --git a/tests/hermes_cli/test_gateway_chat_blocking_controls.py b/tests/hermes_cli/test_gateway_chat_blocking_controls.pyindex bd8de20370a..359e16d5403 100644--- a/tests/hermes_cli/test_gateway_chat_blocking_controls.py+++ b/tests/hermes_cli/test_gateway_chat_blocking_controls.py@@ -96,6 +96,8 @@ async def test_oneshot_applies_foreign_control_settlement_before_receipt(kind):events = asyncio.Queue()async def rpc(self, method, **params):+ if method == "prompt.receipt":+ return {"status": "terminal", "result": {"completed": True, "final_response": "done"}}assert method == "prompt.submit"self.events.put_nowait(_control_event(kind))self.events.put_nowait({diff --git a/tests/hermes_cli/test_gateway_chat_failures.py b/tests/hermes_cli/test_gateway_chat_failures.pyindex c7f63104e4d..7a0664496c6 100644--- a/tests/hermes_cli/test_gateway_chat_failures.py+++ b/tests/hermes_cli/test_gateway_chat_failures.py@@ -47,6 +47,9 @@ async def test_oneshot_matches_own_terminal_receipt_not_neighbor(capsys):class Peer:events = asyncio.Queue()async def rpc(self, method, **params):+ if method == "prompt.receipt":+ assert params["admission_id"] == "mine"+ return {"status": "terminal"}assert method == "prompt.submit"for admission, outcome in (("neighbor", "completed"), ("mine", "failed")):self.events.put_nowait({"method": "event", "params": {@@ -70,6 +73,8 @@ async def test_stream_json_oneshot_filters_neighbor_events_that_arrive_before_suevents = asyncio.Queue()async def rpc(self, method, **params):+ if method == "prompt.receipt":+ return {"status": "terminal", "result": {"completed": True, "final_response": "right"}}assert method == "prompt.submit"for admission, text in (("neighbor", "wrong"), ("mine", "right")):self.events.put_nowait({"method": "event", "params": {@@ -100,6 +105,62 @@ async def test_stream_json_oneshot_filters_neighbor_events_that_arrive_before_suassert all("wrong" not in json.dumps(row) and "neighbor-tool" not in json.dumps(row) for row in records)+class _SettledPeer:+ """Owner fake: the turn settles with ``outcome`` while its committed result says ``result``."""++ def __init__(self, outcome, result):+ self.events, self.outcome, self.result = asyncio.Queue(), outcome, result++ async def rpc(self, method, **params):+ if method == "prompt.receipt":+ assert params == {"session_id": "stored", "admission_id": "mine", "include_result": True}+ return {"status": "terminal", "outcome": self.outcome, "result": self.result}+ assert method == "prompt.submit"+ self.events.put_nowait({"method": "event", "params": {+ "type": "message.complete", "session_id": "stored", "admission_id": "mine",+ "payload": {"text": self.result.get("final_response", ""), "outcome": self.outcome}}})+ return {"admission_id": "mine"}+++_BUDGET = {"completed": False, "failed": False, "interrupted": False, "partial": False,+ "turn_exit_reason": "max_iterations_reached(1/1)",+ "final_response": "I reached the iteration limit and couldn't generate a summary."}++[email protected]("outcome,result,chat_code,z_code", [+ ("completed", _BUDGET, 1, 2), # --max-turns: settled 'completed' but the work did not finish+ ("completed", {"completed": True, "final_response": "done"}, 0, 0),+ ("cancelled", {"interrupted": True, "final_response": ""}, 130, 130),+])+async def test_finite_exit_code_follows_the_committed_result_not_the_outcome(outcome, result, chat_code, z_code, capsys):+ """A finite attached turn exits with the in-process contract judged from the settled result:+ `chat -q`/`-Q` 0/1/130 (``turn_exit_code``) and `-z` 0/2/130 (``_oneshot_exit_code``)."""+ from hermes_cli.gateway_chat_view import GatewayChatView++ for unattended, expected in ((False, chat_code), (True, z_code)):+ view = GatewayChatView(_SettledPeer(outcome, result), {"stored_session_id": "stored"}, quiet=True)+ view.unattended = unattended+ assert await asyncio.wait_for(view.run("query", oneshot=True), 2) == expected, (unattended, outcome)+ assert capsys.readouterr().out == (result["final_response"] + "\n") * 2+++async def test_stream_json_result_record_reports_an_unfinished_turn(capsys):+ """The terminal JSONL ``result`` carries the same non-zero exit for a --max-turns stop, plus the+ committed token counts, and the process exit code matches it."""+ import json+ from hermes_cli.gateway_chat_view import GatewayChatView+ from hermes_cli.stream_json import StreamJsonEmitter++ peer = _SettledPeer("completed", {**_BUDGET, "input_tokens": 10, "output_tokens": 5, "total_tokens": 15})+ view = GatewayChatView(peer, {"stored_session_id": "stored"}, emitter=StreamJsonEmitter(model="m", session_id="stored"))+ assert await asyncio.wait_for(view.run("query", oneshot=True), 2) == 1+ record = [json.loads(line) for line in capsys.readouterr().out.splitlines() if line.strip()][-1]+ assert record["type"] == "result" and record["exit_code"] == 1, record+ assert record["tokens"]["total"] == 15 and record["text"] == _BUDGET["final_response"]++@pytest.mark.asyncioasync def test_oneshot_replay_gap_fails_instead_of_waiting_forever():from hermes_cli.gateway_chat_view import GatewayChatView