Skip to content

The agent that grows with you

fix(cli): `hermes -z` exits non-zero for partial, failed and interrupted runs even when text was printed

teknium1391a7007fb7e
diff --git a/hermes_cli/oneshot.py b/hermes_cli/oneshot.py
index e06d7158189..524a6c2530e 100644
--- a/hermes_cli/oneshot.py
+++ b/hermes_cli/oneshot.py
@@ -24,11 +24,13 @@ _ALL_TOOLSETS = {"all", "*"}
# Keys copied from the run result into the ``--usage-file`` report. ``service_tier`` is a
# billing-audit field: the tier REQUESTED via request_overrides.extra_body (None when unset), so
-# batch pipelines can verify the tier they pay for went out on the wire.
+# batch pipelines can verify the tier they pay for went out on the wire. ``partial`` /
+# ``interrupted`` / ``turn_exit_reason`` say WHY ``completed`` is false, so a pipeline can tell
+# an iteration-budget stop from a Ctrl-C without parsing stderr (#111770).
_USAGE_KEYS = (
"estimated_cost_usd", "cost_status", "cost_source", "input_tokens", "output_tokens",
"cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "total_tokens", "api_calls",
- "model", "provider", "session_id", "completed",
+ "model", "provider", "session_id", "completed", "partial", "interrupted", "turn_exit_reason",
)
# Counters summed per auxiliary task (vision, compression, title_generation, ...) into the
@@ -82,6 +84,27 @@ def _auxiliary_report(report: dict, by_task: dict[str, dict]) -> None:
"api_calls": (report.get("api_calls") or 0) + totals["api_calls"],
}
+# Exit code for a turn stopped by an interrupt (SIGINT convention, same as ``chat -Q``).
+_INTERRUPTED_EXIT_CODE = 130
+
+
+def _oneshot_exit_code(response: Optional[str], result: dict) -> int:
+ """Map a finished ``-z`` turn onto its exit code: ``0`` only when the turn completed;
+ ``130`` interrupted; ``2`` failed or stopped partway (``partial``, ``completed: False`` such
+ as the iteration budget); ``1`` a completed turn that produced no text at all.
+
+ The outcome is judged from the result, not from whether text was printed: a partial or
+ failed turn usually leaves an explanation on stdout, and exiting 0 for it made scripts treat
+ a half-done job (or a provider error summary) as success (#111770).
+ """
+ if result.get("interrupted"):
+ return _INTERRUPTED_EXIT_CODE
+ if result.get("failed") or result.get("partial") or result.get("completed") is False:
+ return 2
+ if not (response or "").strip():
+ return 1
+ return 0
+
def _normalize_toolsets(toolsets: object = None) -> list[str] | None:
"""Split repeated/comma-separated toolset flags into a clean list (``None`` when empty)."""
@@ -313,13 +336,11 @@ def run_oneshot(
real_stdout.write("\n")
real_stdout.flush()
- if not (response or "").strip():
- if result.get("failed") or result.get("partial"):
- return 2
+ exit_code = _oneshot_exit_code(response, result)
+ if exit_code == 1:
real_stderr.write("hermes -z: no final response was produced; treating the run as failed.\n")
real_stderr.flush()
- return 1
- return 0
+ return exit_code
def _create_session_db_for_oneshot():
diff --git a/tests/hermes_cli/test_oneshot_exit_contract.py b/tests/hermes_cli/test_oneshot_exit_contract.py
new file mode 100644
index 00000000000..ec80f2468ca
--- /dev/null
+++ b/tests/hermes_cli/test_oneshot_exit_contract.py
@@ -0,0 +1,41 @@
+"""``hermes -z`` exit-code contract: the outcome is judged from the turn result, not from
+whether any text was printed (#111770 — an incomplete or failed run that left an explanation on
+stdout used to exit 0, so scripts treated a half-done job as success)."""
+
+from unittest import mock
+
+import hermes_cli.oneshot as oneshot
+
+
+def _run(monkeypatch, tmp_path, response, result):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ usage = tmp_path / "usage.json"
+ with mock.patch.object(oneshot, "_run_agent", return_value=(response, dict(result))):
+ code = oneshot.run_oneshot("q", usage_file=str(usage))
+ return code, usage
+
+
+def test_incomplete_run_with_text_exits_nonzero_and_reports_why(monkeypatch, tmp_path):
+ import json
+
+ partial = {"final_response": "Got as far as step 2.", "completed": False, "partial": True,
+ "turn_exit_reason": "iteration_limit"}
+ code, usage = _run(monkeypatch, tmp_path, "Got as far as step 2.", partial)
+ assert code == 2
+ report = json.loads(usage.read_text(encoding="utf-8"))
+ assert report["completed"] is False and report["partial"] is True
+ assert report["turn_exit_reason"] == "iteration_limit"
+
+ interrupted = {"final_response": "Stopping.", "completed": False, "interrupted": True}
+ code, usage = _run(monkeypatch, tmp_path, "Stopping.", interrupted)
+ assert code == 130
+ assert json.loads(usage.read_text(encoding="utf-8"))["interrupted"] is True
+
+ failed = {"final_response": "Provider returned 401.", "completed": False, "failed": True}
+ code, _ = _run(monkeypatch, tmp_path, "Provider returned 401.", failed)
+ assert code == 2
+
+
+def test_completed_run_still_exits_zero(monkeypatch, tmp_path):
+ code, _ = _run(monkeypatch, tmp_path, "Paris.", {"final_response": "Paris.", "completed": True, "failed": False})
+ assert code == 0
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index a799d8f5a6b..4c6917123f5 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -237,9 +237,15 @@ HERMES_INFERENCE_MODEL=anthropic/claude-sonnet-4.6 hermes -z "…"
Same agent, same tools, same skills — just strips every interactive / cosmetic layer. If you need tool output in the transcript too, use `hermes chat --oneshot -q` instead; `-z` is explicitly for "I only want the final answer".
+Exit codes: `0` the turn completed; `2` it failed or stopped partway (`partial`,
+iteration budget, `completed: false`) — even when an explanation was printed;
+`130` it was interrupted; `1` a completed turn produced no text at all; `2` also
+for usage errors (bad flags) before the run starts. Judge the run by the exit
+code (or the `--usage-file` flags), not by whether stdout is non-empty.
+
#### `--usage-file` — JSON usage report for pipelines
-`hermes -z "…" --usage-file /path/report.json` writes a machine-readable usage report after the run: `estimated_cost_usd`, `input_tokens` / `output_tokens` / `cache_read_tokens` / `cache_write_tokens` / `reasoning_tokens` / `total_tokens`, `api_calls`, `model`, `provider`, `session_id`, `service_tier`, and `completed` / `failed` flags. Those top-level counters cover the **main agent loop** only. Auxiliary LLM calls made on the same run (title generation, vision, context compression, `web_extract`, background review, …) are reported separately under `auxiliary` — the same totals plus a per-task `by_task` map — and `total_including_auxiliary` (`estimated_cost_usd`, `total_tokens`, `api_calls`) is the grand total to bill on. The report is written **even when the run fails**, so batch pipelines can always account for spend. It has no effect outside `-z`/`--oneshot`, and a broken usage write never masks the run's own outcome.
+`hermes -z "…" --usage-file /path/report.json` writes a machine-readable usage report after the run: `estimated_cost_usd`, `input_tokens` / `output_tokens` / `cache_read_tokens` / `cache_write_tokens` / `reasoning_tokens` / `total_tokens`, `api_calls`, `model`, `provider`, `session_id`, `service_tier`, the `completed` / `failed` / `partial` / `interrupted` flags and `turn_exit_reason` (why `completed` is false, e.g. `max_iterations_reached(3/3)`). Those top-level counters cover the **main agent loop** only. Auxiliary LLM calls made on the same run (title generation, vision, context compression, `web_extract`, background review, …) are reported separately under `auxiliary` — the same totals plus a per-task `by_task` map — and `total_including_auxiliary` (`estimated_cost_usd`, `total_tokens`, `api_calls`) is the grand total to bill on. The report is written **even when the run fails**, so batch pipelines can always account for spend. It has no effect outside `-z`/`--oneshot`, and a broken usage write never masks the run's own outcome.
```bash
hermes -z "summarize this repo" --usage-file /tmp/usage.json