The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway_chat): one-shot refuses an unknown-blocked session; stream-json always closes with a result
teknium108b6ebd05155
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 789996698ac..a6e16db55aa 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -26,8 +26,11 @@ class GatewayChatView:from hermes_cli.gateway_mutations import PreparedMutationsself.mutations = PreparedMutations()+ def unknown_admissions(self):+ return [row["admission_id"] for row in self.pending if row["status"] == "unknown"]+def show_pending(self):- unknown = any(row["status"] == "unknown" for row in self.pending)+ unknown = bool(self.unknown_admissions())if unknown:print("Execution outcome unknown after restart. Discard acknowledges the lost turn ""without replaying it; queued work may then continue.", file=sys.stderr)@@ -165,12 +168,27 @@ class GatewayChatView:return Trueraise GatewayClientError("Unsupported gateway CLI command; use /help. No local command was run.")+ def _detach(self, message):+ """One-shot cannot go on without a human: say why on stderr, exit 3, and in stream-json+ mode close the protocol with a failed ``result`` (a consumer parsing stdout must never be+ left without a terminal record)."""+ print(message, file=sys.stderr)+ if self.emitter is not None:+ return self.emitter.emit_result({"failed": True, "error": message}, session_id=self.session_id, exit_code=3)+ return 3+async def run(self, query=None, *, oneshot=False):self.quiet = self.quiet or oneshotself.finite = oneshotself.show_pending()for prompt in self.prompts.values():self.show_prompt(prompt)+ if oneshot and self.unknown_admissions():+ # A new admission would queue behind the unknown row and never run; refuse BEFORE+ # submitting so nothing is left queued for the next interactive resume to find.+ lost = " ".join(self.unknown_admissions())+ return self._detach("Unknown execution blocks this session; nothing was submitted. Resolve it "+ f"interactively with /discard {lost} (prompt.resolve_unknown), then retry.")renderer = asyncio.create_task(self.render())try:receipt = await self.submit(query) if query else None@@ -183,8 +201,7 @@ class GatewayChatView:if self.failure:raise self.failureif self.prompts:- print("Input required; detached without cancelling. Resume this session interactively.", file=sys.stderr)- return 3+ return self._detach("Input required; detached without cancelling. Resume this session interactively.")await self.changed.wait()terminal = self.completions[admission]outcome = terminal.get("outcome")diff --git a/tests/hermes_cli/test_gateway_chat_failures.py b/tests/hermes_cli/test_gateway_chat_failures.pyindex dda0a4183f7..08994134616 100644--- a/tests/hermes_cli/test_gateway_chat_failures.py+++ b/tests/hermes_cli/test_gateway_chat_failures.py@@ -57,3 +57,50 @@ async def test_oneshot_matches_own_terminal_receipt_not_neighbor(capsys):view = GatewayChatView(Peer(), {"stored_session_id": "stored"}, quiet=True)assert await asyncio.wait_for(view.run("query", oneshot=True), 2) == 1assert capsys.readouterr().out == "mine\n"+++async def test_oneshot_refuses_unknown_blocked_session_before_submitting(capsys):+ """After a SIGKILL mid-turn the head admission is ``unknown``; a new -q admission would queue+ behind it forever. One-shot refuses BEFORE submitting (exit 3) and names the discard remedy."""+ from hermes_cli.gateway_chat_view import GatewayChatView++ class Peer:+ events = asyncio.Queue()+ async def rpc(self, method, **params):+ raise AssertionError(f"nothing may be submitted behind an unknown row: {method}")++ lost = "admission-unknown-0123456789abcdef"+ snapshot = {"stored_session_id": "stored", "pending": [{"admission_id": lost, "status": "unknown", "execution_generation": 4}]}+ assert await asyncio.wait_for(GatewayChatView(Peer(), snapshot, quiet=True).run("pong", oneshot=True), 2) == 3+ err = capsys.readouterr().err+ assert f"/discard {lost}" in err and "prompt.resolve_unknown" in err and "nothing was submitted" in err++[email protected]("blocker", ["unknown_row", "approval_prompt"])+async def test_stream_json_oneshot_always_closes_with_a_result_record(capsys, blocker):+ """``--format stream-json`` consumers parse stdout: every exit-3 detach (unknown row refused,+ approval needed) must end the JSONL with a failed ``result`` record carrying exit_code 3."""+ import json+ from hermes_cli.gateway_chat_view import GatewayChatView+ from hermes_cli.stream_json import StreamJsonEmitter++ class Peer:+ events = asyncio.Queue()+ async def rpc(self, method, **params):+ assert blocker == "approval_prompt" and method == "prompt.submit"+ self.events.put_nowait({"method": "event", "params": {+ "type": "approval.request", "session_id": "stored", "admission_id": "mine",+ "payload": {"prompt_id": "p1", "kind": "approval", "command": "rm -rf /", "choices": ["yes", "no"],+ "execution_generation": 1}}})+ return {"admission_id": "mine"}++ pending = [{"admission_id": "lost", "status": "unknown", "execution_generation": 4}] if blocker == "unknown_row" else []+ emitter = StreamJsonEmitter(model="m", session_id="stored")+ view = GatewayChatView(Peer(), {"stored_session_id": "stored", "pending": pending}, emitter=emitter)+ assert await asyncio.wait_for(view.run("pong", oneshot=True), 2) == 3+ records = [json.loads(line) for line in capsys.readouterr().out.splitlines() if line.strip()]+ assert records[0]["type"] == "system" and records[-1]["type"] == "result", records+ assert records[-1]["exit_code"] == 3 and records[-1]["error"], records[-1]+ assert sum(r["type"] == "result" for r in records) == 1