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(runner): qwen rides the relay everywhere; flatten tool content on rejection

richard-epsilla34e393578cb7
diff --git a/runner/server.py b/runner/server.py
index 62de975a..14b73cb0 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -1950,6 +1950,29 @@ def _normalize_openai_chat_body(body: bytes) -> bytes:
return body
+def _stringify_tool_content(body: bytes) -> bytes:
+ """Tool-role message content: array-of-parts -> plain string, in one chat-completions body.
+
+ OpenAI accepts both shapes; qwen-code sends the array form and stricter endpoints refuse it
+ ('400 tool message content must be a string' — LLMTR, measured live 2026-08-27, killing the
+ request AFTER the tool call, so the turn died mid-flight). Only text parts exist in a shell
+ tool result, so the flatten is lossless where it applies; applied only after a provider says
+ exactly that."""
+ try:
+ obj = json.loads(body)
+ changed = False
+ for m in obj.get("messages") or []:
+ if isinstance(m, dict) and m.get("role") == "tool" and isinstance(m.get("content"), list):
+ m["content"] = "".join(p.get("text", "") for p in m["content"]
+ if isinstance(p, dict))
+ changed = True
+ if changed:
+ return json.dumps(obj, separators=(",", ":")).encode()
+ except Exception: # noqa: BLE001 — a body we cannot parse is a body we must not alter
+ pass
+ return body
+
+
def _rename_max_tokens(body: bytes) -> bytes:
"""max_tokens -> max_completion_tokens in one chat-completions body.
@@ -2078,6 +2101,8 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
body = _normalize_openai_chat_body(body)
if flags.get("rename_max_tokens"):
body = _rename_max_tokens(body)
+ if flags.get("stringify_tool_content"):
+ body = _stringify_tool_content(body)
headers["content-length"] = str(len(body))
resp = None
for attempt in (0, 1):
@@ -2096,6 +2121,13 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
body = renamed
headers["content-length"] = str(len(body))
continue
+ stringified = _stringify_tool_content(body) if body is not None else None
+ if (attempt == 0 and e.code == 400 and b"content must be a string" in data
+ and stringified is not None and stringified != body):
+ flags["stringify_tool_content"] = True
+ body = stringified
+ headers["content-length"] = str(len(body))
+ continue
# pass provider errors through verbatim
self.send_response(e.code)
self.send_header("content-type", e.headers.get("content-type") or "application/json")
@@ -2407,11 +2439,13 @@ def _build_qwen(provider: str, auth: Auth, model: str, prompt: str, cwd: str, en
raise HTTPException(400, f"unknown qwen provider '{pr}' (one of {sorted(QWEN_PROVIDERS)})")
if not auth.base_url:
raise HTTPException(400, "qwen needs a base_url (none configured)")
- if auth.api_format == "openai" and auth.api_key:
- # A custom OpenAI endpoint rides the loopback relay, exactly like opencode's: request
- # shapes strict endpoints refuse are repaired in flight (Azure's gpt-5.x deployments 400
- # on max_tokens), and the real key never enters the CLI's environment — which matters
- # more here than anywhere, because qwen takes its credential ONLY via env.
+ if auth.api_key:
+ # EVERY qwen turn rides the loopback relay, not just custom endpoints: request shapes
+ # strict endpoints refuse are repaired in flight (qwen sends tool-result content as an
+ # array of parts, which aggregators 400 with 'content must be a string' — measured live
+ # against LLMTR; Azure's gpt-5.x deployments 400 on max_tokens), and the real key never
+ # enters the CLI's environment — which matters more here than anywhere, because qwen
+ # takes its credential ONLY via env.
relay_base, relay_tok = _hermes_relay_route(auth.base_url, auth.api_key)
auth = auth.model_copy(update={"base_url": relay_base, "api_key": relay_tok})
home = pathlib.Path(cwd) / ".harness" / "home"
diff --git a/runner/tests/test_hermes_relay.py b/runner/tests/test_hermes_relay.py
index a3238295..bdefad65 100644
--- a/runner/tests/test_hermes_relay.py
+++ b/runner/tests/test_hermes_relay.py
@@ -166,3 +166,69 @@ def test_relay_retries_a_max_tokens_rejection_and_sticks():
assert len(calls) == 3 and "max_completion_tokens" in calls[2]
finally:
up.shutdown()
+
+# ── tool-content stringify-on-rejection (qwen x LLMTR, 2026-08-27) ──────────────────────────────
+# qwen-code sends tool-result content as an array of parts; strict aggregators 400 with
+# 'tool message content must be a string' — measured live, killing the turn after the tool ran.
+
+def test_stringify_tool_content_helper():
+ from server import _stringify_tool_content
+ body = json.dumps({"messages": [
+ {"role": "user", "content": [{"type": "text", "text": "leave arrays on non-tool roles"}]},
+ {"role": "tool", "tool_call_id": "c1",
+ "content": [{"type": "text", "text": "TOOL-"}, {"type": "text", "text": "OUT"}]},
+ ]}).encode()
+ out = json.loads(_stringify_tool_content(body))
+ assert out["messages"][1]["content"] == "TOOL-OUT"
+ assert isinstance(out["messages"][0]["content"], list) # user parts untouched
+ already = json.dumps({"messages": [{"role": "tool", "content": "s"}]}).encode()
+ assert _stringify_tool_content(already) == already
+ assert _stringify_tool_content(b"not json") == b"not json"
+
+
+def test_relay_retries_a_tool_content_rejection_and_sticks():
+ calls = []
+
+ class Upstream(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self): # noqa: N802
+ body = json.loads(self.rfile.read(int(self.headers["content-length"])))
+ calls.append(body)
+ if any(m.get("role") == "tool" and not isinstance(m.get("content"), str)
+ for m in body["messages"]):
+ data = b'{"error": {"message": "tool message content must be a string"}}'
+ self.send_response(400)
+ else:
+ data = b'{"ok": true}'
+ self.send_response(200)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def log_message(self, *a):
+ pass
+
+ up = ThreadingHTTPServer(("127.0.0.1", 0), Upstream)
+ threading.Thread(target=up.serve_forever, daemon=True).start()
+ try:
+ base, tok = _hermes_relay_route(f"http://127.0.0.1:{up.server_address[1]}/v1", "sk-real")
+ body = json.dumps({"model": "m", "messages": [
+ {"role": "user", "content": "run it"},
+ {"role": "tool", "tool_call_id": "c1",
+ "content": [{"type": "text", "text": "TOOL-Q"}]},
+ ]}).encode()
+ req = urllib.request.Request(base + "/chat/completions", data=body, method="POST",
+ headers={"authorization": f"Bearer {tok}",
+ "content-type": "application/json"})
+ assert json.loads(urllib.request.urlopen(req, timeout=10).read()) == {"ok": True}
+ assert len(calls) == 2 # rejected once, flattened, succeeded
+ assert calls[1]["messages"][1]["content"] == "TOOL-Q"
+ # Sticky for the route: the next request flattens preemptively.
+ urllib.request.urlopen(urllib.request.Request(
+ base + "/chat/completions", data=body, method="POST",
+ headers={"authorization": f"Bearer {tok}", "content-type": "application/json"}), timeout=10)
+ assert len(calls) == 3 and calls[2]["messages"][1]["content"] == "TOOL-Q"
+ finally:
+ up.shutdown()
diff --git a/runner/tests/test_qwen_build.py b/runner/tests/test_qwen_build.py
index 8fd23a1e..625e6d59 100644
--- a/runner/tests/test_qwen_build.py
+++ b/runner/tests/test_qwen_build.py
@@ -39,14 +39,17 @@ def test_resume_uses_dash_r():
assert cmd[-2:] == ["-r", "8e039a38-f91f"]
-def test_auth_is_environment_only_never_disk():
- """qwen is the one backend with NO credential at rest: env OPENAI_API_KEY/BASE_URL only.
- settings.json must not carry the key."""
+def test_auth_is_environment_only_and_relayed():
+ """qwen takes its credential ONLY via env, so every provider rides the loopback relay: the
+ CLI's environment holds a per-route relay token — never the real key — and its base URL is
+ the relay, which also repairs shapes strict endpoints refuse (LLMTR 400s the array-form
+ tool content qwen sends). settings.json must carry neither."""
_, d, env = _argv()
- assert env["OPENAI_API_KEY"] == "sk-t"
- assert env["OPENAI_BASE_URL"] == "https://relay.example/v1"
+ assert env["OPENAI_API_KEY"].startswith("hr-relay-")
+ assert "sk-t" not in env["OPENAI_API_KEY"]
+ assert env["OPENAI_BASE_URL"].startswith("http://127.0.0.1:")
st = pathlib.Path(d, ".harness", "home", ".qwen", "settings.json").read_text()
- assert "sk-t" not in st
+ assert "sk-t" not in st and "hr-relay-" not in st
def test_home_is_redirected_into_the_workspace():