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.

A Gemini thought signature goes back only to the model that made it; another model's goes as Google's sentinel (#604)

github-actions[bot]cd4c4e4e9350
diff --git a/runner/server.py b/runner/server.py
index 71b0fb15..6525bdb5 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -4950,6 +4950,41 @@ def _refused_top_level_field(refused: bytes) -> str:
_GOOGLE_SIG_SKIP = "skip_thought_signature_validator"
_GOOGLE_HOST = "generativelanguage.googleapis.com"
+# A signature belongs to the model that made it. A conversation that moves from one Gemini model to another
+# replays the first model's calls, and Google refuses the second model's request when they carry the first
+# one's signatures: 400 "Corrupted thought signature." (hosted, 2026-10-27: a fast-agent deck conversation,
+# gemini-4-argon's turn, then gemini-3.6-flash, 3.5-flash, 3.5-flash-lite and 3.1-pro-preview each refused
+# twice; fast-agent keeps the signatures in its own history). So the relay keeps, for the life of the
+# process, which model made each tool call it saw a signature for, and a replayed call made by another model
+# goes with Google's sentinel instead, whether the signature came from this relay or from the harness.
+# OpenRouter's encrypted reasoning is the same: another model's entry is not put back. A route lives one
+# turn, so this is kept beside the routes. A signature whose maker this process never saw (a runner
+# restarted since) is kept as the harness sent it, and if Google calls it corrupted the call goes once more
+# with the sentinel in its place. The hosted broker keeps the same record per session.
+_SIG_MAKERS: dict[str, str] = {}
+_SIG_MAKERS_MAX = 50_000
+_SIG_MAKERS_LOCK = threading.Lock()
+_GOOGLE_SIG_CORRUPT_RE = re.compile(rb"Corrupted thought signature", re.I)
+
+
+def _sig_makers_keep(ids, model: str) -> None:
+ """Note `model` as the maker of each tool call id (the oldest notes go past _SIG_MAKERS_MAX)."""
+ if not model:
+ return
+ with _SIG_MAKERS_LOCK:
+ for cid in ids:
+ if cid:
+ _SIG_MAKERS.pop(str(cid), None)
+ _SIG_MAKERS[str(cid)] = model
+ while len(_SIG_MAKERS) > _SIG_MAKERS_MAX:
+ del _SIG_MAKERS[next(iter(_SIG_MAKERS))]
+
+
+def _sig_by_another(cid: str, want: str) -> bool:
+ """Whether the call `cid` was made by a model other than `want`, as far as this process saw."""
+ maker = _SIG_MAKERS.get(cid, "") if cid else ""
+ return bool(maker and want) and not _same_model(want, maker)
+
# The relay's route carries no provider, only the upstream: a Gemini channel is known by its host.
# TokenRouter serves Google's native API under its own root, and the hosted HarnessRouter service
@@ -5225,9 +5260,13 @@ def _google_signatures_in_line(line: bytes) -> list[tuple[str, str]]:
return _google_signatures_in(doc) if isinstance(doc, dict) else []
-def _google_with_signatures(body: bytes, sigs: dict) -> bytes:
+def _google_with_signatures(body: bytes, sigs: dict, distrust: bool = False, fill: bool = True) -> bytes:
"""The request with every replayed assistant tool call carrying a thought signature: the one
- this relay saw on the answer, else Google's sentinel. A body without tool calls is untouched."""
+ this relay saw on the answer, else Google's sentinel. A call another model made goes with the
+ sentinel even when the harness carried its signature (_SIG_MAKERS); with `distrust` (Google called
+ a signature corrupted), so does every call whose maker this process never saw. Without `fill`
+ (a route not known to be Google's) only signatures the harness carried are looked at. A body
+ without tool calls is untouched."""
if b"tool_calls" not in body:
return body
try:
@@ -5236,6 +5275,7 @@ def _google_with_signatures(body: bytes, sigs: dict) -> bytes:
return body
if not isinstance(doc, dict) or not isinstance(doc.get("messages"), list):
return body
+ want = str(doc.get("model") or "")
changed = False
for msg in doc["messages"]:
if not isinstance(msg, dict) or msg.get("role") != "assistant":
@@ -5243,11 +5283,16 @@ def _google_with_signatures(body: bytes, sigs: dict) -> bytes:
for tc in msg.get("tool_calls") or []:
if not isinstance(tc, dict):
continue
+ cid = str(tc.get("id") or "")
+ own = not _sig_by_another(cid, want) and not (distrust and cid not in _SIG_MAKERS)
ec = tc.get("extra_content")
- if isinstance(ec, dict) and isinstance(ec.get("google"), dict) and ec["google"].get("thought_signature"):
+ carried = isinstance(ec, dict) and isinstance(ec.get("google"), dict) and ec["google"].get("thought_signature")
+ if (carried and own) or (not carried and not fill):
continue
- cid = str(tc.get("id") or "")
- tc["extra_content"] = {"google": {"thought_signature": sigs.get(cid) or _GOOGLE_SIG_SKIP}}
+ sig = (sigs.get(cid) if own else "") or _GOOGLE_SIG_SKIP
+ if carried == sig:
+ continue
+ tc["extra_content"] = {"google": {"thought_signature": sig}}
changed = True
return json.dumps(doc).encode() if changed else body
@@ -5295,12 +5340,14 @@ def _with_encrypted_reasoning(body: bytes, held: dict) -> bytes:
return body
if not isinstance(doc, dict) or not isinstance(doc.get("messages"), list):
return body
+ want = str(doc.get("model") or "")
changed = False
for msg in doc["messages"]:
if not isinstance(msg, dict) or msg.get("role") != "assistant" or msg.get("reasoning_details"):
continue
+ # another model's encrypted reasoning is not put back (see _SIG_MAKERS)
got = [held[cid] for cid in (str(tc.get("id") or "") for tc in msg.get("tool_calls") or []
- if isinstance(tc, dict)) if cid in held]
+ if isinstance(tc, dict)) if cid in held and not _sig_by_another(cid, want)]
if got:
msg["reasoning_details"] = got
changed = True
@@ -5978,8 +6025,11 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
body = _with_encrypted_reasoning(body, flags["encrypted_reasoning"])
headers["content-length"] = str(len(body))
google = _GOOGLE_HOST in base or bool(flags.get("thought_signature"))
- if google and body is not None and self.path.endswith("/chat/completions"):
- body = _google_with_signatures(body, flags.setdefault("google_sigs", {}))
+ if ((google or (body is not None and b"thought_signature" in body))
+ and body is not None and self.path.endswith("/chat/completions")):
+ # on any route, a carried signature another model made is not sent (see _SIG_MAKERS)
+ body = _google_with_signatures(body, flags.setdefault("google_sigs", {}),
+ distrust=bool(flags.get("sig_distrust")), fill=google)
headers["content-length"] = str(len(body))
if ((((_gemini_channel(base) or flags.get("gemini_schemas"))
and "gemini" in str(_body_model).lower())
@@ -6203,6 +6253,20 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
# printed only its own "↻ Resumed session" line when Vercel refused gpt-6.1-sol for
# a spent budget (2026-10-13), and that line was the turn's whole error.
flags["last_refusal"] = _refusal_words(e.code, data)
+ distrusted = (_google_with_signatures(body, flags.setdefault("google_sigs", {}), distrust=True)
+ if (attempt < 2 and e.code == 400 and body is not None and not flags.get("sig_distrust")
+ and _GOOGLE_SIG_CORRUPT_RE.search(data or b"")
+ and self.path.endswith("/chat/completions")) else None)
+ if distrusted is not None and distrusted != body:
+ # Google called a replayed signature corrupted: one whose maker this process never saw
+ # (see _SIG_MAKERS) goes as the sentinel, for this turn's calls from now on.
+ flags["sig_distrust"] = flags["thought_signature"] = True
+ google = True
+ body = distrusted
+ headers["content-length"] = str(len(body))
+ print(f"[relay] provider called a thought signature corrupted for model={_body_model}; "
+ f"sent again with the sentinel for calls of unknown origin", flush=True)
+ continue
if (attempt < 2 and e.code == 400 and b"thought_signature" in data
and not flags.get("thought_signature") and body is not None):
# a Gemini 3 endpoint this relay did not recognise as Google names the need itself
@@ -6412,12 +6476,14 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
call_thinking = seen_thinking
for rd in _encrypted_reasoning_in_line(line):
flags.setdefault("encrypted_reasoning", {})[str(rd["id"])] = rd
+ _sig_makers_keep([rd["id"]], str(_body_model))
if flags.get("turn_reasoning_only"):
flags.setdefault("items_minted", set()).update(_output_item_ids_in_line(line))
if sigs is not None:
for cid, sig in _google_signatures_in_line(line):
sigs[cid] = sig
flags["thought_signature"] = True
+ _sig_makers_keep([cid], str(_body_model))
if out_lines is not None:
chunk = b"".join(out_lines)
_stream_fold(flags, call_usage, call_thinking, folded) # on the route before the client has it
@@ -6488,6 +6554,7 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
try:
for rd in _encrypted_reasoning_in(json.loads(data)):
flags.setdefault("encrypted_reasoning", {})[str(rd["id"])] = rd
+ _sig_makers_keep([rd["id"]], str(_body_model))
except (ValueError, UnicodeDecodeError):
pass
if sigs is not None and b"thought_signature" in data:
@@ -6500,6 +6567,7 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
sigs.update(found)
if found:
flags["thought_signature"] = True
+ _sig_makers_keep([cid for cid, _ in found], str(_body_model))
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
diff --git a/runner/tests/test_relay_signature_maker.py b/runner/tests/test_relay_signature_maker.py
new file mode 100644
index 00000000..aa1b62f6
--- /dev/null
+++ b/runner/tests/test_relay_signature_maker.py
@@ -0,0 +1,158 @@
+"""A Gemini thought signature (and OpenRouter's encrypted reasoning) goes back only to the model that made it
+(2026-10-27). A fast-agent deck conversation moved from gemini-4-argon to gemini-3.6-flash, 3.5-flash, 3.5-flash-lite
+and 3.1-pro-preview on the hosted service, and Google refused each with 400 "Corrupted thought signature.": the
+harness keeps argon's signatures in its own history. The relay keeps which model made each call it saw a signature
+for, beside the per-turn routes, and sends another model's as Google's sentinel."""
+import json
+import sys
+import threading
+import urllib.error
+import urllib.request
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import server # noqa: E402
+
+SKIP = server._GOOGLE_SIG_SKIP
+
+
[email protected](autouse=True)
+def makers(monkeypatch):
+ monkeypatch.setattr(server, "_SIG_MAKERS", {})
+ return server._SIG_MAKERS
+
+
+def _replay(model: str) -> bytes:
+ return json.dumps({"model": model, "messages": [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": None, "tool_calls": [
+ {"id": "c_argon", "type": "function", "function": {"name": "f", "arguments": "{}"},
+ "extra_content": {"google": {"thought_signature": "sigArgon"}}}, # the harness kept it
+ {"id": "c_flash", "type": "function", "function": {"name": "f", "arguments": "{}"}},
+ {"id": "c_unseen", "type": "function", "function": {"name": "f", "arguments": "{}"},
+ "extra_content": {"google": {"thought_signature": "own"}}}]}]}).encode()
+
+
+def _sigs_of(body: bytes) -> list:
+ return [(tc.get("extra_content") or {}).get("google", {}).get("thought_signature")
+ for tc in json.loads(body)["messages"][1]["tool_calls"]]
+
+
+def test_another_gemini_models_signatures_go_as_the_sentinel_on_a_switch():
+ server._sig_makers_keep(["c_argon"], "gemini-4-argon")
+ # the maker is the id the client asked for; the same model with or without a vendor prefix is the same
+ server._sig_makers_keep(["c_flash"], "google/gemini-3.6-flash")
+ sigs = {"c_argon": "sigArgon", "c_flash": "sigFlash"}
+ assert _sigs_of(server._google_with_signatures(_replay("gemini-3.6-flash"), sigs)) == [SKIP, "sigFlash", "own"]
+ assert _sigs_of(server._google_with_signatures(_replay("google/gemini-4-argon"), sigs)) == ["sigArgon", SKIP, "own"]
+
+
+def test_a_route_not_known_as_googles_only_changes_what_the_harness_carried():
+ server._sig_makers_keep(["c_argon"], "gemini-4-argon")
+ out = server._google_with_signatures(_replay("google/gemini-3.6-flash"), {}, fill=False)
+ assert _sigs_of(out) == [SKIP, None, "own"] # nothing added where nothing was carried
+ same = _replay("google/gemini-4-argon")
+ assert server._google_with_signatures(same, {}, fill=False) is same
+
+
+def test_after_a_corrupted_refusal_a_signature_of_unknown_origin_goes_as_the_sentinel():
+ server._sig_makers_keep(["c_flash"], "gemini-3.6-flash")
+ out = server._google_with_signatures(_replay("gemini-3.6-flash"), {"c_flash": "sigFlash"}, distrust=True)
+ assert _sigs_of(out) == [SKIP, "sigFlash", SKIP] # its own call keeps its signature
+
+
+def test_another_models_encrypted_reasoning_is_not_put_back():
+ rd = {"type": "reasoning.encrypted", "data": "x", "id": "c1", "format": "google-gemini-v1"}
+ server._sig_makers_keep(["c1"], "google/gemini-4-argon")
+ body = lambda m: json.dumps({"model": m, "messages": [{"role": "assistant", "content": None, "tool_calls": [ # noqa: E731
+ {"id": "c1", "type": "function", "function": {"name": "f", "arguments": "{}"}}]}]}).encode()
+ same = json.loads(server._with_encrypted_reasoning(body("google/gemini-4-argon"), {"c1": rd}))
+ assert same["messages"][0]["reasoning_details"] == [rd]
+ other = server._with_encrypted_reasoning(body("google/gemini-3.6-flash"), {"c1": rd})
+ assert "reasoning_details" not in json.loads(other)["messages"][0]
+
+
+def test_the_record_is_bounded():
+ for i in range(server._SIG_MAKERS_MAX + 5):
+ server._sig_makers_keep([f"c{i}"], "m")
+ assert len(server._SIG_MAKERS) == server._SIG_MAKERS_MAX and "c0" not in server._SIG_MAKERS
+
+
+# ── through the relay: one turn per route, as the runner gives each turn its own ──────────────────────────
+
+def google_like():
+ """An upstream that answers argon with a signed tool call, and refuses a request whose replay carries a
+ signature another model made, as Google did on 10-27."""
+ got: list[bytes] = []
+ made = {"sigArgon": "gemini-4-argon"}
+
+ class Upstream(BaseHTTPRequestHandler):
+ def do_POST(self):
+ raw = self.rfile.read(int(self.headers["content-length"]))
+ got.append(raw)
+ doc = json.loads(raw)
+ carried = [((tc.get("extra_content") or {}).get("google") or {}).get("thought_signature")
+ for m in doc["messages"] if m.get("role") == "assistant" for tc in m.get("tool_calls") or []]
+ if any(s and s != SKIP and made.get(s, "unknown") != doc["model"] for s in carried):
+ code, out = 400, json.dumps({"error": {"code": 400, "message": "Corrupted thought signature.",
+ "status": "INVALID_ARGUMENT"}}).encode()
+ elif doc["model"] == "gemini-4-argon" and len(doc["messages"]) == 1:
+ code, out = 200, json.dumps({"object": "chat.completion", "model": doc["model"], "choices": [
+ {"index": 0, "finish_reason": "tool_calls", "message": {"role": "assistant", "content": None, "tool_calls": [
+ {"id": "c_argon", "type": "function", "function": {"name": "f", "arguments": "{}"},
+ "extra_content": {"google": {"thought_signature": "sigArgon"}}}]}}]}).encode()
+ else:
+ code, out = 200, json.dumps({"object": "chat.completion", "model": doc["model"], "choices": [
+ {"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "DONE"}}]}).encode()
+ self.send_response(code)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(out)))
+ self.end_headers()
+ self.wfile.write(out)
+
+ def log_message(self, *a):
+ pass
+
+ up = ThreadingHTTPServer(("127.0.0.1", 0), Upstream)
+ threading.Thread(target=up.serve_forever, daemon=True).start()
+
+ def turn(body: dict) -> int:
+ base, tok = server._hermes_relay_route(f"http://127.0.0.1:{up.server_address[1]}/v1", "sk-key")
+ req = urllib.request.Request(base + "/chat/completions", data=json.dumps(body).encode(), method="POST",
+ headers={"authorization": f"Bearer {tok}", "content-type": "application/json"})
+ try:
+ return urllib.request.urlopen(req, timeout=10).status
+ except urllib.error.HTTPError as e:
+ return e.code
+ yield turn, got
+ up.shutdown()
+
+
+ASK = {"role": "user", "content": "make the deck"}
+ARGON_CALL = {"role": "assistant", "content": None, "tool_calls": [
+ {"id": "c_argon", "type": "function", "function": {"name": "f", "arguments": "{}"},
+ "extra_content": {"google": {"thought_signature": "sigArgon"}}}]}
+RESULT = {"role": "tool", "tool_call_id": "c_argon", "content": "ok"}
+
+
+def test_a_switch_in_the_next_turn_sends_the_sentinel_for_the_first_models_call(google_like):
+ turn, got = google_like
+ assert turn({"model": "gemini-4-argon", "messages": [ASK]}) == 200 # argon's turn signs c_argon
+ assert server._SIG_MAKERS.get("c_argon") == "gemini-4-argon"
+ # the next turn, its own route, on flash: the harness replays argon's call with argon's signature
+ assert turn({"model": "gemini-3.6-flash", "messages": [ASK, ARGON_CALL, RESULT]}) == 200
+ assert len(got) == 2 and _sigs_of(got[1]) == [SKIP] # fitted before it went
+ # back on argon, its own signature goes back
+ assert turn({"model": "gemini-4-argon", "messages": [ASK, ARGON_CALL, RESULT]}) == 200
+ assert _sigs_of(got[2]) == ["sigArgon"]
+
+
+def test_a_runner_that_never_saw_the_call_learns_from_the_refusal(google_like, makers):
+ turn, got = google_like
+ makers.clear() # a runner started since
+ assert turn({"model": "gemini-3.6-flash", "messages": [ASK, ARGON_CALL, RESULT]}) == 200
+ assert len(got) == 2 and _sigs_of(got[0]) == ["sigArgon"] and _sigs_of(got[1]) == [SKIP]
diff --git a/runner/tests/test_relay_thought_signature.py b/runner/tests/test_relay_thought_signature.py
index 39c08650..2e80ba9a 100644
--- a/runner/tests/test_relay_thought_signature.py
+++ b/runner/tests/test_relay_thought_signature.py
@@ -87,7 +87,9 @@ def test_an_aggregator_that_streams_signatures_gets_them_back_on_the_replay():
post(json.dumps({"model": "google/gemini-3.5-flash-lite", "stream": True,
"messages": [{"role": "user", "content": "hi"}]}).encode())
- post(_replay()) # call_1's tool call replayed WITHOUT its extra_content, as an OpenAI-shaped client does
+ # call_1's tool call replayed WITHOUT its extra_content, as an OpenAI-shaped client does, to the model
+ # that made it (another model's goes as the sentinel: test_relay_signature_maker.py)
+ post(_replay().replace(b'"gemini-3.6-flash"', b'"google/gemini-3.5-flash-lite"'))
calls = {tc["id"]: tc for m in got[1]["messages"] for tc in m.get("tool_calls") or []}
assert calls["call_1"]["extra_content"]["google"]["thought_signature"] == "sigA"
assert calls["call_k"]["extra_content"]["google"]["thought_signature"] == "kept"