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.

fix: four ports from the hosted platform recall (served spelling, restore raise, CLI error line, failure reason) (#137)

github-actions[bot]ad179b425e11
diff --git a/gateway/app.py b/gateway/app.py
index 6d840055..596cea8e 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -2040,14 +2040,28 @@ async def _hydrate(sid: str, rec: dict, force: bool = False) -> None:
# span a minute and a half. A refused allocation (429) is asked again the same way. The last
# answer is always recorded before the decision, so a refusal names its cause, never "unknown".
for attempt, pause in enumerate(_HYDRATE_PAUSES):
- r = await _hydrate_relay(sid, params)
- rec["hydrated"] = r.status_code < 400
- rec["hydrate"] = r.json() if r.headers.get("content-type", "").startswith("application/json") else None
- if rec["hydrated"]:
- break
- rec["hydrate_error"] = f"HTTP {r.status_code} {(r.text or '')[:200]}"
+ refused = False
+ try:
+ r = await _hydrate_relay(sid, params)
+ except Exception as e: # noqa: BLE001
+ # The relay itself raised: the sandbox dropped the streaming POST under a burst, or
+ # the blob read failed. Twelve restores in two minutes went this way on hosted while
+ # the pool was refusing allocations (2026-09-08 08:10Z), each recorded as "unknown"
+ # (an httpx error's str is empty) and none asked again. The restore is idempotent
+ # (wipe and untar), so a raise is one more failed try on the same ladder, named by
+ # its class.
+ rec["hydrated"] = False
+ rec["hydrate"] = None
+ rec["hydrate_error"] = f"{type(e).__name__}: {str(e)[:160]}".rstrip(": ")
+ else:
+ rec["hydrated"] = r.status_code < 400
+ rec["hydrate"] = r.json() if r.headers.get("content-type", "").startswith("application/json") else None
+ if rec["hydrated"]:
+ break
+ rec["hydrate_error"] = f"HTTP {r.status_code} {(r.text or '')[:200]}"
+ refused = r.status_code == 429
print(f"[hydrate] restore failed sid={sid} attempt={attempt + 1} {rec['hydrate_error']}", flush=True)
- if not (want_sha or r.status_code == 429):
+ if not (want_sha or refused):
break
if pause is not None:
await asyncio.sleep(pause)
@@ -2063,12 +2077,21 @@ async def _hydrate(sid: str, rec: dict, force: bool = False) -> None:
# checkpoint over the good blob from a workspace that isn't that checkpoint.
rec["hydrate_failed_with_checkpoint"] = True
except Exception as e: # noqa: BLE001
- rec["hydrate_error"] = str(e)[:200]
+ rec["hydrate_error"] = f"{type(e).__name__}: {str(e)[:160]}".rstrip(": ")
print(f"[hydrate] restore raised sid={sid} {rec['hydrate_error']}", flush=True)
if str(v.get("ws_sha") or ""):
rec["hydrate_failed_with_checkpoint"] = True
+def _hydrate_reason(rec: dict) -> str:
+ """The restore failure in the person's terms. The sandbox's own refusal names its pod and pool;
+ what the person can act on is that the sandbox was busy."""
+ err = str(rec.get("hydrate_error") or "")
+ if err.startswith("HTTP 429"):
+ return "the sandbox could not be started right now (busy); try again in a minute"
+ return err or "unknown"
+
+
async def _checkpoint(sid: str, rec: dict) -> None:
"""Pull the committed /workspace from the sandbox and persist it to durable blob storage."""
_ws_tar_evict(sid) # workspace changed — next file open refetches
@@ -3363,9 +3386,24 @@ def _provider_refused(err: str) -> bool:
def _turn_failure_message(rec: dict) -> str:
"""What a failed turn says: the org's own key's refusal in plain words when that is why, else
- the list of connections tried."""
+ the last connection's reason in words. Never the tried list itself: its JSON, with our
+ connection names in it, was shown to Richard as the error of a Gemini CLI turn (2026-09-07)."""
tried = rec.get("tried") or []
- return str(rec.get("error_message") or "") or (json.dumps(tried)[:400] if tried else "turn failed")
+ if rec.get("error_message"):
+ return str(rec["error_message"])
+ if not tried:
+ return "turn failed"
+ # The reason is what the last connection that RAN said. A connection skipped before running
+ # (not found, does not serve the model, cannot be brokered) carries no status, and its note is
+ # not why the turn failed unless nothing ran: a hermes turn Opus 5's safeguards refused read
+ # "credential cannot be brokered; refused" because the chain's next entry could not be brokered
+ # (hosted, 2026-09-08).
+ ran = [t for t in tried if t.get("status")]
+ last = (ran or tried)[-1]
+ reason = str(last.get("error") or "").strip() or f"the connection answered {last.get('status') or 'with an error'}"
+ if len(tried) > 1:
+ return f"The turn failed on every connection it tried. The last one said: {reason}"
+ return f"The turn failed: {reason}"
async def _broker_resolve(conn_name: str, org: str | None) -> dict | None:
@@ -6116,7 +6154,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
# error the person can retry is the honest answer.
rec["status"] = "failed"
rec["error_message"] = _HYDRATE_FAILED_MESSAGE
- rec["tried"] = [{"connection": "", "status": "failed", "error": f"workspace restore failed: {rec.get('hydrate_error') or 'unknown'}"}]
+ rec["tried"] = [{"connection": "", "status": "failed", "error": f"workspace restore failed: {_hydrate_reason(rec)}"}]
return "failed", [], rec
# Capture the USER's message as the first trace event of this turn — the runner's
# stream only carries agent/tool/result, never the prompt, so without this the
@@ -6619,7 +6657,7 @@ async def recycle_session_sandbox(sid: str) -> dict:
rec: dict = {}
await _hydrate(sid, rec, force=True)
if not rec.get("hydrated"):
- raise HTTPException(502, f"workspace restore failed: {rec.get('hydrate_error') or 'unknown'}")
+ raise HTTPException(502, f"workspace restore failed: {_hydrate_reason(rec)}")
return {"session_id": sid, "checkpoint_sha": str(v.get("ws_sha") or ""),
"hydrated": bool(rec.get("hydrated")), "hydrate": rec.get("hydrate"), "hydrate_error": rec.get("hydrate_error")}
diff --git a/gateway/tests/test_hydrate_abort.py b/gateway/tests/test_hydrate_abort.py
index a09e6bef..78a5913b 100644
--- a/gateway/tests/test_hydrate_abort.py
+++ b/gateway/tests/test_hydrate_abort.py
@@ -90,3 +90,58 @@ def test_recycle_refuses_when_the_restore_failed(monkeypatch):
with pytest.raises(gw.HTTPException) as e:
asyncio.run(gw.recycle_session_sandbox("hsessx"))
assert e.value.status_code == 502 and "restore failed" in str(e.value.detail)
+
+
+def test_a_relay_that_raises_is_tried_again_on_the_same_ladder_and_names_its_cause(monkeypatch):
+ """Twelve restores in two minutes raised while the pool refused allocations (hosted, 2026-09-08
+ 08:10Z): each was recorded as "unknown" and none was asked again. The restore is idempotent."""
+ import httpx
+ calls = []
+ async def relay(sid, params):
+ calls.append(sid)
+ if len(calls) < 3:
+ raise httpx.ReadError("")
+ return _R(200)
+ async def vertex(sid):
+ return {"ws_sha": "abc123"}
+ async def sleep(s):
+ pass
+ monkeypatch.setattr(gw, "_hydrate_relay", relay)
+ monkeypatch.setattr(gw, "_vertex_get", vertex)
+ monkeypatch.setattr(gw, "COLLAB_URL", "")
+ monkeypatch.setattr(gw.asyncio, "sleep", sleep)
+ rec = {}
+ asyncio.run(gw._hydrate("hsessx", rec, force=True))
+ assert len(calls) == 3 and rec["hydrated"] is True and not rec.get("hydrate_failed_with_checkpoint")
+
+ calls.clear()
+ async def always(sid, params):
+ calls.append(sid)
+ raise httpx.ReadError("")
+ monkeypatch.setattr(gw, "_hydrate_relay", always)
+ rec = {}
+ asyncio.run(gw._hydrate("hsessx", rec, force=True))
+ assert len(calls) == 7 and rec["hydrated"] is False and rec.get("hydrate_failed_with_checkpoint")
+ assert rec["hydrate_error"] == "ReadError" # the class, never "unknown"
+ assert gw._hydrate_reason(rec) == "ReadError"
+
+
+def test_a_raise_without_a_checkpoint_is_not_retried_and_a_pool_refusal_reads_as_busy(monkeypatch):
+ calls = []
+ async def relay(sid, params):
+ calls.append(sid)
+ raise RuntimeError("hydrate blob GET failed: HTTP 503")
+ async def vertex(sid):
+ return {}
+ async def sleep(s):
+ pass
+ monkeypatch.setattr(gw, "_hydrate_relay", relay)
+ monkeypatch.setattr(gw, "_vertex_get", vertex)
+ monkeypatch.setattr(gw, "COLLAB_URL", "")
+ monkeypatch.setattr(gw.asyncio, "sleep", sleep)
+ rec = {}
+ asyncio.run(gw._hydrate("hsessx", rec, force=True))
+ assert len(calls) == 1 and rec["hydrated"] is False and not rec.get("hydrate_failed_with_checkpoint")
+ assert rec["hydrate_error"] == "RuntimeError: hydrate blob GET failed: HTTP 503"
+ assert gw._hydrate_reason({"hydrate_error": "HTTP 429 Error happened when allocating pod for identifier x in pool y"}) \
+ == "the sandbox could not be started right now (busy); try again in a minute"
diff --git a/gateway/tests/test_turn_failure_message.py b/gateway/tests/test_turn_failure_message.py
index e91f5a5d..733b2804 100644
--- a/gateway/tests/test_turn_failure_message.py
+++ b/gateway/tests/test_turn_failure_message.py
@@ -12,10 +12,11 @@ def test_own_key_refusal_is_said_in_words():
assert gw._turn_failure_message(rec) == "Your openai key was refused: OpenAI API error (401): invalid api key"
-def test_an_exhausted_chain_lists_what_was_tried():
+def test_an_exhausted_chain_says_the_last_reason_and_no_connection_name():
rec = {"tried": [{"connection": "a", "error": "not found"}, {"connection": "b", "status": "failed", "error": "boom"}]}
m = gw._turn_failure_message(rec)
- assert '"a"' in m and "boom" in m
+ assert m == "The turn failed on every connection it tried. The last one said: boom"
+ assert '"a"' not in m and "[" not in m
def test_nothing_tried_still_says_something():
@@ -44,3 +45,17 @@ def test_a_models_content_refusal_is_not_a_key_refusal():
assert not gw._provider_refused("The model refused to complete the request")
assert not gw._provider_refused("Your tokenrouter key was refused: The model refused to complete the request")
assert gw._provider_refused("403 Forbidden: key disabled")
+
+
+def test_the_reason_is_the_last_connection_that_ran_not_a_skipped_one():
+ """hermes on hosted, claude-opus-5, 2026-09-08: TokenRouter ran the turn and Opus 5's
+ safeguards refused it; the chain's next connection could not be brokered and its note was
+ shown as the reason."""
+ rec = {"tried": [{"connection": "integration:global:TokenRouter Sponsorship", "status": "failed",
+ "error": "The model refused to complete the request"},
+ {"connection": "integration:global:hermes-bedrock", "error": "credential cannot be brokered; refused"}]}
+ assert gw._turn_failure_message(rec) == \
+ "The turn failed on every connection it tried. The last one said: The model refused to complete the request"
+ only_skips = {"tried": [{"connection": "a", "error": "not found"}, {"connection": "b", "error": "credential cannot be brokered; refused"}]}
+ assert gw._turn_failure_message(only_skips) == \
+ "The turn failed on every connection it tried. The last one said: credential cannot be brokered; refused"
diff --git a/runner/server.py b/runner/server.py
index a313e897..72630ae9 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -881,18 +881,27 @@ import re as _re
# ("API Error: 400 ...", "API Error: 429 ..."), then usually retries and continues. That
# diagnostic is the CLI's own UX, not model output — rendering it as the reply is wrong (it made
# a working opus-4.7/4.8 turn look failed). Drop assistant text blocks that ARE such an error line.
-_CLAUDE_ERR_RE = _re.compile(r"^\s*API Error:\s*\d{3}\b", _re.IGNORECASE)
+# The same line without a status code is the CLI's own account of a turn that ended on an error:
+# Claude Code's "API Error: Opus 5's safeguards flagged this message …" and Qwen Code's
+# "[API Error: Model stream ended with empty response text.]" (both 2026-09-08, hosted's
+# claude-opus-5 recall). Neither is an answer. The text is kept aside as the turn's reason.
+_CLAUDE_ERR_RE = _re.compile(r"^\s*\[?API Error:", _re.IGNORECASE)
-def _strip_claude_error_text(obj: dict) -> dict | None:
- """Remove CLI-injected 'API Error: <code> …' text blocks from an assistant message. Returns the
+def _strip_claude_error_text(obj: dict, state: dict | None = None) -> dict | None:
+ """Remove CLI-injected 'API Error: …' text blocks from an assistant message. Returns the
message with those blocks dropped (None if nothing renderable remains), or the object unchanged
- when it carries no such block."""
+ when it carries no such block. The dropped text is remembered on `state` ("_cli_error") so a
+ turn that ends with no answer can fail with it as the reason."""
if obj.get("type") != "assistant":
return obj
content = (obj.get("message") or {}).get("content")
if not isinstance(content, list):
return obj
+ if state is not None:
+ for c in content:
+ if isinstance(c, dict) and c.get("type") == "text" and _CLAUDE_ERR_RE.match(str(c.get("text") or "")):
+ state["_cli_error"] = str(c.get("text") or "").strip().strip("[]").strip()[:400]
kept = [c for c in content
if not (isinstance(c, dict) and c.get("type") == "text"
and _CLAUDE_ERR_RE.match(str(c.get("text") or "")))]
@@ -904,12 +913,25 @@ def _strip_claude_error_text(obj: dict) -> dict | None:
def _claude_passthrough(obj: dict, state: dict) -> list[dict]:
- # Filter out CLI-injected "API Error: NNN …" diagnostics rendered as assistant text (they are
+ # Filter out CLI-injected "API Error: …" diagnostics rendered as assistant text (they are
# not model output; the CLI retries around them). Applies to both batch + partial modes.
- obj2 = _strip_claude_error_text(obj)
+ obj2 = _strip_claude_error_text(obj, state)
if obj2 is None:
return []
obj = obj2
+ if obj.get("type") == "result":
+ # A turn whose only "answer" is the CLI's error line is a failed turn with that reason: a
+ # Qwen Code turn Opus 5 refused completed with "[API Error: Model stream ended with empty
+ # response text.]" as its reply (hosted, 2026-09-08). A real answer after a retried error
+ # keeps the answer.
+ answer = str(state.get("final") or obj.get("result") or "")
+ if _CLAUDE_ERR_RE.match(answer):
+ state["_cli_error"] = answer.strip().strip("[]").strip()[:400]
+ answer = ""
+ if not answer.strip() and state.get("_cli_error") and not obj.get("is_error"):
+ return [{**obj, "subtype": "error", "is_error": True, "result": state["_cli_error"]}]
+ if obj.get("is_error") and not str(obj.get("result") or "").strip() and state.get("_cli_error"):
+ return [{**obj, "result": state["_cli_error"]}]
# Default (batch) mode: pass the CLI's stream-json through unchanged — the CLI emits one event
# per COMPLETE assistant message, so text lands in a batch.
if not state.get("partial"):
@@ -1895,6 +1917,26 @@ def _pi_usage_add(state: dict, u: dict | None) -> None:
tot[dst] += int(v)
+_MODEL_SNAPSHOT_DATE = re.compile(r"-\d{8}$")
+
+
+def _same_model(requested: str, served: str) -> bool:
+ """Whether two ids name the same model. The check is about substitution (Richard: the models
+ are honest, no fallback), not spelling: a vendor names its model its own way in the response,
+ and pi puts THAT on the assistant message for an Anthropic-shaped stream (pi-ai 0.85.1
+ anthropic-messages.js: `output.model = event.message.model` on message_start; its OpenAI
+ clients stamp the configured id). Through an aggregator the requested id is the routed one,
+ `anthropic/claude-opus-4.8`, and Anthropic answers `claude-opus-4-8`; `claude-haiku-4.5` comes
+ back as the dated snapshot `claude-haiku-4-5-20251001`. Same model, so: a vendor prefix, case,
+ dots against dashes and a trailing snapshot date do not count (every hosted pi restore on an
+ Anthropic id failed as a substitution, 2026-09-08). `gemini-3-flash-preview` for
+ `gemini-3.8-flash` stays a substitution."""
+ def canon(m: str) -> str:
+ m = (m or "").strip().lower().rsplit("/", 1)[-1].replace(".", "-")
+ return _MODEL_SNAPSHOT_DATE.sub("", m)
+ return bool(requested) and bool(served) and canon(requested) == canon(served)
+
+
def _pi_to_claude(obj: dict, state: dict) -> list[dict]:
"""Map ONE pi `--mode json` event to zero+ canonical claude stream-json events.
@@ -1971,7 +2013,7 @@ def _pi_to_claude(obj: dict, state: dict) -> list[dict]:
usage = {k: v for k, v in usage.items() if v}
served = sorted(set(state.get("_served") or []))
requested = str(state.get("model") or "")
- other = [m for m in served if requested and m != requested]
+ other = [m for m in served if requested and not _same_model(requested, m)]
if other and not err:
# the models are honest, no fallback: a turn the CLI ran on another model than the one
# asked for fails with the reason on the record, never completes (the served-model rule
@@ -3889,7 +3931,7 @@ def _gemini_to_claude(obj: dict, state: dict) -> list[dict]:
# gets, and a turn that ran another model than the one asked for must say so, never read
# completed. The settings pin every id to itself; this is the check that they held.
requested = str(state.get("model") or "")
- other = [m for m in served.split(",") if m and requested and m != requested]
+ other = [m for m in served.split(",") if m and requested and not _same_model(requested, m)]
if other:
# the substitution is the more specific cause; the CLI's own error, when it says one, rides along
tail = f" (the CLI ended with {err.get('type') or 'an error'}: {err.get('message')})" if err and err.get("message") else ""
diff --git a/runner/tests/test_claude_error_filter.py b/runner/tests/test_claude_error_filter.py
index 4d769dad..72456384 100644
--- a/runner/tests/test_claude_error_filter.py
+++ b/runner/tests/test_claude_error_filter.py
@@ -50,7 +50,36 @@ def test_result_and_other_events_pass_through():
def test_non_error_text_that_merely_mentions_api_error_is_kept():
- # The guard anchors on a leading "API Error: <3-digit code>" — prose that happens to discuss
- # errors must not be stripped.
+ # The guard anchors on a leading "API Error:" — prose that happens to discuss errors must not
+ # be stripped.
ev = _asst("To handle an API error, catch the 400 status and retry.")
assert rn._claude_passthrough(ev, {}) == [ev]
+
+
+def test_a_turn_whose_only_answer_is_the_clis_error_line_fails_with_that_reason():
+ """Qwen Code, hosted, claude-opus-5 (2026-09-08): Opus 5's safeguards refused the turn, the
+ CLI wrote "[API Error: Model stream ended with empty response text.]" and the turn completed
+ with that as its reply. Claude Code writes the same line without a status code."""
+ state = {}
+ ev = _asst("[API Error: Model stream ended with empty response text.]")
+ assert rn._claude_passthrough(ev, state) == []
+ res = {"type": "result", "subtype": "success", "result": "", "is_error": False}
+ out = rn._claude_passthrough(res, state)
+ assert out == [{"type": "result", "subtype": "error", "result": "API Error: Model stream ended with empty response text.", "is_error": True}]
+ # batch mode: the CLI's result carries the line itself
+ out = rn._claude_passthrough({"type": "result", "subtype": "success", "result": "[API Error: Model stream ended with empty response text.]", "is_error": False}, {})
+ assert out[0]["is_error"] is True and out[0]["result"] == "API Error: Model stream ended with empty response text."
+ # Claude Code's own account of a refusal, no code, and an error result without a message
+ state = {}
+ rn._claude_passthrough(_asst("API Error: Opus 5's safeguards flagged this message. Claude Code can't respond to this message with Opus 5."), state)
+ out = rn._claude_passthrough({"type": "result", "subtype": "error", "result": "", "is_error": True}, state)
+ assert out[0]["result"].startswith("API Error: Opus 5's safeguards flagged this message")
+
+
+def test_a_real_answer_after_a_retried_error_keeps_the_answer():
+ state = {"partial": True}
+ rn._claude_passthrough(_asst("API Error: 429 rate limited"), state)
+ delta = {"type": "stream_event", "event": {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello"}}}
+ rn._claude_passthrough(delta, state)
+ out = rn._claude_passthrough({"type": "result", "subtype": "success", "result": "", "is_error": False}, state)
+ assert out == [{"type": "result", "subtype": "success", "result": "Hello", "is_error": False}]
diff --git a/runner/tests/test_omp_backend.py b/runner/tests/test_omp_backend.py
index ac49c75b..ae67f1ac 100644
--- a/runner/tests/test_omp_backend.py
+++ b/runner/tests/test_omp_backend.py
@@ -5,7 +5,7 @@ import sys
import tempfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
-from server import ( # noqa: E402
+from server import (_same_model, # noqa: E402
_agent_doc_path,
_build_omp,
_pi_to_claude,
@@ -388,3 +388,22 @@ def test_omp_mcp_entries_carry_the_http_type_omp_requires(tmp_path):
doc = json.loads((tmp_path / "mcp.json").read_text())
assert doc["mcpServers"] == {"deepwiki": {"type": "http", "url": "https://mcp.deepwiki.com/mcp",
"headers": {"Authorization": "Bearer tok"}}}
+
+
+def test_the_vendors_own_spelling_of_the_requested_model_is_not_a_substitution():
+ """Through an aggregator pi asks for `anthropic/claude-opus-4.8` and Anthropic's stream names
+ `claude-opus-4-8` (pi stamps the response's model on an Anthropic-shaped message); haiku comes
+ back as its dated snapshot. Same model; a different model still fails (2026-09-08)."""
+ def run(requested, served):
+ evs = [{"type": "session", "id": "s"}, {"type": "message_end", "message": {"role": "assistant", "model": served, "provider": "hr",
+ "content": [{"type": "text", "text": "PONG"}], "usage": {"input": 5, "output": 1}, "stopReason": "stop"}}, {"type": "agent_end"}]
+ chunks, _ = _run_omp_events(evs, model=requested)
+ return [e for e in _flat(chunks) if e.get("type") == "result"][0]
+ for requested, served in (("anthropic/claude-opus-4.8", "claude-opus-4-8"), ("anthropic/claude-haiku-4.5", "claude-haiku-4-5-20251001"),
+ ("anthropic/claude-fable-5", "claude-fable-5"), ("gpt-5.4", "openai/gpt-5.4")):
+ res = run(requested, served)
+ assert res["is_error"] is False and res["result"] == "PONG" and res["model"] == served, (requested, served)
+ res = run("anthropic/claude-sonnet-5", "claude-sonnet-4-6")
+ assert res["is_error"] is True and res["result"] == "the CLI ran claude-sonnet-4-6 instead of anthropic/claude-sonnet-5"
+ assert _same_model("gemini-3.8-flash", "gemini-3-flash-preview") is False
+ assert _same_model("gpt-5.4", "gpt-5.4-mini") is False