Skip to content

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.

agentzero: a failed turn hands the trace its exception with the stack frames, as every other base does (#571)

github-actions[bot]7f036edf545b
diff --git a/runner/agentzero_driver.py b/runner/agentzero_driver.py
index 9ade72d1..908397e9 100644
--- a/runner/agentzero_driver.py
+++ b/runner/agentzero_driver.py
@@ -521,6 +521,33 @@ def _error_reason(ctx, exc: BaseException) -> str:
return text[:2000]
+_DIAGNOSTIC_MAX = 4000 # what the runner keeps of any base's diagnostic (server._DIAG_MAX)
+
+
+def _keep_ends(text: str, cap: int) -> str:
+ """A long diagnostic, kept to `cap` by its two ends: the first line (the exception's message) and
+ the end, where a traceback's innermost frames and the exception line are. Every other base's
+ diagnostic is the tail of its output, so that end is the one kept there too."""
+ if len(text) <= cap:
+ return text
+ head = text.split("\n", 1)[0][:cap // 4]
+ return head + "\n…\n" + text[-(cap - len(head) - 3):]
+
+
+def _error_diagnostic(ctx, exc: BaseException) -> str:
+ """The failure whole, for the trace's error_detail (#546): the `error` log item Agent Zero wrote,
+ traceback included, or the exception's own traceback when it wrote none. _error_reason keeps one
+ line for the record (a message carries no stack trace); this keeps the frames that line leaves
+ out. The exception is handled in-process, so it never reaches the stream the runner reads its
+ other bases' diagnostics from: the driver is the only place that still has the frames."""
+ text = _last_log(ctx, ("error",))
+ if not text:
+ import traceback
+ inner = getattr(exc, "exception", None) or exc
+ text = "".join(traceback.format_exception(type(inner), inner, inner.__traceback__)).strip()
+ return _keep_ends(text, _DIAGNOSTIC_MAX)
+
+
def _mcp_down() -> list[dict]:
try:
from helpers.mcp_handler import MCPConfig
@@ -560,11 +587,12 @@ async def _run(job: dict) -> int:
"import_s": round(time.time() - _T0, 2)})
task = ctx.communicate(UserMessage(message=job["prompt"], attachments=[], id=str(uuid.uuid4())))
- ok, reason = True, ""
+ ok, reason, diagnostic = True, "", ""
try:
result = await task.result()
except BaseException as e: # noqa: BLE001 — HandledException, CancelledError, the step budget
ok, result, reason = False, None, _error_reason(ctx, e)
+ diagnostic = _error_diagnostic(ctx, e)
final = _STATE["final"] or (str(result) if isinstance(result, str) else "")
if ok and not final:
ok, reason = False, "the turn ended without an answer"
@@ -574,7 +602,7 @@ async def _run(job: dict) -> int:
except Exception as e: # noqa: BLE001
_emit("warning", {"text": f"the conversation could not be saved: {e}"})
_emit("result", {"ok": ok, "final": final if ok else "", "error": reason,
- "seconds": round(time.time() - _T0, 2)})
+ "diagnostic": "" if ok else diagnostic, "seconds": round(time.time() - _T0, 2)})
return 0 if ok else 1
diff --git a/runner/server.py b/runner/server.py
index 758a50af..804525cc 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -11456,6 +11456,9 @@ def _agentzero_to_claude(obj: dict, state: dict) -> list[dict]:
{"type": "result", "subtype": "success", "is_error": False, "result": final,
"usage": {}}]
state["_a0_error"] = str(p.get("error") or "")
+ # the failure whole, frames included (#546): the record keeps the one line above, the
+ # trace's error_detail gets this in place of a stderr tail this base never writes to
+ state["diagnostic"] = str(p.get("diagnostic") or "")
# usage is {} on purpose: the relay stamps it (_relay_usage), as for every backend whose
# own record carries none — Agent Zero's LLMResult usage never leaves the process.
return [{"type": "result", "subtype": "error", "is_error": True,
@@ -11987,7 +11990,10 @@ def _run_turn_bg(turn_id: str, cmd: list[str], env: dict, cwd: str, normalize, m
# 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)
+ # a driver that handles the exception in-process hands its diagnostic over in the state (an
+ # agentzero turn, #546); every other base printed it, and it is in the output's tail
+ detail = _failure_detail(str(rec.get("backend") or ""), rec["events"],
+ str(state.get("diagnostic") or "") or tail)
rec["error_detail"] = detail
made = result_ev is None
if made:
diff --git a/runner/tests/test_agentzero_backend.py b/runner/tests/test_agentzero_backend.py
index 89622efb..c4c66aba 100644
--- a/runner/tests/test_agentzero_backend.py
+++ b/runner/tests/test_agentzero_backend.py
@@ -285,6 +285,43 @@ def test_the_error_reason_is_cut_at_the_traceback():
assert drv._error_reason(ctx, Exception("x")) == "litellm.AuthenticationError: bad key"
+def test_the_diagnostic_keeps_what_the_reason_cuts():
+ """#546: the reason is one line for the record; the diagnostic is the same log item whole, frames
+ included, for the trace's error_detail."""
+ whole = "litellm.AuthenticationError: bad key\n\nTraceback (most recent call last):\n File \"x.py\", line 3"
+ item = type("I", (), {"type": "error", "content": whole})()
+ ctx = type("C", (), {"log": type("L", (), {"logs": [item]})()})()
+ assert drv._error_reason(ctx, Exception("x")) == "litellm.AuthenticationError: bad key"
+ assert drv._error_diagnostic(ctx, Exception("x")) == whole
+
+
+def test_with_no_log_item_the_diagnostic_is_the_exceptions_own_traceback():
+ ctx = type("C", (), {"log": type("L", (), {"logs": []})()})()
+ try:
+ raise RuntimeError("the step budget ran out")
+ except RuntimeError as e:
+ text = drv._error_diagnostic(ctx, e)
+ assert "RuntimeError: the step budget ran out" in text and "Traceback" in text
+ assert "test_with_no_log_item_the_diagnostic_is_the_exceptions_own_traceback" in text # its frame
+
+
+def test_a_long_diagnostic_keeps_the_message_and_the_innermost_frames():
+ """Agent Zero writes the message first and the traceback after it, innermost frame last. Cut from
+ the front, the frames that name where it failed were the ones lost (measured: a dead endpoint's
+ 4,000 characters ended mid-frame). Both ends are kept, and the runner's cap is never exceeded."""
+ frames = "".join(f' File "/a0/m{i}.py", line {i}, in f{i}\n call()\n' for i in range(400))
+ whole = "BadGatewayError: the provider did not answer\n\nTraceback (most recent call last):\n" + frames \
+ + "litellm.BadGatewayError: the provider did not answer"
+ item = type("I", (), {"type": "error", "content": whole})()
+ ctx = type("C", (), {"log": type("L", (), {"logs": [item]})()})()
+ text = drv._error_diagnostic(ctx, Exception("x"))
+ assert len(text) <= drv._DIAGNOSTIC_MAX
+ assert text.startswith("BadGatewayError: the provider did not answer\n…\n")
+ assert text.endswith("litellm.BadGatewayError: the provider did not answer")
+ assert 'File "/a0/m399.py", line 399' in text # the innermost frame
+ assert 'File "/a0/m0.py", line 0' not in text # the outermost goes first
+
+
# ── the runner side ──
from server import (Auth, _agent_doc_path, _agentzero_to_claude, _build_agentzero, # noqa: E402
_resume_lost, BACKENDS, CHECKPOINT_EXCLUDE)
diff --git a/runner/tests/test_failure_detail.py b/runner/tests/test_failure_detail.py
index 1334c150..25910075 100644
--- a/runner/tests/test_failure_detail.py
+++ b/runner/tests/test_failure_detail.py
@@ -140,3 +140,42 @@ def test_a_secret_in_the_diagnostic_is_redacted(tmp_path):
assert secret not in json.dumps(out)
assert "[redacted]" in out["error_detail"]["exception"]
assert "[redacted]" in out["events"][-1]["error_detail"]["exception"]
+
+
+def _agentzero_cli(diagnostic: str) -> str:
+ """The agentzero driver's stream: it handles the exception in-process and prints nothing the runner
+ reads as a diagnostic, so its own result event is the only place the frames can come from (#546)."""
+ lines = [
+ "import json,sys",
+ "print(json.dumps({'m':'init','p':{'session_id':'harness'}}), flush=True)",
+ "print(json.dumps({'m':'result','p':{'ok':False,'final':'','error':'ValueError: the tool blew up',"
+ "'diagnostic':" + json.dumps(diagnostic) + "}}), flush=True)",
+ "sys.exit(1)",
+ ]
+ return "\n".join(lines) + "\n"
+
+
+def test_agentzero_hands_over_the_frames_it_handled_in_process(tmp_path):
+ """Every other base prints its exception and the runner reads it from the output's tail. Agent
+ Zero's is handled inside the driver, which cut it at the traceback, so the trace's detail had the
+ message and no frames. The driver now hands the whole text over on its result event."""
+ whole = "ValueError: the tool blew up\n\n" + TRACEBACK
+ rec = _run(tmp_path, _agentzero_cli(whole), "agentzero", rs._agentzero_to_claude)
+ assert rec["status"] == "failed"
+ detail = _detail(rec)
+ assert detail["base"] == "agentzero"
+ assert 'File "/app/tools.py", line 42, in run' in detail["exception"]
+ assert "ValueError: the tool blew up" in detail["exception"]
+ # the record keeps its one line, and the trace's result event carries no second copy
+ assert rec["error"] == "ValueError: the tool blew up" and "Traceback" not in rec["error"]
+ ev = [e for e in rec["events"] if e.get("type") == "result"][-1]
+ assert "diagnostic" not in ev and "Traceback" not in str(ev.get("result"))
+
+
+def test_a_secret_in_agentzeros_diagnostic_is_redacted(tmp_path):
+ secret = "sk-the-calls-own-secret"
+ whole = "ValueError: the tool blew up " + secret + "\n\n" + TRACEBACK
+ rec = _run(tmp_path, _agentzero_cli(whole), "agentzero", rs._agentzero_to_claude, secrets=[secret])
+ out = rs._turn_answer(rec["turn_id"], rec, 0, False)
+ assert secret not in json.dumps(out)
+