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.

feat(custom): anthropic-format customs pointing at Bedrock ride a Messages→InvokeModel adapter

richard-epsilla9350372ff37b
diff --git a/runner/server.py b/runner/server.py
index 91436e80..3dc569b1 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -62,6 +62,7 @@ import stat
import threading
import time
import urllib.error
+import urllib.parse
import urllib.request
import uuid
@@ -1960,6 +1961,42 @@ def _rename_max_tokens(body: bytes) -> bytes:
return body
+def _aws_eventstream_frames(resp):
+ """Yield (headers, payload) per AWS eventstream frame, from a streaming HTTP response.
+
+ Frame: [4B total len][4B headers len][4B prelude CRC][headers][payload][4B message CRC],
+ big-endian; header entries are {1B name len, name, 1B type, value}. Bedrock only sends
+ string-typed (7) headers, so anything else conservatively ends header parsing for that
+ frame. CRCs are skipped on purpose: TLS already guarantees integrity end-to-end, and a
+ stdlib-only parser that verifies CRC32 buys nothing but code."""
+ import struct
+ buf = b""
+ while True:
+ chunk = resp.read(65536)
+ buf += chunk
+ while len(buf) >= 16:
+ total = struct.unpack(">I", buf[:4])[0]
+ if len(buf) < total:
+ break
+ hlen = struct.unpack(">I", buf[4:8])[0]
+ raw = buf[12:12 + hlen]
+ payload = buf[12 + hlen:total - 4]
+ buf = buf[total:]
+ headers = {}
+ i = 0
+ while i + 2 <= len(raw):
+ nlen = raw[i]; i += 1
+ name = raw[i:i + nlen].decode("utf-8", "replace"); i += nlen
+ if i >= len(raw) or raw[i] != 7: # not a string header: bail for this frame
+ break
+ i += 1
+ vlen = struct.unpack(">H", raw[i:i + 2])[0]; i += 2
+ headers[name] = raw[i:i + vlen].decode("utf-8", "replace"); i += vlen
+ yield headers, payload
+ if not chunk:
+ return
+
+
class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
@@ -1984,6 +2021,9 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
headers = {k: v for k, v in self.headers.items() if k.lower() not in drop}
headers["authorization"] = f"Bearer {key}"
headers.setdefault("accept", "*/*")
+ if flags.get("bedrock_anthropic") and tail == "/messages" and body is not None:
+ self._bedrock_anthropic(base, key, body)
+ return
if body is not None and self.path.endswith("/chat/completions"):
body = _normalize_openai_chat_body(body)
if flags.get("rename_max_tokens"):
@@ -2032,6 +2072,79 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(data)
+ def _bedrock_anthropic(self, origin: str, key: str, body: bytes) -> None:
+ """Anthropic Messages -> Bedrock InvokeModel, both directions.
+
+ Bedrock has NO bearer-auth /v1/messages surface (the path answers HTTP 200 wrapping
+ UnknownOperationException - measured 2026-08-27). Its InvokeModel API takes the SAME
+ Anthropic Messages body with exactly three differences, all applied here: the model
+ moves from the body into the URL path, anthropic_version moves into the body, and
+ stream becomes a different endpoint whose reply is AWS binary eventstream framing -
+ each frame's payload is {"bytes": base64(<anthropic SSE event JSON>)}, re-emitted
+ here as ordinary SSE so every Messages client streams unchanged."""
+ model, stream, obj = "", False, {}
+ try:
+ obj = json.loads(body)
+ model = str(obj.pop("model", "") or "")
+ stream = bool(obj.pop("stream", False))
+ obj["anthropic_version"] = "bedrock-2023-05-31"
+ except Exception: # noqa: BLE001
+ model = ""
+ if not model:
+ data = (b'{"type":"error","error":{"type":"invalid_request_error",'
+ b'"message":"bedrock adapter: request body needs a model"}}')
+ self.send_response(400)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ op = "invoke-with-response-stream" if stream else "invoke"
+ url = f"{origin.rstrip('/')}/model/{urllib.parse.quote(model, safe='')}/{op}"
+ req = urllib.request.Request(url, data=json.dumps(obj).encode(), method="POST",
+ headers={"authorization": f"Bearer {key}",
+ "content-type": "application/json",
+ "accept": "*/*"})
+ try:
+ resp = urllib.request.urlopen(req, timeout=600)
+ except urllib.error.HTTPError as e:
+ data = e.read()
+ self.send_response(e.code)
+ self.send_header("content-type", e.headers.get("content-type") or "application/json")
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ if not stream:
+ data = resp.read() # already an Anthropic message response, verbatim
+ self.send_response(resp.status)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ return
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.send_header("transfer-encoding", "chunked")
+ self.end_headers()
+
+ def emit(block: bytes) -> None:
+ self.wfile.write(f"{len(block):x}\r\n".encode() + block + b"\r\n")
+ self.wfile.flush()
+
+ for headers, payload in _aws_eventstream_frames(resp):
+ try:
+ ev_raw = base64.b64decode(json.loads(payload)["bytes"])
+ ev_type = json.loads(ev_raw).get("type", "message")
+ except Exception: # noqa: BLE001 - an exception frame, or a shape we don't know
+ err = json.dumps({"type": "error", "error": {
+ "type": headers.get(":exception-type", "api_error"),
+ "message": payload.decode("utf-8", "replace")[:300]}}).encode()
+ emit(b"event: error\ndata: " + err + b"\n\n")
+ continue
+ emit(b"event: " + ev_type.encode() + b"\ndata: " + ev_raw + b"\n\n")
+ self.wfile.write(b"0\r\n\r\n")
+
def do_POST(self): # noqa: N802
self._forward(self.rfile.read(int(self.headers.get("content-length") or 0)))
@@ -2042,6 +2155,34 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
pass
+def _bedrock_anthropic_route(origin: str, api_key: str) -> tuple[str, str]:
+ """Register a Bedrock-Anthropic adapter route; -> (relay base_url, placeholder bearer)."""
+ with _HERMES_RELAY["lock"]:
+ if _HERMES_RELAY["server"] is None:
+ srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _HermesRelayHandler)
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ _HERMES_RELAY["server"], _HERMES_RELAY["port"] = srv, srv.server_address[1]
+ tok = "hr-relay-" + uuid.uuid4().hex
+ _HERMES_RELAY["routes"][tok] = (origin, api_key, {"bedrock_anthropic": True})
+ return f"http://127.0.0.1:{_HERMES_RELAY['port']}/v1", tok
+
+
+def _adapt_custom_auth(auth):
+ """An anthropic-format custom integration pointing at bedrock-runtime rides the adapter.
+
+ Every anthropic-format backend path converges on POST <base>/v1/messages (claude's CLI and
+ pi's client append it themselves; dsh chains its own relay into ours), so rewriting the auth
+ ONCE here covers all of them - and the real Bedrock key stays in this process, the same
+ credential win the hermes and dsh relays already have."""
+ if auth.api_format != "anthropic" or not (auth.base_url and auth.api_key):
+ return auth
+ host = urllib.parse.urlsplit(auth.base_url).hostname or ""
+ if not (host.startswith("bedrock-runtime.") and host.endswith(".amazonaws.com")):
+ return auth
+ base, tok = _bedrock_anthropic_route(f"https://{host}", auth.api_key)
+ return auth.model_copy(update={"base_url": base, "api_key": tok})
+
+
def _hermes_relay_route(base_url: str, api_key: str) -> tuple[str, str]:
"""Register one turn's upstream; → (relay base_url, placeholder bearer for the CLI)."""
with _HERMES_RELAY["lock"]:
@@ -3433,7 +3574,7 @@ def turn(req: TurnReq, identifier: str = "") -> dict:
# opaque UnknownError. Proven by env bisection on a live failure: with 40 inherited variables,
# removing or correcting PWD alone flips the turn from failing to passing.
env["PWD"] = cwd
- auth = req.auth or Auth()
+ auth = _adapt_custom_auth(req.auth or Auth())
model = req.model or spec["default_model"]
use_appserver = backend == "codex" and bool(req.codex_appserver)
cmd = None
diff --git a/runner/tests/test_bedrock_anthropic_adapter.py b/runner/tests/test_bedrock_anthropic_adapter.py
new file mode 100644
index 00000000..ceb3a77b
--- /dev/null
+++ b/runner/tests/test_bedrock_anthropic_adapter.py
@@ -0,0 +1,118 @@
+"""The Bedrock-Anthropic adapter (custom integrations, anthropic format x bedrock-runtime).
+
+Bedrock has no bearer-auth /v1/messages surface — the path 200s an UnknownOperationException
+envelope (measured 2026-08-27). InvokeModel takes the same Anthropic Messages body with three
+differences the relay applies in flight: model moves to the URL, anthropic_version moves into
+the body, and streaming answers in AWS binary eventstream whose frame payloads wrap the real
+anthropic SSE events as base64. These tests pin the frame parser against hand-built frames and
+run both directions through the real relay against a fake bedrock-runtime upstream.
+"""
+import base64
+import io
+import json
+import pathlib
+import struct
+import sys
+import threading
+import urllib.request
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+from server import Auth, _adapt_custom_auth, _aws_eventstream_frames, _bedrock_anthropic_route # noqa: E402
+
+
+def _frame(event_json: dict) -> bytes:
+ payload = json.dumps({"bytes": base64.b64encode(json.dumps(event_json).encode()).decode()}).encode()
+ name = b":event-type"
+ headers = bytes([len(name)]) + name + bytes([7]) + struct.pack(">H", 5) + b"chunk"
+ total = 12 + len(headers) + len(payload) + 4
+ return (struct.pack(">I", total) + struct.pack(">I", len(headers)) + b"\x00" * 4
+ + headers + payload + b"\x00" * 4)
+
+
+def test_eventstream_parser_roundtrip():
+ events = [{"type": "message_start", "message": {"id": "m1"}},
+ {"type": "content_block_delta", "delta": {"text": "hi"}},
+ {"type": "message_stop"}]
+ blob = b"".join(_frame(e) for e in events)
+ out = []
+ for headers, payload in _aws_eventstream_frames(io.BytesIO(blob)):
+ assert headers[":event-type"] == "chunk"
+ out.append(json.loads(base64.b64decode(json.loads(payload)["bytes"])))
+ assert out == events
+
+
+def test_adapt_custom_auth_matches_only_bedrock_anthropic():
+ a = Auth(api_key="k", base_url="https://bedrock-runtime.us-west-2.amazonaws.com",
+ api_format="anthropic")
+ b = _adapt_custom_auth(a)
+ assert b.base_url.startswith("http://127.0.0.1:") and b.api_key.startswith("hr-relay-")
+ # non-bedrock hosts and openai format pass through untouched
+ for a2 in (Auth(api_key="k", base_url="https://llmtr.com", api_format="anthropic"),
+ Auth(api_key="k", base_url="https://bedrock-runtime.us-west-2.amazonaws.com",
+ api_format="openai")):
+ assert _adapt_custom_auth(a2) is a2
+
+
+def test_adapter_translates_both_directions():
+ seen = {}
+
+ class FakeBedrock(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self): # noqa: N802
+ seen["path"] = self.path
+ seen["auth"] = self.headers.get("authorization")
+ seen["body"] = json.loads(self.rfile.read(int(self.headers["content-length"])))
+ if self.path.endswith("/invoke"):
+ data = json.dumps({"type": "message", "content": [{"type": "text", "text": "ok"}],
+ "stop_reason": "end_turn"}).encode()
+ 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)
+ else: # invoke-with-response-stream
+ blob = b"".join(_frame(e) for e in (
+ {"type": "message_start", "message": {"id": "m1"}},
+ {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "ok"}},
+ {"type": "message_stop"}))
+ self.send_response(200)
+ self.send_header("content-type", "application/vnd.amazon.eventstream")
+ self.send_header("content-length", str(len(blob)))
+ self.end_headers()
+ self.wfile.write(blob)
+
+ def log_message(self, *a):
+ pass
+
+ up = ThreadingHTTPServer(("127.0.0.1", 0), FakeBedrock)
+ threading.Thread(target=up.serve_forever, daemon=True).start()
+ try:
+ base, tok = _bedrock_anthropic_route(f"http://127.0.0.1:{up.server_address[1]}", "bedrock-key")
+ body = {"model": "us.anthropic.claude-haiku-4-5-20251001-v1:0", "max_tokens": 8,
+ "messages": [{"role": "user", "content": "hi"}]}
+ # non-streaming
+ req = urllib.request.Request(base + "/messages", data=json.dumps(body).encode(),
+ method="POST", headers={"authorization": f"Bearer {tok}",
+ "content-type": "application/json"})
+ out = json.loads(urllib.request.urlopen(req, timeout=10).read())
+ assert out["type"] == "message" and out["content"][0]["text"] == "ok"
+ assert seen["path"] == "/model/us.anthropic.claude-haiku-4-5-20251001-v1%3A0/invoke"
+ assert seen["auth"] == "Bearer bedrock-key" # real key injected upstream
+ assert "model" not in seen["body"] and "stream" not in seen["body"]
+ assert seen["body"]["anthropic_version"] == "bedrock-2023-05-31"
+ # streaming: eventstream in, ordinary SSE out
+ req2 = urllib.request.Request(base + "/messages",
+ data=json.dumps({**body, "stream": True}).encode(),
+ method="POST", headers={"authorization": f"Bearer {tok}",
+ "content-type": "application/json"})
+ r2 = urllib.request.urlopen(req2, timeout=10)
+ assert "text/event-stream" in r2.headers.get("content-type", "")
+ sse = r2.read().decode()
+ assert seen["path"].endswith("/invoke-with-response-stream")
+ assert "event: message_start" in sse and "event: content_block_delta" in sse
+ assert '"text": "ok"' in sse or '"text":"ok"' in sse
+ assert "event: message_stop" in sse
+ finally:
+ up.shutdown()