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.

Broker trust: the broker keeps the thinking controls of a turn that asked for a level (#403)

github-actions[bot]f34843eb1d62
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index a1b3bcca..683f13bf 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -2807,3 +2807,58 @@ either way; hermes's first text is its whole answer and its difference here is t
Not ported, with the reason: the hosted change that lets a turn's record writes run beside the loop
(each write costs about 0.4 s there; here the store is a local file), and the per-turn timing log
line that found these.
+
+## The thinking level behind a broker (2026-10-06, 0.30.2)
+
+The hosted service took the thinking level from 0.30.0 and ran the same column against it, and its
+port found what the owner-trust measurement here could not: in broker trust the gateway's own broker
+sits between the agent and the provider, and it removes the thinking controls (`thinking`,
+`context_management`, `output_config.effort`) from every Anthropic-shape request. That rule exists
+for what Claude Code sends by itself, which some model versions refuse. A level the turn had asked
+for was removed with it: the turn ran at the model's default and its record said the level had been
+applied. This tree has the same broker and the same rule.
+
+Fixed the way the hosted service fixed it: the per-turn credential the agent is handed carries the
+level as a fourth field, only when the turn asked for one, and the broker keeps the thinking controls
+of a request that arrives under such a credential. A turn that asked for nothing carries the
+credential it always did and its requests lose the controls as before. On the OpenAI shapes the
+broker never removed anything of the thinking group (`reasoning_effort`, `providerOptions`,
+`extra_body` all pass), which the hosted service pinned in a test and showed live: a Gemini model at
+`none` spent 0 thinking tokens through its broker and TokenRouter.
+
+Measured here in broker trust (a side container with `HR_SANDBOX_TRUST=broker`; the image's
+default is owner trust, where the agent holds the key and no broker is in the way). Claude Code with
+claude-haiku-4.5 through the broker and TokenRouter, output tokens of three runs per level:
+
+| | none | low | high |
+|---|---|---|---|
+| 0.30.1 | 690, 726, 768 | 838, 782, 689 | 931, 774, 712 |
+| with the fix | 730, 538, 824 | 2,277, 2,256, 1,686 | 2,284, 2,754, 3,801 |
+
+On 0.30.1 every turn recorded its level as applied and all nine spent what a turn with no level
+spends. hermes, pi and Codex with gpt-5.4 passed the column in broker trust before and after (their
+level rides `reasoning_effort` through the relay and the broker, which the gateway makes possible by
+naming the route): the first end-to-end run of the level behind this tree's own broker.
+
+The column's judge passed the 0.30.1 row: on output tokens "low below high" held by noise (2,309
+against 2,417). It now also asks, where output tokens stand in for a missing count, that low spend
+at least half again what none does; the 0.30.1 row fails it and every earlier pass still passes.
+
+The hosted column, as that session reported it (`run-column.py` from 915c834, one run per level,
+gpt-5.4 unless said; thinking tokens at none, low, high):
+
+| base | none | low | high | |
+|---|---:|---:|---:|---|
+| hermes | 0 | 62 | 403 | |
+| goose | 0 | 278 | 831 | |
+| cheetahclaws | 0 | 302 | 471 | |
+| kimi | 0 | 224 | 516 | |
+| qwen | 0 | 434 | 779 | |
+| codex | 12 out | 271 out | 501 out | no count: its calls go to the broker without passing a relay there |
+| claude-code, claude-haiku-4.5 | 721 out | 1,964 out | 2,248 out | with the broker keeping the controls |
+| opencode | | | | recorded default at every level on the first image |
+
+7 of 8. opencode, pi and omp talk to the broker directly on the hosted service (they ride the relay
+here for every keyed turn), so the relay never saw their calls; there they now take the relay for a
+turn that asks for a level. That difference between the trees is the hosted one's and is recorded
+here because the column is shared.
diff --git a/gateway/app.py b/gateway/app.py
index 09077674..beafcf8d 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -1016,10 +1016,14 @@ def _calibration_env(hv: dict | None, org: str, sid: str, timeout_s: int | None)
"HR_CALIBRATION_TOKEN": _mint_calibration_token(sid, org, inner, ttl)}
-def _mint_turn_cred(sid: str, conn_name: str) -> str:
- """Per-turn credential: sid.conn.exp.hmac — resolvable back to exactly one connection."""
+def _mint_turn_cred(sid: str, conn_name: str, level: str = "") -> str:
+ """Per-turn credential: sid.conn.exp.hmac — resolvable back to exactly one connection.
+
+ A fourth field names the thinking level the turn asked for, and is there only when it asked for
+ one: the broker keeps such a turn's thinking controls (see _strip_unsupported) and reads that
+ from the credential itself. A turn that asked for none carries the credential it always did."""
exp = str(int(time.time()) + _BROKER_TTL_S)
- body = f"{sid}|{conn_name}|{exp}"
+ body = f"{sid}|{conn_name}|{exp}" + (f"|{level}" if level else "")
sig = hmac.new((INTERNAL_KEY or "dev-insecure").encode(), body.encode(), hashlib.sha256).hexdigest()
return f"hrt_{base64.urlsafe_b64encode(body.encode()).decode().rstrip('=')}.{sig}"
@@ -1031,7 +1035,7 @@ def _verify_turn_cred(tok: str) -> tuple[str, str] | None:
try:
b64, sig = tok[4:].rsplit(".", 1)
body = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4)).decode()
- sid, conn_name, exp = body.split("|")
+ sid, conn_name, exp = body.split("|")[:3]
except Exception: # noqa: BLE001 — malformed token is simply invalid
return None
good = hmac.new((INTERNAL_KEY or "dev-insecure").encode(), body.encode(), hashlib.sha256).hexdigest()
@@ -1040,6 +1044,18 @@ def _verify_turn_cred(tok: str) -> tuple[str, str] | None:
return sid, conn_name
+def _turn_cred_level(tok: str) -> str:
+ """The thinking level a valid per-turn credential says its turn asked for, "" for none."""
+ if not _verify_turn_cred(tok):
+ return ""
+ try:
+ b64 = tok[4:].rsplit(".", 1)[0]
+ parts = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4)).decode().split("|")
+ except Exception: # noqa: BLE001
+ return ""
+ return parts[3] if len(parts) > 3 and parts[3] in reasoning.LEVELS else ""
+
+
# Every field in _AUTH_FIELDS that carries a credential. Removal is driven off THIS list, not off
# the branch that decides brokering, so a secret can never survive because a condition was wrong.
_SECRET_AUTH_FIELDS = ("api_key", "aws_access_key_id", "aws_secret_access_key",
@@ -1050,7 +1066,7 @@ _SECRET_AUTH_FIELDS = ("api_key", "aws_access_key_id", "aws_secret_access_key",
SANDBOX_TRUST = os.environ.get("HR_SANDBOX_TRUST", "").strip().lower()
-def _auth_from_conn(conn: dict, sid: str = "") -> dict | None:
+def _auth_from_conn(conn: dict, sid: str = "", effort: str = "") -> dict | None:
"""What the SANDBOX is allowed to see, or None if it cannot be given anything safely.
The sandbox runs the customer's agent with real bash and network egress, so a provider
@@ -1101,7 +1117,7 @@ def _auth_from_conn(conn: dict, sid: str = "") -> dict | None:
print(f"[broker] refusing to build sandbox auth for provider={provider!r}: {log_reason}",
flush=True)
return None
- out["api_key"] = _mint_turn_cred(sid, str(conn.get("name") or ""))
+ out["api_key"] = _mint_turn_cred(sid, str(conn.get("name") or ""), effort)
out["base_url"] = f"{_sandbox_broker_origin()}/v1/llm"
return out
@@ -3497,7 +3513,11 @@ _BROKER_HOP = ("host", "content-length", "connection", "keep-alive", "transfer-e
# rejects `output_config.effort` and `thinking.adaptive`; `context_management`'s only strategy
# is defined in terms of thinking, so it goes with it. These are model-version rejections, the
# same on the org's own key as on the platform's, so they are stripped for every provider that
-# carries the Anthropic shape (Anthropic, Bedrock, TokenRouter, Vercel, LLMTR).
+# carries the Anthropic shape (Anthropic, Bedrock, TokenRouter, Vercel, LLMTR). EXCEPT for a
+# turn that ASKED for a thinking level (`reasoning.effort`, or the harness's): its controls were
+# written for the model it runs on, by the relay or by the CLI's own switch (runner/reasoning.py),
+# and removing them here ran the turn at the model's default while its record said the level had
+# been applied (found on the hosted service, 2026-10-05).
# * OpenAI-shape requests (`responses`, `responses/*`, `chat/completions`): nothing of the
# thinking group. `reasoning` carries Codex's effort and, on `responses/compact`, the
# `reasoning.context = all_turns` the compaction needs; TokenRouter and OpenRouter both take
@@ -3511,7 +3531,8 @@ _ANTHROPIC_THINKING_FIELDS = ("thinking", "context_management")
_TIER_FIELDS = ("service_tier", "speed", "provider")
-def _strip_unsupported(body: bytes, provider: str = "", byok: bool = False, path: str = "") -> bytes:
+def _strip_unsupported(body: bytes, provider: str = "", byok: bool = False, path: str = "",
+ keep_thinking: bool = False) -> bytes:
"""Remove what this request must not carry (see the rule above). Returns the body unchanged
if it is not JSON — the broker must stay a dumb pipe for anything it does not positively
understand."""
@@ -3525,14 +3546,15 @@ def _strip_unsupported(body: bytes, provider: str = "", byok: bool = False, path
return body
changed = False
anthropic_shape = (path or "").strip("/").startswith("messages")
- fields: tuple[str, ...] = _ANTHROPIC_THINKING_FIELDS if anthropic_shape else ()
+ strip_thinking = anthropic_shape and not keep_thinking
+ fields: tuple[str, ...] = _ANTHROPIC_THINKING_FIELDS if strip_thinking else ()
if not byok:
fields += _TIER_FIELDS
for f in fields:
if f in doc:
doc.pop(f)
changed = True
- if anthropic_shape:
+ if strip_thinking:
# `output_config` carries more than effort; drop only that key, and the object with it
# if nothing else remains, so a provider never sees an empty container it may reject.
oc = doc.get("output_config")
@@ -3990,7 +4012,8 @@ async def llm_broker(path: str, request: Request):
else:
headers["authorization"] = f"Bearer {key}"
- body = _strip_unsupported(await request.body(), provider=provider, byok=True, path=suffix)
+ body = _strip_unsupported(await request.body(), provider=provider, byok=True, path=suffix,
+ keep_thinking=bool(_turn_cred_level(_broker_token(request))))
if provider == "google":
body = _google_with_signatures(body, sid)
if provider in _STRICT_GEMINI_CHANNELS and "gemini" in _body_model_name(body).lower():
@@ -7607,7 +7630,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
rec["tried"].append({"connection": name, "error": why})
continue
conn = _chain_wired(conn, backend)
- sandbox_auth = _auth_from_conn(conn, sid)
+ sandbox_auth = _auth_from_conn(conn, sid, effort)
if sandbox_auth is None:
# Refusing beats running: the only alternative is handing the sandbox a real provider
# key. The chain moves on, and a fully unbrokerable chain fails the turn loudly.
diff --git a/gateway/tests/test_reasoning_effort.py b/gateway/tests/test_reasoning_effort.py
index 93100a9b..be498c88 100644
--- a/gateway/tests/test_reasoning_effort.py
+++ b/gateway/tests/test_reasoning_effort.py
@@ -107,3 +107,62 @@ def test_bases_say_which_levels_each_model_has_and_none_where_none_was_measured(
def test_the_levels_come_from_the_runners_table_not_a_second_one():
assert gw.reasoning.__file__.replace(os.sep, "/").endswith("runner/reasoning.py")
assert gw.reasoning.levels_for("openai/gpt-5.4") == ("none", "low", "medium", "high", "xhigh")
+
+
+# ── broker trust: the gateway's own broker sits between the agent and the provider ─────────────
+
+def test_the_per_turn_credential_says_a_level_only_for_a_turn_that_asked_for_one(monkeypatch):
+ monkeypatch.setattr(gw, "INTERNAL_KEY", "k-test")
+ plain = gw._mint_turn_cred("hsess1", "integration:Anthropic")
+ leveled = gw._mint_turn_cred("hsess1", "integration:Anthropic", "low")
+ assert gw._verify_turn_cred(plain) == gw._verify_turn_cred(leveled) == ("hsess1", "integration:Anthropic")
+ assert gw._turn_cred_level(plain) == "" and gw._turn_cred_level(leveled) == "low"
+ # the credential of a turn that asked for nothing is what it always was: three fields
+ import base64
+ body = base64.urlsafe_b64decode(plain[4:].rsplit(".", 1)[0] + "==").decode()
+ assert body.count("|") == 2
+ # the level is under the signature: one written in by hand is no credential at all
+ b64, sig = plain[4:].rsplit(".", 1)
+ forged = "hrt_" + base64.urlsafe_b64encode((body + "|high").encode()).decode().rstrip("=") + "." + sig
+ assert gw._verify_turn_cred(forged) is None and gw._turn_cred_level(forged) == ""
+ assert gw._turn_cred_level("not-a-token") == ""
+
+
+def test_the_broker_keeps_the_thinking_controls_of_a_turn_that_asked_for_a_level():
+ """The broker removes the thinking controls from every Anthropic-shape request, for the model
+ refusals of what Claude Code sends by itself. A level the turn asked for was removed with them:
+ the turn ran at the model's default and its record said the level had been applied (found on the
+ hosted service, 2026-10-05)."""
+ import json
+ sent = {"model": "claude-sonnet-5-5", "max_tokens": 4000, "messages": [],
+ "thinking": {"type": "adaptive"}, "output_config": {"effort": "low", "format": "x"},
+ "context_management": {"edits": []}, "service_tier": "priority"}
+ raw = json.dumps(sent).encode()
+ as_before = json.loads(gw._strip_unsupported(raw, provider="anthropic", byok=True, path="messages"))
+ assert "thinking" not in as_before and "context_management" not in as_before
+ assert as_before["output_config"] == {"format": "x"}
+ kept = gw._strip_unsupported(raw, provider="anthropic", byok=True, path="messages", keep_thinking=True)
+ assert kept is raw # nothing to remove: the same bytes go on
+ # on the platform's key the priced-tier selectors still go, level or no level
+ platform = json.loads(gw._strip_unsupported(raw, provider="anthropic", byok=False, path="messages", keep_thinking=True))
+ assert "service_tier" not in platform and platform["thinking"] == {"type": "adaptive"}
+ assert platform["output_config"] == {"effort": "low", "format": "x"}
+ # the OpenAI shapes never lost their thinking fields and do not now
+ chat = json.dumps({"model": "gpt-5.4", "messages": [], "reasoning_effort": "low",
+ "providerOptions": {"google": {"thinkingConfig": {"thinkingBudget": 0}}},
+ "extra_body": {"google": {"thinking_config": {"thinking_level": "low"}}}}).encode()
+ assert gw._strip_unsupported(chat, provider="vercel", byok=True, path="chat/completions") is chat
+
+
+def test_in_broker_trust_the_turns_level_rides_its_credential(monkeypatch):
+ monkeypatch.setattr(gw, "SANDBOX_TRUST", "broker")
+ monkeypatch.setattr(gw, "PUBLIC_BASE_URL", "https://hr.example")
+ monkeypatch.setattr(gw, "INTERNAL_KEY", "k-test")
+ conn = {"name": "integration:Anthropic", "backend": "claude", "provider": "anthropic", "api_key": "sk-ant-real"}
+ plain = gw._auth_from_conn(conn, "hsess1")
+ leveled = gw._auth_from_conn(conn, "hsess1", "high")
+ assert plain and leveled and "sk-ant-real" not in str(plain) + str(leveled)
+ assert gw._turn_cred_level(plain["api_key"]) == "" and gw._turn_cred_level(leveled["api_key"]) == "high"
+ src = open(os.path.join(os.path.dirname(__file__), "..", "app.py")).read()
+ assert "sandbox_auth = _auth_from_conn(conn, sid, effort)" in src
+ assert "keep_thinking=bool(_turn_cred_level(_broker_token(request)))" in src
diff --git a/gateway/tests/test_sandbox_broker_origin.py b/gateway/tests/test_sandbox_broker_origin.py
index 1042c394..155116b7 100644
--- a/gateway/tests/test_sandbox_broker_origin.py
+++ b/gateway/tests/test_sandbox_broker_origin.py
@@ -27,6 +27,6 @@ def test_the_sandbox_auth_carries_that_origin(monkeypatch):
monkeypatch.setattr(gw, "PUBLIC_BASE_URL", "https://console.example")
monkeypatch.setattr(gw, "_pool_is_local", lambda: True)
monkeypatch.setattr(gw, "SANDBOX_TRUST", "")
- monkeypatch.setattr(gw, "_mint_turn_cred", lambda sid, name: "hrt_x")
+ monkeypatch.setattr(gw, "_mint_turn_cred", lambda sid, name, *level: "hrt_x")
out = gw._auth_from_conn({"provider": "anthropic", "api_key": "sk-ant-real", "name": "Anthropic"}, "sid1")
assert out["base_url"] == "http://127.0.0.1:8080/v1/llm" and out["api_key"] == "hrt_x" and "sk-ant-real" not in str(out)
diff --git a/scripts/support-matrix/thinking/run-column.py b/scripts/support-matrix/thinking/run-column.py
index f927a37b..bee26c34 100644
--- a/scripts/support-matrix/thinking/run-column.py
+++ b/scripts/support-matrix/thinking/run-column.py
@@ -9,6 +9,8 @@ of thinking tokens. The judge is the provider's figure, never what the agent say
applied each level asked is recorded with the level the model was given
off `none` spends no thinking tokens, where the model has `none`
order the low level spends fewer thinking tokens than the high one
+ effect where output tokens stand in for a missing count, low spends at least half again what
+ none does: without it, a level that is recorded and never reaches the model passes by noise
Where a provider reports no thinking count for the model (Anthropic through some doors), output tokens
stand in, since thinking is billed as output, and the row says so.
@@ -98,6 +100,14 @@ def judge(levels: list[str], turns: list[dict]) -> tuple[str, list[str]]:
return sum(int(t[key] or 0) for t in by.get(lv, []))
if "none" in levels and counted and total("none") != 0:
findings.append(f"none: {total('none')} thinking tokens")
+ # With no thinking count, output tokens stand in, and "low is below high" alone passes by noise
+ # when a level was recorded and never reached the model (a broker that removed the thinking
+ # controls: none 2,184, low 2,309, high 2,417 output tokens over three runs, 2026-10-06). A level
+ # that reached the model spends well over what none does: the low level must be at least half
+ # again the none level.
+ if "none" in levels and "low" in levels and not counted and total("low") < 1.5 * total("none"):
+ findings.append(f"effect: low {total('low')} is not half again none {total('none')} ({key}); "
+ f"the level may be recorded and not reaching the model")
low, high = ("low" if "low" in levels else ""), ("high" if "high" in levels else "")
if low and high and not total(low) < total(high):
findings.append(f"order: {low} {total(low)} is not below {high} {total(high)} ({key})")