HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
runner + gateway: a failed turn keeps the harness's own exception and stack trace, and names the base and the tool that failed (#545)
aswathasaec6af2953ed
diff --git a/gateway/app.py b/gateway/app.pyindex 0e7ce5b0..6902b1f1 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -4378,10 +4378,30 @@ def _refusal_message(conn: dict | None, err: str) -> str:return f"Your {provider} {what} was refused: {err or 'the provider returned an error'}"+def _failure_detail(rec: dict) -> dict:+ """Which base ran the turn and which tool failed, for the error's detail (#504). The message+ says the turn failed and why; this says WHICH harness and WHICH tool, so the debugging does+ not stop at the router. The runner's account of the failure names the tool; the base is the+ harness's own name for the family that ran it."""+ detail: dict = {}+ base = str(rec.get("base") or rec.get("backend") or "")+ if base:+ detail["base"] = base+ tool = str((rec.get("error_detail") or {}).get("tool") or "")+ if tool:+ detail["tool"] = tool+ return detail++def _fail_events(tr: "_RespTranslator", rec: dict) -> list[dict]:"""A failed turn's closing events: the error the turn proved (rec["error"], the hard cap's),- else its reason in words."""- return tr.fail(_turn_failure_message(rec), rec.get("error"))+ else its reason in words — with the detail that names the base and the tool that failed."""+ err = rec.get("error")+ if not isinstance(err, dict):+ err = {"type": "harness_error", "code": "turn_failed", "message": _turn_failure_message(rec)}+ if (detail := _failure_detail(rec)):+ err["detail"] = detail+ return tr.fail(_turn_failure_message(rec), err)def _turn_failure_message(rec: dict) -> str:@@ -8658,6 +8678,10 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s"prompt": prompt, "user_text": user_text, # raw user message — card titles use THIS,"model": model_req or translator.model, "tried": [], "status": "starting"}# never the runtime prompt with its file-note/instructions prepends+ # The base family that ran this turn (its own name for it, e.g. "claude-code"), for the error's+ # detail: which base failed is half of what a debugger needs (#504). The backend is the+ # fallback when the harness says no base of its own.+ rec["base"] = str((hv or {}).get("base") or backend)tr = _session_trace.setdefault(sid, {"prefix": None, "org": org, "since": 0, "chunk": 0, "count": 0})if not tr.get("prefix"):tr["prefix"] = _prefix_from_vertex(sid, await _vertex_get(sid))@@ -8994,6 +9018,11 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, sbreakcontinueheld = bool(s.get("held"))+ if s.get("error_detail"):+ # The runner's own account of the failure (#504): the base that ran, the tool that+ # failed, and the exception it printed. The base and the tool name the failure in+ # the response's error.detail.+ rec["error_detail"] = s["error_detail"]new = s.get("events") or []n_total = s.get("n_total", fed_upto)# Fed and emitted the moment they arrive. Asked for from fed_upto, so nothing comes twice.diff --git a/gateway/tests/test_failure_detail.py b/gateway/tests/test_failure_detail.pynew file mode 100644index 00000000..1874431e--- /dev/null+++ b/gateway/tests/test_failure_detail.py@@ -0,0 +1,169 @@+"""A failed turn's error names the base that ran and the tool that failed (#504).++The message says the turn failed and why; the detail says WHICH harness and WHICH tool, so the+debugging does not stop at the router. The runner's account of the failure (the tool's name) comes+in with the turn's record; the base is the harness's own name for the family that ran it.+"""+import asyncio+import json+import os+import pathlib+import sys+import time++import jsonschema++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+os.environ.setdefault("HR_BACKING", "local")+import app as gw # noqa: E402++_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+_SCHEMA = os.path.join(_ROOT, "protocol", "schema", "uhp-2026-08-11.schema.json")+ORG = "org_e"+++def _rec(**kw) -> dict:+ rec = {"base": "claude-code", "backend": "claude",+ "tried": [{"connection": "c", "status": "failed", "error": "boom"}],+ "error_detail": {"base": "claude", "tool": "Bash",+ "exception": "ValueError: the tool blew up"}}+ rec.update(kw)+ return rec+++def _failed(rec: dict) -> dict:+ tr = gw._RespTranslator("resp_test", "some-model", None, False, 0.0)+ gw._fail_events(tr, rec)+ return tr.error+++def test_the_error_names_the_base_and_the_tool():+ err = _failed(_rec())+ assert err["type"] == "harness_error" and err["code"] == "turn_failed"+ assert err["detail"] == {"base": "claude-code", "tool": "Bash"}+ assert "boom" in err["message"]+++def test_the_error_still_validates_against_the_spec():+ s = json.load(open(_SCHEMA))+ err = _failed(_rec())+ jsonschema.validate(err, {"$defs": s["$defs"], **s["$defs"]["Error"]})+++def test_a_turn_with_no_failing_tool_names_the_base_only():+ rec = _rec(error_detail={"base": "claude", "tool": "", "exception": "boom"})+ err = _failed(rec)+ assert err["detail"] == {"base": "claude-code"}+++def test_the_harnesses_own_base_is_named_when_it_says_one():+ rec = _rec(base="", backend="codex")+ err = _failed(rec)+ assert err["detail"] == {"base": "codex", "tool": "Bash"}+++def test_the_errors_own_detail_is_kept_where_the_turn_has_one():+ """A turn the server cut short (interrupted, capped) carries its own detail; the runner's+ account of a failure does not overwrite it."""+ rec = _rec(error=gw._cap_error())+ err = _failed(rec)+ assert err["detail"] == {"reason": "timeout"}+++# ── the whole path, from the runner's answer to the response and the trace ─────────────────────++def _drive_a_failed_turn(monkeypatch):+ """Run _resp_execute against a runner that answers a failed turn the way the runner answers+ one now: its own account of the failure (the base, the tool, the exception) beside the one+ line of reason. Returns (status, the record, the translator, the events written to the trace).+ """+ detail = {"base": "claude", "tool": "Bash",+ "exception": "ValueError: the tool blew up\n File \"/app/tools.py\", line 42, in run"}+ traced: list = []++ async def _sandbox_json(path, sid, method="POST", body=None, **kw):+ if path == "/turn":+ return {"turn_id": "t1", "status": "running"}+ if path.startswith("/turn/"):+ return {"done": True, "status": "failed", "error": "the CLI own sentence",+ "error_detail": detail,+ "events": [{"type": "result", "subtype": "error", "is_error": True,+ "result": "the CLI own sentence", "error_detail": detail}],+ "n_total": 1}+ return {}++ async def _nothing(*a, **kw):+ return None++ async def _get_connection(org, name):+ return ({"provider": "anthropic", "base_url": "https://proxy.example/v1"}, "tenant-1")++ async def _harness_plugins(*a, **kw):+ return ([], [], [], [], [])++ async def _harness_env(*a, **kw):+ return ({}, [])++ async def _image_auth(*a, **kw):+ return None++ def _auth_from_conn(*a, **kw):+ return {"token": "t", "base_url": "https://proxy.example/v1"}++ async def _turn_cancelled(*a, **kw):+ return False++ async def _collect_produced(*a, **kw):+ return []++ async def _trace_flush(tr, s):+ traced.extend(s.get("events") or [])+ return True++ for name, fn in (("_sandbox_json", _sandbox_json), ("_vertex_get", _nothing),+ ("_vertex_upsert", _nothing), ("_hydrate", _nothing),+ ("_harness_plugins", _harness_plugins), ("_harness_env", _harness_env),+ ("_image_auth", _image_auth), ("_get_connection", _get_connection),+ ("_auth_from_conn", _auth_from_conn), ("_turn_cancelled", _turn_cancelled),+ ("_collect_produced", _collect_produced), ("_blob_put", _nothing),+ ("_checkpoint", _nothing), ("_trace_finalize", _nothing),+ ("_browser_close", _nothing), ("_recover_trace_cursor", _nothing),+ ("_trace_flush", _trace_flush)):+ monkeypatch.setattr(gw, name, fn)+ monkeypatch.setattr(gw, "RESP_POLL_S", 0)+ monkeypatch.setattr(gw.control_store, "enabled", lambda: False)++ tr = gw._RespTranslator("resp_fail", "m", None, True, time.time())+ status, _produced, rec = asyncio.run(gw._resp_execute(+ tr, org=ORG, member="me@local", sid="sess_fail", backend="claude", chain=["anthropic"],+ prompt="hi", files_in=[], resume=None, emit=lambda ev: asyncio.sleep(0)))+ gw._fail_events(tr, rec) # what create_response does with a failed turn+ return status, rec, tr, traced+++def test_the_whole_path_names_the_base_and_the_tool_and_keeps_the_exception(monkeypatch):+ status, rec, tr, traced = _drive_a_failed_turn(monkeypatch)+ assert status == "failed", rec.get("tried")+ err = tr.error+ assert err["type"] == "harness_error" and err["code"] == "turn_failed"+ assert err["detail"] == {"base": "claude", "tool": "Bash"}+ assert "the CLI own sentence" in err["message"]+ # the trace keeps the harness's own account of the failure, exception and stack frames whole+ result_ev = [ev for ev in traced if ev.get("type") == "result"]+ assert result_ev and "ValueError: the tool blew up" in result_ev[-1]["error_detail"]["exception"]+ assert 'line 42, in run' in result_ev[-1]["error_detail"]["exception"]+++def test_a_result_with_the_failure_as_error_adds_no_answer():+ """The runner's own result for a CLI that died before it said anything carries the reason as+ `error` (runner/tests/test_failure_detail.py): fed to the translator it closes the turn and says+ nothing, where a reason in `result` was drawn as the agent's reply."""+ made = {"type": "result", "subtype": "error", "is_error": True, "result": "",+ "error": "ValueError: the tool blew up", "error_detail": {"base": "claude", "tool": ""}}+ tr = gw._RespTranslator("resp_made", "m", None, False, 0.0)+ tr.feed(made)+ assert not tr.any_text+ assert not [o for o in tr.output if o.get("type") == "message"]+ said = gw._RespTranslator("resp_said", "m", None, False, 0.0)+ said.feed({**made, "result": "ValueError: the tool blew up", "error": None})+ assert said.any_text # what the reason in `result` did: an answer the agent never gavediff --git a/runner/server.py b/runner/server.pyindex 58a78f68..68b590ea 100644--- a/runner/server.py+++ b/runner/server.py@@ -602,7 +602,7 @@ def _turn_secrets(env: dict, names: list | None) -> list[str]:# gateway reads the transcript by) or a role, and erase its own transcript from the trace (reported# privately, GHSA-7pwj-vv9r-rh2m). The turn's own fields are kept by POSITION, not by name anywhere:# a tool's input is an arbitrary map, and a "type" inside it is the agent's content.-_ANSWER_CONTENT = ("result", "error", "reason", "handoff", "events")+_ANSWER_CONTENT = ("result", "error", "reason", "handoff", "events", "error_detail")_ANSWER_KEEP = {"event": frozenset({"type", "subtype", "session_id", "uuid", "parent_tool_use_id", "model", "usage", "modelUsage","stop_reason"}),@@ -11896,15 +11896,19 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, mcontinuefor ev in normalize(obj, state):_settle(ev)- with _turns_lock:- rec["events"].append(ev)- if ev.get("type") == "system" and ev.get("subtype") == "init" and ev.get("session_id"):- rec["session_id"] = ev["session_id"] # CLI conversation id → next turn's --resumeif ev.get("type") == "result":+ # The turn's own ending is HELD BACK until the process is done (#504): the+ # harness's account of its failure (the exception and the stack frames) rides+ # this event, and an event already handed to the gateway cannot carry it.result_ev = ev# Claude's stream-json carries the final assistant text on the result event;# the codex normalizer already fills state['final'], so prefer that.state["final"] = state.get("final") or ev.get("result") or ""+ continue+ with _turns_lock:+ rec["events"].append(ev)+ if ev.get("type") == "system" and ev.get("subtype") == "init" and ev.get("session_id"):+ rec["session_id"] = ev["session_id"] # CLI conversation id → next turn's --resumeif (step_cap and not state.get("_stop") and ev.get("type") == "assistant"and _count_tool_calls(ev, state) > step_cap):state["_stop"] = "max_turns"@@ -11929,11 +11933,12 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, mif eof is not None and result_ev is None:for ev in eof(state, rc):_settle(ev)- with _turns_lock:- rec["events"].append(ev)if ev.get("type") == "result":- result_ev = ev+ result_ev = ev # held back like the CLI's own (see the loop above)state["final"] = state.get("final") or ev.get("result") or ""+ continue+ with _turns_lock:+ rec["events"].append(ev)if result_ev is None and state.get("_stop") == "max_turns":# Stopped at its budget before the CLI said anything terminal (codex's turn.completed# never comes once it is killed): the turn's result is the budget's, with what its@@ -11943,8 +11948,6 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, mif _running_usage(state):result_ev["usage"] = _running_usage(state) # the translator's count so far (pi, dsh)_settle(result_ev)- with _turns_lock:- rec["events"].append(result_ev)if (result_ev is not None and not result_ev.get("is_error")and _relay_last_finish(env) == "content_filter"):# The provider declined the last request (finish_reason content_filter, seen by the relay)@@ -11981,8 +11984,27 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m# keeps for a provider's refusal.refusal = "the provider declined the request (finish_reason content_filter)"rec["error"] = _failure_reason(refusal, str(ev_err), tail, rc)- if result_ev is not None and not str(result_ev.get("result") or "").strip() and tail:+ # The harness's own account of the failure, kept whole (#504): the exception and the stack+ # frames it printed, and the tool that failed. rec["error"] stays one line for a person —+ # the spec forbids a stack trace in a message — and this rides the trace's result event.+ detail = _failure_detail(str(rec.get("backend") or ""), rec["events"], tail)+ rec["error_detail"] = detail+ made = result_ev is None+ if made:+ # The CLI died before it said anything terminal: the trace gets a result event of its+ # own, so the failure is in the trace and not only in the record (#504). The reason+ # rides as `error`, never as `result`: the gateway shows a result's text as the turn's+ # answer when nothing was said before it, and the CLI said nothing.+ result_ev = {"type": "result", "subtype": "error", "is_error": True,+ "result": "", "error": rec["error"]}+ _settle(result_ev)+ result_ev["error_detail"] = detail+ if not made and not str(result_ev.get("result") or "").strip() and tail:result_ev["result"] = tail[:2000] # so the trace's result event isn't empty either+ if result_ev is not None:+ # The turn's ending goes out last, with the failure's own account of itself on it (#504).+ with _turns_lock:+ rec["events"].append(result_ev)rec["done"] = True@@ -12010,6 +12032,36 @@ def _failure_reason(refusal: str, ev_err: str, tail: str, rc: int) -> str:return (refusal or ev_err or tail or f"exit_code={rc}, no diagnostic output")[:2000]+_DIAG_MAX = 4000 # the harness's own diagnostic (its exception and stack frames), capped+++def _failed_tool(events: list[dict]) -> str:+ """The name of the tool whose result came back an error. Every normaliser emits the same+ Claude-shaped blocks — a tool_use carries the name, the tool_result that follows carries+ is_error — so this reads the same for every base; the LAST failed tool is the turn's."""+ names: dict[str, str] = {}+ failed = ""+ for ev in events:+ msg = ev.get("message")+ blocks = msg.get("content") if isinstance(msg, dict) else None+ for blk in blocks if isinstance(blocks, list) else []:+ if not isinstance(blk, dict):+ continue+ if blk.get("type") == "tool_use":+ names[str(blk.get("id") or "")] = str(blk.get("name") or "")+ elif blk.get("type") == "tool_result" and blk.get("is_error"):+ failed = names.get(str(blk.get("tool_use_id") or ""), "")+ return failed+++def _failure_detail(base: str, events: list[dict], diagnostic: str) -> dict:+ """What the harness itself said about the failure, kept whole (#504): the base that ran it,+ the tool that failed, and the exception and stack frames it printed (capped). The one line+ in rec["error"] is for a person — a message may not carry a stack trace (UHP errors §1) —+ and this is what a debugger needs."""+ return {"base": base, "tool": _failed_tool(events), "exception": diagnostic[:_DIAG_MAX]}++# Codex app-server JSON-RPC driver — the ONLY codex mode that streams assistant text (via# item/agentMessage/delta). Flag-gated; the default codex path stays `codex exec` (batch). We run# one turn per app-server process (spawn -> initialize -> thread start/resume -> turn -> done), a@@ -12276,6 +12328,12 @@ def _run_codex_appserver_bg(turn_id: str, cwd: str, env: dict, model: str, prompev["model"] = served_fill_relay_usage(ev, env)_stamp_thinking(ev, rec)+ if not ok and not stopped:+ # The app-server's own account of the failure, kept whole (#504): the exception and the+ # stack frames it printed, and the tool that failed.+ detail = _failure_detail(str(rec.get("backend") or ""), rec["events"], err_txt)+ ev["error_detail"] = detail+ rec["error_detail"] = detailappend(ev)rec["result"] = state["final"]rec["status"] = ("cancelled" if rec.get("cancelled") else "timeout" if rec.get("capped")@@ -12635,12 +12693,19 @@ def _run_hermes_bg(turn_id: str, cwd: str, env: dict, model: str, provider: str,ev["model"] = served_fill_relay_usage(ev, env)_stamp_thinking(ev, rec)+ status = ("cancelled" if rec.get("cancelled") else "timeout" if rec.get("capped")+ else "done" if ok else "failed")+ if not ok and status in ("failed", "timeout"):+ # hermes's own account of the failure, kept whole (#504): the exception and the stack+ # frames it printed, and the tool that failed.+ detail = _failure_detail(str(rec.get("backend") or ""), rec["events"], err_txt)+ ev["error_detail"] = detail+ rec["error_detail"] = detailappend(ev)rec["exit_code"] = rcrec["result"] = final- rec["status"] = ("cancelled" if rec.get("cancelled") else "timeout" if rec.get("capped")- else "done" if ok else "failed")- if not ok and rec["status"] in ("failed", "timeout"):+ rec["status"] = status+ if not ok and status in ("failed", "timeout"):rec["error"] = err_txtrec["done"] = True@@ -13899,6 +13964,10 @@ def _turn_answer(turn_id: str, rec: dict, since: int, held: bool) -> dict:"error": rec.get("error"), "backend": rec["backend"], "model": rec["model"],"session_id": rec.get("session_id"), "reason": rec.get("reason") or "","handoff": rec.get("handoff"),+ # The harness's own account of a failure (#504): the base, the tool that failed and the+ # exception and stack frames it printed. The gateway puts the base and the tool in the+ # response's error.detail; the trace carries the rest.+ "error_detail": rec.get("error_detail"),"events": evs, "n_total": n, "elapsed": round(time.time() - rec["started"], 1)}if held:out["held"] = Truediff --git a/runner/tests/test_failure_detail.py b/runner/tests/test_failure_detail.pynew file mode 100644index 00000000..1334c150--- /dev/null+++ b/runner/tests/test_failure_detail.py@@ -0,0 +1,142 @@+"""The harness's own account of a failure survives to the trace (#504).++A turn that failed keeps the exception and the stack frames the harness printed, and the name of+the tool that failed. The one line in rec["error"] is for a person — a message may not carry a+stack trace (UHP errors §1) — and the raw text is what a debugger needs. It is read from the+stream every base emits (a tool_use carries the name, the tool_result that follows carries+is_error), so it reads the same for claude and for codex.+"""+import json+import os+import pathlib+import sys+import time+import uuid++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import server as rs # noqa: E402+from server import _run_turn_bg, _turns # noqa: E402+++TRACEBACK = ("Traceback (most recent call last):\n"+ ' File "/app/tools.py", line 42, in run\n'+ ' raise ValueError("the tool blew up")\n'+ "ValueError: the tool blew up\n")+++def _claude_cli(tool: str = "Read", stderr_text: str = TRACEBACK) -> str:+ """A claude-shaped CLI: a tool call whose result came back an error, the CLI's own result+ event, then the traceback it printed when the tool raised."""+ lines = [+ "import json,sys",+ "print(json.dumps({'type':'system','subtype':'init','session_id':'s1'}), flush=True)",+ "print(json.dumps({'type':'assistant','message':{'content':[{'type':'tool_use','id':'t1',"+ + "'name':" + json.dumps(tool) + ",'input':{'file_path':'/etc/hosts'}}]}}), flush=True)",+ "print(json.dumps({'type':'user','message':{'content':[{'type':'tool_result','tool_use_id':'t1',"+ "'is_error':True,'content':'ValueError: the tool blew up'}]}}), flush=True)",+ "print(json.dumps({'type':'result','subtype':'error','is_error':True,"+ "'result':'the CLI own sentence'}), flush=True)",+ f"sys.stderr.write({json.dumps(stderr_text)})",+ "sys.exit(1)",+ ]+ return "\n".join(lines) + "\n"+++def _codex_cli() -> str:+ """A codex-shaped CLI: a command that failed, the turn's own failure, and the traceback."""+ lines = [+ "import json,sys",+ "print(json.dumps({'type':'thread.started','thread_id':'th1'}), flush=True)",+ "print(json.dumps({'type':'item.completed','item':{'type':'commandExecution','id':'c1',"+ "'command':'boom','aggregatedOutput':'ValueError: the tool blew up','exitCode':1}}), flush=True)",+ "print(json.dumps({'type':'turn.failed','error':{'message':'the CLI own sentence'}}), flush=True)",+ f"sys.stderr.write({json.dumps(TRACEBACK)})",+ "sys.exit(1)",+ ]+ return "\n".join(lines) + "\n"+++def _run(tmp_path, script: str, backend: str, normalize, secrets: list[str] | None = None) -> dict:+ turn_id = "err-detail-" + uuid.uuid4().hex+ path = tmp_path / "stream.py"+ path.write_text(script)+ _turns[turn_id] = {"status": "running", "events": [], "result": "", "done": False,+ "started": time.time(), "backend": backend, "model": "m",+ "secrets": list(secrets or [])}+ try:+ _run_turn_bg(turn_id, [sys.executable, str(path)], os.environ.copy(), str(tmp_path),+ normalize, "m", timeout_seconds=30)+ return _turns[turn_id]+ finally:+ _turns.pop(turn_id, None)+++def _detail(rec: dict) -> dict:+ """The detail on the trace's result event — the turn's own ending, with the failure on it."""+ results = [ev for ev in rec["events"] if ev.get("type") == "result"]+ assert results, "the turn left no result event: " + json.dumps(rec["events"])+ return results[-1].get("error_detail") or {}+++def test_a_failed_turn_keeps_the_exception_and_the_stack_frames(tmp_path):+ rec = _run(tmp_path, _claude_cli(), "claude", rs._claude_passthrough)+ assert rec["status"] == "failed"+ detail = _detail(rec)+ assert "ValueError: the tool blew up" in detail["exception"]+ assert 'File "/app/tools.py", line 42, in run' in detail["exception"]+ assert detail["base"] == "claude"+ assert detail["tool"] == "Read" # the tool whose result came back an error+ # the record's own line stays a line: a message may not carry a stack trace (errors §1)+ assert rec["error"] == "the CLI own sentence"+ assert "Traceback" not in rec["error"]+++def test_another_base_reads_the_same_detail_from_its_own_stream(tmp_path):+ """The same code, on codex's stream: the tool's name is codex's own, and the exception and+ the stack frames are as whole as claude's."""+ rec = _run(tmp_path, _codex_cli(), "codex", rs._codex_to_claude)+ assert rec["status"] == "failed"+ detail = _detail(rec)+ assert detail["base"] == "codex"+ assert detail["tool"] == "Bash" # codex's name for the command it ran+ assert "ValueError: the tool blew up" in detail["exception"]+ assert 'File "/app/tools.py", line 42, in run' in detail["exception"]+++def test_a_cli_that_died_before_it_said_anything_still_leaves_a_result_event(tmp_path):+ script = f"import sys\nsys.stderr.write({json.dumps(TRACEBACK)})\nsys.exit(3)\n"+ rec = _run(tmp_path, script, "claude", rs._claude_passthrough)+ assert rec["status"] == "failed"+ detail = _detail(rec)+ assert "ValueError: the tool blew up" in detail["exception"]+ assert detail["tool"] == "" # no tool ran: nothing to name+++def test_the_result_made_for_a_cli_that_said_nothing_is_not_an_answer(tmp_path):+ """The gateway shows a result's text as the turn's answer when nothing was said before it+ (_RespTranslator), so the result the runner makes for a dead CLI carries the reason as `error`:+ with it as `result`, the failure was drawn as the agent's own reply."""+ script = f"import sys\nsys.stderr.write({json.dumps(TRACEBACK)})\nsys.exit(3)\n"+ rec = _run(tmp_path, script, "claude", rs._claude_passthrough)+ ev = [e for e in rec["events"] if e.get("type") == "result"][-1]+ assert not ev.get("result")+ assert ev["error"] == rec["error"] and "ValueError: the tool blew up" in ev["error"]+++def test_the_diagnostic_is_capped(tmp_path):+ tail = TRACEBACK + ("padding line\n" * 2000)+ rec = _run(tmp_path, _claude_cli(stderr_text=tail), "claude", rs._claude_passthrough)+ assert len(_detail(rec)["exception"]) <= rs._DIAG_MAX+++def test_a_secret_in_the_diagnostic_is_redacted(tmp_path):+ secret = "sk-the-calls-own-secret"+ tail = TRACEBACK.replace("the tool blew up", "the tool blew up " + secret)+ rec = _run(tmp_path, _claude_cli(stderr_text=tail), "claude", rs._claude_passthrough,+ secrets=[secret])+ # the answer leaves the runner with the secret redacted — in the detail and in the trace's+ # own copy of it (the runner's own record keeps it, like every other thing the agent wrote)+ out = rs._turn_answer(rec["turn_id"], rec, 0, False)+ assert secret not in json.dumps(out)+ assert "[redacted]" in out["error_detail"]["exception"]+ assert "[redacted]" in out["events"][-1]["error_detail"]["exception"]diff --git a/runner/tests/test_relay_usage.py b/runner/tests/test_relay_usage.pyindex b8f1baed..1b2d8e1d 100644--- a/runner/tests/test_relay_usage.py+++ b/runner/tests/test_relay_usage.py@@ -144,8 +144,8 @@ def test_a_backend_that_reports_its_own_usage_keeps_it():split count (codex, claude) is the record. Pinned on the source of the run loop, which needsa live process to exercise: both result sites go through the one helper."""src = pathlib.Path(__file__).resolve().parents[1].joinpath("server.py").read_text()- # the run loop's _settle (its stream, its eof path and a budget's stop), the hermes and codex- # app-server drivers+ # the run loop's _settle (its stream, its eof path, a budget's stop and a turn that died+ # before it said anything), the hermes and codex app-server driversassert src.count("_fill_relay_usage(ev, env)") == 3- assert src.count("_settle(ev)") == 2 and src.count("_settle(result_ev)") == 1+ assert src.count("_settle(ev)") == 2 and src.count("_settle(result_ev)") == 2assert src.count('if ev.get("type") == "result" and not ev.get("usage"):') == 0