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 conversation's images are fitted to what the model takes: none for a text-only model, the most recent N for one that takes N (#601)

github-actions[bot]d125bb1fe988
diff --git a/runner/server.py b/runner/server.py
index 82e4fd04..3e76c797 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -4623,6 +4623,110 @@ def _effort_shape_refused(data: bytes) -> bool:
return bool(_EFFORT_SHAPE_REFUSED_RE.search(data or b""))
+# ── the images a conversation carries, fitted to what the model takes ────────────────────
+# A harness replays its whole conversation on every call, images included: a deck agent renders its slides
+# and looks at them on every turn, and each look stays in the history. A model that reads text only refuses
+# the next call outright, and a model with an image limit refuses it once the history passes that limit, so a
+# switch to such a model mid-conversation failed every turn after (2026-10-27, Deep Agents Code on the hosted
+# service, all three on Vercel's route): qwen3.7-max "Unexpected item type in content", nemotron-3-super "This
+# model doesn't support the image content block that you provided", mistral-medium-3.5 "Total number of images
+# exceeds the maximum allowed of 8". The call is sent with the images the model can take: none for a model
+# that reads text only, the most recent N for a model that takes N (the earlier looks were already answered in
+# the conversation's own words), each one not sent replaced by a line that says so. Known limits apply before
+# the first call; a refusal that says the model takes no image, or names its limit, is learned for the
+# (upstream host, model) for the life of the process and the call goes once more, fitted.
+_IMAGE_PARTS = {"input_image": "input_text", "image_url": "text", "image": "text"} # image part -> its text part
+_IMAGES_NONE = frozenset({"qwen3.7-max", "glm-5.3", "nemotron-3.5-lightning", "nemotron-3-super"})
+_IMAGES_CAP_FAMILIES = ((re.compile(r"^(?:mistral|magistral|devstral|pixtral|ministral|codestral)\b"), 8),) # Mistral's 8 a request
+_IMAGES_CAP_SEEN: dict[tuple[str, str], int] = {}
+_IMAGES_LIMIT_RE = re.compile(rb"(?:number of images|images?)\b[^0-9\"]{0,60}?(?:maximum|max|limit|more than|up to|at most)"
+ rb"[^0-9\"]{0,20}?(\d{1,4})", re.I)
+_IMAGES_NONE_RE = re.compile(rb"doesn't support the image|does not support (?:the )?image|not support(?:s|ed)? (?:image|vision)"
+ rb"|image input is not supported|Unexpected item type in content", re.I)
+_IMAGE_NOT_SENT = "[An image from earlier in this conversation is not shown here.]"
+_IMAGE_TEXT_ONLY = "[An image is not shown here: this model reads text only.]"
+
+
+def _is_image_part(x: object) -> bool:
+ return isinstance(x, dict) and x.get("type") in _IMAGE_PARTS and (x.get("type") != "image" or "source" in x)
+
+
+def _image_cap(model: str, route: tuple[str, str]) -> int | None:
+ """How many images the model on this route takes in one call: 0, a number, or None (no known limit)."""
+ bare = (model or "").strip().lower().rsplit("/", 1)[-1]
+ caps = [_IMAGES_CAP_SEEN[route]] if route in _IMAGES_CAP_SEEN else []
+ if bare in _IMAGES_NONE:
+ caps.append(0)
+ caps += [n for rx, n in _IMAGES_CAP_FAMILIES if rx.match(bare)]
+ return min(caps) if caps else None
+
+
+def _images_refused(refused: bytes) -> int | None:
+ """The image count a provider's refusal allows: its stated limit, 0 when it takes no image, None when the
+ refusal is not about images."""
+ m = _IMAGES_LIMIT_RE.search(refused or b"")
+ if m:
+ return int(m.group(1))
+ return 0 if _IMAGES_NONE_RE.search(refused or b"") else None
+
+
+def _fit_images(body: bytes, cap: int) -> bytes:
+ """The request with at most `cap` image parts, the most recent kept; each earlier one becomes a text part of
+ the same shape (Responses input_text, chat and Messages text). Any shape: the parts are found wherever they
+ sit (a message's content, a tool result's output). Returned byte for byte when nothing is over the cap."""
+ if not body or (b"image" not in body):
+ return body
+ try:
+ doc = json.loads(body)
+ except (ValueError, UnicodeDecodeError):
+ return body
+ found: list[tuple[list, int]] = []
+
+ def walk(x):
+ if isinstance(x, dict):
+ for v in x.values():
+ walk(v)
+ elif isinstance(x, list):
+ for i, v in enumerate(x):
+ if _is_image_part(v):
+ found.append((x, i))
+ else:
+ walk(v)
+
+ walk(doc)
+ over = len(found) - max(cap, 0)
+ if over <= 0:
+ return body
+ for parent, i in found[:over]:
+ parent[i] = {"type": _IMAGE_PARTS[parent[i]["type"]], "text": _IMAGE_TEXT_ONLY if cap <= 0 else _IMAGE_NOT_SENT}
+ return json.dumps(doc).encode()
+
+
+def _image_count(body: bytes) -> int:
+ """How many image parts the request carries (0 for a body that is not JSON)."""
+ if not body or b"image" not in body:
+ return 0
+ try:
+ doc = json.loads(body)
+ except (ValueError, UnicodeDecodeError):
+ return 0
+ n = 0
+
+ def walk(x):
+ nonlocal n
+ if _is_image_part(x):
+ n += 1
+ elif isinstance(x, dict):
+ for v in x.values():
+ walk(v)
+ elif isinstance(x, list):
+ for v in x:
+ walk(v)
+
+ walk(doc)
+ return n
+
+
def _set_reasoning_effort_none(body: bytes) -> bytes:
"""Set `reasoning_effort: "none"` in one chat-completions body.
@@ -5899,6 +6003,15 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
if fixed != body:
body = fixed
headers["content-length"] = str(len(body))
+ # The conversation's images, as many as this model takes (_IMAGE_PARTS): known limits now, a
+ # refused count learned below. Before the level, so the body kept without it is fitted too.
+ image_route = ((urllib.parse.urlsplit(base).hostname or "").lower(), str(_body_model))
+ image_cap = _image_cap(str(_body_model), image_route) if body is not None else None
+ if image_cap is not None:
+ fitted = _fit_images(body, image_cap)
+ if fitted is not body:
+ body = fitted
+ headers["content-length"] = str(len(body))
# The thinking level the turn asked for, written the way this route and this model take it
# (runner/reasoning.py). Last of the body's changes, so it is what the provider reads. A
# turn that asked for none never reaches here: its body leaves as the client wrote it.
@@ -5944,6 +6057,18 @@ class _HermesRelayHandler(http.server.BaseHTTPRequestHandler):
headers["content-length"] = str(len(body))
continue
effort_back = False
+ # A refusal of the conversation's images (none taken, or more than the model's limit):
+ # learned for this route and sent once more with the images it takes. Any other
+ # refusal goes on to the repairs below.
+ sent_images = _image_count(body) if attempt < 2 and e.code in (400, 413, 422) else 0
+ allowed = _images_refused(data) if sent_images else None
+ if allowed is not None and allowed < sent_images:
+ _IMAGES_CAP_SEEN[image_route] = min(allowed, _IMAGES_CAP_SEEN.get(image_route, allowed))
+ body = _fit_images(body, allowed)
+ headers["content-length"] = str(len(body))
+ print(f"[relay] provider refused {sent_images} images for model={_body_model}; sent again "
+ f"with at most {allowed}, and at most {allowed} from now on on this route", flush=True)
+ continue
bare = (_without_chat_cache(body) if body is not None and flags.get("chat_cache")
and self.path.endswith("/chat/completions") else None)
if (attempt < 2 and e.code in (400, 422) and _cache_control_refused(data)
diff --git a/runner/tests/test_relay_images.py b/runner/tests/test_relay_images.py
new file mode 100644
index 00000000..3d1333be
--- /dev/null
+++ b/runner/tests/test_relay_images.py
@@ -0,0 +1,185 @@
+"""A conversation's images, fitted to what the model takes (2026-10-27). A deck agent renders and looks at its slides
+every turn, and a switch to a model that reads text only, or that takes at most N images, failed every turn after:
+on Deep Agents Code on the hosted service, qwen3.7-max ("Unexpected item type in content"), nemotron-3-super ("This
+model doesn't support the image content block that you provided") and mistral-medium-3.5 ("Total number of images
+exceeds the maximum allowed of 8"), all on Vercel's route. The three provider answers below are the ones those turns
+received; the hosted broker carries the same rung."""
+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
+
+QWEN_SAYS = ("<400> InternalError.Algo.InvalidParameter: The provided messages input is invalid. "
+ "The error info is [Unexpected item type in content.].")
+NEMOTRON_SAYS = "This model doesn't support the image content block that you provided. Update the content block and try again."
+MISTRAL_SAYS = "Total number of images exceeds the maximum allowed of 8."
+PNG = "data:image/png;base64,iVBORw0KGgo="
+
+
+def _responses(n: int, model: str) -> dict:
+ """dcode's shape: a Responses request whose history holds n looks at an image (tool results), then the new ask."""
+ items = [{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "make the deck"}]}]
+ for i in range(n):
+ items += [{"type": "function_call", "call_id": f"c{i}", "name": "read_file", "arguments": json.dumps({"path": f"s{i}.png"})},
+ {"type": "function_call_output", "call_id": f"c{i}",
+ "output": [{"type": "input_image", "image_url": PNG}, {"type": "input_text", "text": f"s{i}.png"}]}]
+ items.append({"type": "message", "role": "user", "content": [{"type": "input_text", "text": "change to brown"}]})
+ return {"model": model, "input": items}
+
+
+def _chat(n: int, model: str) -> dict:
+ content = [{"type": "text", "text": "look"}] + [{"type": "image_url", "image_url": {"url": PNG}} for _ in range(n)]
+ return {"model": model, "messages": [{"role": "user", "content": content}]}
+
+
+def _messages(n: int) -> dict:
+ blocks = [{"type": "tool_result", "tool_use_id": f"t{i}",
+ "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBO"}}]}
+ for i in range(n)]
+ return {"model": "claude-sonnet-5.5", "messages": [{"role": "user", "content": blocks}]}
+
+
+def _err(msg: str) -> bytes:
+ return json.dumps({"error": {"message": msg, "type": "invalid_request_error"}}).encode()
+
+
+def test_each_wording_is_read_and_nothing_else_is():
+ assert server._images_refused(_err(QWEN_SAYS)) == 0
+ assert server._images_refused(_err(NEMOTRON_SAYS)) == 0
+ assert server._images_refused(_err(MISTRAL_SAYS)) == 8
+ assert server._images_refused(_err("max_tokens: 100000 > 64000, which is the maximum allowed")) is None
+ assert server._images_refused(_err("invalid temperature: only 1 is allowed")) is None
+ assert server._images_refused(b"") is None
+
+
+def test_the_known_limits_by_model_and_the_learned_ones_by_route(monkeypatch):
+ monkeypatch.setattr(server, "_IMAGES_CAP_SEEN", {})
+ route = ("ai-gateway.vercel.sh", "alibaba/qwen3.8-max")
+ assert server._image_cap("alibaba/qwen3.7-max", route) == 0
+ assert server._image_cap("nvidia/nemotron-3-super", route) == 0
+ assert server._image_cap("mistral/mistral-medium-3.5", route) == 8
+ assert server._image_cap("openai/gpt-6.1-sol", route) is None
+ server._IMAGES_CAP_SEEN[route] = 4
+ assert server._image_cap("alibaba/qwen3.8-max", route) == 4
+
+
+def test_the_most_recent_images_are_kept_and_each_earlier_one_is_said_in_every_shape():
+ out = json.loads(server._fit_images(json.dumps(_responses(10, "m")).encode(), 8))
+ outs = [i["output"] for i in out["input"] if i.get("type") == "function_call_output"]
+ assert [o[0]["type"] for o in outs] == ["input_text"] * 2 + ["input_image"] * 8 # the two oldest go
+ assert outs[0][0]["text"] == server._IMAGE_NOT_SENT and outs[0][1] == {"type": "input_text", "text": "s0.png"}
+ chat = json.loads(server._fit_images(json.dumps(_chat(3, "m")).encode(), 0))
+ assert [p["type"] for p in chat["messages"][0]["content"]] == ["text"] * 4
+ assert chat["messages"][0]["content"][1]["text"] == server._IMAGE_TEXT_ONLY
+ msgs = json.loads(server._fit_images(json.dumps(_messages(2)).encode(), 1))
+ assert [b["content"][0]["type"] for b in msgs["messages"][0]["content"]] == ["text", "image"]
+
+
+def test_a_body_within_the_limit_goes_byte_for_byte():
+ raw = json.dumps(_responses(3, "m")).encode()
+ assert server._fit_images(raw, 8) is raw and server._fit_images(b"not json image", 0) == b"not json image"
+ assert server._image_count(raw) == 3 and server._image_count(b"not json image") == 0
+
+
+# ── through the relay, against an upstream that refuses as Vercel's routes did ──────────────────────────────
+
+def _vercel_like(doc: dict) -> bytes | None:
+ """The refusal Vercel's route gave for this request on 10-27, or None when it answers."""
+ n, m = server._image_count(json.dumps(doc).encode()), str(doc.get("model"))
+ if "qwen3.7-max" in m and n:
+ return _err(QWEN_SAYS)
+ if "nemotron" in m and n:
+ return _err(NEMOTRON_SAYS)
+ if "mistral" in m and n > 8:
+ return _err(MISTRAL_SAYS)
+ if "qwen3.8-max" in m and n > 4:
+ return _err("Too many images: at most 4 images per request")
+ if "llama" in m:
+ return _err("max_tokens: 100000 > 64000, which is the maximum allowed")
+ return None
+
+
+def upstream(monkeypatch):
+ monkeypatch.setattr(server, "_IMAGES_CAP_SEEN", {})
+ got: list[bytes] = []
+
+ class Upstream(BaseHTTPRequestHandler):
+ def do_POST(self):
+ raw = self.rfile.read(int(self.headers["content-length"]))
+ got.append(raw)
+ doc = json.loads(raw)
+ refused = _vercel_like(doc)
+ if refused is not None:
+ code, out = 400, refused
+ elif self.path.endswith("/responses"):
+ code, out = 200, json.dumps({"id": "resp_1", "object": "response", "status": "completed", "model": doc["model"],
+ "output": [{"type": "message", "role": "assistant", "content": [
+ {"type": "output_text", "text": "DONE"}]}],
+ "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}}).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()
+ base, tok = server._hermes_relay_route(f"http://127.0.0.1:{up.server_address[1]}/v1", "sk-key")
+
+ def post(path: str, body: dict) -> int:
+ req = urllib.request.Request(base + path, 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 post, got
+ up.shutdown()
+
+
+def test_a_text_only_model_mid_conversation_is_sent_no_image_and_answers(upstream):
+ post, got = upstream
+ for model in ("alibaba/qwen3.7-max", "nvidia/nemotron-3-super"):
+ assert post("/responses", _responses(5, model)) == 200, model
+ assert server._image_count(got[-1]) == 0
+ assert len(got) == 2 # known: fitted before the first call, nothing refused
+ assert post("/chat/completions", _chat(3, "alibaba/qwen3.7-max")) == 200 and server._image_count(got[-1]) == 0
+
+
+def test_mistral_takes_its_eight_most_recent_and_answers(upstream):
+ post, got = upstream
+ assert post("/responses", _responses(12, "mistral/mistral-medium-3.5")) == 200
+ assert len(got) == 1 and server._image_count(got[0]) == 8
+
+
+def test_an_unknown_limit_is_learned_from_the_refusal_and_kept_for_the_route(upstream):
+ post, got = upstream
+ assert post("/responses", _responses(6, "alibaba/qwen3.8-max")) == 200 and len(got) == 2
+ assert server._image_count(got[0]) == 6 and server._image_count(got[1]) == 4 # as written, then fitted
+ assert post("/responses", _responses(6, "alibaba/qwen3.8-max")) == 200
+ assert len(got) == 3 and server._image_count(got[2]) == 4 # learned: fitted at once
+
+
+def test_a_model_that_takes_images_is_sent_all_of_them_and_other_refusals_pass_through(upstream):
+ post, got = upstream
+ raw = _responses(12, "openai/gpt-6.1-sol")
+ assert post("/responses", raw) == 200 and server._image_count(got[0]) == 12
+ assert json.loads(got[0])["input"] == raw["input"] # untouched
+ assert post("/responses", _responses(2, "meta/llama-4-maverick")) == 400
+ # not about images: no fitted resend (the relay's other repairs may still try their own)
+ assert all(server._image_count(b) == 2 for b in got[1:])