Skip to content

The agent that grows with you

fix(cli): hermes -z prints the streamed reply and names a textless exit

unsupportedpastels430fcc8f13a9
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 59a64dd17c4..2cd5315513d 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -2072,20 +2072,12 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
async def _run_agent_mark_streamed_delivery(self, response: Any, turn_ctx: TurnContext) -> None:
"""Set ``response["already_sent"]`` when streaming already delivered the final reply.
- Never when the agent failed (the error is unseen content) or on "(empty)". Both suppression
- flags reflect call success, not content, so reconcile against the recorded turn-final
- payload: a mismatch (False, incl. payload-less split delivery) never suppresses; None (no
- record) keeps legacy trust."""
- _sc, source, session_key = turn_ctx.stream_consumer_holder[0], turn_ctx.source, turn_ctx.session_key
- if not isinstance(response, dict) or response.get("failed"):
- return
- # A finite viewer (``hermes -z``, stream-json) prints only the terminal reply: it drops the
- # message.delta frames, so streaming delivered nothing to it however the consumer's transport
- # finalized — the same reason the delta callback raises _NoStreamConsumer (run_turn_runner).
- # Suppressing the final send here blanks the completion frame's text, the one delivery a
- # finite viewer has, and the turn settles "completed" with no reply (#139666).
+ Never when the agent failed (unseen error), on "(empty)", or on a finite (`-z`, `chat -q`) turn:
+ its viewer prints only the completion text, never the deltas (#139666). Both flags reflect call
+ success, not content: a mismatch with the recorded turn-final payload never suppresses."""
from gateway.session_finite import finite_turn_required
- if finite_turn_required() is True:
+ _sc, source, session_key = turn_ctx.stream_consumer_holder[0], turn_ctx.source, turn_ctx.session_key
+ if not isinstance(response, dict) or response.get("failed") or finite_turn_required() is True:
return
_final = response.get("final_response") or ""
_is_empty_sentinel = not _final or _final == "(empty)"
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 95ed7ee5ef5..b0556d8808d 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -398,6 +398,11 @@ class GatewayChatView:
print(f"Turn interrupted{f' ({reason})' if isinstance(reason, str) and reason else ''}; "
"it was not retried. Resume this session to continue.", file=sys.stderr)
+ def _report_no_reply(self, exit_code):
+ """`-z` exit 1 (a completed turn with no reply text): the in-process one-shot's stderr line."""
+ if self.unattended and exit_code == 1:
+ print("hermes -z: no final response was produced; treating the run as failed.", file=sys.stderr)
+
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
@@ -460,6 +465,7 @@ class GatewayChatView:
session_id=self.session_id, exit_code=exit_code)
self._report_silent_interrupt(text, result)
print(text, flush=True)
+ self._report_no_reply(exit_code)
# 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).
diff --git a/tests/hermes_cli/test_gateway_chat_failures.py b/tests/hermes_cli/test_gateway_chat_failures.py
index 7a0664496c6..34e42a386a7 100644
--- a/tests/hermes_cli/test_gateway_chat_failures.py
+++ b/tests/hermes_cli/test_gateway_chat_failures.py
@@ -145,6 +145,19 @@ async def test_finite_exit_code_follows_the_committed_result_not_the_outcome(out
assert capsys.readouterr().out == (result["final_response"] + "\n") * 2
+async def test_textless_oneshot_names_the_failure_on_stderr(capsys):
+ """`-z` exits 1 for a completed turn with no reply text, and says so on stderr as the in-process
+ one-shot did (#139666): a script must not get a silent exit 1."""
+ from hermes_cli.gateway_chat_view import GatewayChatView
+
+ view = GatewayChatView(_SettledPeer("completed", {"completed": True, "final_response": ""}),
+ {"stored_session_id": "stored"}, quiet=True)
+ view.unattended = True
+ assert await asyncio.wait_for(view.run("query", oneshot=True), 2) == 1
+ assert "hermes -z: no final response was produced" in capsys.readouterr().err
+
+
@pytest.mark.asyncio
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
diff --git a/tests/hermes_cli/test_oneshot_streamed_live.py b/tests/hermes_cli/test_oneshot_streamed_live.py
new file mode 100644
index 00000000000..9e0f7ea87ae
--- /dev/null
+++ b/tests/hermes_cli/test_oneshot_streamed_live.py
@@ -0,0 +1,74 @@
+"""`hermes -z` against a real gateway with streaming on: the one-shot prints the reply (#139666).
+
+With ``streaming.enabled`` the local route's stream consumer "delivers" the reply through
+``LocalSessionAdapter`` (every send acknowledges), the turn is marked ``already_sent`` and the
+completion frame used to carry no text. A finite viewer drops ``message.delta`` frames and prints
+only that text, so `-z` printed a bare newline and exited 1 while the answer sat in state.db."""
+import json
+from http.server import ThreadingHTTPServer
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import threading
+import time
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model
+from tests.gateway.test_normal_runtime_boot import control
+
+
+def test_streamed_oneshot_prints_the_reply(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user, work = tmp_path / "state", tmp_path / "user", tmp_path / "work"
+ for path in (user, work):
+ path.mkdir()
+ home.mkdir(mode=0o700)
+ peer = ThreadingHTTPServer(("127.0.0.1", 0), Model)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ url = f"http://127.0.0.1:{peer.server_port}/v1"
+ (home / "config.yaml").write_text(json.dumps({
+ "gateway": {"multiplex_profiles": False},
+ "streaming": {"enabled": True},
+ "model": {"provider": "custom", "default": "oneshot-model", "base_url": url},
+ "auxiliary": {"title_generation": {"enabled": False}}}))
+ env = {k: os.environ[k] for k in ("PATH", "LANG", "TZ") if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ PYTHONUNBUFFERED="1", OPENAI_API_KEY="loopback-only", OPENAI_BASE_URL=url)
+
+ def hermes(*args):
+ return subprocess.run([sys.executable, "-m", "hermes_cli.main", *args], cwd=work, env=env,
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120, check=False)
+
+ with (home / "gw.log").open("w") as log:
+ daemon = subprocess.Popen([sys.executable, "-m", "gateway.run"], cwd=root, env=env,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
+ try:
+ deadline, desc = time.monotonic() + 60, {}
+ while daemon.poll() is None and time.monotonic() < deadline and desc.get("state") != "ready":
+ try:
+ desc = control(home, "identify")
+ except (OSError, ValueError):
+ time.sleep(.1)
+ assert desc.get("state") == "ready", (home / "gw.log").read_text()
+
+ oneshot = hermes("-z", "streamed one shot")
+ assert peer.requests and peer.requests[-1].get("stream"), "the turn must stream"
+ assert (oneshot.returncode, oneshot.stdout) == (0, "RECOVERY_ACK_streamed one shot\n"), oneshot
+ quiet = hermes("chat", "-q", "streamed quiet query", "-Q")
+ assert quiet.returncode == 0 and quiet.stdout.strip() == "RECOVERY_ACK_streamed quiet query", quiet
+ finally:
+ if daemon.poll() is None:
+ daemon.send_signal(signal.SIGINT)
+ try:
+ daemon.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ daemon.kill()
+ daemon.wait(timeout=5)
+ peer.shutdown()
+ peer.server_close()