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.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
A harness field it does not have is refused by name, and a model its base does not run is refused when saved (#445)
github-actions[bot]c213c627e98a
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.mdindex c09b9eb2..5374ab86 100644--- a/docs/self-hosting-guide.md+++ b/docs/self-hosting-guide.md@@ -253,7 +253,10 @@ A model that shipped after this release is one row away: open the integration, athe id the provider uses on the wire, and save. It appears in every model picker the providerdrives, and a task may name it. A task that names a model no connected provider serves on thatbase is refused before it starts (`400 model_not_available`), never run on another model;-`GET /v1/harnesses/{id}/models` lists what a harness can run.+`GET /v1/harnesses/{id}/models` lists what a harness can run. A harness is held to the same rule+when it is saved: a default model its base does not run is refused (`422 model_not_available`, with+the base's models), and so is a field a harness does not have (`422`, naming the field and the+nearest one it has). A harness read with `GET` and sent back as it came saves.<details><summary>Running more than one provider</summary>diff --git a/gateway/app.py b/gateway/app.pyindex 2d1bbda7..2720c5d3 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -26,6 +26,7 @@ import zipfileimport base64import contextlib+import difflibimport functoolsimport hashlibimport ipaddress@@ -44,7 +45,8 @@ from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, Requestfrom fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import FileResponse, JSONResponse, StreamingResponsefrom starlette.background import BackgroundTask-from pydantic import AliasChoices, BaseModel, ConfigDict, Field+from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator+from pydantic_core import PydanticCustomErrorimport backing # pluggable graph/blob/secret stores (vg | local)import media_plane # the media plane (capability catalog, provider adapters, ffmpeg)@@ -16769,6 +16771,28 @@ def _require_supported_base(base: str) -> str:return b+async def _require_offered_model(org: str, base: str, model: str | None, previous: str = "") -> None:+ """A harness's default model must be one its base runs on this instance, by the rule a task+ naming that model is held to (_model_authorized_async: the base's catalog and the provider+ families it takes, or a model an integration that drives the base was given). Refused when the+ harness is saved rather than at its first task: until 2026-10-10 a harness on gemini-2.5-flash,+ which no base runs, saved with a 200 and then refused every task given to it, far from the+ request that made the mistake. An update that leaves the model as it was is not checked again,+ so an unrelated edit to a harness whose model has since gone still saves."""+ base = _require_supported_base(base) # an unknown base is said as that, not as its model+ m = (model or "").strip()+ if not m or m == (previous or "").strip():+ return+ backend = _backend_of_harness({"base": base}) or base+ if await _model_authorized_async(m, backend, org):+ return+ offered = list(_MODEL_CATALOG.get(backend, {}).get("models", []))+ raise uhp_error(422, "model_not_available",+ f"Model '{m}' is not offered on the {base} base. Use one of: {', '.join(offered[:12])}"+ f"{', …' if len(offered) > 12 else ''} (GET /v1/bases lists every base's models).",+ "default_model", {"offered": offered})++def _either(snake: str, schema: dict | None = None):"""A create/update field by its schema name (snake_case, HarnessCreate) OR the name theharness object comes back with (camelCase, Harness). A client that mirrors what GET returned@@ -16847,6 +16871,47 @@ class HarnessBody(BaseModel):calibrates: str | None = _either("calibrates")environment: str | None = None # the environment (henv_) this harness's tasks read at /env/<slug>; UHP Environments+ @model_validator(mode="before")+ @classmethod+ def _known_fields_only(cls, data):+ """A field a harness does not have is refused, by name, with the nearest one it does have.+ Until 2026-10-10 an `instructions` or a `system_promt` was dropped and the harness saved+ without the setting behind a 200; an agent driving the API had nothing to tell it why its+ harness came back empty, and makes the same harness again and again. What a harness comes back with+ and cannot be written (its id, owner, workspace, creation time, kit, plugin files not+ loaded) is let through and ignored, so a harness read and sent back still saves."""+ if not isinstance(data, dict):+ return data+ known = _harness_field_names()+ unknown = [k for k in data if k not in known and k not in _HARNESS_READ_ONLY]+ if unknown:+ k = str(unknown[0])+ near = difflib.get_close_matches(k, sorted(known), n=1, cutoff=0.6)+ raise PydanticCustomError(+ "unknown_field",+ "unknown harness field '{field}'{hint}. A harness takes: {fields} (the camelCase names "+ "it comes back with are accepted too).",+ {"field": k, "hint": f" (did you mean '{near[0]}'?)" if near else "",+ "fields": ", ".join(cls.model_fields)})+ return {k: v for k, v in data.items() if k not in _HARNESS_READ_ONLY}+++# What a harness comes back with (_harness_out) that is not written through these fields, plus the+# protocol's `object` (Harnesses §2), so a harness read from any UHP server can be sent back.+_HARNESS_READ_ONLY = frozenset({"id", "object", "kit", "notLoaded", "member", "workspace", "createdAt"})+++def _harness_field_names() -> frozenset:+ names: set[str] = set()+ for name, f in HarnessBody.model_fields.items():+ names.add(name)+ va = f.validation_alias+ if isinstance(va, AliasChoices):+ names.update(c for c in va.choices if isinstance(c, str))+ elif isinstance(va, str):+ names.add(va)+ return frozenset(names)+def _harness_out(v: dict) -> dict:"""VG vertex (snake_case, JSON-string lists) -> the frontend CustomHarness shape (camelCase)."""@@ -18055,6 +18120,7 @@ async def create_harness(org: str, body: HarnessBody, request: Request) -> dict:member = p.get("member") or request.headers.get("x-harness-member", "")# a key held to a workspace stamps its own, whatever header it sends; any other caller names itworkspace = _key_scope(p) or request.headers.get("x-harness-workspace", "")+ await _require_offered_model(org, body.base, body.default_model)body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)await _environment_check_ref(org, body.environment)@@ -18156,6 +18222,7 @@ async def update_harness(org: str, hid: str, body: HarnessBody, request: Request"A harness's base cannot change; create a different harness for a different base.","base", {"base": cur.get("base")})body.base = str(cur.get("base") or body.base)+ await _require_offered_model(org, body.base, body.default_model, str(cur.get("default_model") or ""))# coalesce-upsert: created_at/org are untouched (only the provided props are set)body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)@@ -18326,6 +18393,7 @@ async def create_harness_public(body: HarnessBody, request: Request) -> dict:org, member = p.get("org", ""), p.get("member", "")if not org:raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")+ await _require_offered_model(org, body.base, body.default_model)body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)await _environment_check_ref(org, body.environment)@@ -19321,6 +19389,7 @@ async def update_harness_public(hid: str, body: HarnessBody, request: Request) -"A harness's base cannot change; create a different harness for a different base.","base", {"base": v.get("base")})body.base = str(v.get("base") or body.base)+ await _require_offered_model(org, body.base, body.default_model, str(v.get("default_model") or ""))body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)await _environment_check_ref(org, body.environment)diff --git a/gateway/tests/test_harness_fields.py b/gateway/tests/test_harness_fields.pynew file mode 100644index 00000000..7c832198--- /dev/null+++ b/gateway/tests/test_harness_fields.py@@ -0,0 +1,141 @@+"""A field a harness does not have is refused by name, and a model its base does not run is refused+when the harness is saved (2026-10-10, the same rule as the hosted service). The camelCase names were+already taken (#212); an unknown name or a typo was dropped in silence behind a 200, and a harness+saved on a model its base does not run answered 200 and then refused every task. An agent driving+the API learns nothing from either, and makes the same harness again and again."""+import asyncio+import os+import re+import sys++import pytest+from fastapi.testclient import TestClient++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+import app # noqa: E402++H = {"x-harness-internal": "test-internal-key", "x-harness-org": "org.fields", "x-harness-member": "[email protected]"}++[email protected](scope="module")+def client():+ with TestClient(app.app) as c:+ yield c+++def _model(base):+ return app._MODEL_CATALOG[app._backend_of_harness({"base": base})]["models"][0]+++def _count(client):+ return len(client.get("/v1/harnesses", headers=H).json()["harnesses"])+++def test_the_names_a_harness_comes_back_with_are_taken_on_the_way_in(client):+ m = _model("pi")+ r = client.post("/v1/harnesses", json={"name": "story", "base": "pi", "systemPrompt": "Write stories.",+ "defaultModel": m, "maxStep": 7, "disabledTools": ["bash"]}, headers=H)+ assert r.status_code == 200, r.text+ h = r.json()+ assert h["systemPrompt"] == "Write stories." and h["defaultModel"] == m and h["maxStep"] == 7+ assert h["disabledTools"] == ["bash"]+++def test_a_harness_read_back_and_sent_again_saves(client):+ m = _model("pi")+ h = client.post("/v1/harnesses", json={"name": "story", "base": "pi", "system_prompt": "v1", "default_model": m}, headers=H).json()+ got = client.get(f"/v1/harnesses/{h['id']}", headers=H).json()+ # the whole object, id, createdAt, member, kit, notLoaded and all, and the protocol's `object`+ got.update(systemPrompt="v2", object="harness")+ r = client.put(f"/v1/harnesses/{h['id']}", json=got, headers=H)+ assert r.status_code == 200, r.text+ assert r.json()["systemPrompt"] == "v2" and r.json()["defaultModel"] == m and r.json()["id"] == h["id"]+++def test_the_snake_case_name_wins_when_a_body_carries_both(client):+ r = client.post("/v1/harnesses", json={"name": "x", "base": "pi", "system_prompt": "mine", "systemPrompt": "copied"}, headers=H)+ assert r.status_code == 200 and r.json()["systemPrompt"] == "mine"+++def test_a_field_the_harness_does_not_have_is_refused_by_name_with_the_nearest_one(client):+ before = _count(client)+ r = client.post("/v1/harnesses", json={"name": "x", "base": "pi", "system_promt": "a typo's value"}, headers=H)+ assert r.status_code == 422+ msg = r.json()["error"]["message"]+ assert "'system_promt' (did you mean 'system_prompt'?). A harness takes: " in msg and "default_model" in msg+ assert "typo's value" not in r.text # the value is never echoed+ r = client.post("/v1/harnesses", json={"name": "x", "base": "pi", "instructions": "do it"}, headers=H)+ assert r.status_code == 422 and "'instructions'" in r.json()["error"]["message"]+ assert _count(client) == before # nothing was written+ # an update is held to the same rule+ h = client.post("/v1/harnesses", json={"name": "y", "base": "pi"}, headers=H).json()+ r = client.put(f"/v1/harnesses/{h['id']}", json={"name": "y", "base": "pi", "model": _model("pi")}, headers=H)+ assert r.status_code == 422 and "'model'" in r.json()["error"]["message"]+++def test_the_servers_own_builders_still_build():+ """Kit launch and plugin install build the body from keywords, which are all fields."""+ b = app.HarnessBody(name="k", base="pi", default_model=_model("pi"), plugins=[], max_step=None)+ assert b.default_model == _model("pi")+++def test_a_model_the_base_does_not_run_is_refused_when_saved(client):+ before = _count(client)+ r = client.post("/v1/harnesses", json={"name": "story", "base": "pi", "default_model": "gemini-2.5-flash"}, headers=H)+ assert r.status_code == 422+ err = r.json()["error"]+ assert err["code"] == "model_not_available" and err["param"] == "default_model"+ assert "gemini-2.5-flash" in err["message"] and _model("pi") in err["message"]+ assert _model("pi") in err["detail"]["offered"]+ assert _count(client) == before+ # no model at all is the base's default, and is fine+ assert client.post("/v1/harnesses", json={"name": "story", "base": "pi"}, headers=H).status_code == 200+ # an unknown base is said as that, not as its model+ r = client.post("/v1/harnesses", json={"name": "s", "base": "nope", "default_model": "x"}, headers=H)+ assert r.status_code == 422 and r.json()["error"]["code"] == "unsupported_base"+++def test_an_edit_that_leaves_a_retired_model_as_it_was_still_saves(client):+ h = client.post("/v1/harnesses", json={"name": "old", "base": "pi", "default_model": _model("pi")}, headers=H).json()+ # a harness saved before the model was retired (or before this check)+ asyncio.run(app._vg_upsert("Harness", h["id"], {"default_model": "gemini-2.5-flash"}))+ r = client.put(f"/v1/harnesses/{h['id']}", json={"name": "renamed", "base": "pi", "default_model": "gemini-2.5-flash"}, headers=H)+ assert r.status_code == 200, r.text+ r = client.put(f"/v1/harnesses/{h['id']}", json={"name": "renamed", "base": "pi", "default_model": "gemini-2.0-pro"}, headers=H)+ assert r.status_code == 422 and r.json()["error"]["code"] == "model_not_available"+ r = client.put(f"/v1/harnesses/{h['id']}", json={"name": "renamed", "base": "pi", "default_model": _model("pi")}, headers=H)+ assert r.status_code == 200 and r.json()["defaultModel"] == _model("pi")+++def test_a_model_an_integration_that_drives_the_base_was_given_is_taken(client, monkeypatch):+ """The rule a task naming the model is held to: a custom endpoint's own model id is in no catalog."""+ async def integrations():+ return [{"name": "Mine", "provider": "custom", "config": {"api_format": "openai"}}]++ async def model_map():+ return {"my-own-model": "Mine"}+ monkeypatch.setattr(app, "_integrations_doc", integrations)+ monkeypatch.setattr(app, "_effective_model_map", model_map)+ r = client.post("/v1/harnesses", json={"name": "own", "base": "pi", "default_model": "my-own-model"}, headers=H)+ assert r.status_code == 200 and r.json()["defaultModel"] == "my-own-model"+ # the same model on a base its format does not drive is refused+ r = client.post("/v1/harnesses", json={"name": "own", "base": "claude-code", "default_model": "my-own-model"}, headers=H)+ assert r.status_code == 422 and r.json()["error"]["code"] == "model_not_available"+++def test_every_model_the_console_offers_on_a_base_is_one_the_gateway_saves():+ """The console fills a new harness's model from its own per-base lists; one the gateway would+ refuse makes a harness the console cannot save."""+ src = open(os.path.join(os.path.dirname(__file__), "..", "..", "ui", "src", "lib", "harness.ts")).read()+ oob = src[src.index("export const OOB"):]+ oob = oob[:oob.index("\n];")]+ blocks = re.split(r"\n \{ id: ", oob)[1:]+ assert len(blocks) == len(app._BASE_CATALOG)+ refused = []+ for blk in blocks:+ base = re.match(r"'([^']+)'", blk).group(1)+ models = re.findall(r"'([^']+)'", re.search(r"models: \[([^\]]*)\]", blk).group(1))+ default = re.search(r"defaultModel: '([^']*)'", blk).group(1)+ backend = app._backend_of_harness({"base": base})+ refused += [(base, m) for m in models + [default] if not app._model_authorized(m, backend)]+ assert not refused, refuseddiff --git a/protocol/VERSIONING.md b/protocol/VERSIONING.mdindex 4e13557e..ad79795a 100644--- a/protocol/VERSIONING.md+++ b/protocol/VERSIONING.md@@ -78,3 +78,13 @@ smooth ones.The protocol now names `DELETE /v1/sessions/{id}` and keeps the old path as an alias rather thanrenaming it, because renaming would break existing clients for a cosmetic gain. A future majorversion may retire the old path through the process above.+- **Harness writes refuse what they cannot store.** Since 2026-10-10 both maintained servers refuse+ a harness create or update that carries a field the harness does not have (`422`, naming the field+ and the nearest one it does have), or a `default_model` its base does not run (`422`,+ `model_not_available`). Both are tightenings the rules above reserve for a new version. They were+ made inside `2026-10-04` because the input they refuse was being stored as nothing behind a `200`,+ and a harness on a model no base runs refused every task given to it; a client, and above all an+ agent driving the API, had no way to learn why. What the harness object comes back with and cannot be written (`id`,+ `object`, `createdAt` and the server's own read-only fields) is still accepted and ignored, so a+ harness read and sent back saves. The next version states both rules in+ [Harnesses §5](versions/2026-10-04/harnesses.md#5-managing-harnesses).